input
stringlengths 50
13.9k
| output_program
stringlengths 5
655k
| output_answer
stringlengths 5
655k
| split
stringclasses 1
value | dataset
stringclasses 1
value |
---|---|---|---|---|
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
Example:
Input: 38
Output: 2
Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
Since 2 has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime? | class Solution:
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
while True:
if num<10:
return num
else:
num=sum([int(i) for i in str(num)]) | class Solution:
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
while True:
if num<10:
return num
else:
num=sum([int(i) for i in str(num)]) | train | APPS_structured |
It started as a discussion with a friend, who didn't fully grasp some way of setting defaults, but I thought the idea was cool enough for a beginner kata: binary `OR` each matching element of two given arrays (or lists, if you do it in Python; vectors in c++) of integers and give the resulting ORed array [starts to sound like a tonguetwister, doesn't it?].
If one array is shorter than the other, use the optional third parametero (defaulted to `0`) to `OR` the unmatched elements.
For example:
```python
or_arrays([1,2,3],[1,2,3]) == [1,2,3]
or_arrays([1,2,3],[4,5,6]) == [5,7,7]
or_arrays([1,2,3],[1,2]) == [1,2,3]
or_arrays([1,2],[1,2,3]) == [1,2,3]
or_arrays([1,2,3],[1,2,3],3) == [1,2,3]
``` | def ind(arr, i, default):
return default if len(arr) - 1 < i else arr[i]
def or_arrays(arr1, arr2, default=0):
return [ind(arr1, i, default) | ind(arr2, i, default) for i in range(max(len(arr1), len(arr2)))] | def ind(arr, i, default):
return default if len(arr) - 1 < i else arr[i]
def or_arrays(arr1, arr2, default=0):
return [ind(arr1, i, default) | ind(arr2, i, default) for i in range(max(len(arr1), len(arr2)))] | train | APPS_structured |
=====Function Descriptions=====
Python has built-in string validation methods for basic data. It can check if a string is composed of alphabetical characters, alphanumeric characters, digits, etc.
str.isalnum()
This method checks if all the characters of a string are alphanumeric (a-z, A-Z and 0-9).
>>> print 'ab123'.isalnum()
True
>>> print 'ab123#'.isalnum()
False
str.isalpha()
This method checks if all the characters of a string are alphabetical (a-z and A-Z).
>>> print 'abcD'.isalpha()
True
>>> print 'abcd1'.isalpha()
False
str.isdigit()
This method checks if all the characters of a string are digits (0-9).
>>> print '1234'.isdigit()
True
>>> print '123edsd'.isdigit()
False
str.islower()
This method checks if all the characters of a string are lowercase characters (a-z).
>>> print 'abcd123#'.islower()
True
>>> print 'Abcd123#'.islower()
False
str.isupper()
This method checks if all the characters of a string are uppercase characters (A-Z).
>>> print 'ABCD123#'.isupper()
True
>>> print 'Abcd123#'.isupper()
False
=====Problem Statement=====
You are given a string S.
Your task is to find out if the string S contains: alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters.
=====Input Format=====
A single line containing a string S.
=====Constraints=====
0 < len(S) < 1000
=====Output Format=====
In the first line, print True if S has any alphanumeric characters. Otherwise, print False.
In the second line, print True if S has any alphabetical characters. Otherwise, print False.
In the third line, print True if S has any digits. Otherwise, print False.
In the fourth line, print True if S has any lowercase characters. Otherwise, print False.
In the fifth line, print True if S has any uppercase characters. Otherwise, print False. | def __starting_point():
s = input()
print((any(char.isalnum() for char in s)))
print((any(char.isalpha() for char in s)))
print((any(char.isdigit() for char in s)))
print((any(char.islower() for char in s)))
print((any(char.isupper() for char in s)))
__starting_point() | def __starting_point():
s = input()
print((any(char.isalnum() for char in s)))
print((any(char.isalpha() for char in s)))
print((any(char.isdigit() for char in s)))
print((any(char.islower() for char in s)))
print((any(char.isupper() for char in s)))
__starting_point() | train | APPS_structured |
Bob watches TV every day. He always sets the volume of his TV to $b$. However, today he is angry to find out someone has changed the volume to $a$. Of course, Bob has a remote control that can change the volume.
There are six buttons ($-5, -2, -1, +1, +2, +5$) on the control, which in one press can either increase or decrease the current volume by $1$, $2$, or $5$. The volume can be arbitrarily large, but can never be negative. In other words, Bob cannot press the button if it causes the volume to be lower than $0$.
As Bob is so angry, he wants to change the volume to $b$ using as few button presses as possible. However, he forgets how to do such simple calculations, so he asks you for help. Write a program that given $a$ and $b$, finds the minimum number of presses to change the TV volume from $a$ to $b$.
-----Input-----
Each test contains multiple test cases. The first line contains the number of test cases $T$ ($1 \le T \le 1\,000$). Then the descriptions of the test cases follow.
Each test case consists of one line containing two integers $a$ and $b$ ($0 \le a, b \le 10^{9}$) — the current volume and Bob's desired volume, respectively.
-----Output-----
For each test case, output a single integer — the minimum number of presses to change the TV volume from $a$ to $b$. If Bob does not need to change the volume (i.e. $a=b$), then print $0$.
-----Example-----
Input
3
4 0
5 14
3 9
Output
2
3
2
-----Note-----
In the first example, Bob can press the $-2$ button twice to reach $0$. Note that Bob can not press $-5$ when the volume is $4$ since it will make the volume negative.
In the second example, one of the optimal ways for Bob is to press the $+5$ twice, then press $-1$ once.
In the last example, Bob can press the $+5$ once, then press $+1$. |
t = int(input())
for gg in range(t):
a, b = list(map(int, input().split()))
d = abs(a-b)
if d == 0:
print(0)
else:
ans = 0
ans += d//5
d%=5
ans+=d//2
d%=2
ans+=d
print(ans)
|
t = int(input())
for gg in range(t):
a, b = list(map(int, input().split()))
d = abs(a-b)
if d == 0:
print(0)
else:
ans = 0
ans += d//5
d%=5
ans+=d//2
d%=2
ans+=d
print(ans)
| train | APPS_structured |
Chef is the new king of the country Chefland. As first and most important responsibility he wants to reconstruct the road system of Chefland. There are N (1 to N) cities in the country and each city i has a population Pi. Chef wants to build some bi-directional roads connecting different cities such that each city is connected to every other city (by a direct road or through some other intermediate city) and starting from any city one can visit every other city in the country through these roads. Cost of building a road between two cities u and v is Pu x Pv. Cost to build the road system is the sum of cost of every individual road that would be built.
Help king Chef to find the minimum cost to build the new road system in Chefland such that every city is connected to each other.
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
First line contains an integer N denoting the number of cities in the country. Second line contains N space separated integers Pi, the population of i-th city.
-----Output-----
For each test case, print a single integer, the minimum cost to build the new road system on separate line.
-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 105
- 1 ≤ Pi ≤ 106
-----Example-----
Input:
2
2
5 10
4
15 10 7 13
Output:
50
266 | # cook your dish here
t=0
try:
t=int(input())
except:
pass
for _ in range(t):
n= int(input())
p=list(map(int, input().split()))
middle = min(p)
p.remove(middle)
cost =0
for i in p:
cost+= i*middle
print(cost) | # cook your dish here
t=0
try:
t=int(input())
except:
pass
for _ in range(t):
n= int(input())
p=list(map(int, input().split()))
middle = min(p)
p.remove(middle)
cost =0
for i in p:
cost+= i*middle
print(cost) | train | APPS_structured |
The fusc function is defined recursively as follows:
1. fusc(0) = 0
2. fusc(1) = 1
3. fusc(2 * n) = fusc(n)
4. fusc(2 * n + 1) = fusc(n) + fusc(n + 1)
The 4 rules above are sufficient to determine the value of `fusc` for any non-negative input `n`. For example, let's say you want to compute `fusc(10)`.
1. `fusc(10) = fusc(5)`, by rule 3.
2. `fusc(5) = fusc(2) + fusc(3)`, by rule 4.
3. `fusc(2) = fusc(1)`, by rule 3.
4. `fusc(1) = 1`, by rule 2.
5. `fusc(3) = fusc(1) + fusc(2)` by rule 4.
6. `fusc(1)` and `fusc(2)` have already been computed are both equal to `1`.
Putting these results together `fusc(10) = fusc(5) = fusc(2) + fusc(3) = 1 + 2 = 3`
Your job is to produce the code for the `fusc` function. In this kata, your function will be tested with small values of `n`, so you should not need to be concerned about stack overflow or timeouts.
Hint: Use recursion.
When done, move on to [Part 2](http://www.codewars.com/kata/the-fusc-function-part-2). | def memoize(func):
cache = {}
def newfunc(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return newfunc
@memoize
def fusc(n):
assert type(n) == int and n >= 0
if n < 2: return n
return fusc(n / 2) + fusc(n / 2 + 1) if n % 2 else fusc(n / 2)
| def memoize(func):
cache = {}
def newfunc(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return newfunc
@memoize
def fusc(n):
assert type(n) == int and n >= 0
if n < 2: return n
return fusc(n / 2) + fusc(n / 2 + 1) if n % 2 else fusc(n / 2)
| train | APPS_structured |
In this Kata, you're to complete the function `sum_square_even_root_odd`.
You will be given a list of numbers, `nums`, as the only argument to the function. Take each number in the list and *square* it if it is even, or *square root* the number if it is odd. Take this new list and find the *sum*, rounding to two decimal places.
The list will never be empty and will only contain values that are greater than or equal to zero.
Good luck! | def sum_square_even_root_odd(l):
return round(sum((n ** 2 if n % 2 == 0 else n ** 0.5) for n in l), 2) | def sum_square_even_root_odd(l):
return round(sum((n ** 2 if n % 2 == 0 else n ** 0.5) for n in l), 2) | train | APPS_structured |
Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die.
Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule.
Example 1:
Input: flowerbed = [1,0,0,0,1], n = 1
Output: True
Example 2:
Input: flowerbed = [1,0,0,0,1], n = 2
Output: False
Note:
The input array won't violate no-adjacent-flowers rule.
The input array size is in the range of [1, 20000].
n is a non-negative integer which won't exceed the input array size. | class Solution:
def canPlaceFlowers(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
if n==0:
return True
temp=0
m=0
if flowerbed[0]==0:
temp=1
for i,plot in enumerate(flowerbed):
if plot==0:
temp+=1
if(i==len(flowerbed)-1):
temp+=1
if plot==1 or i==len(flowerbed)-1:
m+=int((temp-1)/2)
temp=0
if m>=n:
return True
return False
| class Solution:
def canPlaceFlowers(self, flowerbed, n):
"""
:type flowerbed: List[int]
:type n: int
:rtype: bool
"""
if n==0:
return True
temp=0
m=0
if flowerbed[0]==0:
temp=1
for i,plot in enumerate(flowerbed):
if plot==0:
temp+=1
if(i==len(flowerbed)-1):
temp+=1
if plot==1 or i==len(flowerbed)-1:
m+=int((temp-1)/2)
temp=0
if m>=n:
return True
return False
| train | APPS_structured |
### Task:
You have to write a function `pattern` which creates the following pattern (See Examples) upto desired number of rows.
If the Argument is `0` or a Negative Integer then it should return `""` i.e. empty string.
### Examples:
`pattern(9)`:
123456789
234567891
345678912
456789123
567891234
678912345
789123456
891234567
912345678
`pattern(5)`:
12345
23451
34512
45123
51234
Note: There are no spaces in the pattern
Hint: Use `\n` in string to jump to next line | from collections import deque
def pattern(n):
result = []
line = deque([str(num) for num in range(1, n + 1)])
for i in range(n):
result.append("".join(line))
line.rotate(-1)
return "\n".join(result) | from collections import deque
def pattern(n):
result = []
line = deque([str(num) for num in range(1, n + 1)])
for i in range(n):
result.append("".join(line))
line.rotate(-1)
return "\n".join(result) | train | APPS_structured |
Mathison and Chef are playing a new teleportation game. This game is played on a $R \times C$ board where each cell $(i, j)$ contains some value $V_{i, j}$. The purpose of this game is to collect a number of values by teleporting from one cell to another. A teleportation can be performed using a tel-pair.
A player is given $N$ tel-pairs. Each tel-pair can be used at most once and a player can use them in any order they like. Suppose a player is at cell $(a, b)$ and the tel-pair is $(dx, dy)$. Then, the player can reach in one teleportation any cell $(c, d)$ from $(a, b)$ such that $|a − c| = dx$ and $|b − d| = dy$.
It is Mathison’s turn next in the game to make a sequence of moves. He would like to know what is the highest value of a path of length at most $N+1$ that starts in $(Sx, Sy)$ and uses some (possibly none) of the tel-pairs given. The length of a path is equal to the number of cells in the path. The value of a path is equal to the sum of $V_{i, j}$ over all cells in the path.
-----Input-----
- The first line contains a single integer, $T$, the number of tests.
- Each test starts with three integers, $R$, $C$, and $N$, representing the number of rows, columns, and tel-pairs.
- The next line contains two integers, $Sx$, and $Sy$, representing the coordinates of the starting cell.
- The next two lines will contain the description of the tel-pairs, each containing $N$ space separated integers. The first will contain the $x$-component of each tel-pair, the second one will contain the y-component of each tel-pair.
- Finally, there will be $R$ lines, each containing $C$ space-separated integers, the description of the board.
-----Output-----
The output file will contain $T$ lines. Each line will contain the answer (i.e. the highest value of a path) to the corresponding test.
-----Constraints and notes-----
- $1 \leq T \leq 100$
- $1 \leq R, C \leq 1000$
- $1 \leq N \leq 9$
- $0 \leq Sx < R$
- $0 \leq Sy < C$
- $0 \leq dx \leq R$
- $0 \leq dy \leq C$
- $1 \leq V_{i, j} \leq 10^6$
- You are allowed to visit a cell multiple times in a path, and the value for the cell must be added each time you visit it.
-----Subtaks-----
Subtask #1 (15 points):
- $1 \leq T \leq 100$
- $1 \leq R, C \leq 10$
- $1 \leq N \leq 4$
Subtask #2 (25 points):
- $1 \leq T \leq 25$
- $1 \leq R, C \leq 100$
- $1 \leq N \leq 8$
Subtask #3 (30 points):
- $1 \leq T \leq 5$
- $1 \leq R, C \leq 1000$
- $1 \leq N \leq 8$
Subtask #4 (30 points):
- $1 \leq T \leq 5$
- $1 \leq R, C \leq 1000$
- $1 \leq N \leq 9$
-----Example Input-----
3
5 5 2
2 2
1 2
2 1
10 11 62 14 15
57 23 34 75 21
17 12 14 11 53
84 61 24 85 22
43 89 14 15 43
3 3 2
0 0
1 1
1 1
9 8 7
5 6 4
1 3 2
2 2 1
1 1
2
2
5 6
8 3
-----Example Output-----
188
24
3
-----Explanation-----
Test Case 1:
Mathison starts at $(2, 2)$.
Mathison has two tel-pairs $(2, 1)$ and $(1, 2)$.
The following path (i.e. bolded numbers) generates the maximum value: $(2, 2)$ → $(4, 1)$ → $(3, 3)$
Test Case 2:
Mathison starts at $(0, 0)$.
Mathison has two tel-pairs $(1, 1)$ and $(1, 1)$.
The following path (i.e. bolded numbers) generates the maximum value: $(0, 0)$ → $(1, 1)$ → $(0, 0)$
Test Case 3:
Mathison starts at $(1, 1)$.
Mathison has one tel-pair, $(2, 2)$.
He can't use the tel-pair so the answer is $3$ (the value of the starting cell). | # cook your dish here
from collections import namedtuple
CurrentPosition = namedtuple('current_position', 'points, cell, pairs')
T = int(input())
for _ in range(T):
R, C, N = map(int, input().split())
Sx, Sy = map(int, input().split())
tx = map(int, input().split())
ty = map(int, input().split())
tel_pairs = list(zip(tx, ty))
board = []
for _ in range(R):
board += [[int(c) for c in input().split()]]
def explore(p):
next_pos = []
for i, (dx, dy) in enumerate(p.pairs):
sx, sy = p.cell
new_pairs = p.pairs[:i]+p.pairs[i+1:]
# case (+, +)
px, py = sx + dx, sy + dy
if px < R and py < C:
next_pos += [CurrentPosition(p.points+board[px][py], (px, py), new_pairs)]
# case (+, -)
px, py = sx + dx, sy - dy
if px < R and 0 <= py:
next_pos += [CurrentPosition(p.points+board[px][py], (px, py), new_pairs)]
# case (-, +)
px, py = sx - dx, sy + dy
if 0 <= px and py < C:
next_pos += [CurrentPosition(p.points+board[px][py], (px, py), new_pairs)]
# case (-, -)
px, py = sx - dx, sy - dy
if 0 <= px and 0 <= py:
next_pos += [CurrentPosition(p.points+board[px][py], (px, py), new_pairs)]
return next_pos
pos = [CurrentPosition(board[Sx][Sy], (Sx, Sy), tel_pairs)]
result = board[Sx][Sy]
while pos:
p = pos.pop(0)
if p.pairs:
pos += explore(p)
else:
result = max(result, p.points)
print(result)
| # cook your dish here
from collections import namedtuple
CurrentPosition = namedtuple('current_position', 'points, cell, pairs')
T = int(input())
for _ in range(T):
R, C, N = map(int, input().split())
Sx, Sy = map(int, input().split())
tx = map(int, input().split())
ty = map(int, input().split())
tel_pairs = list(zip(tx, ty))
board = []
for _ in range(R):
board += [[int(c) for c in input().split()]]
def explore(p):
next_pos = []
for i, (dx, dy) in enumerate(p.pairs):
sx, sy = p.cell
new_pairs = p.pairs[:i]+p.pairs[i+1:]
# case (+, +)
px, py = sx + dx, sy + dy
if px < R and py < C:
next_pos += [CurrentPosition(p.points+board[px][py], (px, py), new_pairs)]
# case (+, -)
px, py = sx + dx, sy - dy
if px < R and 0 <= py:
next_pos += [CurrentPosition(p.points+board[px][py], (px, py), new_pairs)]
# case (-, +)
px, py = sx - dx, sy + dy
if 0 <= px and py < C:
next_pos += [CurrentPosition(p.points+board[px][py], (px, py), new_pairs)]
# case (-, -)
px, py = sx - dx, sy - dy
if 0 <= px and 0 <= py:
next_pos += [CurrentPosition(p.points+board[px][py], (px, py), new_pairs)]
return next_pos
pos = [CurrentPosition(board[Sx][Sy], (Sx, Sy), tel_pairs)]
result = board[Sx][Sy]
while pos:
p = pos.pop(0)
if p.pairs:
pos += explore(p)
else:
result = max(result, p.points)
print(result)
| train | APPS_structured |
Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Note: Please solve it without division and in O(n).
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.) | class Solution:
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
p = 1
result = []
for i in range(0, len(nums)):
result.append(p)
p = p * nums[i]
p = 1
for i in range(len(nums)-1, -1, -1):
result[i] = result[i] * p
p = p * nums[i]
return result | class Solution:
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
p = 1
result = []
for i in range(0, len(nums)):
result.append(p)
p = p * nums[i]
p = 1
for i in range(len(nums)-1, -1, -1):
result[i] = result[i] * p
p = p * nums[i]
return result | train | APPS_structured |
Create a __moreZeros__ function which will __receive a string__ for input, and __return an array__ (or null terminated string in C) containing only the characters from that string whose __binary representation of its ASCII value__ consists of _more zeros than ones_.
You should __remove any duplicate characters__, keeping the __first occurence__ of any such duplicates, so they are in the __same order__ in the final array as they first appeared in the input string.
Examples
All input will be valid strings of length > 0. Leading zeros in binary should not be counted. | def more_zeros(s):
L=[]
L1=[]
L2=[]
for i in s:
a=int(' '.join(format(ord(x), 'b') for x in i))
for j in str(a):
if j=="0":
L1.append(j)
else:
L2.append(j)
if len(L1)>len(L2):
if i not in L:
L.append(str(i))
L1=[]
L2=[]
return L | def more_zeros(s):
L=[]
L1=[]
L2=[]
for i in s:
a=int(' '.join(format(ord(x), 'b') for x in i))
for j in str(a):
if j=="0":
L1.append(j)
else:
L2.append(j)
if len(L1)>len(L2):
if i not in L:
L.append(str(i))
L1=[]
L2=[]
return L | train | APPS_structured |
You will be given two strings `a` and `b` consisting of lower case letters, but `a` will have at most one asterix character. The asterix (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase letters. No other character of string `a` can be replaced. If it is possible to replace the asterix in `a` to obtain string `b`, then string `b` matches the pattern.
If the string matches, return `true` else `false`.
```
For example:
solve("code*s","codewars") = true, because we can replace the asterix(*) with "war" to match the second string.
solve("codewar*s","codewars") = true, because we can replace the asterix(*) with "" to match the second string.
solve("codewars","codewars") = true, because the strings already match.
solve("a","b") = false
```
More examples in test cases.
Good luck! | def solve(a,b):
s = a.find("*")
if s == -1:
return a == b
else:
a = list(a)
b = list(b)
del b[s:s+1+len(b)-len(a)]
a.remove("*")
return a == b | def solve(a,b):
s = a.find("*")
if s == -1:
return a == b
else:
a = list(a)
b = list(b)
del b[s:s+1+len(b)-len(a)]
a.remove("*")
return a == b | train | APPS_structured |
Let's call a sequence good if the sum of all its elements is $0$.
You have a sequence of integers $A_1, A_2, \ldots, A_N$. You may perform any number of operations on this sequence (including zero). In one operation, you should choose a valid index $i$ and decrease $A_i$ by $i$. Can you make the sequence good using these operations?
-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.
-----Output-----
For each test case, print a single line containing the string "YES" if it is possible to make the given sequence good or "NO" if it is impossible.
-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le N \le 10$
- $|A_i| \le 100$ for each valid $i$
-----Subtasks-----
Subtask #1 (10 points): $N = 1$
Subtask #2 (30 points): $N \le 2$
Subtask #3 (60 points): original constraints
-----Example Input-----
2
1
-1
2
1 2
-----Example Output-----
NO
YES
-----Explanation-----
Example case 2: We can perform two operations ― subtract $1$ from $A_1$ and $2$ from $A_2$. | # cook your dish here
t=int(input())
while t>0:
n=int(input())
l=list(map(int,input().split()))
s=sum(l)
if s>=0:
print("YES")
else:
print("NO")
t=t-1 | # cook your dish here
t=int(input())
while t>0:
n=int(input())
l=list(map(int,input().split()))
s=sum(l)
if s>=0:
print("YES")
else:
print("NO")
t=t-1 | train | APPS_structured |
There is only little time left until the New Year! For that reason, Chef decided to make a present for his best friend. He made a connected and undirected simple graph with N$N$ vertices and M$M$ edges.
Since Chef does not like odd numbers and his friend does not like undirected graphs, Chef decided to direct each edge in one of two possible directions in such a way that the indegrees of all vertices of the resulting graph are even. The indegree of a vertex is the number of edges directed to that vertex from another vertex. As usual, Chef is busy in the kitchen, so you need to help him with directing the edges. Find one possible way to direct them or determine that it is impossible under the given conditions, so that Chef could bake a cake as a present instead.
-----Input-----
- The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows.
- The first line of each test case contains two space-separated integers N$N$ and M$M$.
- M$M$ lines follow. For each i$i$ (1≤i≤M$1 \le i \le M$), the i$i$-th of these lines contains two space-separated integers ui$u_i$ and vi$v_i$ denoting an edge between vertices ui$u_i$ and vi$v_i$.
-----Output-----
For each test case:
- If a valid way to direct the edges does not exist, print a single line containing one integer −1$-1$.
- Otherwise, print a single line containing M$M$ space-separated integers. For each valid i$i$, the i$i$-th of these integers should be 0$0$ if edge i$i$ is directed from ui$u_i$ to vi$v_i$ or 1$1$ if it is directed from vi$v_i$ to ui$u_i$.
-----Constraints-----
- 1≤T≤5$1 \le T \le 5$
- 1≤N,M≤105$1 \le N, M \le 10^5$
- 1≤ui,vi≤N$1 \le u_i, v_i \le N$ for each valid i$i$
- the graph on the input is connected, does not contain multiple edges or self-loops
-----Subtasks-----
Subtask #1 (30 points): 1≤N,M≤1,000$1 \le N, M \le 1,000$
Subtask #2 (70 points): original constraints
-----Example Input-----
2
4 4
1 2
1 3
2 4
3 4
3 3
1 2
2 3
1 3
-----Example Output-----
0 0 1 1
-1 | for __ in range(int(input())):
n,m=map(int,input().split())
g=[[]for _ in range(n+1)]
long=[]
di={}
stable=[0 for _ in range(n+1)]
edges=[0 for _ in range(m)]
for i in range(m):
x,y=map(int,input().split())
g[x].append(y)
g[y].append(x)
stable[y]+=1
long.append([x,y])
di[(x,y)]=i
di[(y,x)]=i
f=1
if m%2:
f=0
for i in range(m):
c,d=long[i][0],long[i][1]
if stable[c]%2==1 and stable[d]%2==1:
stable[c]+=1
stable[d]-=1
edges[i]=1
s=[]
for i in range(1,n+1):
if stable[i]%2==1:
s.append(i)
while s and f:
set1=set()
for i in s:
if stable[i]%2:
y=g[i][0]
w=di[(i,y)]
stable[y]+=1
stable[i]-=1
set1.add(y)
edges[w]=abs(edges[w]-1)
s=set1
if(f):
print(*edges)
else:
print(-1)
| for __ in range(int(input())):
n,m=map(int,input().split())
g=[[]for _ in range(n+1)]
long=[]
di={}
stable=[0 for _ in range(n+1)]
edges=[0 for _ in range(m)]
for i in range(m):
x,y=map(int,input().split())
g[x].append(y)
g[y].append(x)
stable[y]+=1
long.append([x,y])
di[(x,y)]=i
di[(y,x)]=i
f=1
if m%2:
f=0
for i in range(m):
c,d=long[i][0],long[i][1]
if stable[c]%2==1 and stable[d]%2==1:
stable[c]+=1
stable[d]-=1
edges[i]=1
s=[]
for i in range(1,n+1):
if stable[i]%2==1:
s.append(i)
while s and f:
set1=set()
for i in s:
if stable[i]%2:
y=g[i][0]
w=di[(i,y)]
stable[y]+=1
stable[i]-=1
set1.add(y)
edges[w]=abs(edges[w]-1)
s=set1
if(f):
print(*edges)
else:
print(-1)
| train | APPS_structured |
A pair of numbers has a unique LCM but a single number can be the LCM of more than one possible
pairs. For example `12` is the LCM of `(1, 12), (2, 12), (3,4)` etc. For a given positive integer N, the number of different integer pairs with LCM is equal to N can be called the LCM cardinality of that number N. In this kata your job is to find out the LCM cardinality of a number. | from itertools import combinations
from math import gcd
def lcm_cardinality(n):
return 1 + sum(1 for a, b in combinations(divisors(n), 2) if lcm(a, b) == n)
def divisors(n):
d = {1, n}
for k in range(2, int(n**0.5) + 1):
if n % k == 0:
d.add(k)
d.add(n // k)
return sorted(d)
def lcm(a, b):
return a * b // gcd(a, b) | from itertools import combinations
from math import gcd
def lcm_cardinality(n):
return 1 + sum(1 for a, b in combinations(divisors(n), 2) if lcm(a, b) == n)
def divisors(n):
d = {1, n}
for k in range(2, int(n**0.5) + 1):
if n % k == 0:
d.add(k)
d.add(n // k)
return sorted(d)
def lcm(a, b):
return a * b // gcd(a, b) | train | APPS_structured |
In this Kata we focus on finding a sum S(n) which is the total number of divisors taken for all natural numbers less or equal to n. More formally, we investigate the sum of n components denoted by d(1) + d(2) + ... + d(n) in which for any i starting from 1 up to n the value of d(i) tells us how many distinct numbers divide i without a remainder.
Your solution should work for possibly large values of n without a timeout.
Assume n to be greater than zero and not greater than 999 999 999 999 999.
Brute force approaches will not be feasible options in such cases. It is fairly simple to conclude that for every n>1 there holds a recurrence S(n) = S(n-1) + d(n) with initial case S(1) = 1.
For example:
S(1) = 1
S(2) = 3
S(3) = 5
S(4) = 8
S(5) = 10
But is the fact useful anyway? If you find it is rather not, maybe this will help:
Try to convince yourself that for any natural k, the number S(k) is the same as the number of pairs (m,n) that solve the inequality mn <= k in natural numbers.
Once it becomes clear, we can think of a partition of all the solutions into classes just by saying that a pair (m,n) belongs to the class indexed by n.
The question now arises if it is possible to count solutions of n-th class. If f(n) stands for the number of solutions that belong to n-th class, it means that S(k) = f(1) + f(2) + f(3) + ...
The reasoning presented above leads us to some kind of a formula for S(k), however not necessarily the most efficient one. Can you imagine that all the solutions to inequality mn <= k can be split using sqrt(k) as pivotal item? | def count_divisors(n):
return 2 * sum(n//k for k in range(int(n ** 0.5), 0, -1)) - int(n ** 0.5) ** 2 | def count_divisors(n):
return 2 * sum(n//k for k in range(int(n ** 0.5), 0, -1)) - int(n ** 0.5) ** 2 | train | APPS_structured |
Consider the range `0` to `10`. The primes in this range are: `2, 3, 5, 7`, and thus the prime pairs are: `(2,2), (2,3), (2,5), (2,7), (3,3), (3,5), (3,7),(5,5), (5,7), (7,7)`.
Let's take one pair `(2,7)` as an example and get the product, then sum the digits of the result as follows: `2 * 7 = 14`, and `1 + 4 = 5`. We see that `5` is a prime number. Similarly, for the pair `(7,7)`, we get: `7 * 7 = 49`, and `4 + 9 = 13`, which is a prime number.
You will be given a range and your task is to return the number of pairs that revert to prime as shown above. In the range `(0,10)`, there are only `4` prime pairs that end up being primes in a similar way: `(2,7), (3,7), (5,5), (7,7)`. Therefore, `solve(0,10) = 4)`
Note that the upperbound of the range will not exceed `10000`. A range of `(0,10)` means that: `0 <= n < 10`.
Good luck!
If you like this Kata, please try
[Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3)
[Prime reduction](https://www.codewars.com/kata/59aa6567485a4d03ff0000ca)
[Dominant primes](https://www.codewars.com/kata/59ce11ea9f0cbc8a390000ed) | from itertools import compress, combinations_with_replacement
import numpy as np
s = np.ones(10001)
s[:2] = s[4::2] = 0
for i in range(3, int(len(s)**0.5)+1, 2):
if s[i]:
s[i*i::i] = 0
PRIMES = list(compress(list(range(len(s))), s))
def solve(a, b):
i, j = np.searchsorted(PRIMES, a), np.searchsorted(PRIMES, b)
return sum(s[sum(map(int, str(x * y)))] for x, y in combinations_with_replacement(PRIMES[i:j], 2))
| from itertools import compress, combinations_with_replacement
import numpy as np
s = np.ones(10001)
s[:2] = s[4::2] = 0
for i in range(3, int(len(s)**0.5)+1, 2):
if s[i]:
s[i*i::i] = 0
PRIMES = list(compress(list(range(len(s))), s))
def solve(a, b):
i, j = np.searchsorted(PRIMES, a), np.searchsorted(PRIMES, b)
return sum(s[sum(map(int, str(x * y)))] for x, y in combinations_with_replacement(PRIMES[i:j], 2))
| train | APPS_structured |
In this Kata, you will sort elements in an array by decreasing frequency of elements. If two elements have the same frequency, sort them by increasing value.
More examples in test cases.
Good luck!
Please also try [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2) | def solve(arr):
freq = {n: -arr.count(n) for n in set(arr)}
return sorted(sorted(arr), key=freq.get) | def solve(arr):
freq = {n: -arr.count(n) for n in set(arr)}
return sorted(sorted(arr), key=freq.get) | train | APPS_structured |
Given a string, determine if it's a valid identifier.
## Here is the syntax for valid identifiers:
* Each identifier must have at least one character.
* The first character must be picked from: alpha, underscore, or dollar sign. The first character cannot be a digit.
* The rest of the characters (besides the first) can be from: alpha, digit, underscore, or dollar sign. In other words, it can be any valid identifier character.
### Examples of valid identifiers:
* i
* wo_rd
* b2h
### Examples of invalid identifiers:
* 1i
* wo rd
* !b2h | is_valid=lambda idn: bool(__import__("re").match("^[a-zA-Z_$][\w$]*$",idn))
| is_valid=lambda idn: bool(__import__("re").match("^[a-zA-Z_$][\w$]*$",idn))
| train | APPS_structured |
Recently, Chef got obsessed with piano. He is a just a rookie in this stuff and can not move his fingers from one key to other fast enough. He discovered that the best way to train finger speed is to play scales.
There are different kinds of scales which are divided on the basis of their interval patterns. For instance, major scale is defined by pattern T-T-S-T-T-T-S, where ‘T’ stands for a whole tone whereas ‘S’ stands for a semitone. Two semitones make one tone. To understand how they are being played, please refer to the below image of piano’s octave – two consecutive keys differ by one semitone.
If we start playing from first key (note C), then we’ll play all white keys in a row (notes C-D-E-F-G-A-B-C – as you can see C and D differ for a tone as in pattern, and E and F differ for a semitone).
This pattern could be played some number of times (in cycle).
Each time Chef takes some type of a scale and plays using some number of octaves. Sometimes Chef can make up some scales, so please don’t blame him if you find some scale that does not exist in real world.
Formally, you have a set of 12 keys (i.e. one octave) and you have N such sets in a row. So in total, you have 12*N keys. You also have a pattern that consists of letters 'T' and 'S', where 'T' means move forward for two keys (from key x to key x + 2, and 'S' means move forward for one key (from key x to key x + 1).
Now, you can start playing from any of the 12*N keys. In one play, you can repeat the pattern as many times as you want, but you cannot go outside the keyboard.
Repeating pattern means that if, for example, you have pattern STTST, you can play STTST as well as STTSTSTTST, as well as STTSTSTTSTSTTST, as well as any number of repeating. For this pattern, if you choose to repeat it once, if you start at some key x, you'll press keys: x (letter 'S')-> x + 1 (letter 'T')-> x + 3 (letter 'T')-> x + 5 (letter 'S') -> x + 6 (letter 'T')-> x + 8. Also 1 ≤ x, x + 8 ≤ 12*N so as to avoid going off the keyboard.
You are asked to calculate number of different plays that can be performed. Two plays differ if and only if they start at different keys or patterns are repeated different number of times.
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
First line of each test case contains scale’s pattern – string s consisting of letters ‘T’ and ‘S’ only.
Second line contains one integer N – number of octaves he’ll be using.
-----Output-----
For each test case output a single number in a line corresponding to number of different scales he’ll play.
-----Constraints-----
- 1 ≤ T ≤ 105
- 1 ≤ |S| ≤ 100
- 1 ≤ n ≤ 7
-----Subtasks-----
Subtask 1: T < 10 4, N = 1
Subtask 2: No additional constraints.
-----Example-----
Input:
2
TTTT
1
TTSTTTS
3
Output:
4
36
-----Explanation-----
Example case 1. In the first case there is only one octave and Chef can play scale (not in cycle each time) starting with notes C, C#, D, D# - four together. | t =int(input())
for i in range(t):
C=[ord(x)-ord('R') for x in list(input())]
N=int(input())
L=sum(C)
r=1
c=0
while(r*L<N*12):
c+=N*12-r*L
r+=1
print(c)
| t =int(input())
for i in range(t):
C=[ord(x)-ord('R') for x in list(input())]
N=int(input())
L=sum(C)
r=1
c=0
while(r*L<N*12):
c+=N*12-r*L
r+=1
print(c)
| train | APPS_structured |
Given a string s consisting only of letters 'a' and 'b'. In a single step you can remove one palindromic subsequence from s.
Return the minimum number of steps to make the given string empty.
A string is a subsequence of a given string, if it is generated by deleting some characters of a given string without changing its order.
A string is called palindrome if is one that reads the same backward as well as forward.
Example 1:
Input: s = "ababa"
Output: 1
Explanation: String is already palindrome
Example 2:
Input: s = "abb"
Output: 2
Explanation: "abb" -> "bb" -> "".
Remove palindromic subsequence "a" then "bb".
Example 3:
Input: s = "baabb"
Output: 2
Explanation: "baabb" -> "b" -> "".
Remove palindromic subsequence "baab" then "b".
Example 4:
Input: s = ""
Output: 0
Constraints:
0 <= s.length <= 1000
s only consists of letters 'a' and 'b' | class Solution:
def removePalindromeSub(self, s: str) -> int:
if not s:
return 0
elif s == s[::-1]:
return 1
else:
return 2
| class Solution:
def removePalindromeSub(self, s: str) -> int:
if not s:
return 0
elif s == s[::-1]:
return 1
else:
return 2
| train | APPS_structured |
Binary with 0 and 1 is good, but binary with only 0 is even better! Originally, this is a concept designed by Chuck Norris to send so called unary messages.
Can you write a program that can send and receive this messages?
Rules
The input message consists of ASCII characters between 32 and 127 (7-bit)
The encoded output message consists of blocks of 0
A block is separated from another block by a space
Two consecutive blocks are used to produce a series of same value bits (only 1 or 0 values):
First block is always 0 or 00. If it is 0, then the series contains 1, if not, it contains 0
The number of 0 in the second block is the number of bits in the series
Example
Let’s take a simple example with a message which consists of only one character (Letter 'C').'C' in binary is represented as 1000011, so with Chuck Norris’ technique this gives:
0 0 - the first series consists of only a single 1
00 0000 - the second series consists of four 0
0 00 - the third consists of two 1
So 'C' is coded as: 0 0 00 0000 0 00
Second example, we want to encode the message "CC" (i.e. the 14 bits 10000111000011) :
0 0 - one single 1
00 0000 - four 0
0 000 - three 1
00 0000 - four 0
0 00 - two 1
So "CC" is coded as: 0 0 00 0000 0 000 00 0000 0 00
Note of thanks
Thanks to the author of the original kata. I really liked this kata. I hope that other warriors will enjoy it too. | import re
def send(text):
tmp = (ord(char) for char in text)
tmp = (f"{x:07b}" for x in tmp)
tmp = "".join(tmp)
tmp = re.findall("0+|1+", tmp)
tmp = (f"{'0' if group[0] == '1' else '00'} {'0' * len(group)}" for group in tmp)
return " ".join(tmp)
def receive(unary):
tmp = re.findall("(0+) (0+)", unary)
tmp = (("0" if digit == "00" else "1") * len(count) for digit, count in tmp)
tmp = "".join(tmp)
tmp = re.findall(".{7}", tmp)
tmp = (chr(int(x, 2)) for x in tmp)
return "".join(tmp) | import re
def send(text):
tmp = (ord(char) for char in text)
tmp = (f"{x:07b}" for x in tmp)
tmp = "".join(tmp)
tmp = re.findall("0+|1+", tmp)
tmp = (f"{'0' if group[0] == '1' else '00'} {'0' * len(group)}" for group in tmp)
return " ".join(tmp)
def receive(unary):
tmp = re.findall("(0+) (0+)", unary)
tmp = (("0" if digit == "00" else "1") * len(count) for digit, count in tmp)
tmp = "".join(tmp)
tmp = re.findall(".{7}", tmp)
tmp = (chr(int(x, 2)) for x in tmp)
return "".join(tmp) | train | APPS_structured |
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K to form a new pattern. Help the chef to code this pattern problem.
-----Input:-----
- First-line will contain $T$, the number of test cases. Then the test cases follow.
- Each test case contains a single line of input, one integer $K$.
-----Output:-----
For each test case, output as the pattern.
-----Constraints-----
- $1 \leq T \leq 100$
- $1 \leq K \leq 100$
-----Sample Input:-----
4
1
2
3
4
-----Sample Output:-----
*
*
*
*
***
***
*
*
***
***
*****
*****
*
*
***
***
*****
*****
*******
*******
-----EXPLANATION:-----
No need, else pattern can be decode easily. | for _ in range(int(input())):
n = int(input())
s = '*'
for i in range(n):
x = ' ' * ((n * 2 - 1 - len(s)) // 2)
print(x + s + x)
print(x + s + x)
s = '*' + s + '*' | for _ in range(int(input())):
n = int(input())
s = '*'
for i in range(n):
x = ' ' * ((n * 2 - 1 - len(s)) // 2)
print(x + s + x)
print(x + s + x)
s = '*' + s + '*' | train | APPS_structured |
We want to find the numbers higher or equal than 1000 that the sum of every four consecutives digits cannot be higher than a certain given value.
If the number is ``` num = d1d2d3d4d5d6 ```, and the maximum sum of 4 contiguous digits is ```maxSum```, then:
```python
d1 + d2 + d3 + d4 <= maxSum
d2 + d3 + d4 + d5 <= maxSum
d3 + d4 + d5 + d6 <= maxSum
```
For that purpose, we need to create a function, ```max_sumDig()```, that receives ```nMax```, as the max value of the interval to study (the range (1000, nMax) ), and a certain value, ```maxSum```, the maximum sum that every four consecutive digits should be less or equal to. The function should output the following list with the data detailed bellow:
```[(1), (2), (3)]```
(1) - the amount of numbers that satisfy the constraint presented above
(2) - the closest number to the mean of the results, if there are more than one, the smallest number should be chosen.
(3) - the total sum of all the found numbers
Let's see a case with all the details:
```
max_sumDig(2000, 3) -------> [11, 1110, 12555]
(1) -There are 11 found numbers: 1000, 1001, 1002, 1010, 1011, 1020, 1100, 1101, 1110, 1200 and 2000
(2) - The mean of all the found numbers is:
(1000 + 1001 + 1002 + 1010 + 1011 + 1020 + 1100 + 1101 + 1110 + 1200 + 2000) /11 = 1141.36363,
so 1110 is the number that is closest to that mean value.
(3) - 12555 is the sum of all the found numbers
1000 + 1001 + 1002 + 1010 + 1011 + 1020 + 1100 + 1101 + 1110 + 1200 + 2000 = 12555
Finally, let's see another cases
```
max_sumDig(2000, 4) -----> [21, 1120, 23665]
max_sumDig(2000, 7) -----> [85, 1200, 99986]
max_sumDig(3000, 7) -----> [141, 1600, 220756]
```
Happy coding!! | from statistics import mean
def max_sumDig(nMax, maxSum):
def okay(x):
L = list(map(int, str(x)))
return all(sum(t) <= maxSum for t in zip(L, L[1:], L[2:], L[3:]))
result = list(filter(okay, range(1000, nMax+1)))
m = mean(result)
return [len(result), min(result, key=lambda x:abs(x-m)), sum(result)] | from statistics import mean
def max_sumDig(nMax, maxSum):
def okay(x):
L = list(map(int, str(x)))
return all(sum(t) <= maxSum for t in zip(L, L[1:], L[2:], L[3:]))
result = list(filter(okay, range(1000, nMax+1)))
m = mean(result)
return [len(result), min(result, key=lambda x:abs(x-m)), sum(result)] | train | APPS_structured |
Given a certain array of integers, create a function that may give the minimum number that may be divisible for all the numbers of the array.
```python
min_special_mult([2, 3 ,4 ,5, 6, 7]) == 420
```
The array may have integers that occurs more than once:
```python
min_special_mult([18, 22, 4, 3, 21, 6, 3]) == 2772
```
The array should have all its elements integer values. If the function finds an invalid entry (or invalid entries) like strings of the alphabet or symbols will not do the calculation and will compute and register them, outputting a message in singular or plural, depending on the number of invalid entries.
```python
min_special_mult([16, 15, 23, 'a', '&', '12']) == "There are 2 invalid entries: ['a', '&']"
min_special_mult([16, 15, 23, 'a', '&', '12', 'a']) == "There are 3 invalid entries: ['a', '&', 'a']"
min_special_mult([16, 15, 23, 'a', '12']) == "There is 1 invalid entry: a"
```
If the string is a valid number, the function will convert it as an integer.
```python
min_special_mult([16, 15, 23, '12']) == 5520
min_special_mult([16, 15, 23, '012']) == 5520
```
All the `None`/`nil` elements of the array will be ignored:
```python
min_special_mult([18, 22, 4, , None, 3, 21, 6, 3]) == 2772
```
If the array has a negative number, the function will convert to a positive one.
```python
min_special_mult([18, 22, 4, , None, 3, -21, 6, 3]) == 2772
min_special_mult([16, 15, 23, '-012']) == 5520
```
Enjoy it | from functools import reduce
gcd = lambda a, b: a if not b else gcd(b, a%b)
lcm = lambda a, b: a * b / gcd(a, b)
def min_special_mult(arr):
errors = []
xs = set()
for x in [_f for _f in arr if _f]:
try: xs.add(int(x))
except: errors.append(x)
if not errors: return reduce(lcm, xs)
if not errors[1:]: return "There is 1 invalid entry: %s" % errors[0]
return "There are %d invalid entries: %s" % (len(errors), errors)
| from functools import reduce
gcd = lambda a, b: a if not b else gcd(b, a%b)
lcm = lambda a, b: a * b / gcd(a, b)
def min_special_mult(arr):
errors = []
xs = set()
for x in [_f for _f in arr if _f]:
try: xs.add(int(x))
except: errors.append(x)
if not errors: return reduce(lcm, xs)
if not errors[1:]: return "There is 1 invalid entry: %s" % errors[0]
return "There are %d invalid entries: %s" % (len(errors), errors)
| train | APPS_structured |
No Story
No Description
Only by Thinking and Testing
Look at the results of the testcases, and guess the code!
---
## Series:
01. [A and B?](http://www.codewars.com/kata/56d904db9963e9cf5000037d)
02. [Incomplete string](http://www.codewars.com/kata/56d9292cc11bcc3629000533)
03. [True or False](http://www.codewars.com/kata/56d931ecc443d475d5000003)
04. [Something capitalized](http://www.codewars.com/kata/56d93f249c844788bc000002)
05. [Uniq or not Uniq](http://www.codewars.com/kata/56d949281b5fdc7666000004)
06. [Spatiotemporal index](http://www.codewars.com/kata/56d98b555492513acf00077d)
07. [Math of Primary School](http://www.codewars.com/kata/56d9b46113f38864b8000c5a)
08. [Math of Middle school](http://www.codewars.com/kata/56d9c274c550b4a5c2000d92)
09. [From nothingness To nothingness](http://www.codewars.com/kata/56d9cfd3f3928b4edd000021)
10. [Not perfect? Throw away!](http://www.codewars.com/kata/56dae2913cb6f5d428000f77)
11. [Welcome to take the bus](http://www.codewars.com/kata/56db19703cb6f5ec3e001393)
12. [A happy day will come](http://www.codewars.com/kata/56dc41173e5dd65179001167)
13. [Sum of 15(Hetu Luosliu)](http://www.codewars.com/kata/56dc5a773e5dd6dcf7001356)
14. [Nebula or Vortex](http://www.codewars.com/kata/56dd3dd94c9055a413000b22)
15. [Sport Star](http://www.codewars.com/kata/56dd927e4c9055f8470013a5)
16. [Falsetto Rap Concert](http://www.codewars.com/kata/56de38c1c54a9248dd0006e4)
17. [Wind whispers](http://www.codewars.com/kata/56de4d58301c1156170008ff)
18. [Mobile phone simulator](http://www.codewars.com/kata/56de82fb9905a1c3e6000b52)
19. [Join but not join](http://www.codewars.com/kata/56dfce76b832927775000027)
20. [I hate big and small](http://www.codewars.com/kata/56dfd5dfd28ffd52c6000bb7)
21. [I want to become diabetic ;-)](http://www.codewars.com/kata/56e0e065ef93568edb000731)
22. [How many blocks?](http://www.codewars.com/kata/56e0f1dc09eb083b07000028)
23. [Operator hidden in a string](http://www.codewars.com/kata/56e1161fef93568228000aad)
24. [Substring Magic](http://www.codewars.com/kata/56e127d4ef93568228000be2)
25. [Report about something](http://www.codewars.com/kata/56eccc08b9d9274c300019b9)
26. [Retention and discard I](http://www.codewars.com/kata/56ee0448588cbb60740013b9)
27. [Retention and discard II](http://www.codewars.com/kata/56eee006ff32e1b5b0000c32)
28. [How many "word"?](http://www.codewars.com/kata/56eff1e64794404a720002d2)
29. [Hail and Waterfall](http://www.codewars.com/kata/56f167455b913928a8000c49)
30. [Love Forever](http://www.codewars.com/kata/56f214580cd8bc66a5001a0f)
31. [Digital swimming pool](http://www.codewars.com/kata/56f25b17e40b7014170002bd)
32. [Archery contest](http://www.codewars.com/kata/56f4202199b3861b880013e0)
33. [The repair of parchment](http://www.codewars.com/kata/56f606236b88de2103000267)
34. [Who are you?](http://www.codewars.com/kata/56f6b4369400f51c8e000d64)
35. [Safe position](http://www.codewars.com/kata/56f7eb14f749ba513b0009c3)
---
## Special recommendation
Another series, innovative and interesting, medium difficulty. People who like challenges, can try these kata:
* [Play Tetris : Shape anastomosis](http://www.codewars.com/kata/56c85eebfd8fc02551000281)
* [Play FlappyBird : Advance Bravely](http://www.codewars.com/kata/56cd5d09aa4ac772e3000323) | def mystery(n):
if n <= 0:
return []
factors = [i for i in range(1, n+1) if n % i == 0]
valid = [j for j in factors if j % 2 == 1]
return valid | def mystery(n):
if n <= 0:
return []
factors = [i for i in range(1, n+1) if n % i == 0]
valid = [j for j in factors if j % 2 == 1]
return valid | train | APPS_structured |
Design a data structure that supports all following operations in average O(1) time.
insert(val): Inserts an item val to the set if not already present.
remove(val): Removes an item val from the set if present.
getRandom: Returns a random element from current set of elements. Each element must have the same probability of being returned.
Example:
// Init an empty set.
RandomizedSet randomSet = new RandomizedSet();
// Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomSet.insert(1);
// Returns false as 2 does not exist in the set.
randomSet.remove(2);
// Inserts 2 to the set, returns true. Set now contains [1,2].
randomSet.insert(2);
// getRandom should return either 1 or 2 randomly.
randomSet.getRandom();
// Removes 1 from the set, returns true. Set now contains [2].
randomSet.remove(1);
// 2 was already in the set, so return false.
randomSet.insert(2);
// Since 2 is the only number in the set, getRandom always return 2.
randomSet.getRandom(); | class RandomizedSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.dic = {}
self.l = []
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""
if val in self.dic:
return False
self.l.append(val)
self.dic[val] = len(self.l) - 1
return True
def remove(self, val):
"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""
if val not in self.dic:
return False
self.dic[self.l[-1]] = self.dic[val]
self.l[self.dic[val]], self.l[-1] = self.l[-1], self.l[self.dic[val]]
self.l.pop()
del self.dic[val]
return True
def getRandom(self):
"""
Get a random element from the set.
:rtype: int
"""
return random.choice(self.l)
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
| class RandomizedSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.dic = {}
self.l = []
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""
if val in self.dic:
return False
self.l.append(val)
self.dic[val] = len(self.l) - 1
return True
def remove(self, val):
"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""
if val not in self.dic:
return False
self.dic[self.l[-1]] = self.dic[val]
self.l[self.dic[val]], self.l[-1] = self.l[-1], self.l[self.dic[val]]
self.l.pop()
del self.dic[val]
return True
def getRandom(self):
"""
Get a random element from the set.
:rtype: int
"""
return random.choice(self.l)
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
| train | APPS_structured |
Your wizard cousin works at a Quidditch stadium and wants you to write a function that calculates the points for the Quidditch scoreboard!
# Story
Quidditch is a sport with two teams. The teams score goals by throwing the Quaffle through a hoop, each goal is worth **10 points**.
The referee also deducts 30 points (**- 30 points**) from the team who are guilty of carrying out any of these fouls: Blatching, Blurting, Bumphing, Haverstacking, Quaffle-pocking, Stooging
The match is concluded when the Snitch is caught, and catching the Snitch is worth **150 points**. Let's say a Quaffle goes through the hoop just seconds after the Snitch is caught, in that case the points of that goal should not end up on the scoreboard seeing as the match is already concluded.
You don't need any prior knowledge of how Quidditch works in order to complete this kata, but if you want to read up on what it is, here's a link: https://en.wikipedia.org/wiki/Quidditch
# Task
You will be given a string with two arguments, the first argument will tell you which teams are playing and the second argument tells you what's happened in the match. Calculate the points and return a string containing the teams final scores, with the team names sorted in the same order as in the first argument.
# Examples:
# Given an input of:
# The expected output would be:
Separate the team names from their respective points with a colon and separate the two teams with a comma.
Good luck! | def quidditch_scoreboard(teams, actions):
def formatter(team, pts): return ', '.join(f'{t}: {p}' for p,t in zip(pts,teams))
pts, teams = [0,0], teams.split(' vs ')
for act in actions.split(', '):
for i,t in enumerate(teams):
p = act.startswith(t) * (10*act.endswith('goal') + 150 * act.endswith('Snitch') - 30*act.endswith('foul'))
pts[i] += p
if p==150: return formatter(teams, pts)
return formatter(teams,pts) | def quidditch_scoreboard(teams, actions):
def formatter(team, pts): return ', '.join(f'{t}: {p}' for p,t in zip(pts,teams))
pts, teams = [0,0], teams.split(' vs ')
for act in actions.split(', '):
for i,t in enumerate(teams):
p = act.startswith(t) * (10*act.endswith('goal') + 150 * act.endswith('Snitch') - 30*act.endswith('foul'))
pts[i] += p
if p==150: return formatter(teams, pts)
return formatter(teams,pts) | train | APPS_structured |
Chef likes to play with big numbers. Today, he has a big positive integer N. He can select any two digits from this number (the digits can be same but their positions should be different) and orders them in any one of the two possible ways. For each of these ways, he creates a two digit number from it (might contain leading zeros). Then, he will pick a character corresponding to the ASCII value equal to this number, i.e. the number 65 corresponds to 'A', 66 to 'B' and so on till 90 for 'Z'. Chef is only interested in finding which of the characters in the range 'A' to 'Z' can possibly be picked this way.
-----Input-----
The first line of the input contains an integer T denoting the number of test cases.
The first line of the input contains an integer N.
-----Output-----
For each test case, output a string containing characters Chef can pick in sorted order If the resulting size of string is zero, you should output a new line.
-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 10100000
-----Subtasks-----
- Subtask #1 (40 points) N ≤ 1010
- Subtask #2 (60 points) Original Constraints
-----Example-----
Input:
4
65
566
11
1623455078
Output:
A
AB
ACDFGHIJKLNPQRSTUVW
-----Explanation-----
Example case 1. Chef can pick digits 6 and 5 and create integers 56 and 65. The integer 65 corresponds to 'A'.
Example case 2. Chef can pick digits 6 and 5 and create 'A' as it equals 65. He can pick 6 and 6 (they are picked from position 2 and position 3, respectively) to create 'B' too. Hence answer is "AB".
Example case 3. It's not possible to create any character from 'A' to 'Z'. Hence, we just print a new line. | test=int(input())
for i in range(test):
N=input()
X=[]
for x in N:
X.append(x)
Y=[]
list1=[]
output=''
for y in X:
if int(y)>=6 and int(y) not in Y:
Y.append(y)
for x in Y:
for y in X:
if int(x)==6:
if int(y)>=5:
n=int(x)*10+int(y)
list1.append(n)
elif int(x)==9:
if int(y)==0:
n=int(x)*10+int(y)
list1.append(n)
else:
n=int(x)*10+int(y)
list1.append(n)
for j in Y:
if int(j)!=9:
m=int(j)*10+int(j)
list1.remove(m)
list1.sort()
if len(list1)==0:
print(" ")
else:
list1.sort()
for k in list1:
if chr(k) not in output:
output+=chr(k)
print(output) | test=int(input())
for i in range(test):
N=input()
X=[]
for x in N:
X.append(x)
Y=[]
list1=[]
output=''
for y in X:
if int(y)>=6 and int(y) not in Y:
Y.append(y)
for x in Y:
for y in X:
if int(x)==6:
if int(y)>=5:
n=int(x)*10+int(y)
list1.append(n)
elif int(x)==9:
if int(y)==0:
n=int(x)*10+int(y)
list1.append(n)
else:
n=int(x)*10+int(y)
list1.append(n)
for j in Y:
if int(j)!=9:
m=int(j)*10+int(j)
list1.remove(m)
list1.sort()
if len(list1)==0:
print(" ")
else:
list1.sort()
for k in list1:
if chr(k) not in output:
output+=chr(k)
print(output) | train | APPS_structured |
Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x and its coefficient.
If there is no solution for the equation, return "No solution".
If there are infinite solutions for the equation, return "Infinite solutions".
If there is exactly one solution for the equation, we ensure that the value of x is an integer.
Example 1:
Input: "x+5-3+x=6+x-2"
Output: "x=2"
Example 2:
Input: "x=x"
Output: "Infinite solutions"
Example 3:
Input: "2x=x"
Output: "x=0"
Example 4:
Input: "2x+3x-6x=x+2"
Output: "x=-1"
Example 5:
Input: "x=x+2"
Output: "No solution" | import re
class Solution:
def solveEquation(self, equation):
"""
:type equation: str
:rtype: str
"""
# Gets sum of x's in an eq
def get_x_sum(s):
total = 0
curr = ""
sign = "+"
for c in s:
if c == "x":
if curr == "":
total += int(sign+"1")
else:
total += int(sign+curr)
elif c == "+" or c == "-":
curr = ""
sign = c
else:
curr += c
return total
# Gets sum of ints in an eq
def get_int_sum(s):
total = 0
curr = ""
sign = "+"
for c in s:
if c == "x":
curr = ""
sign = "+"
elif c == "+" or c == "-":
if curr != "":
total += int(sign+curr)
curr = ""
sign = c
else:
curr += c
if curr != "":
total += int(sign+curr)
return total
lhs,rhs = equation.split("=")
lhs_sum_x = get_x_sum(lhs)
lhs_sum_int = get_int_sum(lhs)
rhs_sum_x = get_x_sum(rhs)
rhs_sum_int = get_int_sum(rhs)
if lhs_sum_int == rhs_sum_int:
if lhs_sum_x == rhs_sum_x:
return "Infinite solutions"
return "x=0"
else:
if lhs_sum_x == rhs_sum_x:
return "No solution"
diff_x = lhs_sum_x-rhs_sum_x
diff_int = rhs_sum_int - lhs_sum_int
return "x=" + str(diff_int // diff_x)
| import re
class Solution:
def solveEquation(self, equation):
"""
:type equation: str
:rtype: str
"""
# Gets sum of x's in an eq
def get_x_sum(s):
total = 0
curr = ""
sign = "+"
for c in s:
if c == "x":
if curr == "":
total += int(sign+"1")
else:
total += int(sign+curr)
elif c == "+" or c == "-":
curr = ""
sign = c
else:
curr += c
return total
# Gets sum of ints in an eq
def get_int_sum(s):
total = 0
curr = ""
sign = "+"
for c in s:
if c == "x":
curr = ""
sign = "+"
elif c == "+" or c == "-":
if curr != "":
total += int(sign+curr)
curr = ""
sign = c
else:
curr += c
if curr != "":
total += int(sign+curr)
return total
lhs,rhs = equation.split("=")
lhs_sum_x = get_x_sum(lhs)
lhs_sum_int = get_int_sum(lhs)
rhs_sum_x = get_x_sum(rhs)
rhs_sum_int = get_int_sum(rhs)
if lhs_sum_int == rhs_sum_int:
if lhs_sum_x == rhs_sum_x:
return "Infinite solutions"
return "x=0"
else:
if lhs_sum_x == rhs_sum_x:
return "No solution"
diff_x = lhs_sum_x-rhs_sum_x
diff_int = rhs_sum_int - lhs_sum_int
return "x=" + str(diff_int // diff_x)
| train | APPS_structured |
-----Problem Statement-----
Chef has a sequence of N segments: [L1, R1], [L2, R2], ..., [LN, RN]. He wants to transform the first segment to the last one (with index N). His plan is to do this big deal with a number of transformations: firstly he will transform
the first segment to the second one, then to the third one, then to the fourth one, and so on till N-th one.
Chef can use operation of a single type: shift one segment border by one unit. So, if he has segment [L, R], he can transform it into one of the following segments: [L + 1, R] (we will denote such operation with string L+), [L, R + 1] (will be denoted as R+), [L - 1, R] (L-), [L, R - 1] (R-). Chef doesn't like empty segments, therefore he cannot use any operation that makes a segment empty (L = R).
Chef really wants to transform his segment as fast as possible. Please, help him. Find the sequence with minimal number of operations that transforms his segment. If there are multiple such sequences pick the lexicographically minimal one.
-----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 segments Chef has.
The following N lines contain pairs of integers. The i-th line contains integers Li, Ri, denoting i-th Chef's segment.
-----Output-----
For each test case print an answer - two lines. The first line should contain the minimal number of operations. The second line should contain the sequence of operations
without any whitespaces.
-----Constraints-----
- 1 ≤ T, N ≤ 1000.
- -1000 ≤ Li < Ri ≤ 1000.
The total sum of N values for all test cases doesn't exceed 1000.
-----Example-----
Input:
4
3
-1 0
0 1
3 5
1
0 1
3
-2 -1
-2 -1
-2 0
4
4 6
3 5
-1 1
1 2
Output:
9
R+L+R+L+R+L+R+L+R+
0
1
R+
13
L-R-L-L-L-L-R-R-R-R-L+R+L+ | for tc in range(int(input())):
N = int(input())
a, b = list(map(int, input().split()))
pr = []
# 'L' is lexicographically lower than 'R'.
# so, we should first try to apply L+ or L-
# if we can't then only we'll try to apply R+ or R-
for i in range(N - 1):
l, r = list(map(int, input().split()))
#continue the following process until a == l and b == r
while a != l or b != r:
# trying to apply L-
if a > l:
a -= 1
pr.append('L-')
# now, trying to apply L+ (if a < b)
elif a + 1 < b and a < l:
a += 1
pr.append('L+')
# ok, so far, so good... now, let's try to apply R+
elif b < r:
b += 1
pr.append('R+')
# finally, lastly, trying to apply R- (if a < b)
elif b - 1 > a and b > r:
b -= 1
pr.append('R-')
print(len(pr))
print(''.join(pr)) | for tc in range(int(input())):
N = int(input())
a, b = list(map(int, input().split()))
pr = []
# 'L' is lexicographically lower than 'R'.
# so, we should first try to apply L+ or L-
# if we can't then only we'll try to apply R+ or R-
for i in range(N - 1):
l, r = list(map(int, input().split()))
#continue the following process until a == l and b == r
while a != l or b != r:
# trying to apply L-
if a > l:
a -= 1
pr.append('L-')
# now, trying to apply L+ (if a < b)
elif a + 1 < b and a < l:
a += 1
pr.append('L+')
# ok, so far, so good... now, let's try to apply R+
elif b < r:
b += 1
pr.append('R+')
# finally, lastly, trying to apply R- (if a < b)
elif b - 1 > a and b > r:
b -= 1
pr.append('R-')
print(len(pr))
print(''.join(pr)) | train | APPS_structured |
Tonight, Chef would like to hold a party for his $N$ friends.
All friends are invited and they arrive at the party one by one in an arbitrary order. However, they have certain conditions — for each valid $i$, when the $i$-th friend arrives at the party and sees that at that point, strictly less than $A_i$ other people (excluding Chef) have joined the party, this friend leaves the party; otherwise, this friend joins the party.
Help Chef estimate how successful the party can be — find the maximum number of his friends who could join the party (for an optimal choice of the order of arrivals).
-----Input-----
- The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows.
- The first line of each test case contains a single integer $N$.
- The second line contains $N$ space-separated integers $A_1, A_2, \ldots, A_N$.
-----Output-----
For each test case, print a single line containing one integer — the maximum number of Chef's friends who could join the party.
-----Constraints-----
- $1 \le T \le 1,000$
- $1 \le N \le 10^5$
- the sum of $N$ over all test cases does not exceed $10^6$
-----Example Input-----
3
2
0 0
6
3 1 0 0 5 5
3
1 2 3
-----Example Output-----
2
4
0
-----Explanation-----
Example case 1: Chef has two friends. Both of them do not require anyone else to be at the party before they join, so they will both definitely join the party.
Example case 2: At the beginning, friends $3$ and $4$ can arrive and join the party, since they do not require anyone else to be at the party before they join. After that, friend $2$ can arrive; this friend would see that there are two people at the party and therefore also join. Then, friend $1$ will also join, so in the end, there would be $4$ people attending the party.
Example case 3: No one will attend the party because each of Chef's friends will find zero people at the party and leave, regardless of the order in which they arrive. | for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
a.sort()
c=0
for i in range(n):
if c>=a[i]:
c+=1
else:
break
print(c)
| for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
a.sort()
c=0
for i in range(n):
if c>=a[i]:
c+=1
else:
break
print(c)
| train | APPS_structured |
## Your story
You've always loved both Fizz Buzz katas and cuckoo clocks, and when you walked by a garage sale and saw an ornate cuckoo clock with a missing pendulum, and a "Beyond-Ultimate Raspberry Pi Starter Kit" filled with all sorts of sensors and motors and other components, it's like you were suddenly hit by a beam of light and knew that it was your mission to combine the two to create a computerized Fizz Buzz cuckoo clock!
You took them home and set up shop on the kitchen table, getting more and more excited as you got everything working together just perfectly. Soon the only task remaining was to write a function to select from the sounds you had recorded depending on what time it was:
## Your plan
* When a minute is evenly divisible by three, the clock will say the word "Fizz".
* When a minute is evenly divisible by five, the clock will say the word "Buzz".
* When a minute is evenly divisible by both, the clock will say "Fizz Buzz", with two exceptions:
1. On the hour, instead of "Fizz Buzz", the clock door will open, and the cuckoo bird will come out and "Cuckoo" between one and twelve times depending on the hour.
2. On the half hour, instead of "Fizz Buzz", the clock door will open, and the cuckoo will come out and "Cuckoo" just once.
* With minutes that are not evenly divisible by either three or five, at first you had intended to have the clock just say the numbers ala Fizz Buzz, but then you decided at least for version 1.0 to just have the clock make a quiet, subtle "tick" sound for a little more clock nature and a little less noise.
Your input will be a string containing hour and minute values in 24-hour time, separated by a colon, and with leading zeros. For example, 1:34 pm would be `"13:34"`.
Your return value will be a string containing the combination of Fizz, Buzz, Cuckoo, and/or tick sounds that the clock needs to make at that time, separated by spaces. Note that although the input is in 24-hour time, cuckoo clocks' cuckoos are in 12-hour time.
## Some examples
```
"13:34" "tick"
"21:00" "Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo"
"11:15" "Fizz Buzz"
"03:03" "Fizz"
"14:30" "Cuckoo"
"08:55" "Buzz"
"00:00" "Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo"
"12:00" "Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo"
```
Have fun! | def fizz_buzz_cuckoo_clock(time):
h, m = list(map(int, time.split(':')))
if m % 30 < 1:
return ' '.join(['Cuckoo']*(m==30 or (h-1) % 12 + 1))
else:
return ('Fizz ' * (m % 3 < 1) + 'Buzz ' * (m % 5 < 1))[:-1] or 'tick'
| def fizz_buzz_cuckoo_clock(time):
h, m = list(map(int, time.split(':')))
if m % 30 < 1:
return ' '.join(['Cuckoo']*(m==30 or (h-1) % 12 + 1))
else:
return ('Fizz ' * (m % 3 < 1) + 'Buzz ' * (m % 5 < 1))[:-1] or 'tick'
| train | APPS_structured |
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"
Note:
The length of both num1 and num2 is < 110.
Both num1 and num2 contain only digits 0-9.
Both num1 and num2 do not contain any leading zero, except the number 0 itself.
You must not use any built-in BigInteger library or convert the inputs to integer directly. | class Solution:
def multiply(self,num1, num2):
a=['0','1','2','3','4','5','6','7','8','9']
z=0
x=0
for i,element in enumerate(num1):
for j in range(10):
if element==a[j]:
z+=j*(10**(len(num1)-i-1))
for c,b in enumerate(num2):
for k in range(10):
if b==a[k]:
x+=k*(10**(len(num2)-c-1))
mul=z*x
return(''.join('%d'%mul))
| class Solution:
def multiply(self,num1, num2):
a=['0','1','2','3','4','5','6','7','8','9']
z=0
x=0
for i,element in enumerate(num1):
for j in range(10):
if element==a[j]:
z+=j*(10**(len(num1)-i-1))
for c,b in enumerate(num2):
for k in range(10):
if b==a[k]:
x+=k*(10**(len(num2)-c-1))
mul=z*x
return(''.join('%d'%mul))
| train | APPS_structured |
Given a certain integer ```n```, we need a function ```big_primefac_div()```, that give an array with the highest prime factor and the highest divisor (not equal to n).
Let's see some cases:
```python
big_primefac_div(100) == [5, 50]
big_primefac_div(1969) == [179, 179]
```
If n is a prime number the function will output an empty list:
```python
big_primefac_div(997) == []
```
If ```n``` is an negative integer number, it should be considered the division with tha absolute number of the value.
```python
big_primefac_div(-1800) == [5, 900]
```
If ```n``` is a float type, will be rejected if it has a decimal part with some digits different than 0. The output "The number has a decimal part. No Results". But ```n ``` will be converted automatically to an integer if all the digits of the decimal part are 0.
```python
big_primefac_div(-1800.00) == [5, 900]
big_primefac_div(-1800.1) == "The number has a decimal part. No Results"
```
Optimization and fast algorithms are a key factor to solve this kata.
Happy coding and enjoy it! |
def big_primefac_div(n):
#We need only absolute values
n = abs(n)
maxi = 0
#Checking if the number has a decimal part
if n % 1 == 0:
#Loop for finding Biggest Divisor
listy = [num for num in range(2, int(n**.5 + 1)) if n % num == 0]
fancy_list = list(listy)
for number in listy:
temp_numb = n // number
fancy_list.append(int(temp_numb))
#Loop for finding Biggest Prime Factor
for numb in sorted(fancy_list, reverse=True):
for i in range(2, int(numb**.5 + 1)):
if numb % i == 0:
break
else:
maxi = numb
break
if fancy_list:
return [maxi, max(set(fancy_list))]
#In case we gonna have one number as prime factor itself
else:
return []
else:
return ("The number has a decimal part. No Results") |
def big_primefac_div(n):
#We need only absolute values
n = abs(n)
maxi = 0
#Checking if the number has a decimal part
if n % 1 == 0:
#Loop for finding Biggest Divisor
listy = [num for num in range(2, int(n**.5 + 1)) if n % num == 0]
fancy_list = list(listy)
for number in listy:
temp_numb = n // number
fancy_list.append(int(temp_numb))
#Loop for finding Biggest Prime Factor
for numb in sorted(fancy_list, reverse=True):
for i in range(2, int(numb**.5 + 1)):
if numb % i == 0:
break
else:
maxi = numb
break
if fancy_list:
return [maxi, max(set(fancy_list))]
#In case we gonna have one number as prime factor itself
else:
return []
else:
return ("The number has a decimal part. No Results") | train | APPS_structured |
The rgb function is incomplete. Complete it so that passing in RGB decimal values will result in a hexadecimal representation being returned. Valid decimal values for RGB are 0 - 255. Any values that fall out of that range must be rounded to the closest valid value.
Note: Your answer should always be 6 characters long, the shorthand with 3 will not work here.
The following are examples of expected output values:
```python
rgb(255, 255, 255) # returns FFFFFF
rgb(255, 255, 300) # returns FFFFFF
rgb(0,0,0) # returns 000000
rgb(148, 0, 211) # returns 9400D3
```
```if:nasm
char \*rgb(int r, int g, int b, char \*outp)
``` | def rgb(r, g, b):
return ''.join(['%02X' % max(0, min(x, 255)) for x in [r, g, b]]) | def rgb(r, g, b):
return ''.join(['%02X' % max(0, min(x, 255)) for x in [r, g, b]]) | train | APPS_structured |
Calculate the product of all elements in an array.
```if:csharp
If the array is *null*, you should throw `ArgumentNullException` and if the array is empty, you should throw `InvalidOperationException`.
As a challenge, try writing your method in just one line of code. It's possible to have only 36 characters within your method.
```
```if:javascript
If the array is `null` or is empty, the function should return `null`.
```
```if:haskell
If the array is empty then return Nothing, else return Just product.
```
```if:php
If the array is `NULL` or empty, return `NULL`.
```
```if:python
If the array is empty or `None`, return `None`.
```
```if:ruby
If the array is `nil` or is empty, the function should return `nil`.
```
```if:crystal
If the array is `nil` or is empty, the function should return `nil`.
```
```if:groovy
If the array is `null` or `empty` return `null`.
```
```if:julia
If the input is `nothing` or an empty array, return `nothing`
``` | def product(numbers):
if not numbers:
return None
prod = 1
for i in numbers:
prod *= i
return prod | def product(numbers):
if not numbers:
return None
prod = 1
for i in numbers:
prod *= i
return prod | train | APPS_structured |
# Task
Make a custom esolang interpreter for the language Stick. Stick is a simple, stack-based esoteric programming language with only 7 commands.
# Commands
* `^`: Pop the stack.
* `!`: Add new element to stack with the value of 0.
* `+`: Increment element. 255+1=0.
* `-`: Decrement element. 0-1=255.
* `*`: Add ascii value of **top** element to the output stream.
* `[`: Skip past **next** `]` if element value is 0.
* `]`: Jump back to the command after **previous** `[` if element value is nonzero.
# Syntax and other info
* You don't need to add support for nested brackets.
* Non-command characters should be ignored.
* Code will always have all brackets closed.
* Note the highlighted **next** and **previous** in the commands reference.
* Program begins with the top element having the value of 0 and being the only element in the stack.
* Program ends when command executor reaches the end.
# Examples
## Hello, World!
```python
'++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*!+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*!++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*!++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*!+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*!++++++++++++++++++++++++++++++++++++++++++++*!++++++++++++++++++++++++++++++++*!+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*!+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*!++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*!++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*!++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*!+++++++++++++++++++++++++++++++++*!'
```
# Notes
* If this kata is a duplicate, this is not an issue.
* If this kata uses incorrect styling, it is also not an issue.
* Feel free to comment in the discource area.
* Swift versions must throw an error (conforming to the Error Protocol) when abnormal conditions occur.
* Javascript versions should throw when abnormal conditions occur. | def interpreter(tape):
a,stack,out=0, [0], []
while a<len(tape):
command=tape[a]
if command == '^': stack.pop()
elif command == '!': stack.append(0)
elif command == '+': stack[-1]=(stack[-1]+1) % 256
elif command == '-': stack[-1]=(stack[-1]-1) % 256
elif command == '*': out.append(chr(stack[-1]))
elif command == '[' and stack[-1]==0: a=tape.find(']', a)
elif command == ']' and stack[-1]!=0: a=tape.rfind('[', a)
a += 1
return ''.join(out) | def interpreter(tape):
a,stack,out=0, [0], []
while a<len(tape):
command=tape[a]
if command == '^': stack.pop()
elif command == '!': stack.append(0)
elif command == '+': stack[-1]=(stack[-1]+1) % 256
elif command == '-': stack[-1]=(stack[-1]-1) % 256
elif command == '*': out.append(chr(stack[-1]))
elif command == '[' and stack[-1]==0: a=tape.find(']', a)
elif command == ']' and stack[-1]!=0: a=tape.rfind('[', a)
a += 1
return ''.join(out) | train | APPS_structured |
You are given a graph consisting of $n$ vertices and $m$ edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges.
You have to direct undirected edges in such a way that the resulting graph is directed and acyclic (i.e. the graph with all edges directed and having no directed cycles). Note that you have to direct all undirected edges.
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 $m$ ($2 \le n \le 2 \cdot 10^5$, $1 \le m \le min(2 \cdot 10^5, \frac{n(n-1)}{2})$) — the number of vertices and the number of edges in the graph, respectively.
The next $m$ lines describe edges of the graph. The $i$-th edge is described with three integers $t_i$, $x_i$ and $y_i$ ($t_i \in [0; 1]$, $1 \le x_i, y_i \le n$) — the type of the edge ($t_i = 0$ if the edge is undirected and $t_i = 1$ if the edge is directed) and vertices this edge connects (the undirected edge connects vertices $x_i$ and $y_i$ and directed edge is going from the vertex $x_i$ to the vertex $y_i$). It is guaranteed that the graph do not contain self-loops (i.e. edges from the vertex to itself) and multiple edges (i.e. for each pair ($x_i, y_i$) there are no other pairs ($x_i, y_i$) or ($y_i, x_i$)).
It is guaranteed that both sum $n$ and sum $m$ do not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$; $\sum m \le 2 \cdot 10^5$).
-----Output-----
For each test case print the answer — "NO" if it is impossible to direct undirected edges in such a way that the resulting graph is directed and acyclic, otherwise print "YES" on the first line and $m$ lines describing edges of the resulted directed acyclic graph (in any order). Note that you cannot change the direction of the already directed edges. If there are several answers, you can print any.
-----Example-----
Input
4
3 1
0 1 3
5 5
0 2 1
1 1 5
1 5 4
0 5 2
1 3 5
4 5
1 1 2
0 4 3
1 3 1
0 2 3
1 2 4
4 5
1 4 1
1 1 3
0 1 2
1 2 4
1 3 2
Output
YES
3 1
YES
2 1
1 5
5 4
2 5
3 5
YES
1 2
3 4
3 1
3 2
2 4
NO
-----Note-----
Explanation of the second test case of the example:
[Image]
Explanation of the third test case of the example:
[Image] | def main():
import sys
from collections import deque, defaultdict
from heapq import heappop, heappush
sys.setrecursionlimit(10**9)
input = sys.stdin.readline
for __ in [0]*int(input()):
N, M = list(map(int, input().split()))
deg = [0]*N
directed = defaultdict(list)
undirected = defaultdict(list)
for _ in [0]*M:
t, a, b = list(map(int, input().split()))
a -= 1
b -= 1
if t:
directed[a].append(b)
deg[b] += 1
else:
undirected[a].append(b)
undirected[b].append(a)
q = deque([i for i, d in enumerate(deg) if d == 0])
topological = []
while q:
v = q.popleft()
topological.append(v)
if v not in directed:
continue
for u in directed[v]:
deg[u] -= 1
if deg[u] == 0:
q.append(u)
if len(topological) != N:
print('NO')
continue
del deg
print('YES')
used = [0]*N
for v in topological:
if v in directed:
for u in directed[v]:
print(v+1, u+1)
if v in undirected:
for u in undirected[v]:
if used[u]:
continue
print(v+1, u+1)
used[v] = 1
del used
def __starting_point():
main()
__starting_point() | def main():
import sys
from collections import deque, defaultdict
from heapq import heappop, heappush
sys.setrecursionlimit(10**9)
input = sys.stdin.readline
for __ in [0]*int(input()):
N, M = list(map(int, input().split()))
deg = [0]*N
directed = defaultdict(list)
undirected = defaultdict(list)
for _ in [0]*M:
t, a, b = list(map(int, input().split()))
a -= 1
b -= 1
if t:
directed[a].append(b)
deg[b] += 1
else:
undirected[a].append(b)
undirected[b].append(a)
q = deque([i for i, d in enumerate(deg) if d == 0])
topological = []
while q:
v = q.popleft()
topological.append(v)
if v not in directed:
continue
for u in directed[v]:
deg[u] -= 1
if deg[u] == 0:
q.append(u)
if len(topological) != N:
print('NO')
continue
del deg
print('YES')
used = [0]*N
for v in topological:
if v in directed:
for u in directed[v]:
print(v+1, u+1)
if v in undirected:
for u in undirected[v]:
if used[u]:
continue
print(v+1, u+1)
used[v] = 1
del used
def __starting_point():
main()
__starting_point() | train | APPS_structured |
Given a string, swap the case for each of the letters.
e.g. CodEwArs --> cODeWaRS
### Examples
```
"" -> ""
"CodeWars" -> "cODEwARS"
"abc" -> "ABC"
"ABC" -> "abc"
"123235" -> "123235"
``` | def swap(string_):
return string_.swapcase() | def swap(string_):
return string_.swapcase() | train | APPS_structured |
Abhi Ram analyses london stock exchange and invests in a software company C-.gate . He wants to sell his shares after 5 weeks.
Given the investment m, increase or decrease of share prices of 5 weeks(+/- pi) , help him to calculate his net profit or loss percentage(n%) of his investment to establish his own company KMC.
-----Input:-----
- The first line contains an integer T which denotes the number of test cases.
- Each test case comprises of two lines: the first line contains the integer m which denotes the amount invested.
The second line consists of five space separated integers(p1, p2, p3, p4, p5) each preceeded by + (increase) or - (decrease) which give the percentage of change in share prices over 5 weeks.
.
-----Output:-----
The output contains a single number n which gives the percentage of profit or loss preceeded by + (profit) or - (loss).
-----Constraints:-----
- 1 ≤ T ≤ 100
- 1 ≤ m ≤ 105
- -100 ≤ pi ≤ 100
-----Example:-----
Input:
2
10000
+5 -3 -2 +10 +15
6256250
-24 +22 +4 -16 +20
Output:
+26.2634
-2.79977 | for i in range(int(input())):
n = int(input())
P = list(map(float, input().split()))
pr = 1
for p in P:
a = 100+p
pr = (pr*a)/100
pr = (pr-1)*100
x = 6-len(str(int(abs(pr))))
if (x==1):
if (pr==0):
print(0)
elif (pr>0):
print("+"+str("%.1f" % round(pr,x)))
else:
print(str("%.1f" % round(pr,x)))
elif (x==2):
if (pr==0):
print(0)
elif (pr>0):
print("+"+str("%.2f" % round(pr,x)))
else:
print(str("%.2f" % round(pr,x)))
elif (x==3):
if (pr==0):
print(0)
elif (pr>0):
print("+"+str("%.3f" % round(pr,x)))
else:
print(str("%.3f" % round(pr,x)))
elif (x==4):
if (pr==0):
print(0)
elif (pr>0):
print("+"+str("%.4f" % round(pr,x)))
else:
print(str("%.4f" % round(pr,x)))
elif (x==5):
if (pr==0):
print(0)
elif (pr>0):
print("+"+str("%.5f" % round(pr,x)))
else:
print(str("%.5f" % round(pr,x)))
elif (x==6):
if (pr==0):
print(0)
elif (pr>0):
print("+"+str("%.6f" % round(pr,x)))
else:
print(str("%.6f" % round(pr,x))) | for i in range(int(input())):
n = int(input())
P = list(map(float, input().split()))
pr = 1
for p in P:
a = 100+p
pr = (pr*a)/100
pr = (pr-1)*100
x = 6-len(str(int(abs(pr))))
if (x==1):
if (pr==0):
print(0)
elif (pr>0):
print("+"+str("%.1f" % round(pr,x)))
else:
print(str("%.1f" % round(pr,x)))
elif (x==2):
if (pr==0):
print(0)
elif (pr>0):
print("+"+str("%.2f" % round(pr,x)))
else:
print(str("%.2f" % round(pr,x)))
elif (x==3):
if (pr==0):
print(0)
elif (pr>0):
print("+"+str("%.3f" % round(pr,x)))
else:
print(str("%.3f" % round(pr,x)))
elif (x==4):
if (pr==0):
print(0)
elif (pr>0):
print("+"+str("%.4f" % round(pr,x)))
else:
print(str("%.4f" % round(pr,x)))
elif (x==5):
if (pr==0):
print(0)
elif (pr>0):
print("+"+str("%.5f" % round(pr,x)))
else:
print(str("%.5f" % round(pr,x)))
elif (x==6):
if (pr==0):
print(0)
elif (pr>0):
print("+"+str("%.6f" % round(pr,x)))
else:
print(str("%.6f" % round(pr,x))) | train | APPS_structured |
As we all know, Dhoni loves drinking milk. Once he and Sir Jadeja were invited in the inauguration of a Dairy company in Ranchi.
The company had arranged n jars of milk from various breeds of cows , jar number i containing a[i] litres of milk. Since Dhoni loves driking milk more than Sir Jadeja, so Kohli suggested a plan for them. His plan was that each time Dhoni will choose a jar containing the maximum amount of milk. If this jar has less than k litres of milk or if Dhoni has already drunk more than m number of times from this jar, then the milk contained in the jar will be drunk by Sir Jadeja. Sir Jadeja will drink all the milk left in that jar. Otherwise Dhoni will drink exactly k litres of milk from the jar and put it back at its position. Dhoni will do so until he has given all jars to Sir Jadeja.
You have to calculate how much milk Sir Jadega will get after Dhoni satisfies his hunger modulo 1,000,000,007.
-----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 integer N , M, K denoting the number of milk jars, maximum number of time Dhoni will drink from any jar and maximum amount of milk Dhoni will drink at any time respectively. The second line contains N space-separated integers A1, A2, ..., AN denoting the amount of milk in each jar.
-----Output-----
- For each test case, output a single line containing the amount of milk Sir Jadega will get modulo 1,000,000,007.
-----Constraints-----
- 1 ≤ T ≤ 10
- 1 ≤ N ≤ 10^5
- 0 ≤ M ≤ 10^6
- 1 ≤ K ≤ 10^6
- 0 ≤ Ai ≤ 10^9
-----Example-----
Input:
1
3 3 3
15 8 10
Output:
9 | import sys
MOD = 10**9+7
for __ in range(eval(input())) :
n , m , k = list(map(int,sys.stdin.readline().split()))
lists = list(map(int,sys.stdin.readline().split()))
ans = 0
for i in lists :
msd = i/k
if msd > m :
jaddu = i-(m*k)
else :
jaddu = i%k
ans += jaddu%MOD
print(ans%MOD)
| import sys
MOD = 10**9+7
for __ in range(eval(input())) :
n , m , k = list(map(int,sys.stdin.readline().split()))
lists = list(map(int,sys.stdin.readline().split()))
ans = 0
for i in lists :
msd = i/k
if msd > m :
jaddu = i-(m*k)
else :
jaddu = i%k
ans += jaddu%MOD
print(ans%MOD)
| train | APPS_structured |
Write a function `take_umbrella()` that takes two arguments: a string representing the current weather and a float representing the chance of rain today.
Your function should return `True` or `False` based on the following criteria.
* You should take an umbrella if it's currently raining or if it's cloudy and the chance of rain is over `0.20`.
* You shouldn't take an umbrella if it's sunny unless it's more likely to rain than not.
The options for the current weather are `sunny`, `cloudy`, and `rainy`.
For example, `take_umbrella('sunny', 0.40)` should return `False`.
As an additional challenge, consider solving this kata using only logical operaters and not using any `if` statements. | def take_umbrella(weather, rain_chance):
# Your code here.
a = (weather == 'sunny' and rain_chance > 0.5)
b = (weather == 'rainy')
c = (weather == 'cloudy' and rain_chance > 0.2)
return bool(a or b or c)
| def take_umbrella(weather, rain_chance):
# Your code here.
a = (weather == 'sunny' and rain_chance > 0.5)
b = (weather == 'rainy')
c = (weather == 'cloudy' and rain_chance > 0.2)
return bool(a or b or c)
| train | APPS_structured |
In this Kata, you will be given a string and your task will be to return the length of the longest prefix that is also a suffix. A prefix is the start of a string while the suffix is the end of a string. For instance, the prefixes of the string `"abcd"` are `["a","ab","abc"]`. The suffixes are `["bcd", "cd", "d"]`. You should not overlap the prefix and suffix.
```Haskell
for example:
solve("abcd") = 0, because no prefix == suffix.
solve("abcda") = 1, because the longest prefix which == suffix is "a".
solve("abcdabc") = 3. Longest prefix which == suffix is "abc".
solve("aaaa") = 2. Longest prefix which == suffix is "aa". You should not overlap the prefix and suffix
solve("aa") = 1. You should not overlap the prefix and suffix.
solve("a") = 0. You should not overlap the prefix and suffix.
```
All strings will be lowercase and string lengths are `1 <= length <= 500`
More examples in test cases. Good luck! | import math
# The function that will check a prefix and a suffix
def prefix_suffix_check(string, indexIn):
return string[:indexIn] == string[(indexIn) * -1 : ]
def solve(initial_string):
# Halves and floors the array size
half_array_size = int(math.floor(len(initial_string) / 2))
# A revese for loop for checking the middle to outer
for x in range(half_array_size, 0, -1):
# If the suffix and prefix are equal return the x
if (prefix_suffix_check(initial_string, x) == True):
return x
# Else return 0
return 0
| import math
# The function that will check a prefix and a suffix
def prefix_suffix_check(string, indexIn):
return string[:indexIn] == string[(indexIn) * -1 : ]
def solve(initial_string):
# Halves and floors the array size
half_array_size = int(math.floor(len(initial_string) / 2))
# A revese for loop for checking the middle to outer
for x in range(half_array_size, 0, -1):
# If the suffix and prefix are equal return the x
if (prefix_suffix_check(initial_string, x) == True):
return x
# Else return 0
return 0
| train | APPS_structured |
You wrote all your unit test names in camelCase.
But some of your colleagues have troubles reading these long test names.
So you make a compromise to switch to underscore separation.
To make these changes fast you wrote a class to translate a camelCase name
into an underscore separated name.
Implement the ToUnderscore() method.
Example:
`"ThisIsAUnitTest" => "This_Is_A_Unit_Test"`
**But of course there are always special cases...**
You also have some calculation tests. Make sure the results don't get split by underscores.
So only add an underscore in front of the first number.
Also Some people already used underscore names in their tests. You don't want to change them.
But if they are not split correct you should adjust them.
Some of your colleagues mark their tests with a leading and trailing underscore.
Don't remove this.
And of course you should handle empty strings to avoid unnecessary errors. Just return an empty string then.
Example:
`"Calculate15Plus5Equals20" => "Calculate_15_Plus_5_Equals_20"`
`"This_Is_Already_Split_Correct" => "This_Is_Already_Split_Correct"`
`"ThisIs_Not_SplitCorrect" => "This_Is_Not_Split_Correct"`
`"_UnderscoreMarked_Test_Name_" => _Underscore_Marked_Test_Name_"` | def toUnderScore(name):
if len(name) ==0:
return ""
hold=[]
for x in name:
hold.append(x)
for index, elem in enumerate(hold):
if index !=0:
test = hold[index-1]
if elem.isupper() and test != "_":
hold.insert(index, "_")
if elem.isdigit() and test.isalpha():
hold.insert(index, "_")
output= ''.join(hold)
return output
pass | def toUnderScore(name):
if len(name) ==0:
return ""
hold=[]
for x in name:
hold.append(x)
for index, elem in enumerate(hold):
if index !=0:
test = hold[index-1]
if elem.isupper() and test != "_":
hold.insert(index, "_")
if elem.isdigit() and test.isalpha():
hold.insert(index, "_")
output= ''.join(hold)
return output
pass | train | APPS_structured |
Zonal Computing Olympiad 2014, 30 Nov 2013
In IPL 2025, the amount that each player is paid varies from match to match. The match fee depends on the quality of opposition, the venue etc.
The match fees for each match in the new season have been announced in advance. Each team has to enforce a mandatory rotation policy so that no player ever plays three matches in a row during the season.
Nikhil is the captain and chooses the team for each match. He wants to allocate a playing schedule for himself to maximize his earnings through match fees during the season.
-----Input format-----
Line 1: A single integer N, the number of games in the IPL season.
Line 2: N non-negative integers, where the integer in
position i represents the fee for match i.
-----Output format-----
The output consists of a single non-negative integer, the
maximum amount of money that Nikhil can earn during this IPL
season.
-----Sample Input 1-----
5
10 3 5 7 3
-----Sample Output 1-----
23
(Explanation: 10+3+7+3)
-----Sample Input 2-----
8
3 2 3 2 3 5 1 3
-----Sample Output 2-----
17
(Explanation: 3+3+3+5+3)
-----Test data-----
There is only one subtask worth 100 marks. In all inputs:
• 1 ≤ N ≤ 2×105
• The fee for each match is between 0 and 104, inclusive.
-----Live evaluation data-----
There are 12 test inputs on the server during the exam. | # cook your dish here
no = int(input())
alls = list(input().split())
dp = [0]*(no+1)
if(no==1):
dp[1]=alls[0]
print(dp[1])
elif(no==2):
dp[2] = int(alls[1])+int(alls[0])
print(dp[2])
elif(no>=3):
dp[1]= int(alls[0])
dp[2] = int(alls[1])+int(alls[0])
a = int(alls[0])+int(alls[1])
b = int(alls[1])+int(alls[2])
c = int(alls[0])+int(alls[2])
dp[3] = max(a,b,c)
for x in range(4,(no+1)):
d = int(dp[x-2]) + int(alls[x-1])
e = int(dp[x-1])
f = int(dp[x-3]+int(alls[x-2])+int(alls[x-1]))
dp[x] = max(d,e,f)
print(dp[no])
| # cook your dish here
no = int(input())
alls = list(input().split())
dp = [0]*(no+1)
if(no==1):
dp[1]=alls[0]
print(dp[1])
elif(no==2):
dp[2] = int(alls[1])+int(alls[0])
print(dp[2])
elif(no>=3):
dp[1]= int(alls[0])
dp[2] = int(alls[1])+int(alls[0])
a = int(alls[0])+int(alls[1])
b = int(alls[1])+int(alls[2])
c = int(alls[0])+int(alls[2])
dp[3] = max(a,b,c)
for x in range(4,(no+1)):
d = int(dp[x-2]) + int(alls[x-1])
e = int(dp[x-1])
f = int(dp[x-3]+int(alls[x-2])+int(alls[x-1]))
dp[x] = max(d,e,f)
print(dp[no])
| train | APPS_structured |
For every string, after every occurrence of `'and'` and `'but'`, insert the substring `'apparently'` directly after the occurrence.
If input does not contain 'and' or 'but', return the original string. If a blank string, return `''`.
If substring `'apparently'` is already directly after an `'and'` and/or `'but'`, do not add another. (Do not add duplicates).
# Examples:
Input 1
'It was great and I've never been on live television before but sometimes I don't watch this.'
Output 1
'It was great and apparently I've never been on live television before but apparently sometimes I don't watch this.'
Input 2
'but apparently'
Output 2
'but apparently'
(no changes because `'apparently'` is already directly after `'but'` and there should not be a duplicate.)
An occurrence of `'and'` and/or `'but'` only counts when it is at least one space separated. For example `'andd'` and `'bbut'` do not count as occurrences, whereas `'b but'` and `'and d'` does count.
reference that may help:
https://www.youtube.com/watch?v=rz5TGN7eUcM | import re
def apparently(string):
return re.sub(r'\b(and|but)\b(?! apparently\b)', r'\1 apparently', string) | import re
def apparently(string):
return re.sub(r'\b(and|but)\b(?! apparently\b)', r'\1 apparently', string) | train | APPS_structured |
### Context and Definitions
You are in charge of developing a new cool JavaScript library that provides functionality similar to that of [Underscore.js](http://underscorejs.org/).
You have started by adding a new **list data type** to your library. You came up with a design of a data structure that represents an [algebraic data type](http://en.wikipedia.org/wiki/Algebraic_data_type) as a pair of elements:
```python
class Cons:
def __init__(self, head, tail):
self.head = head
self.tail = tail
```
You are pretty smart, because using this new data type, we can easily build a list of elements. For instance, a list of numbers:
```python
numbers = Cons(1, Cons(2, Cons(3, Cons(4, Cons(5, None)))))
```
In a code review with your boss, you explained him how every *cons cell* contains a "value" in its head, and in its tail it contains either another cons cell or null. We know we have reached the end of the data structure when the tail is null.
So, your boss is pretty excited about this new data structure and wants to know if you will be able to build some more functionality around it. In a demo you did this week for the rest of your team, in order to illustrate how this works, you showed them a method to transform a list of items of your list data type into a JavaScript array:
```python
# added to the class implementation:
def to_array(self):
tail = self.tail
new_tail = (tail.to_array() if tail is not None else [])
return [self.head] + new_tail
```
And they were amazed when you simply did this:
```python
print(numbers.to_array()) # yields [1,2,3,4,5]
```
### The New Requirements
Now, the team is convinced that this is the way to go and they would like to build the library around this cool new data type, but they want you to provide a few more features for them so that they can start using this type in solving some real world problems.
You have been reading about a technique called [applicative programming](http://quod.lib.umich.edu/s/spobooks/bbv9810.0001.001/1:15?rgn=div1;view=fulltext) which basically consists in applying a function to every element in a list. So, you gave it some thought and you have decided to start adding features like **filter**, **map** and **reduce**. Basically you want to provide equivalent functionality to that of JavaScript arrays and in the future even more.
So, you will now add:
- [filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2Ffilter): create a new algebraic list containing only the elements that satisfy a predicate function.
- [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2Ffilter) : create a new list in which every element is the result of applying a function provided as argument.
- fromArray: a convenient complementary method that creates a list out of a JavaScript array.
For this Kata, the definition of `Cons` and the prototypal/class method `toArray`/`to_array`/`into_vec` are already loaded in your environment.
### Examples of Usage
```python
numbers = Cons.from_array([1,2,3,4,5])
numbers.filter(lambda x: x % 2 == 0).to_array() # yields [2,4]
numbers.map(lambda x: x * x).to_array() # yields [1,4,9,16,25]
digits = Cons.from_array(["1","2","3","4","5"])
integers = digits.map(int) \
.filter(lambda n: n > 3) \
.to_array() # yields [4,5]
```
In other words:
- The static method `Cons.fromArray` (or `from_array`, `from_iter`) produces `Cons(1, Cons(2, Cons(3, Cons 4, Cons 5, null)))))`.
- Above filter creates a new list: `Cons(2, Cons(4, null))`.
- So does above map: `Cons(1, Cos(4, Cons(9, Cons(16, Cons(25, null)))))`. | class Cons:
def __init__(self, head, tail):
self.head = head
self.tail = tail
def to_array(self):
return [self.head] + (self.tail.to_array() if self.tail is not None else [])
@classmethod
def from_array(cls, arr):
if not arr:
return None
return Cons(arr.pop(0), Cons.from_array(arr) if arr else None)
def filter(self, fn):
return Cons.from_array(list(filter(fn, self.to_array())))
def map(self, fn):
return Cons.from_array(list(map(fn, self.to_array()))) | class Cons:
def __init__(self, head, tail):
self.head = head
self.tail = tail
def to_array(self):
return [self.head] + (self.tail.to_array() if self.tail is not None else [])
@classmethod
def from_array(cls, arr):
if not arr:
return None
return Cons(arr.pop(0), Cons.from_array(arr) if arr else None)
def filter(self, fn):
return Cons.from_array(list(filter(fn, self.to_array())))
def map(self, fn):
return Cons.from_array(list(map(fn, self.to_array()))) | train | APPS_structured |
Barney lives in country USC (United States of Charzeh). USC has n cities numbered from 1 through n and n - 1 roads between them. Cities and roads of USC form a rooted tree (Barney's not sure why it is rooted). Root of the tree is the city number 1. Thus if one will start his journey from city 1, he can visit any city he wants by following roads.
[Image]
Some girl has stolen Barney's heart, and Barney wants to find her. He starts looking for in the root of the tree and (since he is Barney Stinson not a random guy), he uses a random DFS to search in the cities. A pseudo code of this algorithm is as follows:
let starting_time be an array of length n
current_time = 0
dfs(v):
current_time = current_time + 1
starting_time[v] = current_time
shuffle children[v] randomly (each permutation with equal possibility)
// children[v] is vector of children cities of city v
for u in children[v]:
dfs(u)
As told before, Barney will start his journey in the root of the tree (equivalent to call dfs(1)).
Now Barney needs to pack a backpack and so he wants to know more about his upcoming journey: for every city i, Barney wants to know the expected value of starting_time[i]. He's a friend of Jon Snow and knows nothing, that's why he asked for your help.
-----Input-----
The first line of input contains a single integer n (1 ≤ n ≤ 10^5) — the number of cities in USC.
The second line contains n - 1 integers p_2, p_3, ..., p_{n} (1 ≤ p_{i} < i), where p_{i} is the number of the parent city of city number i in the tree, meaning there is a road between cities numbered p_{i} and i in USC.
-----Output-----
In the first and only line of output print n numbers, where i-th number is the expected value of starting_time[i].
Your answer for each city will be considered correct if its absolute or relative error does not exceed 10^{ - 6}.
-----Examples-----
Input
7
1 2 1 1 4 4
Output
1.0 4.0 5.0 3.5 4.5 5.0 5.0
Input
12
1 1 2 2 4 4 3 3 1 10 8
Output
1.0 5.0 5.5 6.5 7.5 8.0 8.0 7.0 7.5 6.5 7.5 8.0 | n = int(input())
pos,tree,ans,sz = list(map(int,input().split())) if n > 1 else [],[],[],[]
for i in range(n):
tree.append([])
ans.append(0.0)
sz.append(0)
for i in range(n-1):
tree[pos[i]-1].append(i+1)
for i in range(n)[::-1]:
sz[i] = 1
for to in tree[i]:
sz[i] += sz[to]
for i in range(n):
for to in tree[i]:
ans[to] = ans[i] + 1 + (sz[i]-1-sz[to]) * 0.5
st = lambda i: str(i+1)
print(' '.join(list(map(st,ans)))) | n = int(input())
pos,tree,ans,sz = list(map(int,input().split())) if n > 1 else [],[],[],[]
for i in range(n):
tree.append([])
ans.append(0.0)
sz.append(0)
for i in range(n-1):
tree[pos[i]-1].append(i+1)
for i in range(n)[::-1]:
sz[i] = 1
for to in tree[i]:
sz[i] += sz[to]
for i in range(n):
for to in tree[i]:
ans[to] = ans[i] + 1 + (sz[i]-1-sz[to]) * 0.5
st = lambda i: str(i+1)
print(' '.join(list(map(st,ans)))) | train | APPS_structured |
Given a positive integer `n`, return first n dgits of Thue-Morse sequence, as a string (see examples).
Thue-Morse sequence is a binary sequence with 0 as the first element. The rest of the sequece is obtained by adding the Boolean (binary) complement of a group obtained so far.
```
For example:
0
01
0110
01101001
and so on...
```
![alt](https://upload.wikimedia.org/wikipedia/commons/f/f1/Morse-Thue_sequence.gif)
Ex.:
```python
thue_morse(1); #"0"
thue_morse(2); #"01"
thue_morse(5); #"01101"
thue_morse(10): #"0110100110"
```
- You don't need to test if n is valid - it will always be a positive integer.
- `n` will be between 1 and 10000
[Thue-Morse on Wikipedia](https://en.wikipedia.org/wiki/Thue%E2%80%93Morse_sequence)
[Another kata on Thue-Morse](https://www.codewars.com/kata/simple-fun-number-106-is-thue-morse) by @myjinxin2015 | import math
def thue_morse(n):
return morse(2**((math.log2(n)//1 +1)))[0:n]
def morse(m):
return morse(m/2)+"".join([str(int(i)^1) for i in morse(m/2)]) if m>1 else "0" | import math
def thue_morse(n):
return morse(2**((math.log2(n)//1 +1)))[0:n]
def morse(m):
return morse(m/2)+"".join([str(int(i)^1) for i in morse(m/2)]) if m>1 else "0" | train | APPS_structured |
Given a certain number, how many multiples of three could you obtain with its digits?
Suposse that you have the number 362. The numbers that can be generated from it are:
```
362 ----> 3, 6, 2, 36, 63, 62, 26, 32, 23, 236, 263, 326, 362, 623, 632
```
But only:
```3, 6, 36, 63``` are multiple of three.
We need a function that can receive a number ann may output in the following order:
- the amount of multiples
- the maximum multiple
Let's see a case the number has a the digit 0 and repeated digits:
```
6063 ----> 0, 3, 6, 30, 36, 60, 63, 66, 306, 360, 366, 603, 606, 630, 636, 660, 663, 3066, 3606, 3660, 6036, 6063, 6306, 6360, 6603, 6630
```
In this case the multiples of three will be all except 0
```
6063 ----> 3, 6, 30, 36, 60, 63, 66, 306, 360, 366, 603, 606, 630, 636, 660, 663, 3066, 3606, 3660, 6036, 6063, 6306, 6360, 6603, 6630
```
The cases above for the function:
```python
find_mult_3(362) == [4, 63]
find_mult_3(6063) == [25, 6630]
```
In Javascript ```findMult_3()```.
The function will receive only positive integers (num > 0), and you don't have to worry for validating the entries.
Features of the random tests:
```
Number of test = 100
1000 ≤ num ≤ 100000000
```
Enjoy it!! | from functools import reduce
# get a len = 10 array with occurrences of digits
def num_to_arr(num):
s = str(num)
arr = [0] * 10
for c in s:
arr[int(c)] += 1
return arr
# get an array of distinctive digits in an array as above
def dist_digits(arr):
dist = []
for i in range(0,10):
if arr[i] > 0:
dist.append(i)
return dist
# get all combos given number of digits (m) and an array as above
def all_combos(arr, m):
combos = []
if m == 1:
for i in range(1,10):
if arr[i] > 0:
combos.append([i])
return combos
if m > sum(arr):
return []
digits = dist_digits(arr)
for d in digits:
nextArr = [0] * 10
for i in range(0,10):
if i == d:
nextArr[i] = arr[i] - 1
if i > d:
nextArr[i] = arr[i]
nextCombos = all_combos(nextArr, m - 1)
for nextComb in nextCombos:
nextComb.append(d)
combos.extend(nextCombos)
return combos
# now give all combos with all possible numbers of digits that % 3 == 0
def complete_combos(arr):
combos = []
for i in range(1, len(arr)):
combos.extend(all_combos(arr,i))
return list([arr for arr in combos if sum(arr) % 3 == 0])
def fact(n, zeros = 0):
if n == 0: return 1
if n == 1: return 1
return (n - zeros) * fact(n - 1)
def permus(combo):
arr = [0] * 10
for digit in combo:
arr[digit] += 1
duplicates = 1
for i in range(0,10):
if arr[i] > 1:
duplicates *= fact(arr[i])
return fact(len(combo), zeros = arr[0]) // duplicates
def find_mult_3(num):
# your code here
comp_combos = complete_combos(num_to_arr(num))
return [sum(map(permus,comp_combos)), reduce(lambda x,y: x * 10 + y, comp_combos[-1])]
| from functools import reduce
# get a len = 10 array with occurrences of digits
def num_to_arr(num):
s = str(num)
arr = [0] * 10
for c in s:
arr[int(c)] += 1
return arr
# get an array of distinctive digits in an array as above
def dist_digits(arr):
dist = []
for i in range(0,10):
if arr[i] > 0:
dist.append(i)
return dist
# get all combos given number of digits (m) and an array as above
def all_combos(arr, m):
combos = []
if m == 1:
for i in range(1,10):
if arr[i] > 0:
combos.append([i])
return combos
if m > sum(arr):
return []
digits = dist_digits(arr)
for d in digits:
nextArr = [0] * 10
for i in range(0,10):
if i == d:
nextArr[i] = arr[i] - 1
if i > d:
nextArr[i] = arr[i]
nextCombos = all_combos(nextArr, m - 1)
for nextComb in nextCombos:
nextComb.append(d)
combos.extend(nextCombos)
return combos
# now give all combos with all possible numbers of digits that % 3 == 0
def complete_combos(arr):
combos = []
for i in range(1, len(arr)):
combos.extend(all_combos(arr,i))
return list([arr for arr in combos if sum(arr) % 3 == 0])
def fact(n, zeros = 0):
if n == 0: return 1
if n == 1: return 1
return (n - zeros) * fact(n - 1)
def permus(combo):
arr = [0] * 10
for digit in combo:
arr[digit] += 1
duplicates = 1
for i in range(0,10):
if arr[i] > 1:
duplicates *= fact(arr[i])
return fact(len(combo), zeros = arr[0]) // duplicates
def find_mult_3(num):
# your code here
comp_combos = complete_combos(num_to_arr(num))
return [sum(map(permus,comp_combos)), reduce(lambda x,y: x * 10 + y, comp_combos[-1])]
| train | APPS_structured |
-----Problem description.-----
This problem deals with the I/O methods used in codechef.
You are supposed to print the integer in its reverse form , or in simple words, print the reverse of the given integer . For instance , reverse of 120 is 21 (not 021) .
-----Input-----
- The first line of each test case contains an integer T .
- following T lines contains distinct integers N .
-----Output-----
- Output should contain T line , each line with the distinct integer as asked in question .
-----Constraints-----
- 1 ≤ T ≤ 105
- 1 ≤ N ≤ 1018
Subtask 1 : N ≤ 105
Subtask 2 : N ≤ 109
Subtask 3 : N ≤ 1018
-----Example-----
Input:
3
1234
4567
1
Output:
4321
7654
1
-----Explanation-----
reverse of 1234 is 4321 , 4567 is 7654 & of 1 is 1
NOTE: testcases may contain large range of data, use datatypes accordingly . | t= int(input());
while t>0 :
num = (input());
a=int(num[::-1]);
print(a);
t=t-1; | t= int(input());
while t>0 :
num = (input());
a=int(num[::-1]);
print(a);
t=t-1; | train | APPS_structured |
Jamie is a programmer, and James' girlfriend. She likes diamonds, and wants a diamond string from James. Since James doesn't know how to make this happen, he needs your help.
## Task
You need to return a string that looks like a diamond shape when printed on the screen, using asterisk (`*`) characters. Trailing spaces should be removed, and every line must be terminated with a newline character (`\n`).
Return `null/nil/None/...` if the input is an even number or negative, as it is not possible to print a diamond of even or negative size.
## Examples
A size 3 diamond:
```
*
***
*
```
...which would appear as a string of `" *\n***\n *\n"`
A size 5 diamond:
```
*
***
*****
***
*
```
...that is: `" *\n ***\n*****\n ***\n *\n"` | def diamond(n):
if n < 0 or n % 2 == 0:
return None
result = "*" * n + "\n";
spaces = 1;
n = n - 2
while n > 0:
current = " " * spaces + "*" * n + "\n"
spaces = spaces + 1
n = n - 2
result = current + result + current
return result | def diamond(n):
if n < 0 or n % 2 == 0:
return None
result = "*" * n + "\n";
spaces = 1;
n = n - 2
while n > 0:
current = " " * spaces + "*" * n + "\n"
spaces = spaces + 1
n = n - 2
result = current + result + current
return result | train | APPS_structured |
## Fixed xor
Write a function that takes two hex strings as input and XORs them against each other. If the strings are different lengths the output should be the length of the shortest string.
Hint: The strings would first need to be converted to binary to be XOR'd.
## Note:
If the two strings are of different lengths, the output string should be the same length as the smallest string. This means that the longer string will be cut down to the same size as the smaller string, then xor'd
### Further help
More information on the XOR operation can be found here https://www.khanacademy.org/computing/computer-science/cryptography/ciphers/a/xor-bitwise-operation
More information of the binary and hex bases can be found here https://www.khanacademy.org/math/algebra-home/alg-intro-to-algebra/algebra-alternate-number-bases/v/number-systems-introduction
Examples:
```python
fixed_xor("ab3f", "ac") == "07"
fixed_xor("aadf", "bce2") == "163d"
fixed_xor("1c0111001f010100061a024b53535009181c", "686974207468652062756c6c277320657965") == "746865206b696420646f6e277420706c6179"
``` | def fixed_xor(a, b):
l = min(len(a), len(b))
r = "" if not a[:l] else hex(int(a[:l], 16) ^ int(b[:l], 16))[2:]
return '0' * (l - len(r)) + r | def fixed_xor(a, b):
l = min(len(a), len(b))
r = "" if not a[:l] else hex(int(a[:l], 16) ^ int(b[:l], 16))[2:]
return '0' * (l - len(r)) + r | train | APPS_structured |
Similarly to the [previous kata](https://www.codewars.com/kata/string-subpattern-recognition-i/), you will need to return a boolean value if the base string can be expressed as the repetition of one subpattern.
This time there are two small changes:
* if a subpattern has been used, it will be repeated at least twice, meaning the subpattern has to be shorter than the original string;
* the strings you will be given might or might not be created repeating a given subpattern, then shuffling the result.
For example:
```python
has_subpattern("a") == False #no repeated shorter sub-pattern, just one character
has_subpattern("aaaa") == True #just one character repeated
has_subpattern("abcd") == False #no repetitions
has_subpattern("babababababababa") == True #repeated "ba"
has_subpattern("bbabbaaabbaaaabb") == True #same as above, just shuffled
```
Strings will never be empty and can be composed of any character (just consider upper- and lowercase letters as different entities) and can be pretty long (keep an eye on performances!).
If you liked it, go for either the [previous kata](https://www.codewars.com/kata/string-subpattern-recognition-i/) or the [next kata](https://www.codewars.com/kata/string-subpattern-recognition-iii/) of the series! | from collections import Counter
from functools import reduce
from math import gcd
def has_subpattern(s):
return reduce(gcd, Counter(s).values()) > 1 | from collections import Counter
from functools import reduce
from math import gcd
def has_subpattern(s):
return reduce(gcd, Counter(s).values()) > 1 | train | APPS_structured |
You are given a string S containing only lowercase characters.
You can rearrange the string and you have to print minimum number of characters needed(can be 0) to make it palindrome.
-----Input:-----
- First line contain an interger T denoting number of testcases.
- First line of each testcase contains integer N, size of string.
- Second line of each testcase contains string S.
-----Output:-----
For each test case, print a single line containing one integer ― the minimum number of characters needed(can be 0) to make it palindrome.
-----Constraints-----
- $1 \leq T \leq 1000$
- $1 \leq N \leq 10^5$
-----Sample Input:-----
3
1
a
9
abbbcbddd
6
abcdef
-----Sample Output:-----
0
2
5
-----EXPLANATION:-----
- Example case 1: a is already a palindrome.
- Example case 2: abbddcddbba is palindrome by adding 2 more characters.
- Example case 3: abdefcfedba is palindrome by adding 5 more characters. | for _ in range(int(input())):
n = int(input())
s = input()
dic = dict()
for i in range(n):
dic[s[i]] = dic.setdefault(s[i], 0) + 1
ans = 0
for i in dic:
if dic[i] % 2 != 0:
ans += 1
print(ans - 1 if ans > 0 else ans)
| for _ in range(int(input())):
n = int(input())
s = input()
dic = dict()
for i in range(n):
dic[s[i]] = dic.setdefault(s[i], 0) + 1
ans = 0
for i in dic:
if dic[i] % 2 != 0:
ans += 1
print(ans - 1 if ans > 0 else ans)
| train | APPS_structured |
You are given a integer $n$ ($n > 0$). Find any integer $s$ which satisfies these conditions, or report that there are no such numbers:
In the decimal representation of $s$: $s > 0$, $s$ consists of $n$ digits, no digit in $s$ equals $0$, $s$ is not divisible by any of it's digits.
-----Input-----
The input consists of multiple test cases. The first line of the input contains a single integer $t$ ($1 \leq t \leq 400$), the number of test cases. The next $t$ lines each describe a test case.
Each test case contains one positive integer $n$ ($1 \leq n \leq 10^5$).
It is guaranteed that the sum of $n$ for all test cases does not exceed $10^5$.
-----Output-----
For each test case, print an integer $s$ which satisfies the conditions described above, or "-1" (without quotes), if no such number exists. If there are multiple possible solutions for $s$, print any solution.
-----Example-----
Input
4
1
2
3
4
Output
-1
57
239
6789
-----Note-----
In the first test case, there are no possible solutions for $s$ consisting of one digit, because any such solution is divisible by itself.
For the second test case, the possible solutions are: $23$, $27$, $29$, $34$, $37$, $38$, $43$, $46$, $47$, $49$, $53$, $54$, $56$, $57$, $58$, $59$, $67$, $68$, $69$, $73$, $74$, $76$, $78$, $79$, $83$, $86$, $87$, $89$, $94$, $97$, and $98$.
For the third test case, one possible solution is $239$ because $239$ is not divisible by $2$, $3$ or $9$ and has three digits (none of which equals zero). | tc = int(input())
for _ in range(tc):
n = int(input())
if n > 1:
print("2" + "3" * (n-1))
else:
print(-1)
| tc = int(input())
for _ in range(tc):
n = int(input())
if n > 1:
print("2" + "3" * (n-1))
else:
print(-1)
| train | APPS_structured |
Chef works as a cook in a restaurant. Each morning, he has to drive down a straight road with length K$K$ to reach the restaurant from his home. Let's describe this road using a coordinate X$X$; the position of Chef's home is X=0$X = 0$ and the position of the restaurant is X=K$X = K$.
The road has exactly two lanes (numbered 1$1$ and 2$2$), but there are N$N$ obstacles (numbered 1$1$ through N$N$) on it. For each valid i$i$, the i$i$-th obstacle blocks the lane Li$L_i$ at the position X=Xi$X = X_i$ and does not block the other lane.
When driving, Chef cannot pass through an obstacle. He can switch lanes in zero time at any integer X$X$-coordinate which does not coincide with the X$X$-coordinate of any obstacle. However, whenever he switches lanes, he cannot switch again until driving for at least D$D$ units of distance, and he can travel only in the direction of increasing X$X$. Chef can start driving in any lane he wants. He can not switch lanes at non-integer X$X$-coordinate.
Sometimes, it is impossible to reach the restaurant without stopping at an obstacle. Find the maximum possible distance Chef can travel before he has to reach an obstacle which is in the same lane as him. If he can avoid all obstacles and reach the restaurant, the answer is K$K$.
-----Input-----
- The first line of the input contains a single integer T$T$ denoting the number of test cases. The description of T$T$ test cases follows.
- The first line of each test case contains three space-separated integers N$N$, K$K$ and D$D$.
- The second line contains N$N$ space-separated integers X1,X2,…,XN$X_1, X_2, \ldots, X_N$.
- The third line contains N$N$ space-separated integers L1,L2,…,LN$L_1, L_2, \ldots, L_N$.
-----Output-----
For each test case, print a single line containing one integer ― the maximum distance Chef can travel.
-----Constraints-----
- 1≤T≤1,000$1 \le T \le 1,000$
- 1≤N≤105$1 \le N \le 10^5$
- 2≤K≤109$2 \le K \le 10^9$
- 1≤D≤109$1 \le D \le 10^9$
- 1≤Xi≤K−1$1 \le X_i \le K-1$ for each valid i$i$
- Xi<Xi+1$X_i < X_{i+1}$ for each valid i$i$
- 1≤Li≤2$1 \le L_i \le 2$ for each valid i$i$
- the sum of N$N$ over all test cases does not exceed 106$10^6$
-----Subtasks-----
Subtask #1 (100 points): original constraints
-----Example Input-----
4
2 10 20
4 7
1 2
4 15 20
4 6 9 13
1 2 2 1
5 10 1
1 3 5 7 9
1 2 1 2 1
2 10 2
4 5
1 2
-----Example Output-----
10
13
10
5
-----Explanation-----
Example case 1: Chef can start in lane 2$2$ and switch to lane 1$1$ at the position X=6$X = 6$, then continue until reaching the restaurant.
Example case 2: Chef can start in lane 2$2$ and switch to lane 1$1$ at X=5$X = 5$. However, he cannot avoid the obstacle at X=13$X = 13$, because he has not driven for at least 20$20$ units since the last switch.
Example case 3: Chef should start in lane 2$2$ and then switch lanes at the positions X=2$X=2$, X=4$X=4$, X=6$X=6$ and X=8$X=8$. This way, he can reach the restaurant.
Example case 4: Chef can start in lane 2$2$ but he cannot escape the second obstacle at X$X$=5 since the first obstacle at X$X$=4 doesn't give enough space for Chef to switch lanes. | # cook your dish here
t = int(input())
for _ in range(t):
n, k, d = list(map(int, input().split()))
x = list(map(int, input().split()))
l = list(map(int, input().split()))
lane = 3 - l[0]
switched = -float('inf')
ans = k
for i in range(n):
if l[i] == lane:
if switched + d < x[i] and x[i - 1] + 1 < x[i]:
lane = 3 - lane
switched = max(x[i - 1] + 1, switched + d)
else:
ans = x[i]
break
print(ans)
| # cook your dish here
t = int(input())
for _ in range(t):
n, k, d = list(map(int, input().split()))
x = list(map(int, input().split()))
l = list(map(int, input().split()))
lane = 3 - l[0]
switched = -float('inf')
ans = k
for i in range(n):
if l[i] == lane:
if switched + d < x[i] and x[i - 1] + 1 < x[i]:
lane = 3 - lane
switched = max(x[i - 1] + 1, switched + d)
else:
ans = x[i]
break
print(ans)
| train | APPS_structured |
You have n super washing machines on a line. Initially, each washing machine has some dresses or is empty.
For each move, you could choose any m (1 ≤ m ≤ n) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time .
Given an integer array representing the number of dresses in each washing machine from left to right on the line, you should find the minimum number of moves to make all the washing machines have the same number of dresses. If it is not possible to do it, return -1.
Example1
Input: [1,0,5]
Output: 3
Explanation:
1st move: 1 0 1 1 4
2nd move: 1 2 1 3
3rd move: 2 1 2 2 2
Example2
Input: [0,3,0]
Output: 2
Explanation:
1st move: 0 1 2 0
2nd move: 1 2 --> 0 => 1 1 1
Example3
Input: [0,2,0]
Output: -1
Explanation:
It's impossible to make all the three washing machines have the same number of dresses.
Note:
The range of n is [1, 10000].
The range of dresses number in a super washing machine is [0, 1e5]. | class Solution:
def __init__(self):
pass
def findMinMoves(self, machines):
"""
:type machines: List[int]
:rtype: int
"""
N = len(machines)
if N == 0:
return 0
val_sum = sum(machines)
if val_sum%N != 0:
return -1
val_each = val_sum//N
go_left, go_right, net_change, max_step = 0, 0, 0, 0
for i in range(N):
go_left = -go_right
go_right = go_right + machines[i] - val_each
net_change = go_left + go_right
step = max(abs(go_left), abs(go_right), net_change)
max_step = max(max_step, step)
return max_step | class Solution:
def __init__(self):
pass
def findMinMoves(self, machines):
"""
:type machines: List[int]
:rtype: int
"""
N = len(machines)
if N == 0:
return 0
val_sum = sum(machines)
if val_sum%N != 0:
return -1
val_each = val_sum//N
go_left, go_right, net_change, max_step = 0, 0, 0, 0
for i in range(N):
go_left = -go_right
go_right = go_right + machines[i] - val_each
net_change = go_left + go_right
step = max(abs(go_left), abs(go_right), net_change)
max_step = max(max_step, step)
return max_step | train | APPS_structured |
Given an array of positive integers arr, calculate the sum of all possible odd-length subarrays.
A subarray is a contiguous subsequence of the array.
Return the sum of all odd-length subarrays of arr.
Example 1:
Input: arr = [1,4,2,5,3]
Output: 58
Explanation: The odd-length subarrays of arr and their sums are:
[1] = 1
[4] = 4
[2] = 2
[5] = 5
[3] = 3
[1,4,2] = 7
[4,2,5] = 11
[2,5,3] = 10
[1,4,2,5,3] = 15
If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58
Example 2:
Input: arr = [1,2]
Output: 3
Explanation: There are only 2 subarrays of odd length, [1] and [2]. Their sum is 3.
Example 3:
Input: arr = [10,11,12]
Output: 66
Constraints:
1 <= arr.length <= 100
1 <= arr[i] <= 1000 | class Solution:
def sumOddLengthSubarrays(self, arr: List[int]) -> int:
ans = 0
i = 0
j = 1
while True:
if i > len(arr)-1:
break
if len(arr[i:j]) % 2 != 0:
ans = ans + sum(arr[i:j])
j += 1
if j > len(arr):
i += 1
j = i+1
return ans
| class Solution:
def sumOddLengthSubarrays(self, arr: List[int]) -> int:
ans = 0
i = 0
j = 1
while True:
if i > len(arr)-1:
break
if len(arr[i:j]) % 2 != 0:
ans = ans + sum(arr[i:j])
j += 1
if j > len(arr):
i += 1
j = i+1
return ans
| train | APPS_structured |
Create a function that takes a list of one or more non-negative integers, and arranges them such that they form the largest possible number.
Examples:
`largestArrangement([4, 50, 8, 145])` returns 8504145 (8-50-4-145)
`largestArrangement([4, 40, 7])` returns 7440 (7-4-40)
`largestArrangement([4, 46, 7])` returns 7464 (7-46-4)
`largestArrangement([5, 60, 299, 56])` returns 60565299 (60-56-5-299)
`largestArrangement([5, 2, 1, 9, 50, 56])` returns 95655021 (9-56-5-50-21) | from itertools import permutations
def largest_arrangement(numbers):
return int(max(("".join(r) for r in permutations(list(map(str,numbers)))), key = int))
| from itertools import permutations
def largest_arrangement(numbers):
return int(max(("".join(r) for r in permutations(list(map(str,numbers)))), key = int))
| train | APPS_structured |
You are given a permutation $p_1, p_2, \dots, p_n$. Recall that sequence of $n$ integers is called a permutation if it contains all integers from $1$ to $n$ exactly once.
Find three indices $i$, $j$ and $k$ such that: $1 \le i < j < k \le n$; $p_i < p_j$ and $p_j > p_k$. Or say that there are no such indices.
-----Input-----
The first line contains a single integer $T$ ($1 \le T \le 200$) — the number of test cases.
Next $2T$ lines contain test cases — two lines per test case. The first line of each test case contains the single integer $n$ ($3 \le n \le 1000$) — the length of the permutation $p$.
The second line contains $n$ integers $p_1, p_2, \dots, p_n$ ($1 \le p_i \le n$; $p_i \neq p_j$ if $i \neq j$) — the permutation $p$.
-----Output-----
For each test case: if there are such indices $i$, $j$ and $k$, print YES (case insensitive) and the indices themselves; if there are no such indices, print NO (case insensitive).
If there are multiple valid triples of indices, print any of them.
-----Example-----
Input
3
4
2 1 4 3
6
4 6 1 2 5 3
5
5 3 1 2 4
Output
YES
2 3 4
YES
3 5 6
NO | T = int(input())
for _ in range(T):
n = int(input())
ls = list(map(int, input().split()))
ans = 'NO'
for i in range(1, n -1):
if ls[i] > ls[i-1] and ls[i] > ls[i+1]:
ans = 'YES'
break
if ans == 'NO':
print(ans)
else:
i += 1
print(ans)
print(i-1, i, i+1) | T = int(input())
for _ in range(T):
n = int(input())
ls = list(map(int, input().split()))
ans = 'NO'
for i in range(1, n -1):
if ls[i] > ls[i-1] and ls[i] > ls[i+1]:
ans = 'YES'
break
if ans == 'NO':
print(ans)
else:
i += 1
print(ans)
print(i-1, i, i+1) | train | APPS_structured |
Vasya is an active Internet user. One day he came across an Internet resource he liked, so he wrote its address in the notebook. We know that the address of the written resource has format: <protocol>://<domain>.ru[/<context>]
where: <protocol> can equal either "http" (without the quotes) or "ftp" (without the quotes), <domain> is a non-empty string, consisting of lowercase English letters, the /<context> part may not be present. If it is present, then <context> is a non-empty string, consisting of lowercase English letters.
If string <context> isn't present in the address, then the additional character "/" isn't written. Thus, the address has either two characters "/" (the ones that go before the domain), or three (an extra one in front of the context).
When the boy came home, he found out that the address he wrote in his notebook had no punctuation marks. Vasya must have been in a lot of hurry and didn't write characters ":", "/", ".".
Help Vasya to restore the possible address of the recorded Internet resource.
-----Input-----
The first line contains a non-empty string that Vasya wrote out in his notebook. This line consists of lowercase English letters only.
It is guaranteed that the given string contains at most 50 letters. It is guaranteed that the given string can be obtained from some correct Internet resource address, described above.
-----Output-----
Print a single line — the address of the Internet resource that Vasya liked. If there are several addresses that meet the problem limitations, you are allowed to print any of them.
-----Examples-----
Input
httpsunrux
Output
http://sun.ru/x
Input
ftphttprururu
Output
ftp://http.ru/ruru
-----Note-----
In the second sample there are two more possible answers: "ftp://httpruru.ru" and "ftp://httpru.ru/ru". | s = input()
if(s[0]=='h'):
s = s[:4]+'://'+s[4:]
else:
s = s[:3]+'://'+s[3:]
f=s.find("ru",s.find("://")+4)
s=s[:f]+"."+s[f:]
if(len(s)-f>3):
s=s[:f+3]+'/'+s[f+3:]
print(s)
| s = input()
if(s[0]=='h'):
s = s[:4]+'://'+s[4:]
else:
s = s[:3]+'://'+s[3:]
f=s.find("ru",s.find("://")+4)
s=s[:f]+"."+s[f:]
if(len(s)-f>3):
s=s[:f+3]+'/'+s[f+3:]
print(s)
| train | APPS_structured |
Write a function, which takes a non-negative integer (seconds) as input and returns the time in a human-readable format (`HH:MM:SS`)
* `HH` = hours, padded to 2 digits, range: 00 - 99
* `MM` = minutes, padded to 2 digits, range: 00 - 59
* `SS` = seconds, padded to 2 digits, range: 00 - 59
The maximum time never exceeds 359999 (`99:59:59`)
You can find some examples in the test fixtures. | def make_readable(n):
return f'{n//3600:02d}:{(n%3600)//60:02d}:{n%60:02d}'
| def make_readable(n):
return f'{n//3600:02d}:{(n%3600)//60:02d}:{n%60:02d}'
| train | APPS_structured |
An architect wants to construct a vaulted building supported by a family of arches Cn.
fn(x) = -nx - xlog(x) is the equation of the arch Cn where `x` is a positive real number (0 < x <= 1), `log(x)` is the natural logarithm (base e), `n` a non negative integer. Let fn(0) = 0.
Be An the point of Cn where the tangent to Cn is horizontal and Bn+1 the orthogonal projection of An on the x-axis (it means that An and Bn+1 have the same x -coordinate).
Kn is the intersection of Cn with the x-axis.
The figure shows C0, A0, B1, K0 as C(0), A0, B1, K0.
![alternative text](https://i.imgur.com/Td9aWIJ.png)
The architect wants to support each arch Cn with a wall of glass filling the **curved** surface An Bn+1 Kn under the curve Cn.
On the drawing you can see the surface `A0 B1 K0` in blue.
He asks if we could calculate the weight of the surface of glass he needs to support all arches C0...Cn where n is a positive integer knowing he can choose glass thickness hence glass weight per square unit of surface.
He gives us the absolute value of A0 B1 K0 area (in blue); call it `i0` which is approximately `0.14849853757254047` in square units.
## Task
Write the function `weight` with parameters `n` and `w` where `n` is the number of arches to consider (n >= 1) and `w` is the weight of a square unit of glass depending on the wall thickness.
This function should return the weight of n glass walls as described above.
## Example
```
weight(10, 700) -> 120.21882500408238
weight(8, 1108) -> 190.28922301858418
```
## Hint:
There is no integral to calculate. You can plot C1 and try to see the relationship between the different Cn and then use `i0`.
## Note:
- don't round or truncate your result | from math import e
def weight(n, w):
return -0.17174117862516716*(e**(-2*n) - 1)*w | from math import e
def weight(n, w):
return -0.17174117862516716*(e**(-2*n) - 1)*w | train | APPS_structured |
Alice plays the following game, loosely based on the card game "21".
Alice starts with 0 points, and draws numbers while she has less than K points. During each draw, she gains an integer number of points randomly from the range [1, W], where W is an integer. Each draw is independent and the outcomes have equal probabilities.
Alice stops drawing numbers when she gets K or more points. What is the probability that she has N or less points?
Example 1:
Input: N = 10, K = 1, W = 10
Output: 1.00000
Explanation: Alice gets a single card, then stops.
Example 2:
Input: N = 6, K = 1, W = 10
Output: 0.60000
Explanation: Alice gets a single card, then stops.
In 6 out of W = 10 possibilities, she is at or below N = 6 points.
Example 3:
Input: N = 21, K = 17, W = 10
Output: 0.73278
Note:
0 <= K <= N <= 10000
1 <= W <= 10000
Answers will be accepted as correct if they are within 10^-5 of the correct answer.
The judging time limit has been reduced for this question. | class Solution:
def new21Game(self, N: int, K: int, W: int) -> float:
if K==0 or K-1+W<=N:
return 1
dp=[1]+[0]*N
cursum=1
for i in range(1,N+1):
# dp[i]=sum(dp[max(0,i-W):min(i,K)])*(1/W)
dp[i]=cursum*(1/W)
if i<K:
cursum+=dp[i]
if i>=W:
cursum-=dp[i-W]
return sum(dp[K:]) | class Solution:
def new21Game(self, N: int, K: int, W: int) -> float:
if K==0 or K-1+W<=N:
return 1
dp=[1]+[0]*N
cursum=1
for i in range(1,N+1):
# dp[i]=sum(dp[max(0,i-W):min(i,K)])*(1/W)
dp[i]=cursum*(1/W)
if i<K:
cursum+=dp[i]
if i>=W:
cursum-=dp[i-W]
return sum(dp[K:]) | train | APPS_structured |
Write a function getMean that takes as parameters an array (arr) and 2 integers (x and y). The function should return the mean between the mean of the the first x elements of the array and the mean of the last y elements of the array.
The mean should be computed if both x and y have values higher than 1 but less or equal to the array's length. Otherwise the function should return -1.
getMean([1,3,2,4], 2, 3) should return 2.5 because: the mean of the the first 2 elements of the array is (1+3)/2=2 and the mean of the last 3 elements of the array is (4+2+3)/3=3 so the mean of those 2 means is (2+3)/2=2.5.
getMean([1,3,2,4], 1, 2) should return -1 because x is not higher than 1.
getMean([1,3,2,4], 2, 8) should return -1 because 8 is higher than the array's length. | def get_mean(arr, x, y):
l = len(arr)
if 1 < x <= l and 1 < y <= l:
mx = sum(arr[:x]) / x
my = sum(arr[-y:]) / y
return (mx + my) / 2
else:
return -1
| def get_mean(arr, x, y):
l = len(arr)
if 1 < x <= l and 1 < y <= l:
mx = sum(arr[:x]) / x
my = sum(arr[-y:]) / y
return (mx + my) / 2
else:
return -1
| train | APPS_structured |
A balanced parenthesis string is defined as follows:
- The empty string is balanced
- If P is balanced, (P) is also
- If P and Q are balanced, PQ is also balanced
You are given two even integers n$n$ and k$k$. Find any balanced paranthesis string of length n$n$ that doesn't contain a balanced substring of length k$k$, or claim that no such string exists.
-----Input-----
- First line will contain T$T$, number of testcases. Then the testcases follow.
- Each testcase contains of a single line containing n$n$ and k$k$.
-----Output-----
For every testcase, print on a new line, any balanced paranthesis string of length n$n$ that doesn't contain a balanced substring of length k$k$. If there doesn't exist any such string, print −1$-1$ instead.
-----Constraints-----
- 1≤T≤50000$1 \leq T \leq 50000$
- 2≤k≤n≤105$2 \leq k \leq n \leq 10^5$
- Sum of n$n$ over all testcases doesn't exceed 105$10^5$.
- n$n$ and k$k$ are both even integers.
-----Example Input-----
2
4 2
8 6
-----Example Output-----
-1
(())(())
-----Explanation-----
In the first testcase, the only balanced strings of length 4$4$ are (()) and ()(), both of which contain () as a substring.
In the second testcase, (())(()) is a balanced string that doesn't contain any balanced substring of length 6$6$. | import sys
def input():
return sys.stdin.readline().strip()
for i in range(int(input())):
n, k = map(int, input().split())
arr = []
if k == 2 or k == 4 or n % 2 != 0 or n == k:
arr.append('-1')
elif k % 2 != 0:
for i in range(int(n / 2)):
arr.append('(')
for i in range(int(n / 2)):
arr.append(')')
elif int(n / (k - 2)) == 1:
if (n - 2) % 4 == 0:
for i in range(int((n - 2) / 4)):
arr.append('(')
for i in range(int((n - 2) / 4)):
arr.append(')')
arr.append('()')
for i in range(int((n - 2) / 4)):
arr.append('(')
for i in range(int((n - 2) / 4)):
arr.append(')')
else:
for i in range(int((n - 4) / 4)):
arr.append('(')
for i in range(int((n - 4) / 4)):
arr.append(')')
arr.append('(())')
for i in range(int((n - 4) / 4)):
arr.append('(')
for i in range(int((n - 4) / 4)):
arr.append(')')
else:
for i in range(int((n % (k - 2)) / 2)):
arr.append('(')
for i in range(int(n / (k - 2))):
for j in range(int((k - 2) / 2)):
arr.append('(')
for j in range(int((k - 2) / 2)):
arr.append(')')
for i in range(int((n % (k - 2)) / 2)):
arr.append(')')
print("".join(arr))
| import sys
def input():
return sys.stdin.readline().strip()
for i in range(int(input())):
n, k = map(int, input().split())
arr = []
if k == 2 or k == 4 or n % 2 != 0 or n == k:
arr.append('-1')
elif k % 2 != 0:
for i in range(int(n / 2)):
arr.append('(')
for i in range(int(n / 2)):
arr.append(')')
elif int(n / (k - 2)) == 1:
if (n - 2) % 4 == 0:
for i in range(int((n - 2) / 4)):
arr.append('(')
for i in range(int((n - 2) / 4)):
arr.append(')')
arr.append('()')
for i in range(int((n - 2) / 4)):
arr.append('(')
for i in range(int((n - 2) / 4)):
arr.append(')')
else:
for i in range(int((n - 4) / 4)):
arr.append('(')
for i in range(int((n - 4) / 4)):
arr.append(')')
arr.append('(())')
for i in range(int((n - 4) / 4)):
arr.append('(')
for i in range(int((n - 4) / 4)):
arr.append(')')
else:
for i in range(int((n % (k - 2)) / 2)):
arr.append('(')
for i in range(int(n / (k - 2))):
for j in range(int((k - 2) / 2)):
arr.append('(')
for j in range(int((k - 2) / 2)):
arr.append(')')
for i in range(int((n % (k - 2)) / 2)):
arr.append(')')
print("".join(arr))
| train | APPS_structured |
Polycarp took $n$ videos, the duration of the $i$-th video is $a_i$ seconds. The videos are listed in the chronological order, i.e. the $1$-st video is the earliest, the $2$-nd video is the next, ..., the $n$-th video is the last.
Now Polycarp wants to publish exactly $k$ ($1 \le k \le n$) posts in Instabram. Each video should be a part of a single post. The posts should preserve the chronological order, it means that the first post should contain one or more of the earliest videos, the second post should contain a block (one or more videos) going next and so on. In other words, if the number of videos in the $j$-th post is $s_j$ then:
$s_1+s_2+\dots+s_k=n$ ($s_i>0$), the first post contains the videos: $1, 2, \dots, s_1$; the second post contains the videos: $s_1+1, s_1+2, \dots, s_1+s_2$; the third post contains the videos: $s_1+s_2+1, s_1+s_2+2, \dots, s_1+s_2+s_3$; ... the $k$-th post contains videos: $n-s_k+1,n-s_k+2,\dots,n$.
Polycarp is a perfectionist, he wants the total duration of videos in each post to be the same.
Help Polycarp to find such positive integer values $s_1, s_2, \dots, s_k$ that satisfy all the conditions above.
-----Input-----
The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 10^5$). The next line contains $n$ positive integer numbers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^4$), where $a_i$ is the duration of the $i$-th video.
-----Output-----
If solution exists, print "Yes" in the first line. Print $k$ positive integers $s_1, s_2, \dots, s_k$ ($s_1+s_2+\dots+s_k=n$) in the second line. The total duration of videos in each post should be the same. It can be easily proven that the answer is unique (if it exists).
If there is no solution, print a single line "No".
-----Examples-----
Input
6 3
3 3 1 4 1 6
Output
Yes
2 3 1
Input
3 3
1 1 1
Output
Yes
1 1 1
Input
3 3
1 1 2
Output
No
Input
3 1
1 10 100
Output
Yes
3 | n,k=map(int,input().split())
arr=list(map(int,input().split()))
ansarr=[]
m=0
su=0
ans=0
s=sum(arr)
le=s//k;
if(s%k!=0):
print('No')
return
else:
for i in range(n):
su+=arr[m]
m+=1
ans+=1
if(su==le):
ansarr.append(ans)
ans=0
su=0
elif(su>le):
print('No')
return
print('Yes')
print(*ansarr) | n,k=map(int,input().split())
arr=list(map(int,input().split()))
ansarr=[]
m=0
su=0
ans=0
s=sum(arr)
le=s//k;
if(s%k!=0):
print('No')
return
else:
for i in range(n):
su+=arr[m]
m+=1
ans+=1
if(su==le):
ansarr.append(ans)
ans=0
su=0
elif(su>le):
print('No')
return
print('Yes')
print(*ansarr) | train | APPS_structured |
Given N, count how many permutations of [1, 2, 3, ..., N] satisfy the following property.
Let P1, P2, ..., PN denote the permutation. The property we want to satisfy is that there exists an i between 2 and n-1 (inclusive) such that
- Pj > Pj + 1 ∀ i ≤ j ≤ N - 1.
- Pj > Pj - 1 ∀ 2 ≤ j ≤ i.
-----Input-----
First line contains T, the number of test cases. Each test case consists of N in one line.
-----Output-----
For each test case, output the answer modulo 109+7.
-----Constraints-----
- 1 ≤ T ≤ 100
- 1 ≤ N ≤ 109
-----Subtasks-----
- Subtask #1(40 points): 1 ≤ N ≤ 1000
- Subtask #2(60 points): original constraints
-----Example-----
Input:
2
2
3
Output:
0
2
-----Explanation-----
Test case 1:
No permutation satisfies.
Test case 2:
Permutations [1, 3, 2] and [2, 3, 1] satisfy the property. | try:
for _ in range(int(input())):
n = int(input())
print(0) if(n==1) else print(pow(2,n-1,10**9+7)-2)
except EOFError:
pass
| try:
for _ in range(int(input())):
n = int(input())
print(0) if(n==1) else print(pow(2,n-1,10**9+7)-2)
except EOFError:
pass
| train | APPS_structured |
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array $a$ of $n$ non-negative integers.
Dark created that array $1000$ years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer $k$ ($0 \leq k \leq 10^{9}$) and replaces all missing elements in the array $a$ with $k$.
Let $m$ be the maximum absolute difference between all adjacent elements (i.e. the maximum value of $|a_i - a_{i+1}|$ for all $1 \leq i \leq n - 1$) in the array $a$ after Dark replaces all missing elements with $k$.
Dark should choose an integer $k$ so that $m$ is minimized. Can you help him?
-----Input-----
The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \leq t \leq 10^4$) — the number of test cases. The description of the test cases follows.
The first line of each test case contains one integer $n$ ($2 \leq n \leq 10^{5}$) — the size of the array $a$.
The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($-1 \leq a_i \leq 10 ^ {9}$). If $a_i = -1$, then the $i$-th integer is missing. It is guaranteed that at least one integer is missing in every test case.
It is guaranteed, that the sum of $n$ for all test cases does not exceed $4 \cdot 10 ^ {5}$.
-----Output-----
Print the answers for each test case in the following format:
You should print two integers, the minimum possible value of $m$ and an integer $k$ ($0 \leq k \leq 10^{9}$) that makes the maximum absolute difference between adjacent elements in the array $a$ equal to $m$.
Make sure that after replacing all the missing elements with $k$, the maximum absolute difference between adjacent elements becomes $m$.
If there is more than one possible $k$, you can print any of them.
-----Example-----
Input
7
5
-1 10 -1 12 -1
5
-1 40 35 -1 35
6
-1 -1 9 -1 3 -1
2
-1 -1
2
0 -1
4
1 -1 3 -1
7
1 -1 7 5 2 -1 5
Output
1 11
5 35
3 6
0 42
0 0
1 2
3 4
-----Note-----
In the first test case after replacing all missing elements with $11$ the array becomes $[11, 10, 11, 12, 11]$. The absolute difference between any adjacent elements is $1$. It is impossible to choose a value of $k$, such that the absolute difference between any adjacent element will be $\leq 0$. So, the answer is $1$.
In the third test case after replacing all missing elements with $6$ the array becomes $[6, 6, 9, 6, 3, 6]$. $|a_1 - a_2| = |6 - 6| = 0$; $|a_2 - a_3| = |6 - 9| = 3$; $|a_3 - a_4| = |9 - 6| = 3$; $|a_4 - a_5| = |6 - 3| = 3$; $|a_5 - a_6| = |3 - 6| = 3$.
So, the maximum difference between any adjacent elements is $3$. | from math import *
zzz = int(input())
for zz in range(zzz):
n = int(input())
a = [int(i) for i in input().split()]
b = set()
for i in range(n):
if a[i] == -1:
if i > 0:
if a[i-1] >= 0:
b.add(a[i-1])
if i < n - 1:
if a[i+1] >= 0:
b.add(a[i+1])
b = list(b)
if len(b) == 0:
print(0, 0)
else:
k = (min(b) + max(b)) // 2
m = 0
for i in range(n):
if a[i] == -1:
a[i] = k
for i in range(1, n):
m = max(m, abs(a[i-1]- a[i]))
print(m, k)
| from math import *
zzz = int(input())
for zz in range(zzz):
n = int(input())
a = [int(i) for i in input().split()]
b = set()
for i in range(n):
if a[i] == -1:
if i > 0:
if a[i-1] >= 0:
b.add(a[i-1])
if i < n - 1:
if a[i+1] >= 0:
b.add(a[i+1])
b = list(b)
if len(b) == 0:
print(0, 0)
else:
k = (min(b) + max(b)) // 2
m = 0
for i in range(n):
if a[i] == -1:
a[i] = k
for i in range(1, n):
m = max(m, abs(a[i-1]- a[i]))
print(m, k)
| train | APPS_structured |
Consider a sequence [a_1, a_2, ... , a_{n}]. Define its prefix product sequence $[ a_{1} \operatorname{mod} n,(a_{1} a_{2}) \operatorname{mod} n, \cdots,(a_{1} a_{2} \cdots a_{n}) \operatorname{mod} n ]$.
Now given n, find a permutation of [1, 2, ..., n], such that its prefix product sequence is a permutation of [0, 1, ..., n - 1].
-----Input-----
The only input line contains an integer n (1 ≤ n ≤ 10^5).
-----Output-----
In the first output line, print "YES" if such sequence exists, or print "NO" if no such sequence exists.
If any solution exists, you should output n more lines. i-th line contains only an integer a_{i}. The elements of the sequence should be different positive integers no larger than n.
If there are multiple solutions, you are allowed to print any of them.
-----Examples-----
Input
7
Output
YES
1
4
3
6
5
2
7
Input
6
Output
NO
-----Note-----
For the second sample, there are no valid sequences. | import math
import sys
input = sys.stdin.readline
n = int(input())
def isPrime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
if isPrime(n):
print('YES')
print('\n'.join(list(map(str, [1] + [i * pow(i - 1, n - 2, n) % n for i in range(2, n)] + [n]))[:n]))
elif n == 4:
print('YES')
print('\n'.join(map(str, [1, 3, 2, 4])))
else:
print('NO')
| import math
import sys
input = sys.stdin.readline
n = int(input())
def isPrime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
if isPrime(n):
print('YES')
print('\n'.join(list(map(str, [1] + [i * pow(i - 1, n - 2, n) % n for i in range(2, n)] + [n]))[:n]))
elif n == 4:
print('YES')
print('\n'.join(map(str, [1, 3, 2, 4])))
else:
print('NO')
| train | APPS_structured |
Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 positive integers. No floats or non-positive integers will be passed.
For example, when an array is passed like `[19, 5, 42, 2, 77]`, the output should be `7`.
`[10, 343445353, 3453445, 3453545353453]` should return `3453455`. | from heapq import nsmallest
def sum_two_smallest_numbers(numbers):
return sum(nsmallest(2,numbers)) | from heapq import nsmallest
def sum_two_smallest_numbers(numbers):
return sum(nsmallest(2,numbers)) | train | APPS_structured |
I love Fibonacci numbers in general, but I must admit I love some more than others.
I would like for you to write me a function that when given a number (n) returns the n-th number in the Fibonacci Sequence.
For example:
```python
nth_fib(4) == 2
```
Because 2 is the 4th number in the Fibonacci Sequence.
For reference, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two. | def nth_fib(n):
n -= 1
if n == 0: return 0
if n == 1: return 1
a, b, p, q = 1, 0, 0, 1
while n > 0:
if n % 2 == 0:
tp = p
p = p ** 2 + q ** 2
q = 2 * tp * q + q ** 2
n //= 2
else:
ta = a
a = b * q + a * q + a * p
b = b * p + ta * q
n -= 1
return b | def nth_fib(n):
n -= 1
if n == 0: return 0
if n == 1: return 1
a, b, p, q = 1, 0, 0, 1
while n > 0:
if n % 2 == 0:
tp = p
p = p ** 2 + q ** 2
q = 2 * tp * q + q ** 2
n //= 2
else:
ta = a
a = b * q + a * q + a * p
b = b * p + ta * q
n -= 1
return b | train | APPS_structured |
This kata is the first of a sequence of four about "Squared Strings".
You are given a string of `n` lines, each substring being `n` characters long: For example:
`s = "abcd\nefgh\nijkl\nmnop"`
We will study some transformations of this square of strings.
- Vertical mirror:
vert_mirror (or vertMirror or vert-mirror)
```
vert_mirror(s) => "dcba\nhgfe\nlkji\nponm"
```
- Horizontal mirror:
hor_mirror (or horMirror or hor-mirror)
```
hor_mirror(s) => "mnop\nijkl\nefgh\nabcd"
```
or printed:
```
vertical mirror |horizontal mirror
abcd --> dcba |abcd --> mnop
efgh hgfe |efgh ijkl
ijkl lkji |ijkl efgh
mnop ponm |mnop abcd
```
# Task:
- Write these two functions
and
- high-order function `oper(fct, s)` where
- fct is the function of one variable f to apply to the string `s`
(fct will be one of `vertMirror, horMirror`)
# Examples:
```
s = "abcd\nefgh\nijkl\nmnop"
oper(vert_mirror, s) => "dcba\nhgfe\nlkji\nponm"
oper(hor_mirror, s) => "mnop\nijkl\nefgh\nabcd"
```
# Note:
The form of the parameter `fct` in oper
changes according to the language. You can see each form according to the language in "Sample Tests".
# Bash Note:
The input strings are separated by `,` instead of `\n`. The output strings should be separated by `\r` instead of `\n`. See "Sample Tests".
Forthcoming katas will study other transformations. | def vert_mirror(s):
return '\n'.join(_[::-1] for _ in s.split())
def hor_mirror(s):
return '\n'.join(s.split()[::-1])
def oper(fct, s):
return fct(s)
# Flez
| def vert_mirror(s):
return '\n'.join(_[::-1] for _ in s.split())
def hor_mirror(s):
return '\n'.join(s.split()[::-1])
def oper(fct, s):
return fct(s)
# Flez
| train | APPS_structured |
The Monty Hall problem is a probability puzzle base on the American TV show "Let's Make A Deal".
In this show, you would be presented with 3 doors: One with a prize behind it, and two without (represented with goats).
After choosing a door, the host would open one of the other two doors which didn't include a prize, and ask the participant if he or she wanted to switch to the third door. Most wouldn't. One would think you have a fifty-fifty chance of winning after having been shown a false door, however the math proves that you significantly increase your chances, from 1/3 to 2/3 by switching.
Further information about this puzzle can be found on https://en.wikipedia.org/wiki/Monty_Hall_problem.
In this program you are given an array of people who have all guessed on a door from 1-3, as well as given the door which includes the price. You need to make every person switch to the other door, and increase their chances of winning. Return the win percentage (as a rounded int) of all participants. | def monty_hall(correct, guesses):
return round(100-100.0*guesses.count(correct)/len(guesses)) | def monty_hall(correct, guesses):
return round(100-100.0*guesses.count(correct)/len(guesses)) | train | APPS_structured |
Your job is to write a function that takes a string and a maximum number of characters per line and then inserts line breaks as necessary so that no line in the resulting string is longer than the specified limit.
If possible, line breaks should not split words. However, if a single word is longer than the limit, it obviously has to be split. In this case, the line break should be placed after the first part of the word (see examples below).
Really long words may need to be split multiple times.
#Input
A word consists of one or more letters.
Input text will be the empty string or a string consisting of one or more words separated by single spaces. It will not contain any punctiation or other special characters.
The limit will always be an integer greater or equal to one.
#Examples
**Note:** Line breaks in the results have been replaced with two dashes to improve readability.
1. ("test", 7) -> "test"
2. ("hello world", 7) -> "hello--world"
3. ("a lot of words for a single line", 10) -> "a lot of--words for--a single--line"
4. ("this is a test", 4) -> "this--is a--test"
5. ("a longword", 6) -> "a long--word"
6. ("areallylongword", 6) -> "areall--ylongw--ord"
**Note:** Sometimes spaces are hard to see in the test results window. | # rule: if a word is longer than limit, split it anyway
def word_wrap(text, limit):
answer = []
words = text.split()[::-1]
line = ""
while words:
word = words.pop()
if not line:
if len(word) <= limit:
line += word
else:
line += word[:limit]
words.append(word[limit:])
else:
if len(line) + 1 + len(word) <= limit:
line += " " + word
elif len(word) > limit:
upto = limit - len(line) - 1
line += " " + word[:upto]
words.append(word[upto:])
lenNext = len(words[-1]) if words else 0
if not words or len(line) == limit or\
(lenNext <= limit and len(line) + 1 + lenNext > limit):
answer.append(line)
line = ""
return "\n".join(answer) | # rule: if a word is longer than limit, split it anyway
def word_wrap(text, limit):
answer = []
words = text.split()[::-1]
line = ""
while words:
word = words.pop()
if not line:
if len(word) <= limit:
line += word
else:
line += word[:limit]
words.append(word[limit:])
else:
if len(line) + 1 + len(word) <= limit:
line += " " + word
elif len(word) > limit:
upto = limit - len(line) - 1
line += " " + word[:upto]
words.append(word[upto:])
lenNext = len(words[-1]) if words else 0
if not words or len(line) == limit or\
(lenNext <= limit and len(line) + 1 + lenNext > limit):
answer.append(line)
line = ""
return "\n".join(answer) | train | APPS_structured |
Hey, Path Finder, where are you?
## Path Finder Series:
- [#1: can you reach the exit?](https://www.codewars.com/kata/5765870e190b1472ec0022a2)
- [#2: shortest path](https://www.codewars.com/kata/57658bfa28ed87ecfa00058a)
- [#3: the Alpinist](https://www.codewars.com/kata/576986639772456f6f00030c)
- [#4: where are you?](https://www.codewars.com/kata/5a0573c446d8435b8e00009f)
- [#5: there's someone here](https://www.codewars.com/kata/5a05969cba2a14e541000129) | direction = [(1, 0), (0, 1), (-1, 0), (0, -1)]
operations = {'l': +1, 'r': -1, 'L': -2, 'R': 2}
vector = 2
position = [0, 0]
def i_am_here(path):
nonlocal vector, position
step = 0
for c in path:
if c.isnumeric():
step = step * 10 + int(c)
else:
if step > 0:
position = [position[0] + direction[vector][0]*step, position[1] + direction[vector][1]*step]
step = 0
step = 0
o = operations.get(c)
vector += o
vector %= len(direction)
if step > 0:
position = [position[0] + direction[vector][0] * step, position[1] + direction[vector][1] * step]
return position
| direction = [(1, 0), (0, 1), (-1, 0), (0, -1)]
operations = {'l': +1, 'r': -1, 'L': -2, 'R': 2}
vector = 2
position = [0, 0]
def i_am_here(path):
nonlocal vector, position
step = 0
for c in path:
if c.isnumeric():
step = step * 10 + int(c)
else:
if step > 0:
position = [position[0] + direction[vector][0]*step, position[1] + direction[vector][1]*step]
step = 0
step = 0
o = operations.get(c)
vector += o
vector %= len(direction)
if step > 0:
position = [position[0] + direction[vector][0] * step, position[1] + direction[vector][1] * step]
return position
| train | APPS_structured |
Given two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted order.
Return the intersection of these two interval lists.
(Formally, a closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b. The intersection of two closed intervals is a set of real numbers that is either empty, or can be represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].)
Example 1:
Input: A = [[0,2],[5,10],[13,23],[24,25]], B = [[1,5],[8,12],[15,24],[25,26]]
Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
Note:
0 <= A.length < 1000
0 <= B.length < 1000
0 <= A[i].start, A[i].end, B[i].start, B[i].end < 10^9 | class Solution:
def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
if not A or not B:
return []
res = []
i = j = 0
while i < len(A) and j < len(B):
s, e = max(A[i][0], B[j][0]), min(A[i][1], B[j][1])
if s <= e:
res.append([s, e])
if A[i][1] < B[j][1]:
i += 1
else:
j += 1
return res
| class Solution:
def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
if not A or not B:
return []
res = []
i = j = 0
while i < len(A) and j < len(B):
s, e = max(A[i][0], B[j][0]), min(A[i][1], B[j][1])
if s <= e:
res.append([s, e])
if A[i][1] < B[j][1]:
i += 1
else:
j += 1
return res
| train | APPS_structured |
Andrii is good in Math, but not in Programming. He is asking you to solve following problem: Given an integer number N and two sets of integer A and B. Let set A contain all numbers from 1 to N and set B contain all numbers from N + 1 to 2N. Multiset C contains all sums a + b such that a belongs to A and b belongs to B. Note that multiset may contain several elements with the same values. For example, if N equals to three, then A = {1, 2, 3}, B = {4, 5, 6} and C = {5, 6, 6, 7, 7, 7, 8, 8, 9}. Andrii has M queries about multiset C. Every query is defined by a single integer q. Andrii wants to know the number of times q is contained in C. For example, number 6 is contained two times, 1 is not contained in C at all.
Please, help Andrii to answer all the queries.
-----Input-----
The first line of the input contains two integers N and M. Each of the next M line contains one integer q, the query asked by Andrii.
-----Output-----
Output the answer for each query in separate lines as in example.
-----Constraints-----
- 1 ≤ N ≤ 109
- 1 ≤ M ≤ 105
- 1 ≤ q ≤ 3N
-----Example-----
Input:
3 5
6
2
9
7
5
Output:
2
0
1
3
1 | ans = []
N,M = [int(i) for i in input().split()]
for i in range(M):
q = int(input())
if(q<=N):
s = 0
elif(q<=2*N):
s = q-N-1
else:
s = N - (q-2*N-1)
ans.append(s)
for i in ans:
print(i)
| ans = []
N,M = [int(i) for i in input().split()]
for i in range(M):
q = int(input())
if(q<=N):
s = 0
elif(q<=2*N):
s = q-N-1
else:
s = N - (q-2*N-1)
ans.append(s)
for i in ans:
print(i)
| train | APPS_structured |
>
**Note**: This kata is a translation of this (Java) one: http://www.codewars.com/kata/rotate-array. I have not translated this first one as usual because I did not solved it, and I fear not being able to solve it (Java is **not** my cup of... tea). @cjmcgraw, if you want to use my translation on your kata feel free to use it.
Create a function named "rotate" that takes an array and returns a new one with the elements inside rotated n spaces.
If n is greater than 0 it should rotate the array to the right. If n is less than 0 it should rotate the array to the left. If n is 0, then it should return the array unchanged.
Example:
```python
data = [1, 2, 3, 4, 5];
rotate(data, 1) # => [5, 1, 2, 3, 4]
rotate(data, 2) # => [4, 5, 1, 2, 3]
rotate(data, 3) # => [3, 4, 5, 1, 2]
rotate(data, 4) # => [2, 3, 4, 5, 1]
rotate(data, 5) # => [1, 2, 3, 4, 5]
rotate(data, 0) # => [1, 2, 3, 4, 5]
rotate(data, -1) # => [2, 3, 4, 5, 1]
rotate(data, -2) # => [3, 4, 5, 1, 2]
rotate(data, -3) # => [4, 5, 1, 2, 3]
rotate(data, -4) # => [5, 1, 2, 3, 4]
rotate(data, -5) # => [1, 2, 3, 4, 5]
```
Furthermore the method should take ANY array of objects and perform this operation on them:
```python
rotate(['a', 'b', 'c'], 1) # => ['c', 'a', 'b']
rotate([1.0, 2.0, 3.0], 1) # => [3.0, 1.0, 2.0]
rotate([True, True, False], 1) # => [False, True, True]
```
Finally the rotation shouldn't be limited by the indices available in the array. Meaning that if we exceed the indices of the array it keeps rotating.
Example:
```python
data = [1, 2, 3, 4, 5]
rotate(data, 7) # => [4, 5, 1, 2, 3]
rotate(data, 11) # => [5, 1, 2, 3, 4]
rotate(data, 12478) # => [3, 4, 5, 1, 2]
``` | def rotate(arr, n):
rot = (-n)%len(arr)
return arr[rot:] + arr[:rot] | def rotate(arr, n):
rot = (-n)%len(arr)
return arr[rot:] + arr[:rot] | train | APPS_structured |
Create a program that will return whether an input value is a str, int, float, or bool. Return the name of the value.
### Examples
- Input = 23 --> Output = int
- Input = 2.3 --> Output = float
- Input = "Hello" --> Output = str
- Input = True --> Output = bool | def types(n):
return type(n).__name__ | def types(n):
return type(n).__name__ | train | APPS_structured |
Cersei wants to be the queen of seven kingdoms.
For this to happen, she needs to address the soldiers in her army. There are n$n$ soldiers in her army (numbered 1$1$ through n$n$). Cersei passes on the message to the first soldier (soldier 1).
This message needs to reach every soldier in the army. For this, the soldiers communicate among themselves by one soldier passing the message to another soldier through some communication links. It is known that the message could reach every soldier using the given links.
Now, each soldier will receive the message from exactly one soldier or Cersei and could pass on the message to atmost two soldiers. That is each soldier (except soldier 1) has only one incoming link and every soldier (including soldier 1) has atmost two outgoing links.
Now, the High Sparrow feels that Cersei is planning to kill his people first. Hence, for the sake of his people, he decided to appoint some sparrows to overhear every conversation between the soldiers (The conversation between Cersei and the first soldier needn't be overheard due to the fear of Ser Gregor Clegane).
To overhear a conversation between soldiers A$A$ and B$B$, there needs to be a sparrow either at soldier A$A$ or soldier B$B$ or both.
Also, by his research, the High Sparrow has found that the soldiers are partitioned into some classes (1$1$ to k$k$). That is, every soldier belongs to exactly one class. He then demands the presence of atleast one sparrow with each class he knows (1$1$ to k$k$).
Find the minimum number of sparrows the High Sparrow needs to recruit for the job or tell that he couldn't.
-----Input:-----
- The first line of the input contains the number of test cases t$t$.
- The first line of each test case gives the number of soldiers n$n$ in the army, the number of communication links m$m$ between the soldiers and the number of classes k$k$ in soldiers.
- The next line of the test case consists of n$n$ integers A1,A2....An$A_1,A_2....A_n$ each denoting the class of the ith$i^{th}$ soldier.
- The next m$m$ lines of the test case contain two integers u$u$ and v$v$, which denotes that soldier u$u$ can pass a message to soldier v$v$ (u≠v$u \neq v$).
-----Output:-----
For each test case, print in a single line the minimum number of sparrows required for the above task or print −1$-1$ if no such way is possible.
-----Constraints-----
- 1≤t≤500$1 \leq t \leq 500$
- 1≤n≤2500$1 \leq n \leq 2500$
- m=n−1$m = n - 1$
- 1≤k≤10$1 \leq k \leq 10$
- 1≤ai≤k$1 \leq a_i \leq k$
- The sum of n$n$ over all test cases is ≤2500$\leq 2500$.
-----Sample Input:-----
1
5 4 3
1 1 2 2 3
1 2
1 3
2 4
2 5
-----Sample Output:-----
3
-----EXPLANATION:-----
Selecting soldiers 1,4,5 would satisfy all the conditions.
-----Sample Input:-----
1
5 4 5
1 1 2 2 3
1 2
1 3
2 4
2 5
-----Sample Output:-----
-1
-----EXPLANATION:-----
Classes 4 and 5 are not present. So, there is no way possible. | # cook your dish here
# cook your dish here
# cook your dish here
dt, a = None, None
def dfs(z):
r = [{}, {}]
ln = len(dt[z])
if ln == 0:
r[0][0] = 0
r[1][1 << a[z]] = 1
elif ln == 1:
l = dfs(dt[z][0])
r[0] = l[1]
for m in l[0]:
r[1][(1 << a[z]) | m] = min(r[1][(1 << a[z]) | m], l[0][m] + 1) if (1 << a[z]) | m in r[1] else l[0][m] + 1
for m in l[1]:
r[1][(1 << a[z]) | m] = min(r[1][(1 << a[z]) | m], l[1][m] + 1) if (1 << a[z]) | m in r[1] else l[1][m] + 1
elif ln == 2:
l0 = dfs(dt[z][0])
l1 = dfs(dt[z][1])
for i0 in range(2):
for i1 in range(2):
for m0 in l0[i0]:
for m1 in l1[i1]:
r[1][(1 << a[z]) | m0 | m1] = min(r[1][(1 << a[z]) | m0 | m1], l0[i0][m0] + l1[i1][m1] + 1) if (1 << a[z]) | m0 | m1 in r[1] else l0[i0][m0] + l1[i1][m1] + 1
for m0 in l0[1]:
for m1 in l1[1]:
r[0][m0 | m1] = min(r[0][m0 | m1], l0[1][m0] + l1[1][m1]) if m0 | m1 in r[0] else l0[1][m0] + l1[1][m1]
return r
t = int(input())
for i in range(t):
n, m, k = map(int, input().split())
a = [0] + [int(x) - 1 for x in input().split()]
dt = [[] for i in range(n + 1)]
for i in range(m):
u, v = map(int, input().split())
dt[u].append(v)
r = dfs(1)
k = (1 << k) - 1
if (k in r[0]):
v = min(r[0][k], r[1][k])
elif (k in r[1]):
v = r[1][k]
else:
v = -1
print(v)
| # cook your dish here
# cook your dish here
# cook your dish here
dt, a = None, None
def dfs(z):
r = [{}, {}]
ln = len(dt[z])
if ln == 0:
r[0][0] = 0
r[1][1 << a[z]] = 1
elif ln == 1:
l = dfs(dt[z][0])
r[0] = l[1]
for m in l[0]:
r[1][(1 << a[z]) | m] = min(r[1][(1 << a[z]) | m], l[0][m] + 1) if (1 << a[z]) | m in r[1] else l[0][m] + 1
for m in l[1]:
r[1][(1 << a[z]) | m] = min(r[1][(1 << a[z]) | m], l[1][m] + 1) if (1 << a[z]) | m in r[1] else l[1][m] + 1
elif ln == 2:
l0 = dfs(dt[z][0])
l1 = dfs(dt[z][1])
for i0 in range(2):
for i1 in range(2):
for m0 in l0[i0]:
for m1 in l1[i1]:
r[1][(1 << a[z]) | m0 | m1] = min(r[1][(1 << a[z]) | m0 | m1], l0[i0][m0] + l1[i1][m1] + 1) if (1 << a[z]) | m0 | m1 in r[1] else l0[i0][m0] + l1[i1][m1] + 1
for m0 in l0[1]:
for m1 in l1[1]:
r[0][m0 | m1] = min(r[0][m0 | m1], l0[1][m0] + l1[1][m1]) if m0 | m1 in r[0] else l0[1][m0] + l1[1][m1]
return r
t = int(input())
for i in range(t):
n, m, k = map(int, input().split())
a = [0] + [int(x) - 1 for x in input().split()]
dt = [[] for i in range(n + 1)]
for i in range(m):
u, v = map(int, input().split())
dt[u].append(v)
r = dfs(1)
k = (1 << k) - 1
if (k in r[0]):
v = min(r[0][k], r[1][k])
elif (k in r[1]):
v = r[1][k]
else:
v = -1
print(v)
| train | APPS_structured |
A function $f : R \rightarrow R$ is called Lipschitz continuous if there is a real constant K such that the inequality |f(x) - f(y)| ≤ K·|x - y| holds for all $x, y \in R$. We'll deal with a more... discrete version of this term.
For an array $h [ 1 . . n ]$, we define it's Lipschitz constant $L(h)$ as follows: if n < 2, $L(h) = 0$ if n ≥ 2, $L(h) = \operatorname{max} [ \frac{|h [ j ] - h [ i ]|}{j - i} ]$ over all 1 ≤ i < j ≤ n
In other words, $L = L(h)$ is the smallest non-negative integer such that |h[i] - h[j]| ≤ L·|i - j| holds for all 1 ≤ i, j ≤ n.
You are given an array [Image] of size n and q queries of the form [l, r]. For each query, consider the subarray $s = a [ l . . r ]$; determine the sum of Lipschitz constants of all subarrays of $S$.
-----Input-----
The first line of the input contains two space-separated integers n and q (2 ≤ n ≤ 100 000 and 1 ≤ q ≤ 100) — the number of elements in array [Image] and the number of queries respectively.
The second line contains n space-separated integers $a [ 1 . . n ]$ ($0 \leq a [ i ] \leq 10^{8}$).
The following q lines describe queries. The i-th of those lines contains two space-separated integers l_{i} and r_{i} (1 ≤ l_{i} < r_{i} ≤ n).
-----Output-----
Print the answers to all queries in the order in which they are given in the input. For the i-th query, print one line containing a single integer — the sum of Lipschitz constants of all subarrays of [Image].
-----Examples-----
Input
10 4
1 5 2 9 1 3 4 2 1 7
2 4
3 8
7 10
1 9
Output
17
82
23
210
Input
7 6
5 7 7 4 6 6 2
1 2
2 3
2 6
1 7
4 7
3 5
Output
2
0
22
59
16
8
-----Note-----
In the first query of the first sample, the Lipschitz constants of subarrays of $[ 5,2,9 ]$ with length at least 2 are: $L([ 5,2 ]) = 3$ $L([ 2,9 ]) = 7$ $L([ 5,2,9 ]) = 7$
The answer to the query is their sum. | f = lambda: map(int, input().split())
n, m = f()
t = list(f())
p = [1e9] + [abs(b - a) for a, b in zip(t, t[1:])] + [1e9]
L, R = [0] * n, [0] * n
for i in range(1, n):
j = n - i
x, y = i - 1, j + 1
a, b = p[i], p[j]
while a > p[x]: x = L[x]
while b >= p[y]: y = R[y]
L[i], R[j] = x, y
for k in range(m):
l, r = f()
print(sum((i - max(l - 1, L[i])) * (min(r, R[i]) - i) * p[i] for i in range(l, r))) | f = lambda: map(int, input().split())
n, m = f()
t = list(f())
p = [1e9] + [abs(b - a) for a, b in zip(t, t[1:])] + [1e9]
L, R = [0] * n, [0] * n
for i in range(1, n):
j = n - i
x, y = i - 1, j + 1
a, b = p[i], p[j]
while a > p[x]: x = L[x]
while b >= p[y]: y = R[y]
L[i], R[j] = x, y
for k in range(m):
l, r = f()
print(sum((i - max(l - 1, L[i])) * (min(r, R[i]) - i) * p[i] for i in range(l, r))) | train | APPS_structured |
You've got a bunch of textual data with embedded phone numbers. Write a function `area_code()` that finds and returns just the area code portion of the phone number.
```python
>>> message = "The supplier's phone number is (555) 867-5309"
>>> area_code(message)
'555'
```
The returned area code should be a string, not a number.
Every phone number is formatted like in the example, and the only non-alphanumeric characters in the string are apostrophes `'` or the punctuation used in the phone number. | import re
def area_code(text):
return re.search(r'\((\d{3})\)',text).group(1) | import re
def area_code(text):
return re.search(r'\((\d{3})\)',text).group(1) | train | APPS_structured |
Given are integer sequence of length N, A = (A_1, A_2, \cdots, A_N), and an integer K.
For each X such that 1 \le X \le K, find the following value:
\left(\displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} (A_L+A_R)^X\right) \bmod 998244353
-----Constraints-----
- All values in input are integers.
- 2 \le N \le 2 \times 10^5
- 1 \le K \le 300
- 1 \le A_i \le 10^8
-----Input-----
Input is given from Standard Input in the following format:
N K
A_1 A_2 \cdots A_N
-----Output-----
Print K lines.
The X-th line should contain the value \left(\displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} (A_L+A_R)^X \right) \bmod 998244353.
-----Sample Input-----
3 3
1 2 3
-----Sample Output-----
12
50
216
In the 1-st line, we should print (1+2)^1 + (1+3)^1 + (2+3)^1 = 3 + 4 + 5 = 12.
In the 2-nd line, we should print (1+2)^2 + (1+3)^2 + (2+3)^2 = 9 + 16 + 25 = 50.
In the 3-rd line, we should print (1+2)^3 + (1+3)^3 + (2+3)^3 = 27 + 64 + 125 = 216. |
import numpy as np
N,K = list(map(int,input().split()))
A=np.array(list(map(int,input().split())))
#A=list(map(int,input().split()))
mod = 998244353
fact = [1]*(K+1)
for i in range(1,K+1):
fact[i]=i*fact[i-1]%mod
inv_fact = [pow(f,mod-2,mod) for f in fact]
# r = [sum(pow(aa,t,mod) for aa in A)%mod for t in range(K+1)]
r = [0]*(K+1)
r[0] = N
temp = np.ones(N,dtype="int32")
for i in range(1,K+1):
temp = temp*A%mod
r[i] = int(np.sum(temp))%mod
inv2 = pow(2,mod-2,mod)
for x in range(1,K+1):
# ans = sum((fact[x]*inv_fact[t]*inv_fact[x-t] *r[x-t]*r[t]) %mod
# for t in range(x+1))%mod
# ans-= r[x]*pow(2,x,mod) %mod
ans = 0
for t in range(x+1):
comb = fact[x]*inv_fact[t]*inv_fact[x-t] %mod
#comb = fact[x]* pow(fact[t],mod-2,mod)*pow(fact[x-t],mod-2,mod) %mod
ans += comb * r[x-t] * r[t] %mod
ans-= r[x]*pow(2,x,mod) %mod
print(((ans*inv2)%mod))
|
import numpy as np
N,K = list(map(int,input().split()))
A=np.array(list(map(int,input().split())))
#A=list(map(int,input().split()))
mod = 998244353
fact = [1]*(K+1)
for i in range(1,K+1):
fact[i]=i*fact[i-1]%mod
inv_fact = [pow(f,mod-2,mod) for f in fact]
# r = [sum(pow(aa,t,mod) for aa in A)%mod for t in range(K+1)]
r = [0]*(K+1)
r[0] = N
temp = np.ones(N,dtype="int32")
for i in range(1,K+1):
temp = temp*A%mod
r[i] = int(np.sum(temp))%mod
inv2 = pow(2,mod-2,mod)
for x in range(1,K+1):
# ans = sum((fact[x]*inv_fact[t]*inv_fact[x-t] *r[x-t]*r[t]) %mod
# for t in range(x+1))%mod
# ans-= r[x]*pow(2,x,mod) %mod
ans = 0
for t in range(x+1):
comb = fact[x]*inv_fact[t]*inv_fact[x-t] %mod
#comb = fact[x]* pow(fact[t],mod-2,mod)*pow(fact[x-t],mod-2,mod) %mod
ans += comb * r[x-t] * r[t] %mod
ans-= r[x]*pow(2,x,mod) %mod
print(((ans*inv2)%mod))
| train | APPS_structured |
The wide mouth frog is particularly interested in the eating habits of other creatures.
He just can't stop asking the creatures he encounters what they like to eat. But then he meet the alligator who just LOVES to eat wide-mouthed frogs!
When he meets the alligator, it then makes a tiny mouth.
Your goal in this kata is to create complete the `mouth_size` method this method take one argument `animal` which corresponds to the animal encountered by frog. If this one is an `alligator` (case insensitive) return `small` otherwise return `wide`. | def mouth_size(animal):
# code
if(animal.lower() == "alligator"):
return "small"
return "wide" | def mouth_size(animal):
# code
if(animal.lower() == "alligator"):
return "small"
return "wide" | train | APPS_structured |
In a 1 million by 1 million grid, the coordinates of each grid square are (x, y) with 0 <= x, y < 10^6.
We start at the source square and want to reach the target square. Each move, we can walk to a 4-directionally adjacent square in the grid that isn't in the given list of blocked squares.
Return true if and only if it is possible to reach the target square through a sequence of moves.
Example 1:
Input: blocked = [[0,1],[1,0]], source = [0,0], target = [0,2]
Output: false
Explanation:
The target square is inaccessible starting from the source square, because we can't walk outside the grid.
Example 2:
Input: blocked = [], source = [0,0], target = [999999,999999]
Output: true
Explanation:
Because there are no blocked cells, it's possible to reach the target square.
Note:
0 <= blocked.length <= 200
blocked[i].length == 2
0 <= blocked[i][j] < 10^6
source.length == target.length == 2
0 <= source[i][j], target[i][j] < 10^6
source != target | class Solution:
def isEscapePossible(self, blocked, source, target):
blocked = {tuple(p) for p in blocked}
def bfs(source, target):
bfs, seen = [source], {tuple(source)}
for x0, y0 in bfs:
for i, j in [[0, 1], [1, 0], [-1, 0], [0, -1]]:
x, y = x0 + i, y0 + j
if 0 <= x < 10**6 and 0 <= y < 10**6 and (x, y) not in seen and (x, y) not in blocked:
if [x, y] == target: return True
bfs.append([x, y])
seen.add((x, y))
if len(bfs) == 20000: return True
return False
return bfs(source, target) and bfs(target, source)
| class Solution:
def isEscapePossible(self, blocked, source, target):
blocked = {tuple(p) for p in blocked}
def bfs(source, target):
bfs, seen = [source], {tuple(source)}
for x0, y0 in bfs:
for i, j in [[0, 1], [1, 0], [-1, 0], [0, -1]]:
x, y = x0 + i, y0 + j
if 0 <= x < 10**6 and 0 <= y < 10**6 and (x, y) not in seen and (x, y) not in blocked:
if [x, y] == target: return True
bfs.append([x, y])
seen.add((x, y))
if len(bfs) == 20000: return True
return False
return bfs(source, target) and bfs(target, source)
| train | APPS_structured |
###Instructions
Write a function that takes a negative or positive integer, which represents the number of minutes before (-) or after (+) Sunday midnight, and returns the current day of the week and the current time in 24hr format ('hh:mm') as a string.
```python
day_and_time(0) should return 'Sunday 00:00'
day_and_time(-3) should return 'Saturday 23:57'
day_and_time(45) should return 'Sunday 00:45'
day_and_time(759) should return 'Sunday 12:39'
day_and_time(1236) should return 'Sunday 20:36'
day_and_time(1447) should return 'Monday 00:07'
day_and_time(7832) should return 'Friday 10:32'
day_and_time(18876) should return 'Saturday 02:36'
day_and_time(259180) should return 'Thursday 23:40'
day_and_time(-349000) should return 'Tuesday 15:20'
``` | from time import gmtime, strftime
def day_and_time(mins):
#your code here
return strftime("%A %H:%M", gmtime(3600*24*3+60*mins)) | from time import gmtime, strftime
def day_and_time(mins):
#your code here
return strftime("%A %H:%M", gmtime(3600*24*3+60*mins)) | train | APPS_structured |
Consider a directed graph, with nodes labelled 0, 1, ..., n-1. In this graph, each edge is either red or blue, and there could be self-edges or parallel edges.
Each [i, j] in red_edges denotes a red directed edge from node i to node j. Similarly, each [i, j] in blue_edges denotes a blue directed edge from node i to node j.
Return an array answer of length n, where each answer[X] is the length of the shortest path from node 0 to node X such that the edge colors alternate along the path (or -1 if such a path doesn't exist).
Example 1:
Input: n = 3, red_edges = [[0,1],[1,2]], blue_edges = []
Output: [0,1,-1]
Example 2:
Input: n = 3, red_edges = [[0,1]], blue_edges = [[2,1]]
Output: [0,1,-1]
Example 3:
Input: n = 3, red_edges = [[1,0]], blue_edges = [[2,1]]
Output: [0,-1,-1]
Example 4:
Input: n = 3, red_edges = [[0,1]], blue_edges = [[1,2]]
Output: [0,1,2]
Example 5:
Input: n = 3, red_edges = [[0,1],[0,2]], blue_edges = [[1,0]]
Output: [0,1,1]
Constraints:
1 <= n <= 100
red_edges.length <= 400
blue_edges.length <= 400
red_edges[i].length == blue_edges[i].length == 2
0 <= red_edges[i][j], blue_edges[i][j] < n | class Solution:
def shortestAlternatingPaths(self, n: int, red_edges: List[List[int]], blue_edges: List[List[int]]) -> List[int]:
graph_red = defaultdict(list)
graph_blue = defaultdict(list)
for a, b in red_edges:
graph_red[a].append(b)
for a, b in blue_edges:
graph_blue[a].append(b)
def bfs(target):
BLUE = 1
RED = 2
seen = set()
queue = deque([(0, 0, BLUE), (0,0,RED)])
while queue:
node, steps, color = queue.popleft()
if node == target:
return steps
if color == RED:
for next_node in graph_blue[node]:
if (next_node, BLUE) not in seen:
seen.add((next_node, BLUE))
queue.append((next_node, steps + 1, BLUE))
else:
for next_node in graph_red[node]:
if (next_node, RED) not in seen:
seen.add((next_node, RED))
queue.append((next_node, steps + 1, RED))
return -1
res = []
for i in range(n):
res.append(bfs(i))
return res | class Solution:
def shortestAlternatingPaths(self, n: int, red_edges: List[List[int]], blue_edges: List[List[int]]) -> List[int]:
graph_red = defaultdict(list)
graph_blue = defaultdict(list)
for a, b in red_edges:
graph_red[a].append(b)
for a, b in blue_edges:
graph_blue[a].append(b)
def bfs(target):
BLUE = 1
RED = 2
seen = set()
queue = deque([(0, 0, BLUE), (0,0,RED)])
while queue:
node, steps, color = queue.popleft()
if node == target:
return steps
if color == RED:
for next_node in graph_blue[node]:
if (next_node, BLUE) not in seen:
seen.add((next_node, BLUE))
queue.append((next_node, steps + 1, BLUE))
else:
for next_node in graph_red[node]:
if (next_node, RED) not in seen:
seen.add((next_node, RED))
queue.append((next_node, steps + 1, RED))
return -1
res = []
for i in range(n):
res.append(bfs(i))
return res | train | APPS_structured |
Kuroni has $n$ daughters. As gifts for them, he bought $n$ necklaces and $n$ bracelets: the $i$-th necklace has a brightness $a_i$, where all the $a_i$ are pairwise distinct (i.e. all $a_i$ are different), the $i$-th bracelet has a brightness $b_i$, where all the $b_i$ are pairwise distinct (i.e. all $b_i$ are different).
Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the $i$-th daughter receives a necklace with brightness $x_i$ and a bracelet with brightness $y_i$, then the sums $x_i + y_i$ should be pairwise distinct. Help Kuroni to distribute the gifts.
For example, if the brightnesses are $a = [1, 7, 5]$ and $b = [6, 1, 2]$, then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of $a_3 + b_1 = 11$. Give the first necklace and the third bracelet to the second daughter, for a total brightness of $a_1 + b_3 = 3$. Give the second necklace and the second bracelet to the third daughter, for a total brightness of $a_2 + b_2 = 8$.
Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of $a_1 + b_1 = 7$. Give the second necklace and the second bracelet to the second daughter, for a total brightness of $a_2 + b_2 = 8$. Give the third necklace and the third bracelet to the third daughter, for a total brightness of $a_3 + b_3 = 7$.
This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!
-----Input-----
The input consists of multiple test cases. The first line contains an integer $t$ ($1 \le t \le 100$) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer $n$ ($1 \le n \le 100$) — the number of daughters, necklaces and bracelets.
The second line of each test case contains $n$ distinct integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 1000$) — the brightnesses of the necklaces.
The third line of each test case contains $n$ distinct integers $b_1, b_2, \dots, b_n$ ($1 \le b_i \le 1000$) — the brightnesses of the bracelets.
-----Output-----
For each test case, print a line containing $n$ integers $x_1, x_2, \dots, x_n$, representing that the $i$-th daughter receives a necklace with brightness $x_i$. In the next line print $n$ integers $y_1, y_2, \dots, y_n$, representing that the $i$-th daughter receives a bracelet with brightness $y_i$.
The sums $x_1 + y_1, x_2 + y_2, \dots, x_n + y_n$ should all be distinct. The numbers $x_1, \dots, x_n$ should be equal to the numbers $a_1, \dots, a_n$ in some order, and the numbers $y_1, \dots, y_n$ should be equal to the numbers $b_1, \dots, b_n$ in some order.
It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.
-----Example-----
Input
2
3
1 8 5
8 4 5
3
1 7 5
6 1 2
Output
1 8 5
8 4 5
5 1 7
6 2 1
-----Note-----
In the first test case, it is enough to give the $i$-th necklace and the $i$-th bracelet to the $i$-th daughter. The corresponding sums are $1 + 8 = 9$, $8 + 4 = 12$, and $5 + 5 = 10$.
The second test case is described in the statement. | for _ in range(int(input())):
n = int(input())
ar1 = list(map(int, input().split()))
ar2 = list(map(int, input().split()))
ar1.sort()
ar2.sort()
print(*ar1)
print(*ar2) | for _ in range(int(input())):
n = int(input())
ar1 = list(map(int, input().split()))
ar2 = list(map(int, input().split()))
ar1.sort()
ar2.sort()
print(*ar1)
print(*ar2) | train | APPS_structured |
-----Problem description-----
As a holiday gift, Tojo received a probability problem. The problem read as follows
Consider an N by M grid. Rows are numbered 1 to N, from top to bottom. Columns are numbered 1 to M, from left to right. You are initially at cell (1, 1) and want to go to cell (N, M). From any cell you can move to the cell below it or to the cell right to it. You should never go out of the grid. At any point you should consider all the possibilities of movement with equal probability
Let P[i][j] be the probability of visiting cell (i, j). You need to calculate the sum of P[i][j] for 1 ≤ i ≤ N, 1 ≤ i ≤ M.
As we all know, Tojo really hates probability related problems. He wants you to solve this task
-----Input-----
The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.Only line of each test case has two integer N and M.
-----Output-----
For each test case, output a single line containing the required answer. Answers within an absolute or relative error of 10-6 will be accepted.
-----Constraints-----
- 1 ≤ T ≤ 1000
- 1 ≤ N ≤ 1000
- 1 ≤ M ≤ 1000
-----Example-----
Input:
2
2 2
1 6
Output:
3.000000
6.000000
-----Explanation-----
Example case 1
Probability matrix P for N=2, M=2 is
1.0 0.5
0.5 1.0
You are at (1, 1) initially. So the probablity of visiting (1, 1) is 1. At (1, 1) you have 2 options, move below to (2, 1) or to right cell (1, 2). Probablity of going to (1, 2) is 0.5. Probability of going to (2, 1) is 0.5. You always end up at (2, 2), so P[2][2] is 1. Required sum = 1.0 + 0.5 + 0.5 + 1.0 = 3.0
Example case 2
Probability matrix P for N=1, M=6 is
1.0 1.0 1.0 1.0 1.0 1.0
Because at any position there is only one possible next position. | for t in range(int(input())):
n,m=map(int,input().split())
print(m+n-1) | for t in range(int(input())):
n,m=map(int,input().split())
print(m+n-1) | train | APPS_structured |
Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.
Example:
Given n = 2, return 91. (The answer should be the total numbers in the range of 0 ≤ x < 100, excluding [11,22,33,44,55,66,77,88,99])
Credits:Special thanks to @memoryless for adding this problem and creating all test cases. | class Solution:
def countNumbersWithUniqueDigits(self, n):
"""
:type n: int
:rtype: int
"""
answer = 10 ** n
for i in range(1, n + 1):
all_count = 9 * 10 ** (i - 1)
invalid = 9
for j in range(1, i):
invalid *= (10 - j)
answer -= (all_count - invalid)
return answer | class Solution:
def countNumbersWithUniqueDigits(self, n):
"""
:type n: int
:rtype: int
"""
answer = 10 ** n
for i in range(1, n + 1):
all_count = 9 * 10 ** (i - 1)
invalid = 9
for j in range(1, i):
invalid *= (10 - j)
answer -= (all_count - invalid)
return answer | train | APPS_structured |
Given a group of two strings, you need to find the longest uncommon subsequence of this group of two strings.
The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other strings.
A subsequence is a sequence that can be derived from one sequence by deleting some characters without changing the order of the remaining elements. Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string.
The input will be two strings, and the output needs to be the length of the longest uncommon subsequence. If the longest uncommon subsequence doesn't exist, return -1.
Example 1:
Input: "aba", "cdc"
Output: 3
Explanation: The longest uncommon subsequence is "aba" (or "cdc"), because "aba" is a subsequence of "aba", but not a subsequence of any other strings in the group of two strings.
Note:
Both strings' lengths will not exceed 100.
Only letters from a ~ z will appear in input strings. | class Solution:
def findLUSlength(self, a, b):
if len(a) != len(b):
return max(len(a), len(b))
else:
if a == b:
return -1
else:
return len(a)
| class Solution:
def findLUSlength(self, a, b):
if len(a) != len(b):
return max(len(a), len(b))
else:
if a == b:
return -1
else:
return len(a)
| train | APPS_structured |
An array is called `zero-balanced` if its elements sum to `0` and for each positive element `n`, there exists another element that is the negative of `n`. Write a function named `ìsZeroBalanced` that returns `true` if its argument is `zero-balanced` array, else return `false`. Note that an `empty array` will not sum to `zero`. | def is_zero_balanced(arr):
pos = (n for n in arr if n > 0)
neg = (-n for n in arr if n < 0)
return sorted(pos) == sorted(neg) if arr else False
| def is_zero_balanced(arr):
pos = (n for n in arr if n > 0)
neg = (-n for n in arr if n < 0)
return sorted(pos) == sorted(neg) if arr else False
| train | APPS_structured |
Jump is a simple one-player game:
You are initially at the first cell of an array of cells containing non-negative integers;
At each step you can jump ahead in the array as far as the integer at the current cell, or any smaller number of cells.
You win if there is a path that allows you to jump from one cell to another, eventually jumping past the end of the array, otherwise you lose.
For instance, if the array contains the integers
`[2, 0, 3, 5, 0, 0, 3, 0, 0, 3, 1, 0]`,
you can win by jumping from **2**, to **3**, to **5**, to **3**, to **3**, then past the end of the array.
You can also directly jump from from the initial cell(first cell) past the end of the array if they are integers to the right of that cell.
E.g
`[6, 1, 1]` is winnable
`[6]` is **not** winnable
Note: You can **not** jump from the last cell!
`[1, 1, 3]` is **not** winnable
## -----
Your task is to complete the function `canJump()` that determines if a given game is winnable.
### More Examples
``` javascript
canJump([5]) //=> false
canJump([2, 5]) //=> true
canJump([3, 0, 2, 3]) //=> true (3 to 2 then past end of array)
canJump([4, 1, 2, 0, 1]) //=> false
canJump([5, 0, 0, 0]) //=> true
canJump([1, 1]) //=> false
``` | def can_jump(arr):
last = len(arr)
for i in reversed(range(len(arr)-1)):
if arr[i] >= last-i: last = i
return not last | def can_jump(arr):
last = len(arr)
for i in reversed(range(len(arr)-1)):
if arr[i] >= last-i: last = i
return not last | train | APPS_structured |
Consider the following algorithm
order(arr, i) {
if length(arr) <= 1 {
return arr
}
l = []
r = []
n = length(arr) - 1
for j in 0, 1, ..., n {
if ( (arr[j] modulo power(2,i+1)) < power(2,i) ) {
append arr[j] to l
}else{
append arr[j] to r
}
}
l = order(l, i + 1)
r = order(r, i + 1)
c = concatenate(l, r)
return c
}
Note that $concatenate(l, r)$ returns an array which is the array $l$, followed by the array $r$. Similarly $power(x,y)$ returns $x^y$.
Let $a$ be the array $a_0,a_1,a_2,a_3, \ldots,a_n$ where $a_j = j$ for each index $j$ and the last index $n = (2^p-1)$ for a fixed integer parameter $p$. Given an integer $p$ and an index $idx$, your task is calculate the element at index $idx$ in the array returned by executing $order(a, 0)$.
For example, suppose $ p = 3$ and $idx = 3$.
- The initial array is $a = [0, 1, 2, 3, 4, 5, 6, 7]$.
- Executing $order(a, 0)$ first creates two new arrays $l == [0, 2, 4, 6]$ and $r == [1, 3, 5, 7]$.
- Next, $order(l, 1)$ and $order(r, 1)$ are executed.
- $order(l, 1)$, in turn, executes $order([0, 4], 2)$ and $order([2, 6], 2)$ which return $[0, 4]$ and $[2, 6]$, respectively. These are then concatenated, so $order(l, 1)$ returns $[0, 4, 2, 6]$.
- Similarly, $order(r, 1)$ returns $[1, 5, 3, 7]$.
- These two are concatenated as the final result, so the array returned by $order(a, 0)$ is $[0, 4, 2, 6, 1, 5, 3, 7]$.
So, if the input is $p = 3$, and $idx = 3$, the answer is $6$. If $p = 3$ and $idx = 7$, the answer should be $7$.
-----Input Format:-----
- The first line contains a single integer, $T$, which is the number of testcases. The description of each testcase follows.
- Each testcase is described by a single line with two integers: $p$ and $idx$, where $p$ is the parameter that determines the length of the array $a$ and $idx$ is the index at which you have to report the value in the output of $order(a, 0)$.
-----Output Format:-----
- You should print the answer in a new line for each testcase, which should be a single integer, the element at index $idx$ after executing $order(a, 0)$ for the array $a$ defined by the parameter $p$.
-----Constraints:-----
- $1 \leq T \leq 10$
- $1 \leq p \leq 50$
- $0 \leq idx \leq 2^p-1$
-----SUBTASKS:-----
- Subtask 1: 20% points : $1 \leq p \leq 20$
- Subtask 2: 80% points: Original constraints
-----Sample Input:-----
2
3 3
3 7
-----Sample Output:-----
6
7
-----Explanation:-----
Both the testcases have been explained in the problem statement. | def calc(i, p):
if p == 1:
return [0, 1][i]
if i >= 2 ** (p - 1): # second half
t = calc(i - 2 ** (p - 1), p)
return t + 1
else: # first half
t = calc(i, p - 1)
return 2 * t
for t in range(int(input())):
# print("for p =", p)
# print(order([i for i in range(2**p)], 0))
[p, i] = [int(i) for i in input().split()]
print(calc(i, p))
| def calc(i, p):
if p == 1:
return [0, 1][i]
if i >= 2 ** (p - 1): # second half
t = calc(i - 2 ** (p - 1), p)
return t + 1
else: # first half
t = calc(i, p - 1)
return 2 * t
for t in range(int(input())):
# print("for p =", p)
# print(order([i for i in range(2**p)], 0))
[p, i] = [int(i) for i in input().split()]
print(calc(i, p))
| train | APPS_structured |
You are given two strings of equal length $s$ and $t$ consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings.
During each operation you choose two adjacent characters in any string and assign the value of the first character to the value of the second or vice versa.
For example, if $s$ is "acbc" you can get the following strings in one operation: "aabc" (if you perform $s_2 = s_1$); "ccbc" (if you perform $s_1 = s_2$); "accc" (if you perform $s_3 = s_2$ or $s_3 = s_4$); "abbc" (if you perform $s_2 = s_3$); "acbb" (if you perform $s_4 = s_3$);
Note that you can also apply this operation to the string $t$.
Please determine whether it is possible to transform $s$ into $t$, applying the operation above any number of times.
Note that you have to answer $q$ independent queries.
-----Input-----
The first line contains one integer $q$ ($1 \le q \le 100$) — the number of queries. Each query is represented by two consecutive lines.
The first line of each query contains the string $s$ ($1 \le |s| \le 100$) consisting of lowercase Latin letters.
The second line of each query contains the string $t$ ($1 \le |t| \leq 100$, $|t| = |s|$) consisting of lowercase Latin letters.
-----Output-----
For each query, print "YES" if it is possible to make $s$ equal to $t$, and "NO" otherwise.
You may print every letter in any case you want (so, for example, the strings "yEs", "yes", "Yes", and "YES" will all be recognized as positive answer).
-----Example-----
Input
3
xabb
aabx
technocup
technocup
a
z
Output
YES
YES
NO
-----Note-----
In the first query, you can perform two operations $s_1 = s_2$ (after it $s$ turns into "aabb") and $t_4 = t_3$ (after it $t$ turns into "aabb").
In the second query, the strings are equal initially, so the answer is "YES".
In the third query, you can not make strings $s$ and $t$ equal. Therefore, the answer is "NO". | q = int(input())
for i in range(q):
s = input()
t = input()
s = set(s)
t = set(t)
if len(s.intersection(t)) > 0:
print('YES')
else:
print('NO') | q = int(input())
for i in range(q):
s = input()
t = input()
s = set(s)
t = set(t)
if len(s.intersection(t)) > 0:
print('YES')
else:
print('NO') | train | APPS_structured |
Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.
```python
move_zeros([False,1,0,1,2,0,1,3,"a"]) # returns[False,1,1,2,1,3,"a",0,0]
``` | def move_zeros(array):
a_len = len(array)
array = [v for v in array if type(v) is bool or v != 0]
array.extend([0]*(a_len-len(array)))
return array | def move_zeros(array):
a_len = len(array)
array = [v for v in array if type(v) is bool or v != 0]
array.extend([0]*(a_len-len(array)))
return array | train | APPS_structured |