input stringlengths 50 13.9k | output_program stringlengths 5 655k | output_answer stringlengths 5 655k | split stringclasses 1
value | dataset stringclasses 1
value |
|---|---|---|---|---|
Today is rose day, batch mates of Kabir and Tara decided to celebrate this day by exchanging roses with each other.
Note:$Note:$ exchanging means both the boy and the girl will give rose to each other.
In the class there are B$B$ boys and G$G$ girls.
Exchange of rose will take place if and only if at least one of th... | # cook your dish here
for i in range(int(input())):
print(2*(sum(list(map(int, input().split())))-1)) | # cook your dish here
for i in range(int(input())):
print(2*(sum(list(map(int, input().split())))-1)) | train | APPS_structured |
You are given three numbers $a$, $b$, $c$ . Write a program to determine the largest number that is less than or equal to $c$ and leaves a remainder $b$ when divided by $a$.
-----Input:-----
- First line will contain $T$, number of testcases. Then the testcases follow.
- Each testcase contains a single line of input, h... | # cook your dish here
t = int(input())
for i in range(0,t):
a=input().split()
b=list(map(int,a))
n=int(b[2]/b[0])
if((b[0])*n+b[1]<=b[2]):
print((b[0])*n+b[1])
else:
print((b[0])*(n-1)+b[1]) | # cook your dish here
t = int(input())
for i in range(0,t):
a=input().split()
b=list(map(int,a))
n=int(b[2]/b[0])
if((b[0])*n+b[1]<=b[2]):
print((b[0])*n+b[1])
else:
print((b[0])*(n-1)+b[1]) | train | APPS_structured |
This is the simple version of Shortest Code series. If you need some challenges, please try the [challenge version](http://www.codewars.com/kata/570f45fab29c705d330004e3)
## Task:
There is a rectangular land and we need to plant trees on the edges of that land.
I will give you three parameters:
```width``` and ```lengt... | def sc(width,length,gaps):
#your code here
a, b = divmod(2*width + 2*length - 4, gaps+1)
return 0 if b else a | def sc(width,length,gaps):
#your code here
a, b = divmod(2*width + 2*length - 4, gaps+1)
return 0 if b else a | train | APPS_structured |
You are given two integer sequences, each of length N: a_1, ..., a_N and b_1, ..., b_N.
There are N^2 ways to choose two integers i and j such that 1 \leq i, j \leq N. For each of these N^2 pairs, we will compute a_i + b_j and write it on a sheet of paper.
That is, we will write N^2 integers in total.
Compute the XOR o... | N = int(input())
A = [int(a) for a in input().split()]
B = [int(a) for a in input().split()]
def xor(L):
a = 0
for l in L: a ^= l
return a
def chk(L1, L2, k):
L1.sort()
L2.sort()
s, j = 0, 0
for i in range(N)[::-1]:
while j < N and L1[i] + L2[j] < k:
j += 1
s +=... | N = int(input())
A = [int(a) for a in input().split()]
B = [int(a) for a in input().split()]
def xor(L):
a = 0
for l in L: a ^= l
return a
def chk(L1, L2, k):
L1.sort()
L2.sort()
s, j = 0, 0
for i in range(N)[::-1]:
while j < N and L1[i] + L2[j] < k:
j += 1
s +=... | train | APPS_structured |
## Description:
Remove all exclamation marks from the end of words. Words are separated by spaces in the sentence.
### Examples
```
remove("Hi!") === "Hi"
remove("Hi!!!") === "Hi"
remove("!Hi") === "!Hi"
remove("!Hi!") === "!Hi"
remove("Hi! Hi!") === "Hi Hi"
remove("!!!Hi !!hi!!! !hi") === "!!!Hi !!hi !hi"
``` | import re
def remove(s):
return re.sub(r"(?<=\w)!+(?=\W)*", "", s) | import re
def remove(s):
return re.sub(r"(?<=\w)!+(?=\W)*", "", s) | train | APPS_structured |
# Task
Suppose there are `n` people standing in a circle and they are numbered 1 through n in order.
Person 1 starts off with a sword and kills person 2. He then passes the sword to the next person still standing, in this case person 3. Person 3 then uses the sword to kill person 4, and passes it to person 5. This p... | circle_slash=lambda n:int(bin(n)[3:]+'1',2) | circle_slash=lambda n:int(bin(n)[3:]+'1',2) | train | APPS_structured |
## Snail Sort
Given an `n x n` array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.
```
array = [[1,2,3],
[4,5,6],
[7,8,9]]
snail(array) #=> [1,2,3,6,9,8,7,4,5]
```
For better understanding, please follow the numbers of the next array consecutiv... | def trans(array):
#Do an inverse transpose (i.e. rotate left by 90 degrees
return [[row[-i-1] for row in array] for i in range(len(array[0]))] if len(array)>0 else array
def snail(array):
output=[]
while len(array)>0:
#Add the 1st row of the array
output+=array[0]
#Chop of... | def trans(array):
#Do an inverse transpose (i.e. rotate left by 90 degrees
return [[row[-i-1] for row in array] for i in range(len(array[0]))] if len(array)>0 else array
def snail(array):
output=[]
while len(array)>0:
#Add the 1st row of the array
output+=array[0]
#Chop of... | train | APPS_structured |
Some languages like Chinese, Japanese, and Thai do not have spaces between words. However, most natural languages processing tasks like part-of-speech tagging require texts that have segmented words. A simple and reasonably effective algorithm to segment a sentence into its component words is called "MaxMatch".
## MaxM... | # KenKamau's solution
def max_match(st):
for i in range(len(st),0,-1):
if i == 1 or st[:i] in VALID_WORDS:
return [st[:i]] + max_match(st[i:])
return [] | # KenKamau's solution
def max_match(st):
for i in range(len(st),0,-1):
if i == 1 or st[:i] in VALID_WORDS:
return [st[:i]] + max_match(st[i:])
return [] | train | APPS_structured |
Dhruvil has always been a studious person and will be completing his Engineering soon. He is always kneen about solving problems and is preparing hard for his next interview at Hackerrank. He has practiced lots of problems and now he came across this problem.
Given a message containing English letters(A-Z), it is being... | import sys
import math
import bisect
from sys import stdin,stdout
from math import gcd,floor,sqrt,log
from collections import defaultdict as dd
from bisect import bisect_left as bl,bisect_right as br
sys.setrecursionlimit(100000000)
ii =lambda: int(input())
si =lambda: input()
jn =lambda x,l: x.join(map(str,l))
sl =l... | import sys
import math
import bisect
from sys import stdin,stdout
from math import gcd,floor,sqrt,log
from collections import defaultdict as dd
from bisect import bisect_left as bl,bisect_right as br
sys.setrecursionlimit(100000000)
ii =lambda: int(input())
si =lambda: input()
jn =lambda x,l: x.join(map(str,l))
sl =l... | train | APPS_structured |
**This Kata is intended as a small challenge for my students**
All Star Code Challenge #16
Create a function called noRepeat() that takes a string argument and returns a single letter string of the **first** not repeated character in the entire string.
``` haskell
noRepeat "aabbccdde" `shouldBe` 'e'
noRepeat "wxyz" ... | def no_repeat(string):
if string.count(string[0]) == 1:
return string[0]
else:
return no_repeat(string.replace(string[0], '')) | def no_repeat(string):
if string.count(string[0]) == 1:
return string[0]
else:
return no_repeat(string.replace(string[0], '')) | train | APPS_structured |
In Finite Encyclopedia of Integer Sequences (FEIS), all integer sequences of lengths between 1 and N (inclusive) consisting of integers between 1 and K (inclusive) are listed.
Let the total number of sequences listed in FEIS be X. Among those sequences, find the (X/2)-th (rounded up to the nearest integer) lexicographi... | # coding: utf-8
# Your code here!
import sys
read = sys.stdin.read
readline = sys.stdin.readline
sys.setrecursionlimit(10**5)
k,n = list(map(int, read().split()))
if k%2==0:
print((*([k//2]+[k]*(n-1))))
return
if k==1:
print((*[1]*((n+1)//2)))
return
ans = [(k+1)//2]*n
d = 0
def f(k,i,d):
# d <=... | # coding: utf-8
# Your code here!
import sys
read = sys.stdin.read
readline = sys.stdin.readline
sys.setrecursionlimit(10**5)
k,n = list(map(int, read().split()))
if k%2==0:
print((*([k//2]+[k]*(n-1))))
return
if k==1:
print((*[1]*((n+1)//2)))
return
ans = [(k+1)//2]*n
d = 0
def f(k,i,d):
# d <=... | train | APPS_structured |
Implement a function which convert the given boolean value into its string representation. | def boolean_to_string(b):
#your code he
p = str(b);
print (type(p))
print (p)
return p | def boolean_to_string(b):
#your code he
p = str(b);
print (type(p))
print (p)
return p | train | APPS_structured |
Chef has a strip of length $N$ units and he wants to tile it using $4$ kind of tiles
-A Red tile of $2$ unit length
-A Red tile of $1$ unit length
-A Blue tile of $2$ unit length
-A Blue tile of $1$ unit length
Chef is having an infinite supply of each of these tiles. He wants to find out the number of ways in which... | # Fibonacci Series using
# Optimized Method
# function that returns nth
# Fibonacci number
MOD = 1000000007
def fib(n):
F = [[2, 2],
[1, 0]]
power(F, n - 1)
ans = [6, 2]
return (F[0][0] * 6 + F[0][1] * 2) % MOD
# return F[0][0]
def multiply(F, M):
x = (F[0][0] * M[... | # Fibonacci Series using
# Optimized Method
# function that returns nth
# Fibonacci number
MOD = 1000000007
def fib(n):
F = [[2, 2],
[1, 0]]
power(F, n - 1)
ans = [6, 2]
return (F[0][0] * 6 + F[0][1] * 2) % MOD
# return F[0][0]
def multiply(F, M):
x = (F[0][0] * M[... | train | APPS_structured |
Your task is to find the number couple with the greatest difference from a given array of number-couples.
All number couples will be given as strings and all numbers in them will be positive integers.
For instance: ['56-23','1-100']; in this case, you should identify '1-100' as the number couple with the greatest di... | def diff(arr):
r = arr and max(arr, key = lambda x : abs(eval(x)))
return bool(arr and eval(r)) and r | def diff(arr):
r = arr and max(arr, key = lambda x : abs(eval(x)))
return bool(arr and eval(r)) and r | train | APPS_structured |
Chef and Paja are bored, so they are playing an infinite game of ping pong. The rules of the game are as follows:
- The players play an infinite number of games. At the end of each game, the player who won it scores a point.
- In each game, one of the players serves. Chef serves in the first game.
- After every $K$ poi... | # cook your dish here
# cook your dish here
t=int(input())
for i in range(t):
x,y,k=map(int,input().split())
a=x+y
b=a//k
if b%2==0:
print("Chef")
else:
print("Paja") | # cook your dish here
# cook your dish here
t=int(input())
for i in range(t):
x,y,k=map(int,input().split())
a=x+y
b=a//k
if b%2==0:
print("Chef")
else:
print("Paja") | train | APPS_structured |
Given a string, capitalize the letters that occupy even indexes and odd indexes separately, and return as shown below. Index `0` will be considered even.
For example, `capitalize("abcdef") = ['AbCdEf', 'aBcDeF']`. See test cases for more examples.
The input will be a lowercase string with no spaces.
Good luck!
If you l... | def capitalize(s):
Even = ''
Odd = ''
Result = []
for i in range(len(s)):
if i % 2 == 0:
Even += s[i].upper()
else:
Even += s[i]
if i % 2 != 0:
Odd += s[i].upper()
else:
Odd += s[i]
Result... | def capitalize(s):
Even = ''
Odd = ''
Result = []
for i in range(len(s)):
if i % 2 == 0:
Even += s[i].upper()
else:
Even += s[i]
if i % 2 != 0:
Odd += s[i].upper()
else:
Odd += s[i]
Result... | train | APPS_structured |
Complete the solution so that it returns true if it contains any duplicate argument values. Any number of arguments may be passed into the function.
The array values passed in will only be strings or numbers. The only valid return values are `true` and `false`.
Examples:
```
solution(1, 2, 3) --> false
sol... | def solution(*args):
# your code here
l = list(args)
s = set(l)
return len(s)!=len(l) | def solution(*args):
# your code here
l = list(args)
s = set(l)
return len(s)!=len(l) | train | APPS_structured |
You are teaching students to generate strings consisting of unique lowercase latin characters (a-z). You give an example reference string $s$ to the students.
You notice that your students just copy paste the reference string instead of creating their own string. So, you tweak the requirements for strings submitted by ... | t=int(input())
for _ in range(t):
#lol={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q' ,'r','s','t','u','v','w','x','y','z'}
s,k=input().split()
k=int(k)
n=len(s)
x=list(set(s))
final=''
for i in range(97,123):
if(chr(i) in x):
if(k>0):
final+=chr(i)
k-=1
else:
con... | t=int(input())
for _ in range(t):
#lol={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q' ,'r','s','t','u','v','w','x','y','z'}
s,k=input().split()
k=int(k)
n=len(s)
x=list(set(s))
final=''
for i in range(97,123):
if(chr(i) in x):
if(k>0):
final+=chr(i)
k-=1
else:
con... | train | APPS_structured |
In a special ranking system, each voter gives a rank from highest to lowest to all teams participated in the competition.
The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie aga... | class Solution:
def rankTeams(self, votes: List[str]) -> str:
'''
ABC
ACB
X 1 2 3
A 2 0 0
B 0 1 1
C 0 1 1
'''
mem = {}
for vote in votes:
for i in range(len(vote)):
team = vote[i]
if ... | class Solution:
def rankTeams(self, votes: List[str]) -> str:
'''
ABC
ACB
X 1 2 3
A 2 0 0
B 0 1 1
C 0 1 1
'''
mem = {}
for vote in votes:
for i in range(len(vote)):
team = vote[i]
if ... | train | APPS_structured |
**This Kata is intended as a small challenge for my students**
Create a function, called ``removeVowels`` (or ``remove_vowels``), that takes a string argument and returns that same string with all vowels removed (vowels are "a", "e", "i", "o", "u"). | REMOVE_VOWS = str.maketrans('','','aeiou')
def remove_vowels(s):
return s.translate(REMOVE_VOWS) | REMOVE_VOWS = str.maketrans('','','aeiou')
def remove_vowels(s):
return s.translate(REMOVE_VOWS) | train | APPS_structured |
Write a function called `sumIntervals`/`sum_intervals()` that accepts an array of intervals, and returns the sum of all the interval lengths. Overlapping intervals should only be counted once.
### Intervals
Intervals are represented by a pair of integers in the form of an array. The first value of the interval will alw... | def sum_of_intervals(intervals):
list1=[]
for i in intervals:
for j in range(i[0],i[1]):
list1.append(j)
set1=set(list1)
return len(set1) | def sum_of_intervals(intervals):
list1=[]
for i in intervals:
for j in range(i[0],i[1]):
list1.append(j)
set1=set(list1)
return len(set1) | train | APPS_structured |
You want to build a standard house of cards, but you don't know how many cards you will need. Write a program which will count the minimal number of cards according to the number of floors you want to have. For example, if you want a one floor house, you will need 7 of them (two pairs of two cards on the base floor, on... | def house_of_cards(floors):
if floors < 1: raise Exception()
return (floors + 1) * (3*floors + 4) // 2 | def house_of_cards(floors):
if floors < 1: raise Exception()
return (floors + 1) * (3*floors + 4) // 2 | train | APPS_structured |
Create a function taking a positive integer as its parameter and returning a string containing the Roman Numeral representation of that integer.
Modern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals 1990 is ... | units = " I II III IV V VI VII VIII IX".split(" ")
tens = " X XX XXX XL L LX LXX LXXX XC".split(" ")
hundreds = " C CC CCC CD D DC DCC DCCC CM".split(" ")
thousands = " M MM MMM".split(" ")
def solution(n):
return thousands[n//1000] + hundreds[n%1000//100] + tens[n%100//10] + units[n%10] | units = " I II III IV V VI VII VIII IX".split(" ")
tens = " X XX XXX XL L LX LXX LXXX XC".split(" ")
hundreds = " C CC CCC CD D DC DCC DCCC CM".split(" ")
thousands = " M MM MMM".split(" ")
def solution(n):
return thousands[n//1000] + hundreds[n%1000//100] + tens[n%100//10] + units[n%10] | train | APPS_structured |
You are asked to write a simple cypher that rotates every character (in range [a-zA-Z], special chars will be ignored by the cipher) by 13 chars. As an addition to the original ROT13 cipher, this cypher will also cypher numerical digits ([0-9]) with 5 chars.
Example:
"The quick brown fox jumps over the 2 lazy dogs"... | def ROT135(message):
first = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
trance = 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm5678901234'
return message.translate(str.maketrans(first, trance)) | def ROT135(message):
first = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
trance = 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm5678901234'
return message.translate(str.maketrans(first, trance)) | train | APPS_structured |
Complete the function which converts hex number (given as a string) to a decimal number. | hex_to_dec=lambda n: int(n, 16) | hex_to_dec=lambda n: int(n, 16) | train | APPS_structured |
Given a binary tree, return the vertical order traversal of its nodes values.
For each node at position (X, Y), its left and right children respectively will be at positions (X-1, Y-1) and (X+1, Y-1).
Running a vertical line from X = -infinity to X = +infinity, whenever the vertical line touches some nodes, we report t... | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def verticalTraversal(self, root: TreeNode) -> List[List[int]]:
hmap = defaultdict(list)
x_m... | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def verticalTraversal(self, root: TreeNode) -> List[List[int]]:
hmap = defaultdict(list)
x_m... | train | APPS_structured |
Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "aabccc" we replace "aa" by "a2" and ... | class Solution:
def getLengthOfOptimalCompression(self, s: str, k: int) -> int:
@lru_cache(None)
def fuck(start,last,c,left):
if start >= len(s):
return 0
if left == 0:
return (1 if c==99 or c == 9 or c ==1 else 0) + fuck(start+1, last, c +1, ... | class Solution:
def getLengthOfOptimalCompression(self, s: str, k: int) -> int:
@lru_cache(None)
def fuck(start,last,c,left):
if start >= len(s):
return 0
if left == 0:
return (1 if c==99 or c == 9 or c ==1 else 0) + fuck(start+1, last, c +1, ... | train | APPS_structured |
Given the array arr of positive integers and the array queries where queries[i] = [Li, Ri], for each query i compute the XOR of elements from Li to Ri (that is, arr[Li] xor arr[Li+1] xor ... xor arr[Ri] ). Return an array containing the result for the given queries.
Example 1:
Input: arr = [1,3,4,8], queries = [[0,1],[... | class Solution:
def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:
n = len(arr)
out=[]
tree = [0]*(2*n)
for i in range(n):
tree[i+n] = arr[i]
for i in range(n-1,0,-1):
tree[i] = tree[i << 1]^tree[i << 1 | 1]
for q in ... | class Solution:
def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:
n = len(arr)
out=[]
tree = [0]*(2*n)
for i in range(n):
tree[i+n] = arr[i]
for i in range(n-1,0,-1):
tree[i] = tree[i << 1]^tree[i << 1 | 1]
for q in ... | train | APPS_structured |
Now that Chef has finished baking and frosting his cupcakes, it's time to package them. Chef has N cupcakes, and needs to decide how many cupcakes to place in each package. Each package must contain the same number of cupcakes. Chef will choose an integer A between 1 and N, inclusive, and place exactly A cupcakes into ... | for t in range(int(input())):
n=int(input())
print((n//2)+1)
| for t in range(int(input())):
n=int(input())
print((n//2)+1)
| train | APPS_structured |
Chef has $N$ dishes of different types arranged in a row: $A_1, A_2, \ldots, A_N$, where $A_i$ denotes the type of the $i^{th}$ dish. He wants to choose as many dishes as possible from the given list but while satisfying two conditions:
- He can choose only one type of dish.
- No two chosen dishes should be adjacen... | for _ in range(int(input())):
n=int(input())
l=list(map(int,input().split()))
s=set(l)
for i in range(1,n):
if l[i]==l[i-1]:
l[i]=-1
# print(l)
m=0
sx=list(s)
sx.sort()
for i in sx:
x=l.count(i)
if m<x:
m=x
z=i
print(z) | for _ in range(int(input())):
n=int(input())
l=list(map(int,input().split()))
s=set(l)
for i in range(1,n):
if l[i]==l[i-1]:
l[i]=-1
# print(l)
m=0
sx=list(s)
sx.sort()
for i in sx:
x=l.count(i)
if m<x:
m=x
z=i
print(z) | train | APPS_structured |
Write a program that prints a chessboard with N rows and M columns with the following rules:
The top left cell must be an asterisk (*)
Any cell touching (left, right, up or down) a cell with an asterisk must be a dot (.)
Any cell touching (left, right, up or down) a cell with a dot must be an asterisk.
A chessboard of ... | def chessboard(s):m,n=map(int,s.split());return'\n'.join(('*.'*n)[i%2:n+i%2]for i in range(m)) | def chessboard(s):m,n=map(int,s.split());return'\n'.join(('*.'*n)[i%2:n+i%2]for i in range(m)) | train | APPS_structured |
Write a method `alternate_sq_sum()` (JS: `alternateSqSum` ) that takes an array of integers as input and finds the sum of squares of the elements at even positions (*i.e.,* 2nd, 4th, *etc.*) plus the sum of the rest of the elements at odd position.
NOTE:
The values at even *position* need to be squared. For a language ... | def alternate_sq_sum(arr):
return sum(num if not i%2 else num**2 for i,num in enumerate(arr)) | def alternate_sq_sum(arr):
return sum(num if not i%2 else num**2 for i,num in enumerate(arr)) | train | APPS_structured |
One player came to a casino and found a slot machine where everything depends only on how he plays. The rules follow.
A positive integer $a$ is initially on the screen. The player can put a coin into the machine and then add $1$ to or subtract $1$ from any two adjacent digits. All digits must remain from $0$ to $9$ aft... | def main():
n = int(input())
a = list(map(int, (x for x in input())))
b = list(map(int, (x for x in input())))
x = [0] * (n - 1)
x[0] = b[0] - a[0]
for i in range(1, n - 1):
x[i] = b[i] - a[i] - x[i - 1]
if a[n - 1] + x[n - 2] != b[n - 1]:
print(-1)
return
cnt = s... | def main():
n = int(input())
a = list(map(int, (x for x in input())))
b = list(map(int, (x for x in input())))
x = [0] * (n - 1)
x[0] = b[0] - a[0]
for i in range(1, n - 1):
x[i] = b[i] - a[i] - x[i - 1]
if a[n - 1] + x[n - 2] != b[n - 1]:
print(-1)
return
cnt = s... | train | APPS_structured |
In this Kata, we define an arithmetic progression as a series of integers in which the differences between adjacent numbers are the same. You will be given an array of ints of `length > 2` and your task will be to convert it into an arithmetic progression by the following rule:
```Haskell
For each element there are exa... | def solve(ls):
result = [ls[each]-ls[each-1] for each in range(1, len(ls))]
gap = round(sum(result)/len(result))
tries = [ls[0]+1, ls[0], ls[0]-1]
answer = []
while True:
count = 0
copy_ls = ls[:]
copy_ls[0] = tries.pop(0)
if copy_ls[0] != ls[0]:
... | def solve(ls):
result = [ls[each]-ls[each-1] for each in range(1, len(ls))]
gap = round(sum(result)/len(result))
tries = [ls[0]+1, ls[0], ls[0]-1]
answer = []
while True:
count = 0
copy_ls = ls[:]
copy_ls[0] = tries.pop(0)
if copy_ls[0] != ls[0]:
... | train | APPS_structured |
Many websites use weighted averages of various polls to make projections for elections. They’re weighted based on a variety of factors, such as historical accuracy of the polling firm, sample size, as well as date(s). The weights, in this kata, are already calculated for you. All you need to do is convert a set of poll... | from operator import itemgetter
from numpy import average
def predict(candidates, polls):
votes = zip(*map(itemgetter(0), polls))
weights = list(map(itemgetter(1), polls))
return {x:round1(average(next(votes), weights=weights)) for x in candidates} | from operator import itemgetter
from numpy import average
def predict(candidates, polls):
votes = zip(*map(itemgetter(0), polls))
weights = list(map(itemgetter(1), polls))
return {x:round1(average(next(votes), weights=weights)) for x in candidates} | train | APPS_structured |
In the wake of the npm's `left-pad` debacle, you decide to write a new super padding method that superceds the functionality of `left-pad`. Your version will provide the same functionality, but will additionally add right, and justified padding of string -- the `super_pad`.
Your function `super_pad` should take three a... | from itertools import chain, islice, cycle
padding = lambda fill, size: islice(cycle(fill), size)
def super_pad(string, width, fill=" "):
if not width: return ''
if not fill: return string[:width]
size = width - len(string)
if size <= 0: return string[:width] if fill[0] in '>^' else string[-width:]
... | from itertools import chain, islice, cycle
padding = lambda fill, size: islice(cycle(fill), size)
def super_pad(string, width, fill=" "):
if not width: return ''
if not fill: return string[:width]
size = width - len(string)
if size <= 0: return string[:width] if fill[0] in '>^' else string[-width:]
... | train | APPS_structured |
Given a number $n$, give the last digit of sum of all the prime numbers from 1 to $n$ inclusive.
-----Input:-----
- First line contains number of testcase $t$.
- Each testcase contains of a single line of input, number $n$.
-----Output:-----
Last digit of sum of every prime number till n.
-----Constraints-----
- $1 \l... |
def sumOfPrimes(n):
prime = [True] * (n + 1)
p = 2
while p * p <= n:
if prime[p] == True:
i = p * 2
while i <= n:
prime[i] = False
i += p
p += 1
sum = 0
for i in range (2, n + 1):
if(prime[i]):
sum += i
return sum
for _ in range(int(input())):
n = int(input())
zzz... |
def sumOfPrimes(n):
prime = [True] * (n + 1)
p = 2
while p * p <= n:
if prime[p] == True:
i = p * 2
while i <= n:
prime[i] = False
i += p
p += 1
sum = 0
for i in range (2, n + 1):
if(prime[i]):
sum += i
return sum
for _ in range(int(input())):
n = int(input())
zzz... | train | APPS_structured |
Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither.
IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots ("."), e.g.,172.16.254.1;
Besides, leading zeros in the IPv4 is ... | class Solution:
def validIPAddress(self, IP):
"""
:type IP: str
:rtype: str
"""
def is_hex(hexs):
hex_set = set('0123456789abcdefABCDEF')
return set(hexs)<hex_set
result = 'Neither'
if '.' in IP:
sub_str... | class Solution:
def validIPAddress(self, IP):
"""
:type IP: str
:rtype: str
"""
def is_hex(hexs):
hex_set = set('0123456789abcdefABCDEF')
return set(hexs)<hex_set
result = 'Neither'
if '.' in IP:
sub_str... | train | APPS_structured |
In this kata, we will check is an array is (hyper)rectangular.
A rectangular array is an N-dimensional array with fixed sized within one dimension. Its sizes can be repsented like A1xA2xA3...xAN. That means a N-dimensional array has N sizes. The 'As' are the hyperrectangular properties of an array.
You should impleme... | def hp(arr):
if not isinstance(arr, list):
return ()
elif not arr:
return (0,)
xs = list(map(hp, arr))
if None not in xs and all(x == xs[0] for x in xs):
return (len(arr),) + xs[0]
hyperrectangularity_properties = hp | def hp(arr):
if not isinstance(arr, list):
return ()
elif not arr:
return (0,)
xs = list(map(hp, arr))
if None not in xs and all(x == xs[0] for x in xs):
return (len(arr),) + xs[0]
hyperrectangularity_properties = hp | train | APPS_structured |
Chef and Abhishek both are fighting for the post of Chairperson to be part of ACE committee and are trying their best. To select only one student their teacher gave them a binary string (string consisting of only 0's and 1's) and asked them to find number of sub-strings present in the given string that satisfy the foll... | for t in range(int(input())):
def csbstr(str,n,a,b):
tot,c=0,0
for i in range(n):
if(str[i]==a):
c+=1
if(str[i]==b):
tot+=c
return tot
n=int(input())
str=input()
count1=csbstr(str,n,"1","0")
count2=csbstr(str,n,"0","1")... | for t in range(int(input())):
def csbstr(str,n,a,b):
tot,c=0,0
for i in range(n):
if(str[i]==a):
c+=1
if(str[i]==b):
tot+=c
return tot
n=int(input())
str=input()
count1=csbstr(str,n,"1","0")
count2=csbstr(str,n,"0","1")... | train | APPS_structured |
Consider the following series:
`0,1,2,3,4,5,6,7,8,9,10,22,11,20,13,24...`There is nothing special between numbers `0` and `10`.
Let's start with the number `10` and derive the sequence. `10` has digits `1` and `0`. The next possible number that does not have a `1` or a `0` is `22`. All other numbers between `10` and `... | M = [0]
while len(M) <= 500:
k, s = 0, {c for c in str(M[-1])}
while k in M or {c for c in str(k)} & s:
k += 1
M.append(k)
find_num = lambda n: M[n] | M = [0]
while len(M) <= 500:
k, s = 0, {c for c in str(M[-1])}
while k in M or {c for c in str(k)} & s:
k += 1
M.append(k)
find_num = lambda n: M[n] | train | APPS_structured |
**Steps**
1. Square the numbers that are greater than zero.
2. Multiply by 3 every third number.
3. Multiply by -1 every fifth number.
4. Return the sum of the sequence.
**Example**
`{ -2, -1, 0, 1, 2 }` returns `-6`
```
1. { -2, -1, 0, 1 * 1, 2 * 2 }
2. { -2, -1, 0 * 3, 1, 4 }
3. { -2, -1, 0, 1, -1 * 4 }
4. -6
```
... | def calc(a):
return sum(i**(1,2)[i>0]*(1,3)[idx%3==2]*(1,-1)[idx%5==4] for idx,i in enumerate(a)) | def calc(a):
return sum(i**(1,2)[i>0]*(1,3)[idx%3==2]*(1,-1)[idx%5==4] for idx,i in enumerate(a)) | train | APPS_structured |
Today a plane was hijacked by a maniac. All the passengers of the flight are taken as hostage. Chef is also one of them.
He invited one of the passengers to play a game with him. If he loses the game, he will release all the passengers, otherwise he will kill all of them. A high risk affair it is.
Chef volunteered for ... | T = eval(input())
for _ in range(T):
col = sorted(map(int, input().split()))
k = eval(input())
ans = min(col[0], k-1) + min(col[1], k-1) + min(col[2], k-1) + 1
print(ans) | T = eval(input())
for _ in range(T):
col = sorted(map(int, input().split()))
k = eval(input())
ans = min(col[0], k-1) + min(col[1], k-1) + min(col[2], k-1) + 1
print(ans) | train | APPS_structured |
It's your Birthday. Your colleagues buy you a cake. The numbers of candles on the cake is provided (x). Please note this is not reality, and your age can be anywhere up to 1,000. Yes, you would look a mess.
As a surprise, your colleagues have arranged for your friend to hide inside the cake and burst out. They pretend ... | def cake(candles,debris):
total = 0
for i,x in enumerate(list(debris)):
total += ord(x)-(96 if i%2==1 else 0)
return 'That was close!' if candles*0.7>total or candles==0 else 'Fire!'
| def cake(candles,debris):
total = 0
for i,x in enumerate(list(debris)):
total += ord(x)-(96 if i%2==1 else 0)
return 'That was close!' if candles*0.7>total or candles==0 else 'Fire!'
| train | APPS_structured |
Iahub likes trees very much. Recently he discovered an interesting tree named propagating tree. The tree consists of n nodes numbered from 1 to n, each node i having an initial value a_{i}. The root of the tree is node 1.
This tree has a special property: when a value val is added to a value of node i, the value -val i... | class BIT():
"""区間加算、一点取得クエリをそれぞれO(logN)で応えるデータ構造を構築する
add: 区間[begin, end)にvalを加える
get_val: i番目(0-indexed)の値を求める
"""
def __init__(self, n):
self.n = n
self.bit = [0] * (n + 1)
def get_val(self, i):
i = i + 1
s = 0
while i <= self.n:
s += self.... | class BIT():
"""区間加算、一点取得クエリをそれぞれO(logN)で応えるデータ構造を構築する
add: 区間[begin, end)にvalを加える
get_val: i番目(0-indexed)の値を求める
"""
def __init__(self, n):
self.n = n
self.bit = [0] * (n + 1)
def get_val(self, i):
i = i + 1
s = 0
while i <= self.n:
s += self.... | train | APPS_structured |
*** Nova polynomial subtract***
This kata is from a series on polynomial handling. ( [#1](http://www.codewars.com/kata/nova-polynomial-1-add-1) [#2](http://www.codewars.com/kata/570eb07e127ad107270005fe) [#3](http://www.codewars.com/kata/5714041e8807940ff3001140 ) [#4](http://www.codewars.com/kata/571a2e2df24bdfd... | from itertools import zip_longest
def poly_subtract(a, b):
return [x - y for x, y in zip_longest(a, b, fillvalue=0)] | from itertools import zip_longest
def poly_subtract(a, b):
return [x - y for x, y in zip_longest(a, b, fillvalue=0)] | train | APPS_structured |
_A mad sociopath scientist just came out with a brilliant invention! He extracted his own memories to forget all the people he hates! Now there's a lot of information in there, so he needs your talent as a developer to automatize that task for him._
> You are given the memories as a string containing people's surname a... | def select(memory):
lst = memory.split(', ')
bad = {who.strip('!') for prev,who in zip(['']+lst,lst+['']) if who.startswith('!') or prev.startswith('!')}
return ', '.join(who for who in map(lambda s: s.strip('!'), lst) if who not in bad) | def select(memory):
lst = memory.split(', ')
bad = {who.strip('!') for prev,who in zip(['']+lst,lst+['']) if who.startswith('!') or prev.startswith('!')}
return ', '.join(who for who in map(lambda s: s.strip('!'), lst) if who not in bad) | train | APPS_structured |
A product-sum number is a natural number N which can be expressed as both the product and the sum of the same set of numbers.
N = a1 × a2 × ... × ak = a1 + a2 + ... + ak
For example, 6 = 1 × 2 × 3 = 1 + 2 + 3.
For a given set of size, k, we shall call the smallest N with this property a minimal product-sum number. The ... | maxi = 12001
res = [2*maxi]*maxi
def rec(p, s, c, x):
k = p - s + c
if k >= maxi: return
res[k] = min(p, res[k])
[rec(p*i, s+i, c+1, i) for i in range(x, 2*maxi//p + 1)]
rec(1, 1, 1, 2)
def productsum(n):
return sum(set(res[2:n+1])) | maxi = 12001
res = [2*maxi]*maxi
def rec(p, s, c, x):
k = p - s + c
if k >= maxi: return
res[k] = min(p, res[k])
[rec(p*i, s+i, c+1, i) for i in range(x, 2*maxi//p + 1)]
rec(1, 1, 1, 2)
def productsum(n):
return sum(set(res[2:n+1])) | train | APPS_structured |
# Task
Imagine `n` horizontal lines and `m` vertical lines.
Some of these lines intersect, creating rectangles.
How many rectangles are there?
# Examples
For `n=2, m=2,` the result should be `1`.
there is only one 1x1 rectangle.
For `n=2, m=3`, the result should be `3`.
there are two 1x1 rectangles and one 1x2 rectangl... | def rectangles(n, m):
return n*m*(n-1)*(m-1)//4 | def rectangles(n, m):
return n*m*(n-1)*(m-1)//4 | train | APPS_structured |
Three Best Friends $AMAN$ , $AKBAR$ , $ANTHONY$ are planning to go to “GOA” , but just like every other goa trip plan there is a problem to their plan too.
Their parents will only give permission if they can solve this problem for them
They are a given a number N and they have to calculate the total number of triplets... | N = int(input())
r = range(1, N + 1)
count = 0
for i in r:
for j in r:
if i * j >= N: break
count += 1
print(count) | N = int(input())
r = range(1, N + 1)
count = 0
for i in r:
for j in r:
if i * j >= N: break
count += 1
print(count) | train | APPS_structured |
# Task
Changu and Mangu are great buddies. Once they found an infinite paper which had 1,2,3,4,5,6,7,8,......... till infinity, written on it.
Both of them did not like the sequence and started deleting some numbers in the following way.
```
First they deleted every 2nd number.
So remaining numbers on the paper: 1,3... | def survivor(n):
i=2
while i<=n:
if n%i==0:return False
n-=n//i
i+=1
return True | def survivor(n):
i=2
while i<=n:
if n%i==0:return False
n-=n//i
i+=1
return True | train | APPS_structured |
Johnny has just found the new, great tutorial: "How to become a grandmaster?". The tutorial tells many strange and unexpected for Johnny things, such as you have to be patient or that very important is solving many harder and harder problems.
The boy has found an online judge with tasks divided by topics they cover. H... | import sys
readline = sys.stdin.readline
T = int(readline())
Ans = [None]*T
MOD = 10**9+7
mod = 10**9+9
for qu in range(T):
N, P = map(int, readline().split())
A = list(map(int, readline().split()))
if P == 1:
if N&1:
Ans[qu] = 1
else:
Ans[qu] = 0
continue
... | import sys
readline = sys.stdin.readline
T = int(readline())
Ans = [None]*T
MOD = 10**9+7
mod = 10**9+9
for qu in range(T):
N, P = map(int, readline().split())
A = list(map(int, readline().split()))
if P == 1:
if N&1:
Ans[qu] = 1
else:
Ans[qu] = 0
continue
... | train | APPS_structured |
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.
Allen's future parking lot can be repres... | n,k=list(map(int,input().split()))
m=[]
c=0
for i in range(4):
m.append(list(map(int,input().split())))
res=[]
for i in range(n):
if m[1][i] != 0:
if m[1][i] == m[0][i]:
res.append([m[1][i],1,i+1])
m[1][i] = 0
k-=1
for i in range(n):
if m[2][i] != 0:
if m[... | n,k=list(map(int,input().split()))
m=[]
c=0
for i in range(4):
m.append(list(map(int,input().split())))
res=[]
for i in range(n):
if m[1][i] != 0:
if m[1][i] == m[0][i]:
res.append([m[1][i],1,i+1])
m[1][i] = 0
k-=1
for i in range(n):
if m[2][i] != 0:
if m[... | train | APPS_structured |
Write a function that checks the braces status in a string, and return `True` if all braces are properly closed, or `False` otherwise. Available types of brackets: `()`, `[]`, `{}`.
**Please note, you need to write this function without using regex!**
## Examples
```python
'([[some](){text}here]...)' => True
'{([])}'... | parens = dict([')(', '][', '}{'])
opens = set(parens.values())
def braces_status(s):
stack = []
for c in s:
if c in opens:
stack.append(c)
elif c in parens:
if not (stack and stack.pop() == parens[c]):
return False
return not stack | parens = dict([')(', '][', '}{'])
opens = set(parens.values())
def braces_status(s):
stack = []
for c in s:
if c in opens:
stack.append(c)
elif c in parens:
if not (stack and stack.pop() == parens[c]):
return False
return not stack | train | APPS_structured |
Blob is a computer science student. He recently got an internship from Chef's enterprise. Along with the programming he has various other skills too like graphic designing, digital marketing and social media management. Looking at his skills Chef has provided him different tasks A[1…N] which have their own scores. Blog... | def maxval(arr):
fn = [float('-inf')]*(len(arr)+1)
sn = [float('-inf')]*len(arr)
tn = [float('-inf')]*(len(arr)-1)
fon = [float('-inf')]*(len(arr)-2)
for i in reversed(list(range(len(arr)))):
fn[i] = max(fn[i + 1], arr[i])
for i in reversed(list(range(len(arr) - 1))):
sn[i] = max... | def maxval(arr):
fn = [float('-inf')]*(len(arr)+1)
sn = [float('-inf')]*len(arr)
tn = [float('-inf')]*(len(arr)-1)
fon = [float('-inf')]*(len(arr)-2)
for i in reversed(list(range(len(arr)))):
fn[i] = max(fn[i + 1], arr[i])
for i in reversed(list(range(len(arr) - 1))):
sn[i] = max... | train | APPS_structured |
Given an array of integers nums, you start with an initial positive value startValue.
In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right).
Return the minimum positive value of startValue such that the step by step sum is never less than 1.
Example 1:
Input: num... | class Solution:
def minStartValue(self, nums: List[int]) -> int:
running_min = nums[0]
reduction = 0
for i in nums:
reduction += i
running_min = min(running_min, reduction)
return 1 if running_min >= 1 else 1 - running_min | class Solution:
def minStartValue(self, nums: List[int]) -> int:
running_min = nums[0]
reduction = 0
for i in nums:
reduction += i
running_min = min(running_min, reduction)
return 1 if running_min >= 1 else 1 - running_min | train | APPS_structured |
Given an array A of strings, find any smallest string that contains each string in A as a substring.
We may assume that no string in A is substring of another string in A.
Example 1:
Input: ["alex","loves","leetcode"]
Output: "alexlovesleetcode"
Explanation: All permutations of "alex","loves","leetcode" would also be a... | class Solution:
# https://www.youtube.com/watch?v=u_Wc4jwrp3Q
# time: O(n^2 * 2 ^ n), space(n * 2 ^ n)
def shortestSuperstring(self, A: List[str]) -> str:
# add string t in the end of string s. cost = # of chars can't be merged.
def mergecost(s, t):
c = len(t)
for i i... | class Solution:
# https://www.youtube.com/watch?v=u_Wc4jwrp3Q
# time: O(n^2 * 2 ^ n), space(n * 2 ^ n)
def shortestSuperstring(self, A: List[str]) -> str:
# add string t in the end of string s. cost = # of chars can't be merged.
def mergecost(s, t):
c = len(t)
for i i... | train | APPS_structured |
Two words rhyme if their last 3 letters are a match. Given N words, print the test case number (of the format Case : num) followed by the rhyming words in separate line adjacent to each other.
The output can be in anyorder.
-----Input-----
First line contains the number of test case T
The next line contains the number ... | t = int(input())
for i in range(t):
n = int(input())
suffixes = {}
xx = input().split()
for x in range(n):
try:
a = suffixes[xx[x][-3:]]
except Exception as e:
a = []
a.append(xx[x])
suffixes.update({xx[x][-3:]: a})
print("Case : %d" % (i + 1))
for a in sorted(suffixes):
print("".join(b + " " fo... | t = int(input())
for i in range(t):
n = int(input())
suffixes = {}
xx = input().split()
for x in range(n):
try:
a = suffixes[xx[x][-3:]]
except Exception as e:
a = []
a.append(xx[x])
suffixes.update({xx[x][-3:]: a})
print("Case : %d" % (i + 1))
for a in sorted(suffixes):
print("".join(b + " " fo... | train | APPS_structured |
Given an encoded string, return it's decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square bra... | class Solution:
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
m = len(s)
if m == 0:
return ''
result = []
for i in s:
if i != ']':
result.append(i)
else:
ch... | class Solution:
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
m = len(s)
if m == 0:
return ''
result = []
for i in s:
if i != ']':
result.append(i)
else:
ch... | train | APPS_structured |
=====Function Descriptions=====
zeros
The zeros tool returns a new array with a given shape and type filled with 0's.
import numpy
print numpy.zeros((1,2)) #Default type is float
#Output : [[ 0. 0.]]
print numpy.zeros((1,2), dtype = numpy.int) #Type changes to int
#Output : [[0 0]]
ones
The ones to... | import numpy
dims = [int(x) for x in input().strip().split()]
print(numpy.zeros(tuple(dims), dtype = numpy.int))
print(numpy.ones(tuple(dims), dtype = numpy.int)) | import numpy
dims = [int(x) for x in input().strip().split()]
print(numpy.zeros(tuple(dims), dtype = numpy.int))
print(numpy.ones(tuple(dims), dtype = numpy.int)) | train | APPS_structured |
You are required to create a simple calculator that returns the result of addition, subtraction, multiplication or division of two numbers.
Your function will accept three arguments:
The first and second argument should be numbers.
The third argument should represent a sign indicating the operation to perform on these ... | def calculator(x,y,op):
if type(x) != int or type(y) != int:
return('unknown value')
elif op == '/':
return(x/y)
elif op == '*':
return(x*y)
elif op == '-':
return(x-y)
elif op == '+':
return(x+y)
else:
return('unknown value')
pass | def calculator(x,y,op):
if type(x) != int or type(y) != int:
return('unknown value')
elif op == '/':
return(x/y)
elif op == '*':
return(x*y)
elif op == '-':
return(x-y)
elif op == '+':
return(x+y)
else:
return('unknown value')
pass | train | APPS_structured |
Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.
Note:
You may assume the interval's end point is always bigger than its start point.
Intervals like [1,2] and [2,3] have borders "touching" but they don't overlap each other.
Examp... | # Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
def eraseOverlapIntervals(self, intervals):
"""
:type intervals: List[Interval]
:rtype: int
"""
start_end={}
... | # Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
def eraseOverlapIntervals(self, intervals):
"""
:type intervals: List[Interval]
:rtype: int
"""
start_end={}
... | train | APPS_structured |
Mothers arranged a dance party for the children in school. At that party, there are only mothers and their children. All are having great fun on the dance floor when suddenly all the lights went out. It's a dark night and no one can see each other. But you were flying nearby and you can see in the dark and have ability... | def find_children(db):
return ''.join(sorted(db, key = lambda a: (a.upper(), a))) | def find_children(db):
return ''.join(sorted(db, key = lambda a: (a.upper(), a))) | train | APPS_structured |
A manufacturing project consists of exactly $K$ tasks. The board overviewing the project wants to hire $K$ teams of workers — one for each task. All teams begin working simultaneously.
Obviously, there must be at least one person in each team. For a team of $A$ workers, it takes exactly $A$ days to complete the task th... | def find_div(x):
b=[]
e=int(x**0.5)+1
for i in range(2,e):
if x%i==0:
c=0
while x%i==0:
c+=1
x=x//i
b.append(i**c)
if x!=1:
b.append(x)
return b
def solve(a,div,pos):
if pos==len(div):
return sum(a)
ans=2**30
for i in range(len(a)):
a[i]*=div[pos]
ans=min(ans,solve(a,div,pos+1))
... | def find_div(x):
b=[]
e=int(x**0.5)+1
for i in range(2,e):
if x%i==0:
c=0
while x%i==0:
c+=1
x=x//i
b.append(i**c)
if x!=1:
b.append(x)
return b
def solve(a,div,pos):
if pos==len(div):
return sum(a)
ans=2**30
for i in range(len(a)):
a[i]*=div[pos]
ans=min(ans,solve(a,div,pos+1))
... | train | APPS_structured |
We'll create a function that takes in two parameters:
* a sequence (length and types of items are irrelevant)
* a function (value, index) that will be called on members of the sequence and their index. The function will return either true or false.
Your function will iterate through the members of the sequence in order... | def find_in_array(seq, predicate):
for index, value in enumerate(seq):
if predicate(value,index):
return index
return -1
# print(type(predicate)) #function
# print(type(seq)) #list
# print(predicate.__name__) lambda
| def find_in_array(seq, predicate):
for index, value in enumerate(seq):
if predicate(value,index):
return index
return -1
# print(type(predicate)) #function
# print(type(seq)) #list
# print(predicate.__name__) lambda
| train | APPS_structured |
As you might remember, the collector of Siruseri had ordered
a complete revision of the Voters List. He knew that constructing
the list of voters is a difficult task, prone to errors. Some
voters may have been away on vacation, others may have moved
during the enrollment and so on.
To be as accurate as possible, he en... | from sys import stdout, stdin
n,m,o = list(map(int, stdin.readline().split()))
n= n+m+o
l=[]
a=[]
for i in range(n):
b= int(stdin.readline())
if(b in l and b not in a):
l.append(b)
a.append(b)
elif(b not in l):
l.append(b)
a.sort()
stdout.write(str(len(a)) + '\n')
stdout.write(''.j... | from sys import stdout, stdin
n,m,o = list(map(int, stdin.readline().split()))
n= n+m+o
l=[]
a=[]
for i in range(n):
b= int(stdin.readline())
if(b in l and b not in a):
l.append(b)
a.append(b)
elif(b not in l):
l.append(b)
a.sort()
stdout.write(str(len(a)) + '\n')
stdout.write(''.j... | train | APPS_structured |
# Task
Given array of integers, for each position i, search among the previous positions for the last (from the left) position that contains a smaller value. Store this value at position i in the answer. If no such value can be found, store `-1` instead.
# Example
For `items = [3, 5, 2, 4, 5]`, the output should be `... | import numpy as np
def array_previous_less(arr):
arr = arr[::-1]
output = np.full(len(arr), -1)
for i in range(len(arr)):
for j in arr[i+1:]:
if j<arr[i]:
output[i] = j
break
return output.tolist()[::-1] | import numpy as np
def array_previous_less(arr):
arr = arr[::-1]
output = np.full(len(arr), -1)
for i in range(len(arr)):
for j in arr[i+1:]:
if j<arr[i]:
output[i] = j
break
return output.tolist()[::-1] | train | APPS_structured |
Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique.
Example 1:
Input: arr = [1,2,2,1,1,3]
Output: true
Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.
Example... | class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
rec = [arr.count(elem) for elem in set(arr)]
return len(rec) == len(set(rec))
| class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
rec = [arr.count(elem) for elem in set(arr)]
return len(rec) == len(set(rec))
| train | APPS_structured |
When provided with a String, capitalize all vowels
For example:
Input : "Hello World!"
Output : "HEllO WOrld!"
Note: Y is not a vowel in this kata. | swap=lambda s:s.translate(s.maketrans('aiueo','AIUEO')) | swap=lambda s:s.translate(s.maketrans('aiueo','AIUEO')) | train | APPS_structured |
You are given a binary tree:
```python
class Node:
def __init__(self, L, R, n):
self.left = L
self.right = R
self.value = n
```
Your task is to return the list with elements from tree sorted by levels, which means the root element goes first, then root children (from left to right) are secon... | # Use a queue. Add root node, then loop:
# get first queue element, add all its children in the queue, left to right
# and add the current node's value in the result
def tree_by_levels(node):
queue = []
result = []
if node == None:
return result
queue.append(node)
while len(queue) > 0:
... | # Use a queue. Add root node, then loop:
# get first queue element, add all its children in the queue, left to right
# and add the current node's value in the result
def tree_by_levels(node):
queue = []
result = []
if node == None:
return result
queue.append(node)
while len(queue) > 0:
... | train | APPS_structured |
Two moving objects A and B are moving accross the same orbit (those can be anything: two planets, two satellites, two spaceships,two flying saucers, or spiderman with batman if you prefer).
If the two objects start to move from the same point and the orbit is circular, write a function that gives the time the two objec... | def meeting_time(Ta, Tb, r):
if Ta == 0 and Tb == 0: return "0.00"
if Ta == 0: return "%.2f" % abs(Tb)
if Tb == 0: return "%.2f" % abs(Ta)
if (Ta > 0 and Tb > 0) or (Ta < 0 and Tb < 0):
return "%.2f" % (Ta * Tb / abs(abs(Ta) - abs(Tb)))
if ((Ta > 0 and Tb < 0) or (Tb > 0 and Ta < 0)):
... | def meeting_time(Ta, Tb, r):
if Ta == 0 and Tb == 0: return "0.00"
if Ta == 0: return "%.2f" % abs(Tb)
if Tb == 0: return "%.2f" % abs(Ta)
if (Ta > 0 and Tb > 0) or (Ta < 0 and Tb < 0):
return "%.2f" % (Ta * Tb / abs(abs(Ta) - abs(Tb)))
if ((Ta > 0 and Tb < 0) or (Tb > 0 and Ta < 0)):
... | train | APPS_structured |
In recreational mathematics, a [Keith number](https://en.wikipedia.org/wiki/Keith_number) or repfigit number (short for repetitive Fibonacci-like digit) is a number in the following integer sequence:
`14, 19, 28, 47, 61, 75, 197, 742, 1104, 1537, 2208, 2580, 3684, 4788, 7385, 7647, 7909, ...` (sequence A007629 in the O... | def is_keith_number(n):
numList = [int(i) for i in str(n)] # int array
if len(numList) > 1: # min 2 digits
itr = 0
while numList[0] <= n:
# replace array entries by its sum:
numList[itr % len(numList)] = sum(numList)
itr += 1
if n in numList: # ... | def is_keith_number(n):
numList = [int(i) for i in str(n)] # int array
if len(numList) > 1: # min 2 digits
itr = 0
while numList[0] <= n:
# replace array entries by its sum:
numList[itr % len(numList)] = sum(numList)
itr += 1
if n in numList: # ... | train | APPS_structured |
Freddy has a really fat left pinky finger, and every time Freddy tries to type an ```A```, he accidentally hits the CapsLock key!
Given a string that Freddy wants to type, emulate the keyboard misses where each ```A``` supposedly pressed is replaced with CapsLock, and return the string that Freddy actually types. It do... | def fat_fingers(string):
if string == "":
return string
if string is None:
return None
new_string = ""
caps_lock = False
for l in string:
if l.isalpha():
if l.lower() == 'a':
caps_lock = not caps_lock
... | def fat_fingers(string):
if string == "":
return string
if string is None:
return None
new_string = ""
caps_lock = False
for l in string:
if l.isalpha():
if l.lower() == 'a':
caps_lock = not caps_lock
... | train | APPS_structured |
This is the simple version of Shortest Code series. If you need some challenges, please try the [challenge version](http://www.codewars.com/kata/56f928b19982cc7a14000c9d)
## Task:
Every uppercase letter is Father, The corresponding lowercase letters is the Son.
Give you a string ```s```, If the father and son both... | def sc(s):
return ''.join(i for i in s if i.swapcase() in set(s)) | def sc(s):
return ''.join(i for i in s if i.swapcase() in set(s)) | train | APPS_structured |
You may have tried your level best to help Chef but Dr Doof has managed to come up with his masterplan in the meantime. Sadly, you have to help Chef once again. Dr Doof has designed a parenthesis-inator. It throws a stream of $N$ brackets at the target, $1$ bracket per second. The brackets can either be opening or clos... | from collections import deque
from sys import stdin
input=stdin.readline
for _ in range(int(input())):
s=list(input())
n=len(s)
ans=[0]*n
x=0
y=0
a=n-1
b=n-1
stack=deque([])
prev=-1
while a>=0:
if s[a]==')':
stack.append(a)
ans[a] = prev
e... | from collections import deque
from sys import stdin
input=stdin.readline
for _ in range(int(input())):
s=list(input())
n=len(s)
ans=[0]*n
x=0
y=0
a=n-1
b=n-1
stack=deque([])
prev=-1
while a>=0:
if s[a]==')':
stack.append(a)
ans[a] = prev
e... | train | APPS_structured |
Cheffina challanges chef to rearrange the given array as arr[i] > arr[i+1] < arr[i+2] > arr[i+3].. and so on…, i.e. also arr[i] < arr[i+2] and arr[i+1] < arr[i+3] and arr[i] < arr[i+3] so on.. Chef accepts the challenge, chef starts coding but his code is not compiling help him to write new code.
-----Input:-----
- Fir... | # cook your dish here
for _ in range(int(input())):
n=int(input())
arr=[int(i) for i in input().split()]
arr=sorted(arr)
for i in range(n):
if i%2==0:
if i==n-1:
print(arr[i],'',end='')
else:
print(arr[i+1],'',end='')
else:
... | # cook your dish here
for _ in range(int(input())):
n=int(input())
arr=[int(i) for i in input().split()]
arr=sorted(arr)
for i in range(n):
if i%2==0:
if i==n-1:
print(arr[i],'',end='')
else:
print(arr[i+1],'',end='')
else:
... | train | APPS_structured |
The chef is trying to solve some pattern problems, Chef wants your help to code it. Chef has one number K (odd) 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 lin... | import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")
inp = lambda: list(map(int,sys.stdin.readline().rstrip("\r\n").split()))
#______________________________________________________________________________________________________
# from math import *
# from bisect import *
# from heapq import *
# from ... | import sys
input = lambda: sys.stdin.readline().rstrip("\r\n")
inp = lambda: list(map(int,sys.stdin.readline().rstrip("\r\n").split()))
#______________________________________________________________________________________________________
# from math import *
# from bisect import *
# from heapq import *
# from ... | train | APPS_structured |
Your task is the exact same as for the easy version. But this time, the marmots subtract the village's population P from their random number before responding to Heidi's request.
Also, there are now villages with as few as a single inhabitant, meaning that $1 \leq P \leq 1000$.
Can you help Heidi find out whether a vil... | for i in range(int(input())):
a=list(map(int,input().split()))
mx=max(list(map(abs,a)))
std=(sum(list([x*x for x in a]))/len(a))**0.5
print('poisson'if mx/std>2 else'uniform')
| for i in range(int(input())):
a=list(map(int,input().split()))
mx=max(list(map(abs,a)))
std=(sum(list([x*x for x in a]))/len(a))**0.5
print('poisson'if mx/std>2 else'uniform')
| train | APPS_structured |
You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' $\rightarrow$ 'y' $\rightarrow$ 'x' $\rightarrow \ldots \rightarrow$ 'b' $\rightarrow$ 'a' $\rightarrow$ 'z'. In other words, each character is replaced with th... | import sys
def shl(s, be, en):
t = s[:be];
for i in range(be, en):
if s[i]=='a':
t += 'z'
else:
t += chr(ord(s[i])-1)
return t+s[en:]
s = input()
i = 0
L = len(s)
while i<L and s[i]=='a':
i += 1
if i==L:
print(s[:L-1]+'z')
return
j = i+1
while j<L a... | import sys
def shl(s, be, en):
t = s[:be];
for i in range(be, en):
if s[i]=='a':
t += 'z'
else:
t += chr(ord(s[i])-1)
return t+s[en:]
s = input()
i = 0
L = len(s)
while i<L and s[i]=='a':
i += 1
if i==L:
print(s[:L-1]+'z')
return
j = i+1
while j<L a... | train | APPS_structured |
Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm.
Sereja takes a blank piece of paper. Then he starts writing out the sequence in m stages. Each time he either adds a new number to the end of the sequence or takes l first elements of the current sequ... | from bisect import bisect_left
m = int(input())
t, s = [input().split() for i in range(m)], [0] * m
l, n = 0, int(input())
for j, i in enumerate(t):
l += 1 if i[0] == '1' else int(i[1]) * int(i[2])
t[j], s[j] = l, i[1] if i[0] == '1' else int(i[1])
F = {}
def f(i):
if not i in F:
k = bisect_left(t, ... | from bisect import bisect_left
m = int(input())
t, s = [input().split() for i in range(m)], [0] * m
l, n = 0, int(input())
for j, i in enumerate(t):
l += 1 if i[0] == '1' else int(i[1]) * int(i[2])
t[j], s[j] = l, i[1] if i[0] == '1' else int(i[1])
F = {}
def f(i):
if not i in F:
k = bisect_left(t, ... | train | APPS_structured |
You came across this story while reading a book. Long a ago when the modern entertainment systems did not exist people used to go to watch plays in theaters, where people would perform live in front of an audience. There was a beautiful actress who had a disability she could not pronounce the character $'r'$. To win he... | # def count(a, b):
# m = len(a);n = 1
# lookup = [[0] * (n + 1) for i in range(m + 1)]
# for i in range(n+1): lookup[0][i] = 0
# for i in range(m + 1): lookup[i][0] = 1
# for i in range(1, m + 1):
# for j in range(1, n + 1):
# if a[i - 1] == b[j - 1]: lookup[i][j] = lookup[i - 1][j - 1] + lookup[i - 1][j]... | # def count(a, b):
# m = len(a);n = 1
# lookup = [[0] * (n + 1) for i in range(m + 1)]
# for i in range(n+1): lookup[0][i] = 0
# for i in range(m + 1): lookup[i][0] = 1
# for i in range(1, m + 1):
# for j in range(1, n + 1):
# if a[i - 1] == b[j - 1]: lookup[i][j] = lookup[i - 1][j - 1] + lookup[i - 1][j]... | train | APPS_structured |
"The Shell Game" involves cups upturned on a playing surface, with a ball placed underneath one of them. The index of the cups are swapped around multiple times. After that the players will try to find which cup contains the ball.
Your task is as follows. Given the cup that the ball starts under, and list of swaps, r... | def find_the_ball(pos, swaps):
for a, b in swaps:
pos = a if pos == b else b if pos == a else pos
return pos | def find_the_ball(pos, swaps):
for a, b in swaps:
pos = a if pos == b else b if pos == a else pos
return pos | train | APPS_structured |
=====Function Descriptions=====
itertools.combinations_with_replacement(iterable, r)
This tool returns
length subsequences of elements from the input iterable allowing individual elements to be repeated more than once.
Combinations are emitted in lexicographic sorted order. So, if the input iterable is sorted, the comb... | from itertools import *
s,n = input().split()
n = int(n)
s = sorted(s)
for j in combinations_with_replacement(s,n):
print((''.join(j)))
| from itertools import *
s,n = input().split()
n = int(n)
s = sorted(s)
for j in combinations_with_replacement(s,n):
print((''.join(j)))
| train | APPS_structured |
Now that Heidi has made sure her Zombie Contamination level checker works, it's time to strike! This time, the zombie lair is a strictly convex polygon on the lattice. Each vertex of the polygon occupies a point on the lattice. For each cell of the lattice, Heidi knows the level of Zombie Contamination – the number of ... | import math
def lexComp(a, b):
if a[0] != b[0]:
return -1 if a[0] < b[0] else 1
if a[1] != b[1]:
return -1 if a[1] < b[1] else 1
return 0
def turn(a, b, c):
return (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])
def dist2(a, b):
return (a[0] - b[0]) ** 2 + (a[1] ... | import math
def lexComp(a, b):
if a[0] != b[0]:
return -1 if a[0] < b[0] else 1
if a[1] != b[1]:
return -1 if a[1] < b[1] else 1
return 0
def turn(a, b, c):
return (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])
def dist2(a, b):
return (a[0] - b[0]) ** 2 + (a[1] ... | train | APPS_structured |
Everybody loves **pi**, but what if **pi** were a square? Given a number of digits ```digits```, find the smallest integer whose square is greater or equal to the sum of the squares of the first ```digits``` digits of pi, including the ```3``` before the decimal point.
**Note:** Test cases will not extend beyond 100 di... | from math import ceil
from itertools import accumulate
digs = map(int,'031415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679')
MEMO = tuple( ceil(s**.5) for s in accumulate(d*d for d in digs))
square_pi = MEMO.__getitem__ | from math import ceil
from itertools import accumulate
digs = map(int,'031415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679')
MEMO = tuple( ceil(s**.5) for s in accumulate(d*d for d in digs))
square_pi = MEMO.__getitem__ | train | APPS_structured |
Your task is to form an integer array nums from an initial array of zeros arr that is the same size as nums.
Return the minimum number of function calls to make nums from arr.
The answer is guaranteed to fit in a 32-bit signed integer.
Example 1:
Input: nums = [1,5]
Output: 5
Explanation: Increment by 1 (second element... | class Solution:
def minOperations(self, nums: List[int]) -> int:
count=0
res={}
for i in range(len(nums)):
if nums[i]!=0:
res[i]=nums[i]
zeros=[]
while res:
zeros.clear()
for key in res:
if res[key]%2!=0:
... | class Solution:
def minOperations(self, nums: List[int]) -> int:
count=0
res={}
for i in range(len(nums)):
if nums[i]!=0:
res[i]=nums[i]
zeros=[]
while res:
zeros.clear()
for key in res:
if res[key]%2!=0:
... | train | APPS_structured |
You are given an array A of strings.
A move onto S consists of swapping any two even indexed characters of S, or any two odd indexed characters of S.
Two strings S and T are special-equivalent if after any number of moves onto S, S == T.
For example, S = "zzxy" and T = "xyzz" are special-equivalent because we may make ... | class Solution:
def numSpecialEquivGroups(self, A: List[str]) -> int:
return len(set(''.join(sorted(s[0::2])) + ''.join(sorted(s[1::2])) for s in A))
| class Solution:
def numSpecialEquivGroups(self, A: List[str]) -> int:
return len(set(''.join(sorted(s[0::2])) + ''.join(sorted(s[1::2])) for s in A))
| train | APPS_structured |
In this kata, we're going to create the function `nato` that takes a `word` and returns a string that spells the word using the [NATO phonetic alphabet](https://en.wikipedia.org/wiki/NATO_phonetic_alphabet).
There should be a space between each word in the returned string, and the first letter of each word should be ca... | letters = {
"A": "Alpha", "B": "Bravo", "C": "Charlie",
"D": "Delta", "E": "Echo", "F": "Foxtrot",
"G": "Golf", "H": "Hotel", "I": "India",
"J": "Juliett","K": "Kilo", "L": "Lima",
"M": "Mike", "N": "November","O": "Oscar",
"P": "Papa", "Q": "Quebec", "R": "Romeo",
"S": "... | letters = {
"A": "Alpha", "B": "Bravo", "C": "Charlie",
"D": "Delta", "E": "Echo", "F": "Foxtrot",
"G": "Golf", "H": "Hotel", "I": "India",
"J": "Juliett","K": "Kilo", "L": "Lima",
"M": "Mike", "N": "November","O": "Oscar",
"P": "Papa", "Q": "Quebec", "R": "Romeo",
"S": "... | train | APPS_structured |
Tranform of input array of zeros and ones to array in which counts number of continuous ones:
[1, 1, 1, 0, 1] -> [3,1] | def ones_counter(input):
c, result = 0, []
for x in input + [0]:
if x != 1 and c != 0:
result.append(c)
c = 0
elif x == 1:
c += 1
return result | def ones_counter(input):
c, result = 0, []
for x in input + [0]:
if x != 1 and c != 0:
result.append(c)
c = 0
elif x == 1:
c += 1
return result | train | APPS_structured |
# History
This kata is a sequel of my [Mixbonacci](https://www.codewars.com/kata/mixbonacci/python) kata. Zozonacci is a special integer sequence named after [**ZozoFouchtra**](https://www.codewars.com/users/ZozoFouchtra), who came up with this kata idea in the [Mixbonacci discussion](https://www.codewars.com/kata/mixb... | from itertools import cycle
def zozonacci(seq, n):
if not n or not seq:return []
common = {1: [0, 1, 0, 0], 0: [0, 0, 0, 1]}
ini = common[seq[0] == "pad"]
if n<=4:return ini[:n]
fib = lambda:sum(ini[-2:])
jac = lambda:ini[-1] + 2 * ini[-2]
pad = lambda:sum(ini[-3:-1])
pel = lambda:2 * in... | from itertools import cycle
def zozonacci(seq, n):
if not n or not seq:return []
common = {1: [0, 1, 0, 0], 0: [0, 0, 0, 1]}
ini = common[seq[0] == "pad"]
if n<=4:return ini[:n]
fib = lambda:sum(ini[-2:])
jac = lambda:ini[-1] + 2 * ini[-2]
pad = lambda:sum(ini[-3:-1])
pel = lambda:2 * in... | 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 i... | for _ in range(int(input())):
n=int(input())
for i in range(n+1):
k=n
for j in range(1,n-i+1):
print(' ',end='')
for j in range(i+1):
print(k,end='')
k-=1
print()
for i in range(n-1,-1,-1):
k=n
for j in range(1,n-i+1):
... | for _ in range(int(input())):
n=int(input())
for i in range(n+1):
k=n
for j in range(1,n-i+1):
print(' ',end='')
for j in range(i+1):
print(k,end='')
k-=1
print()
for i in range(n-1,-1,-1):
k=n
for j in range(1,n-i+1):
... | train | APPS_structured |
Given the array orders, which represents the orders that customers have done in a restaurant. More specifically orders[i]=[customerNamei,tableNumberi,foodItemi] where customerNamei is the name of the customer, tableNumberi is the table customer sit at, and foodItemi is the item customer orders.
Return the restaurant's ... | class Solution:
def displayTable(self, orders: List[List[str]]) -> List[List[str]]:
table = []
output = [[]]
temp = []
for i in range(len(orders)):
if orders[i][1] not in table:
table.append(orders[i][1])
for j in range(len(table)):
t... | class Solution:
def displayTable(self, orders: List[List[str]]) -> List[List[str]]:
table = []
output = [[]]
temp = []
for i in range(len(orders)):
if orders[i][1] not in table:
table.append(orders[i][1])
for j in range(len(table)):
t... | train | APPS_structured |
## Task:
You have to write a function `pattern` which returns the following Pattern(See Examples) upto n number of rows.
* Note:```Returning``` the pattern is not the same as ```Printing``` the pattern.
### Rules/Note:
* The pattern should be created using only unit digits.
* If `n < 1` then it should return "" i.e. e... | def pattern(n):
return "\n".join("".join(str(max(r, c) % 10) for c in range(n, 0, -1)) for r in range(n, 0, -1))
| def pattern(n):
return "\n".join("".join(str(max(r, c) % 10) for c in range(n, 0, -1)) for r in range(n, 0, -1))
| train | APPS_structured |
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example "Aa" is not considered a palindrome here.
Note:
Assume the length of given string will not exceed 1,010.
Example:
Input:
"abccccdd"
Outpu... | class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
dic = {}
for ss in s:
dic[ss] = dic.get(ss, 0) + 1
res = 0
for _, value in list(dic.items()):
res += (value//2)*2
... | class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
dic = {}
for ss in s:
dic[ss] = dic.get(ss, 0) + 1
res = 0
for _, value in list(dic.items()):
res += (value//2)*2
... | train | APPS_structured |
The Golomb sequence $G_1, G_2, \ldots$ is a non-decreasing integer sequence such that for each positive integer $n$, $G_n$ is the number of occurrences of $n$ in this sequence. The first few elements of $G$ are $[1, 2, 2, 3, 3, 4, 4, 4, 5, \ldots]$. Do you know the recurrence relation for the Golomb sequence? It is $G_... | '''
Name : Jaymeet Mehta
codechef id :mj_13
Problem :
'''
from sys import stdin,stdout
import math
from bisect import bisect_left
mod=1000000007
def mul(a,b):
nonlocal mod
return ((a%mod)*(b%mod))%mod
def add(a,b):
nonlocal mod
return ((a%mod)+(b%mod))%mod
g=[0,1]
pre=[0,1]
ans=[0,1]
i=2
while(True):
g.append(1+g... | '''
Name : Jaymeet Mehta
codechef id :mj_13
Problem :
'''
from sys import stdin,stdout
import math
from bisect import bisect_left
mod=1000000007
def mul(a,b):
nonlocal mod
return ((a%mod)*(b%mod))%mod
def add(a,b):
nonlocal mod
return ((a%mod)+(b%mod))%mod
g=[0,1]
pre=[0,1]
ans=[0,1]
i=2
while(True):
g.append(1+g... | train | APPS_structured |
In a fictitious city of CODASLAM there were many skyscrapers. The mayor of the city decided to make the city beautiful and for this he decided to arrange the skyscrapers in descending order of their height, and the order must be strictly decreasing but he also didn’t want to waste much money so he decided to get the mi... | import sys
num=int(sys.stdin.readline())
s=sys.stdin.readline().split()
sky=list(map(int,s))
sky.reverse()
cuts=0
change=0
t=False
i=1
while i<len(sky):
if sky[i]<=sky[i-1]:
for j in range(i-1,-1,-1):
if sky[j]<=sky[i]-(i-j):
break
else:
change+=sky[j]-(sky[i]-(i-j))
if change>=sky[i]:
... | import sys
num=int(sys.stdin.readline())
s=sys.stdin.readline().split()
sky=list(map(int,s))
sky.reverse()
cuts=0
change=0
t=False
i=1
while i<len(sky):
if sky[i]<=sky[i-1]:
for j in range(i-1,-1,-1):
if sky[j]<=sky[i]-(i-j):
break
else:
change+=sky[j]-(sky[i]-(i-j))
if change>=sky[i]:
... | train | APPS_structured |
Consider the word `"abode"`. We can see that the letter `a` is in position `1` and `b` is in position `2`. In the alphabet, `a` and `b` are also in positions `1` and `2`. Notice also that `d` and `e` in `abode` occupy the positions they would occupy in the alphabet, which are positions `4` and `5`.
Given an array of w... | def solve(arr):
abc = "abcdefghijklmnopqrstuvwxyz"
res = []
for word in arr:
count = 0
word = word.lower()
for i, letter in enumerate(word):
if i == abc.index(letter):
count += 1
res.append(count)
return res
| def solve(arr):
abc = "abcdefghijklmnopqrstuvwxyz"
res = []
for word in arr:
count = 0
word = word.lower()
for i, letter in enumerate(word):
if i == abc.index(letter):
count += 1
res.append(count)
return res
| train | APPS_structured |
# Description:
Move all exclamation marks to the end of the sentence
# Examples
```
remove("Hi!") === "Hi!"
remove("Hi! Hi!") === "Hi Hi!!"
remove("Hi! Hi! Hi!") === "Hi Hi Hi!!!"
remove("Hi! !Hi Hi!") === "Hi Hi Hi!!!"
remove("Hi! Hi!! Hi!") === "Hi Hi Hi!!!!"
``` | def remove(s):
return s.replace('!','') + s.count('!') * '!' | def remove(s):
return s.replace('!','') + s.count('!') * '!' | train | APPS_structured |
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwk... | class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
L, res, last = -1, 0, {}
for R, char in enumerate(s):
if char in last and last[char] > L:
L = last[char]
elif R-L > res:
... | class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
L, res, last = -1, 0, {}
for R, char in enumerate(s):
if char in last and last[char] > L:
L = last[char]
elif R-L > res:
... | train | APPS_structured |
Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a==c and b==d), or (a==d and b==c) - that is, one domino can be rotated to be equal to another domino.
Return the number of pairs (i, j) for which 0 <= i < j < dominoes.length, and dominoes[i] is equivalent to do... | class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
from collections import defaultdict
counter = defaultdict(int)
for domino in dominoes:
counter[tuple(sorted(domino))] +=1
return sum([v*(v-1)//2 for v in counter.values()]) | class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
from collections import defaultdict
counter = defaultdict(int)
for domino in dominoes:
counter[tuple(sorted(domino))] +=1
return sum([v*(v-1)//2 for v in counter.values()]) | train | APPS_structured |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.