input stringlengths 50 13.9k | output_program stringlengths 5 655k | output_answer stringlengths 5 655k | split stringclasses 1
value | dataset stringclasses 1
value |
|---|---|---|---|---|
In this Kata, you will be given an array of arrays and your task will be to return the number of unique arrays that can be formed by picking exactly one element from each subarray.
For example: `solve([[1,2],[4],[5,6]]) = 4`, because it results in only `4` possiblites. They are `[1,4,5],[1,4,6],[2,4,5],[2,4,6]`.
```i... | import functools
from operator import mul
def solve(arr):
return functools.reduce(mul, (len(set(i)) for i in arr)) | import functools
from operator import mul
def solve(arr):
return functools.reduce(mul, (len(set(i)) for i in arr)) | train | APPS_structured |
=====Problem Statement=====
You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa.
=====Example=====
Www.HackerRank.com → wWW.hACKERrANK.COM
Pythonist 2 → pYTHONIST 2
=====Input Format=====
A single line containing a string S.
=====Outpu... | def swap_case(s):
out = ''
for ind, let in enumerate(s):
if let.isalpha():
if let.islower():
out += s[ind].capitalize()
else:
out += s[ind].lower()
else:
out += let
return out | def swap_case(s):
out = ''
for ind, let in enumerate(s):
if let.isalpha():
if let.islower():
out += s[ind].capitalize()
else:
out += s[ind].lower()
else:
out += let
return out | train | APPS_structured |
You are given a tree with $N$ vertices (numbered $1$ through $N$) and a bag with $N$ markers. There is an integer written on each marker; each of these integers is $0$, $1$ or $2$. You must assign exactly one marker to each vertex.
Let's define the unattractiveness of the resulting tree as the maximum absolute differen... | # cook your dish here
import numpy as np
tests = int(input())
for _ in range(tests):
n = int(input())
weights = [int(j) for j in input().split()]
edges = [[0] for _ in range(n-1)]
for i in range(n-1):
edges[i] = [int(j)-1 for j in input().split()]
vertex_set = [[] for _ in range(n)]
for i in ran... | # cook your dish here
import numpy as np
tests = int(input())
for _ in range(tests):
n = int(input())
weights = [int(j) for j in input().split()]
edges = [[0] for _ in range(n-1)]
for i in range(n-1):
edges[i] = [int(j)-1 for j in input().split()]
vertex_set = [[] for _ in range(n)]
for i in ran... | train | APPS_structured |
Polycarp plays a computer game (yet again). In this game, he fights monsters using magic spells.
There are two types of spells: fire spell of power $x$ deals $x$ damage to the monster, and lightning spell of power $y$ deals $y$ damage to the monster and doubles the damage of the next spell Polycarp casts. Each spell ca... | class BIT():
def __init__(self,n):
self.BIT=[0]*(n+1)
self.num=n
def query(self,idx):
res_sum = 0
while idx > 0:
res_sum += self.BIT[idx]
idx -= idx&(-idx)
return res_sum
#Ai += x O(logN)
def update(self,idx,x):
while idx <= self.... | class BIT():
def __init__(self,n):
self.BIT=[0]*(n+1)
self.num=n
def query(self,idx):
res_sum = 0
while idx > 0:
res_sum += self.BIT[idx]
idx -= idx&(-idx)
return res_sum
#Ai += x O(logN)
def update(self,idx,x):
while idx <= self.... | train | APPS_structured |
Zookeeper is buying a carton of fruit to feed his pet wabbit. The fruits are a sequence of apples and oranges, which is represented by a binary string $s_1s_2\ldots s_n$ of length $n$. $1$ represents an apple and $0$ represents an orange.
Since wabbit is allergic to eating oranges, Zookeeper would like to find the long... |
from sys import stdin
import sys
import heapq
def bitadd(a,w,bit):
x = a+1
while x <= (len(bit)-1):
bit[x] += w
x += x & (-1 * x)
def bitsum(a,bit):
ret = 0
x = a+1
while x > 0:
ret += bit[x]
x -= x & (-1 * x)
return ret
n = int(stdin.readline())
s = stdi... |
from sys import stdin
import sys
import heapq
def bitadd(a,w,bit):
x = a+1
while x <= (len(bit)-1):
bit[x] += w
x += x & (-1 * x)
def bitsum(a,bit):
ret = 0
x = a+1
while x > 0:
ret += bit[x]
x -= x & (-1 * x)
return ret
n = int(stdin.readline())
s = stdi... | train | APPS_structured |
The chef has a recipe he wishes to use for his guests,
but the recipe will make far more food than he can serve to the guests.
The chef therefore would like to make a reduced version of the recipe which has the same ratios of ingredients, but makes less food.
The chef, however, does not like fractions.
The original rec... | #! /usr/bin/env python
from sys import stdin
from functools import reduce
def gcd(a,b):
while b!=0:
a,b=b,a%b
return a
def gcdl(l):
return reduce(gcd, l[1:],l[0])
def __starting_point():
T=int(stdin.readline())
for case in range(T):
numbers=list(map(int, stdin.readline().split()[1:]))
g=gcdl(numbers)
... | #! /usr/bin/env python
from sys import stdin
from functools import reduce
def gcd(a,b):
while b!=0:
a,b=b,a%b
return a
def gcdl(l):
return reduce(gcd, l[1:],l[0])
def __starting_point():
T=int(stdin.readline())
for case in range(T):
numbers=list(map(int, stdin.readline().split()[1:]))
g=gcdl(numbers)
... | train | APPS_structured |
Yesterday, Chef found $K$ empty boxes in the cooler and decided to fill them with apples. He ordered $N$ apples, where $N$ is a multiple of $K$. Now, he just needs to hire someone who will distribute the apples into the boxes with professional passion.
Only two candidates passed all the interviews for the box filling ... | for _ in range(int(input())):
n, k = list(map(int, input().split()))
if n//k%k == 0:
print("NO")
else:
print("YES") | for _ in range(int(input())):
n, k = list(map(int, input().split()))
if n//k%k == 0:
print("NO")
else:
print("YES") | train | APPS_structured |
Chef has a rectangular matrix A of nxm integers. Rows are numbered by integers from 1 to n from top to bottom, columns - from 1 to m from left to right. Ai, j denotes the j-th integer of the i-th row.
Chef wants you to guess his matrix. To guess integers, you can ask Chef questions of next type: "How many integers from... | import sys,numpy as np
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return array[idx]
n,m,c=list(map(int,input().split()))
max=[]
li=[]
options=[]
for i in range(1,51):
print(1,1,n,1,m,i,i)
sys.stdout.flush()
ans=int(input())
max.append(ans)
... | import sys,numpy as np
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return array[idx]
n,m,c=list(map(int,input().split()))
max=[]
li=[]
options=[]
for i in range(1,51):
print(1,1,n,1,m,i,i)
sys.stdout.flush()
ans=int(input())
max.append(ans)
... | train | APPS_structured |
After a wonderful evening in the restaurant the time to go home came. Leha as a true gentlemen suggested Noora to give her a lift. Certainly the girl agreed with pleasure. Suddenly one problem appeared: Leha cannot find his car on a huge parking near the restaurant. So he decided to turn to the watchman for help.
Forma... | mod = 1000000007
def sum(x, y, k, add) :
if k < add : return 0
up = x + add
if up > k : up = k
add = add + 1
return y * ( ( (add + up) * (up - add + 1) // 2 ) % mod ) % mod
def solve(x, y, k, add = 0) :
if x == 0 or y == 0 : return 0
if x > y :
x, y = y, x
pw = 1
while (pw ... | mod = 1000000007
def sum(x, y, k, add) :
if k < add : return 0
up = x + add
if up > k : up = k
add = add + 1
return y * ( ( (add + up) * (up - add + 1) // 2 ) % mod ) % mod
def solve(x, y, k, add = 0) :
if x == 0 or y == 0 : return 0
if x > y :
x, y = y, x
pw = 1
while (pw ... | train | APPS_structured |
A [Power Law](https://en.wikipedia.org/wiki/Power_law) distribution occurs whenever "a relative change in one quantity results in a proportional relative change in the other quantity." For example, if *y* = 120 when *x* = 1 and *y* = 60 when *x* = 2 (i.e. *y* halves whenever *x* doubles) then when *x* = 4, *y* = 30 and... | import math
def power_law(x1y1, x2y2, x3):
x1=x1y1[0]
y1=x1y1[1]
x2=x2y2[0]
y2=x2y2[1]
x=x2/x1
y=y2/y1
if x1==x2: return y2
return round(y1*y**(math.log(x3/x1)/math.log(x))) | import math
def power_law(x1y1, x2y2, x3):
x1=x1y1[0]
y1=x1y1[1]
x2=x2y2[0]
y2=x2y2[1]
x=x2/x1
y=y2/y1
if x1==x2: return y2
return round(y1*y**(math.log(x3/x1)/math.log(x))) | train | APPS_structured |
In input string ```word```(1 word):
* replace the vowel with the nearest left consonant.
* replace the consonant with the nearest right vowel.
P.S. To complete this task imagine the alphabet is a circle (connect the first and last element of the array in the mind). For example, 'a' replace with 'z', 'y' with 'a', etc.(... | def replace_letters(word):
return word.translate(str.maketrans('abcdefghijklmnopqrstuvwxyz','zeeediiihooooonuuuuutaaaaa'))
| def replace_letters(word):
return word.translate(str.maketrans('abcdefghijklmnopqrstuvwxyz','zeeediiihooooonuuuuutaaaaa'))
| train | APPS_structured |
You would like to get the 'weight' of a name by getting the sum of the ascii values. However you believe that capital letters should be worth more than mere lowercase letters. Spaces, numbers, or any other character are worth 0.
Normally in ascii
a has a value of 97
A has a value of 65
' ' has a value of 32... | import string as q
def get_weight(name):
return sum(ord(char.swapcase()) for char in name if char in q.ascii_letters) | import string as q
def get_weight(name):
return sum(ord(char.swapcase()) for char in name if char in q.ascii_letters) | train | APPS_structured |
You are an evil sorcerer at a round table with $N$ sorcerers (including yourself). You can cast $M$ spells which have distinct powers $p_1, p_2, \ldots, p_M$.
You may perform the following operation any number of times (possibly zero):
- Assign a living sorcerer to each positive integer cyclically to your left starting... | # cook your dish here
def _gcd(a,b):
while(b!=0):
a,b=b,a%b
return a
def __gcd(mp):
if(len(mp)==1):
return mp[0]
gcd=_gcd(mp[0],mp[1])
for i in range(2,len(mp)):
gcd=_gcd(gcd,mp[i])
return gcd
def factors(hcf):
if(hcf==0):
return [1]
factor_list=[]
for i in range(1,int(hcf**(0.5))+1):
if(hcf%i==0... | # cook your dish here
def _gcd(a,b):
while(b!=0):
a,b=b,a%b
return a
def __gcd(mp):
if(len(mp)==1):
return mp[0]
gcd=_gcd(mp[0],mp[1])
for i in range(2,len(mp)):
gcd=_gcd(gcd,mp[i])
return gcd
def factors(hcf):
if(hcf==0):
return [1]
factor_list=[]
for i in range(1,int(hcf**(0.5))+1):
if(hcf%i==0... | train | APPS_structured |
You are given an n by n ( square ) grid of characters, for example:
```python
[['m', 'y', 'e'],
['x', 'a', 'm'],
['p', 'l', 'e']]
```
You are also given a list of integers as input, for example:
```python
[1, 3, 5, 8]
```
You have to find the characters in these indexes of the grid if you think of the indexes as:
`... | def grid_index(grid, indexes):
flat = tuple(x for e in grid for x in e)
return ''.join(flat[e-1] for e in indexes) | def grid_index(grid, indexes):
flat = tuple(x for e in grid for x in e)
return ''.join(flat[e-1] for e in indexes) | train | APPS_structured |
The purpose of this problem is to verify whether the method you are using to read input data is sufficiently fast to handle problems branded with the enormous Input/Output warning. You are expected to be able to process at least 2.5MB of input data per second at runtime.
-----Input-----
The input begins with two positi... | n,k=map(int,input().split())
ans=0
for i in range(n):
t=int(input())
if t%k==0:
ans+=1
print(ans) | n,k=map(int,input().split())
ans=0
for i in range(n):
t=int(input())
if t%k==0:
ans+=1
print(ans) | train | APPS_structured |
Lеt's create function to play cards. Our rules:
We have the preloaded `deck`:
```
deck = ['joker','2♣','3♣','4♣','5♣','6♣','7♣','8♣','9♣','10♣','J♣','Q♣','K♣','A♣',
'2♦','3♦','4♦','5♦','6♦','7♦','8♦','9♦','10♦','J♦','Q♦','K♦','A♦',
'2♥','3♥','4♥','5♥','6♥','7♥','8♥','9♥','10♥','J♥','Q♥',... | def card_game(card_1, card_2, t):
if card_1 == card_2:
return "Someone cheats."
if card_1 == 'joker':
return "The first card won."
if card_2 == 'joker':
return "The second card won."
f_val = lambda v: int(v) if v.isdigit() else 10 + ' JQKA'.index(v)
c1, t1 = f_val(card_1[:-1]... | def card_game(card_1, card_2, t):
if card_1 == card_2:
return "Someone cheats."
if card_1 == 'joker':
return "The first card won."
if card_2 == 'joker':
return "The second card won."
f_val = lambda v: int(v) if v.isdigit() else 10 + ' JQKA'.index(v)
c1, t1 = f_val(card_1[:-1]... | train | APPS_structured |
Complete the function/method (depending on the language) to return `true`/`True` when its argument is an array that has the same nesting structures and same corresponding length of nested arrays as the first array.
For example:
```python
# should return True
same_structure_as([ 1, 1, 1 ], [ 2, 2, 2 ] )
same_structure_a... | def islist(A):
return isinstance(A, list)
def same_structure_as(original,other):
if islist(original) != islist(other):
return False
elif islist(original):
if len(original) != len(other):
return False
for i in range(len(original)):
if not same_structure_as(orig... | def islist(A):
return isinstance(A, list)
def same_structure_as(original,other):
if islist(original) != islist(other):
return False
elif islist(original):
if len(original) != len(other):
return False
for i in range(len(original)):
if not same_structure_as(orig... | train | APPS_structured |
Write a function
```python
alternate_sort(l)
```
that combines the elements of an array by sorting the elements ascending by their **absolute value** and outputs negative and non-negative integers alternatingly (starting with the negative value, if any).
E.g.
```python
alternate_sort([5, -42, 2, -3, -4, 8, -9,]) == [-3... | from itertools import chain, zip_longest
def alternate_sort(l):
return list(filter(lambda x: x is not None, chain(*zip_longest( sorted(filter(lambda x: x<0,l))[::-1],sorted(filter(lambda x: x>-1,l)))))) | from itertools import chain, zip_longest
def alternate_sort(l):
return list(filter(lambda x: x is not None, chain(*zip_longest( sorted(filter(lambda x: x<0,l))[::-1],sorted(filter(lambda x: x>-1,l)))))) | train | APPS_structured |
Given a list of prime factors, ```primesL```, and an integer, ```limit```, try to generate in order, all the numbers less than the value of ```limit```, that have **all and only** the prime factors of ```primesL```
## Example
```python
primesL = [2, 5, 7]
limit = 500
List of Numbers Under 500 Prime Factorizati... | from functools import reduce
from collections import deque
def count_find_num(primesL, limit):
q = deque()
q.append(reduce(lambda x, y: x*y, primesL))
Max, Count = 0, 0
while len(q)!=0:
if q[0] <= limit:
Count += 1
Max = max(Max, q[0])
for i in primesL:
... | from functools import reduce
from collections import deque
def count_find_num(primesL, limit):
q = deque()
q.append(reduce(lambda x, y: x*y, primesL))
Max, Count = 0, 0
while len(q)!=0:
if q[0] <= limit:
Count += 1
Max = max(Max, q[0])
for i in primesL:
... | train | APPS_structured |
Kim has broken in to the base, but after walking in circles, perplexed by the unintelligible base design of the JSA, he has found himself in a large, empty, and pure white, room.
The room is a grid with H∗W$H*W$ cells, divided into H$H$ rows and W$W$ columns. The cell (i,j)$(i,j)$ is at height A[i][j]$A[i][j]$. Unfort... | def traverse(l,h,w,i,j,p):
c=0
queue=[(i,j)]
visited=[[False for i in range(w)] for i in range(h)]
visited[i][j]=True
while queue:
newq=[]
c+=len(queue)
for i in range(len(queue)):
d=queue[i]
x,y=d[0],d[1]
if x+1<h and l[x+1][y]<... | def traverse(l,h,w,i,j,p):
c=0
queue=[(i,j)]
visited=[[False for i in range(w)] for i in range(h)]
visited[i][j]=True
while queue:
newq=[]
c+=len(queue)
for i in range(len(queue)):
d=queue[i]
x,y=d[0],d[1]
if x+1<h and l[x+1][y]<... | train | APPS_structured |
Base on the fairy tale [Diamonds and Toads](https://en.wikipedia.org/wiki/Diamonds_and_Toads) from Charles Perrault. In this kata you will have to complete a function that take 2 arguments:
- A string, that correspond to what the daugther says.
- A string, that tell you wich fairy the girl have met, this one can be `g... | def diamonds_and_toads(sentence,fairy):
res={}
if fairy == 'good':
res['ruby']=sentence.count('r')+sentence.count('R')*2
res['crystal']=sentence.count('c')+sentence.count('C')*2
elif fairy == 'evil':
res['python']=sentence.count('p')+sentence.count('P')*2
res['squirrel']=sent... | def diamonds_and_toads(sentence,fairy):
res={}
if fairy == 'good':
res['ruby']=sentence.count('r')+sentence.count('R')*2
res['crystal']=sentence.count('c')+sentence.count('C')*2
elif fairy == 'evil':
res['python']=sentence.count('p')+sentence.count('P')*2
res['squirrel']=sent... | train | APPS_structured |
For two strings s and t, we say "t divides s" if and only if s = t + ... + t (t concatenated with itself 1 or more times)
Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2.
Example 1:
Input: str1 = "ABCABC", str2 = "ABC"
Output: "ABC"
Example 2:
Input: str1 = "ABABAB",... | class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
contender = ''
for i in str1:
contender += i
if str1.count(contender) * len(contender) == len(str1) and str2.count(contender) * len(contender) == len(str2):
break
orig = contender
... | class Solution:
def gcdOfStrings(self, str1: str, str2: str) -> str:
contender = ''
for i in str1:
contender += i
if str1.count(contender) * len(contender) == len(str1) and str2.count(contender) * len(contender) == len(str2):
break
orig = contender
... | train | APPS_structured |
When multiple master devices are connected to a single bus (https://en.wikipedia.org/wiki/System_bus), there needs to be an arbitration in order to choose which of them can have access to the bus (and 'talk' with a slave).
We implement here a very simple model of bus mastering. Given `n`, a number representing the numb... | import re
def arbitrate(s,_):
p,m,b=s.partition('1')
return p+m+'0'*len(b) | import re
def arbitrate(s,_):
p,m,b=s.partition('1')
return p+m+'0'*len(b) | train | APPS_structured |
# Task
You are given an array of integers `a` and a non-negative number of operations `k`, applied to the array. Each operation consists of two parts:
```
find the maximum element value of the array;
replace each element a[i] with (maximum element value - a[i]).```
How will the array look like after `k` such operation... | def array_operations(a, k):
b = [max(a)-i for i in a]
c = [max(b)-i for i in b]
return b if k%2 else c if k>0 else a | def array_operations(a, k):
b = [max(a)-i for i in a]
c = [max(b)-i for i in b]
return b if k%2 else c if k>0 else a | train | APPS_structured |
Given the values at the leaf nodes of a complete binary tree. The total number of nodes in the binary tree, is also given. Sum of the values at both the children of a node is equal to the value of the node itself. You can add any value or subtract any value from a node. Print the minimum change(difference made) in the ... | print(0) | print(0) | train | APPS_structured |
Deoxyribonucleic acid (DNA) is a chemical found in the nucleus of cells and carries the "instructions" for the development and functioning of living organisms.
If you want to know more http://en.wikipedia.org/wiki/DNA
In DNA strings, symbols "A" and "T" are complements of each other, as "C" and "G".
You have function ... | def DNA_strand(dna):
# code here
dnaComplement=""
for string in dna:
if string=="A":
dnaComplement+="T"
elif string =="T":
dnaComplement+="A"
elif string =="G":
dnaComplement+="C"
elif string == "C":
dnaComplement+="G"
retur... | def DNA_strand(dna):
# code here
dnaComplement=""
for string in dna:
if string=="A":
dnaComplement+="T"
elif string =="T":
dnaComplement+="A"
elif string =="G":
dnaComplement+="C"
elif string == "C":
dnaComplement+="G"
retur... | train | APPS_structured |
During the archaeological research in the Middle East you found the traces of three ancient religions: First religion, Second religion and Third religion. You compiled the information on the evolution of each of these beliefs, and you now wonder if the followers of each religion could coexist in peace.
The Word of Univ... | n, q = map(int, input().split())
s = '!' + input()
nxt = [[n + 1] * (n + 2) for _ in range(26)]
for i in range(n - 1, -1, -1):
c = ord(s[i + 1]) - 97
for j in range(26):
nxt[j][i] = nxt[j][i + 1]
nxt[c][i] = i + 1
w = [[-1], [-1], [-1]]
idx = lambda i, j, k: i * 65536 + j * 256 + k
dp = [0] * (256... | n, q = map(int, input().split())
s = '!' + input()
nxt = [[n + 1] * (n + 2) for _ in range(26)]
for i in range(n - 1, -1, -1):
c = ord(s[i + 1]) - 97
for j in range(26):
nxt[j][i] = nxt[j][i + 1]
nxt[c][i] = i + 1
w = [[-1], [-1], [-1]]
idx = lambda i, j, k: i * 65536 + j * 256 + k
dp = [0] * (256... | train | APPS_structured |
Chef was bored staying at home in the lockdown. He wanted to go out for a change. Chef and Chefu are fond of eating Cakes,so they decided to go the Cake shop where cakes of all possible price are available .
They decided to purchase cakes of equal price and each of them will pay for their cakes. Chef only has coins of ... | def compute_gcd(x, y):
while(y):
x, y = y, x % y
return x
def cm(x, y):
lcm = (x*y)//compute_gcd(x,y)
return lcm
for _ in range(int(input())):
n,m=list(map(int,input().split()))
print(cm(n,m))
| def compute_gcd(x, y):
while(y):
x, y = y, x % y
return x
def cm(x, y):
lcm = (x*y)//compute_gcd(x,y)
return lcm
for _ in range(int(input())):
n,m=list(map(int,input().split()))
print(cm(n,m))
| train | APPS_structured |
There is a pizza with 3n slices of varying size, you and your friends will take slices of pizza as follows:
You will pick any pizza slice.
Your friend Alice will pick next slice in anti clockwise direction of your pick.
Your friend Bob will pick next slice in clockwise direction of your pick.
Repeat until there are no... | class Solution:
def maxSizeSlices(self, slices: List[int]) -> int:
def helper(start, end):
dp = [[0] * n for _ in range(end-start+1)]
dp[0] = [slices[start]] * n
dp[1] = [max(slices[start], slices[start+1])] * n
for i in range(start+2, end+1):
... | class Solution:
def maxSizeSlices(self, slices: List[int]) -> int:
def helper(start, end):
dp = [[0] * n for _ in range(end-start+1)]
dp[0] = [slices[start]] * n
dp[1] = [max(slices[start], slices[start+1])] * n
for i in range(start+2, end+1):
... | train | APPS_structured |
Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the nth lake, the nth lake becomes full of water. If it rains over a lake which is full of water, there will be a flood. Your goal is to avoid the flood in any lake.
Given an integer array rains where:
rains[i] > 0 ... | class Solution:
def avoidFlood(self, rains: List[int]) -> List[int]:
n = len(rains)
res = [-1] * n
dry = []
rained = {}
for i, r in enumerate(rains):
if r:
if r not in rained:
rained[r] = i
else:
... | class Solution:
def avoidFlood(self, rains: List[int]) -> List[int]:
n = len(rains)
res = [-1] * n
dry = []
rained = {}
for i, r in enumerate(rains):
if r:
if r not in rained:
rained[r] = i
else:
... | train | APPS_structured |
You get a new job working for Eggman Movers. Your first task is to write a method that will allow the admin staff to enter a person’s name and return what that person's role is in the company.
You will be given an array of object literals holding the current employees of the company. You code must find the employee w... | employees = [{'first_name': 'Ollie', 'last_name': 'Hepburn', 'role': 'Boss'}, {'first_name': 'Morty', 'last_name': 'Smith', 'role': 'Truck Driver'}, {'first_name': 'Peter', 'last_name': 'Ross', 'role': 'Warehouse Manager'}, {'first_name': 'Cal', 'last_name': 'Neil', 'role': 'Sales Assistant'}, {'first_name': 'Jesse', '... | employees = [{'first_name': 'Ollie', 'last_name': 'Hepburn', 'role': 'Boss'}, {'first_name': 'Morty', 'last_name': 'Smith', 'role': 'Truck Driver'}, {'first_name': 'Peter', 'last_name': 'Ross', 'role': 'Warehouse Manager'}, {'first_name': 'Cal', 'last_name': 'Neil', 'role': 'Sales Assistant'}, {'first_name': 'Jesse', '... | train | APPS_structured |
In Russia regular bus tickets usually consist of 6 digits. The ticket is called lucky when the sum of the first three digits equals to the sum of the last three digits. Write a function to find out whether the ticket is lucky or not. Return true if so, otherwise return false. Consider that input is always a string. Wat... | import re
def is_lucky(ticket):
return bool(re.match(r'\d{6}', ticket)) and sum(int(i) for i in ticket[:3]) == sum(int(i) for i in ticket[3:]) | import re
def is_lucky(ticket):
return bool(re.match(r'\d{6}', ticket)) and sum(int(i) for i in ticket[:3]) == sum(int(i) for i in ticket[3:]) | train | APPS_structured |
# Letterss of Natac
In a game I just made up that doesn’t have anything to do with any other game that you may or may not have played, you collect resources on each turn and then use those resources to build settlements, roads, and cities or buy a development. Other kata about this game can be found [here](https://www.... | from collections import Counter
PRICES = {
'road': 'bw',
'settlement': 'bwsg',
'city': 'ooogg',
'development': 'osg'
}
def build_or_buy(hand):
return list(filter(lambda obj: not Counter(PRICES[obj]) - Counter(hand),
PRICES.keys())) | from collections import Counter
PRICES = {
'road': 'bw',
'settlement': 'bwsg',
'city': 'ooogg',
'development': 'osg'
}
def build_or_buy(hand):
return list(filter(lambda obj: not Counter(PRICES[obj]) - Counter(hand),
PRICES.keys())) | train | APPS_structured |
Your friend has invited you to a party, and tells you to meet them in the line to get in. The one problem is it's a masked party. Everyone in line is wearing a colored mask, including your friend. Find which people in line could be your friend.
Your friend has told you that he will be wearing a `RED` mask, and has **TW... | def friend_find(line):
N = len(line)
A = lambda i: line[i] == "red" and B(i)
B = lambda i: C(i) or D(i) or E(i)
C = lambda i: i < N-2 and line[i+1] == line[i+2] == "blue"
D = lambda i: 0 < i < N-1 and line[i-1] == line[i+1] == "blue"
E = lambda i: 1 < i and line[i-2] == line[i-1] == "blue"
r... | def friend_find(line):
N = len(line)
A = lambda i: line[i] == "red" and B(i)
B = lambda i: C(i) or D(i) or E(i)
C = lambda i: i < N-2 and line[i+1] == line[i+2] == "blue"
D = lambda i: 0 < i < N-1 and line[i-1] == line[i+1] == "blue"
E = lambda i: 1 < i and line[i-2] == line[i-1] == "blue"
r... | train | APPS_structured |
If Give an integer N . Write a program to obtain the sum of the first and last digits of this number.
-----Input-----
The first line contains an integer T, the total number of test cases. Then follow T lines, each line contains an integer N.
-----Output-----
For each test case, display the sum of first and last digits... | # cook your dish here
for _ in range(int(input())):
s=str(input())
print(int(s[0])+int(s[-1])) | # cook your dish here
for _ in range(int(input())):
s=str(input())
print(int(s[0])+int(s[-1])) | train | APPS_structured |
Given any number of boolean flags function should return true if and only if one of them is true while others are false. If function is called without arguments it should return false.
```python
only_one() == False
only_one(True, False, False) == True
only_one(True, False, False, True) == False
only_one(False, ... | def only_one(*bool):
sum = 0
for value in bool:
if value:
sum += 1
if sum == 1:
return True
else:
return False | def only_one(*bool):
sum = 0
for value in bool:
if value:
sum += 1
if sum == 1:
return True
else:
return False | train | APPS_structured |
Ms. E.T. came from planet Hex. She has 8 fingers in each hand which makes her count in hexadecimal way. When she meets you, she tells you that she came from 7E light years from the planet Earth. You see she means that it is 126 light years far away and she is telling you the numbers in hexadecimal. Now, you are in trou... | t=int(input())
for _ in range(t):
test_string =input()
res = int(test_string, 16)
print(str(res)) | t=int(input())
for _ in range(t):
test_string =input()
res = int(test_string, 16)
print(str(res)) | train | APPS_structured |
After completing some serious investigation, Watson and Holmes are now chilling themselves in the Shimla hills. Very soon Holmes became bored. Holmes lived entirely for his profession. We know he is a workaholic. So Holmes wants to stop his vacation and get back to work. But after a tiresome season, Watson is in no moo... | def mul3(ip):
q0=[]
q1=[]
q2=[]
ip.sort()
sums=sum(ip)
for i in ip:
if (i % 3) == 0:
q0.insert(0,i)
if (i % 3) == 1:
q1.insert(0,i)
if (i % 3) == 2:
q2.insert(0,i)
if(sums%3==1):
if(len(q1)):
q1.pop()
elif(len(q2)>=2):
q2.pop()
q2.pop()
else:
return -1
elif(sums%3==2):
if(l... | def mul3(ip):
q0=[]
q1=[]
q2=[]
ip.sort()
sums=sum(ip)
for i in ip:
if (i % 3) == 0:
q0.insert(0,i)
if (i % 3) == 1:
q1.insert(0,i)
if (i % 3) == 2:
q2.insert(0,i)
if(sums%3==1):
if(len(q1)):
q1.pop()
elif(len(q2)>=2):
q2.pop()
q2.pop()
else:
return -1
elif(sums%3==2):
if(l... | train | APPS_structured |
Two players are playing a game. The game is played on a sequence of positive integer pairs. The players make their moves alternatively. During his move the player chooses a pair and decreases the larger integer in the pair by a positive multiple of the smaller integer in the pair in such a way that both integers in the... | import sys
t = int(input())
def g(a,b):
if (a > b):
tmp = a
a = b
b = tmp
if (b == a):
return 0
if (b % a == 0):
return int(b/a)-1
r = g(b%a,a)
q = int(b/a)
if (r >= q):
return q-1
else:
return q
def mex(x):
n = len(list(x.keys()))
for i in range(n):
if (i not in x):
return i
return i
d... | import sys
t = int(input())
def g(a,b):
if (a > b):
tmp = a
a = b
b = tmp
if (b == a):
return 0
if (b % a == 0):
return int(b/a)-1
r = g(b%a,a)
q = int(b/a)
if (r >= q):
return q-1
else:
return q
def mex(x):
n = len(list(x.keys()))
for i in range(n):
if (i not in x):
return i
return i
d... | train | APPS_structured |
You are given a sequence a = \{a_1, ..., a_N\} with all zeros, and a sequence b = \{b_1, ..., b_N\} consisting of 0 and 1. The length of both is N.
You can perform Q kinds of operations. The i-th operation is as follows:
- Replace each of a_{l_i}, a_{l_i + 1}, ..., a_{r_i} with 1.
Minimize the hamming distance between... | import sys
input=sys.stdin.readline
n=int(input())
b=list(map(int,input().split()))
ope=[[] for i in range(n)]
Q=int(input())
for i in range(Q):
l,r=list(map(int,input().split()))
ope[r-1].append(l-1)
res=b.count(0)
Data=[(-1)**((b[i]==1)+1) for i in range(n)]
for i in range(1,n):
Data[i]+=Data[i-1]
Dat... | import sys
input=sys.stdin.readline
n=int(input())
b=list(map(int,input().split()))
ope=[[] for i in range(n)]
Q=int(input())
for i in range(Q):
l,r=list(map(int,input().split()))
ope[r-1].append(l-1)
res=b.count(0)
Data=[(-1)**((b[i]==1)+1) for i in range(n)]
for i in range(1,n):
Data[i]+=Data[i-1]
Dat... | train | APPS_structured |
Students went into a class to write a test and sat in some way. The teacher thought: "Probably they sat in this order to copy works of each other. I need to rearrange them in such a way that students that were neighbors are not neighbors in a new seating."
The class can be represented as a matrix with n rows and m colu... | n,m=map(int,input().split())
if n==1and m==1:print('YES\n1')
elif n==3and m==3:
print('YES')
print(6, 1, 8)
print(7,5,3)
print(2,9,4)
elif n<4and m<4:print('NO')
elif n==1 or m==1:
t=max(n,m)
a=[i for i in range(2,t+1,2)]
a+=[i for i in range(1,t+1,2)]
print('YES')
for i in a:print(i... | n,m=map(int,input().split())
if n==1and m==1:print('YES\n1')
elif n==3and m==3:
print('YES')
print(6, 1, 8)
print(7,5,3)
print(2,9,4)
elif n<4and m<4:print('NO')
elif n==1 or m==1:
t=max(n,m)
a=[i for i in range(2,t+1,2)]
a+=[i for i in range(1,t+1,2)]
print('YES')
for i in a:print(i... | train | APPS_structured |
After six days, professor GukiZ decided to give more candies to his students. Like last time, he has $N$ students, numbered $1$ through $N$. Let's denote the number of candies GukiZ gave to the $i$-th student by $p_i$. As GukiZ has a lot of students, he does not remember all the exact numbers of candies he gave to the ... | # https://www.codechef.com/LTIME63B/problems/GHMC
# Finally.... I properly understood what needs to be done.
def ctlt(arr, val):
# find number of values in sorted arr < val
if arr[0] >= val: return 0
lo = 0
hi = len(arr)
while hi-lo > 1:
md = (hi+lo)//2
if arr[md]<val:
... | # https://www.codechef.com/LTIME63B/problems/GHMC
# Finally.... I properly understood what needs to be done.
def ctlt(arr, val):
# find number of values in sorted arr < val
if arr[0] >= val: return 0
lo = 0
hi = len(arr)
while hi-lo > 1:
md = (hi+lo)//2
if arr[md]<val:
... | train | APPS_structured |
We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.
Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.
Example 1:
Input: [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The l... | class Solution:
def findLHS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = collections.Counter(nums)
ret = 0
for i in count:
if i+1 in count:
ret = max(ret, count[i]+count[i+1])
return ret... | class Solution:
def findLHS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = collections.Counter(nums)
ret = 0
for i in count:
if i+1 in count:
ret = max(ret, count[i]+count[i+1])
return ret... | train | APPS_structured |
**An [isogram](https://en.wikipedia.org/wiki/Isogram)** (also known as a "nonpattern word") is a logological term for a word or phrase without a repeating letter. It is also used by some to mean a word or phrase in which each letter appears the same number of times, not necessarily just once.
You task is to write a met... | is_isogram = lambda word: type(word) == str and bool(word) and len(set( __import__("collections").Counter( __import__("re").sub(r'[^a-z]', "", word.lower())).values() )) == 1 | is_isogram = lambda word: type(word) == str and bool(word) and len(set( __import__("collections").Counter( __import__("re").sub(r'[^a-z]', "", word.lower())).values() )) == 1 | train | APPS_structured |
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.
What is the minimum candies you mu... | class Solution:
def candy(self, ratings):
"""
:type ratings: List[int]
:rtype: int
"""
if not ratings: return 0
if len(ratings) == 1: return 1
l2r = [1 for _ in ratings]
r2l = [1 for _ in ratings]
for i in range(1, len(ratings)):
... | class Solution:
def candy(self, ratings):
"""
:type ratings: List[int]
:rtype: int
"""
if not ratings: return 0
if len(ratings) == 1: return 1
l2r = [1 for _ in ratings]
r2l = [1 for _ in ratings]
for i in range(1, len(ratings)):
... | train | APPS_structured |
There is no single treatment that works for every phobia, but some people cure it by being gradually exposed to the phobic situation or object. In this kata we will try curing arachnophobia by drawing primitive spiders.
Our spiders will have legs, body, eyes and a mouth. Here are some examples:
```
/\((OOwOO))/\
/╲(((0... |
L = {1:'^', 2:'/\\', 3:'/╲', 4:'╱╲'}
R = {1:'^', 2:'/\\', 3:'╱\\', 4:'╱╲'}
def draw_spider(leg, body, mouth, eye):
return L[leg] + '(' * body + eye * (2**body//2) + mouth + eye * (2**body//2) + ')' * body + R[leg] |
L = {1:'^', 2:'/\\', 3:'/╲', 4:'╱╲'}
R = {1:'^', 2:'/\\', 3:'╱\\', 4:'╱╲'}
def draw_spider(leg, body, mouth, eye):
return L[leg] + '(' * body + eye * (2**body//2) + mouth + eye * (2**body//2) + ')' * body + R[leg] | train | APPS_structured |
Your music player contains N different songs and she wants to listen to L (not necessarily different) songs during your trip. You create a playlist so that:
Every song is played at least once
A song can only be played again only if K other songs have been played
Return the number of possible playlists. As the answer ... | class Solution:
def numMusicPlaylists(self, N: int, L: int, K: int) -> int:
memo = {}
def dp(i, j):
if i == 0:
return j == 0
if (i, j) in memo: return memo[i, j]
memo[i, j] = dp(i - 1, j - 1) * (N - j + 1) + dp(i - 1, j) * max(j - K, 0)
... | class Solution:
def numMusicPlaylists(self, N: int, L: int, K: int) -> int:
memo = {}
def dp(i, j):
if i == 0:
return j == 0
if (i, j) in memo: return memo[i, j]
memo[i, j] = dp(i - 1, j - 1) * (N - j + 1) + dp(i - 1, j) * max(j - K, 0)
... | train | APPS_structured |
You will be given a vector of strings. You must sort it alphabetically (case-sensitive, and based on the ASCII values of the chars) and then return the first value.
The returned value must be a string, and have `"***"` between each of its letters.
You should not remove or add elements from/to the array. | two_sort = lambda l:'***'.join(sorted(l)[0]) | two_sort = lambda l:'***'.join(sorted(l)[0]) | train | APPS_structured |
You are a skier (marked below by the `X`). You have made it to the Olympics! Well done.
```
\_\_\_X\_
\*\*\*\*\*\
\*\*\*\*\*\*\
\*\*\*\*\*\*\*\
\*\*\*\*\*\*\*\*\
\*\*\*\*\*\*\*\*\*\\.\_\_\_\_/
```
Your job in this kata is to calculate the maximum speed you will achieve during your downhill run. The speed is dictated by... | def ski_jump(mountain):
k=0
l=0
m=0
for i in mountain:
i=mountain[k]
k+=1
l=k*1.5
m=(k*l*9)/10
if m<10:
m=("%.2f" % m)
m=str(m)
m=m +" metres: He's crap!"
return m
elif m>=10 and m<=25:
m=("%.2f"%m)
m=str(m)
m=m+" ... | def ski_jump(mountain):
k=0
l=0
m=0
for i in mountain:
i=mountain[k]
k+=1
l=k*1.5
m=(k*l*9)/10
if m<10:
m=("%.2f" % m)
m=str(m)
m=m +" metres: He's crap!"
return m
elif m>=10 and m<=25:
m=("%.2f"%m)
m=str(m)
m=m+" ... | train | APPS_structured |
Ever since you started work at the grocer, you have been faithfully logging down each item and its category that passes through. One day, your boss walks in and asks, "Why are we just randomly placing the items everywhere? It's too difficult to find anything in this place!" Now's your chance to improve the system, impr... | def group_groceries(groceries):
categories = {"fruit": [], "meat": [], "other": [], "vegetable": []}
for entry in groceries.split(","):
category, item = entry.split("_")
categories[category if category in categories else "other"].append(item)
return "\n".join([f"{category}:{','.join(sorted(i... | def group_groceries(groceries):
categories = {"fruit": [], "meat": [], "other": [], "vegetable": []}
for entry in groceries.split(","):
category, item = entry.split("_")
categories[category if category in categories else "other"].append(item)
return "\n".join([f"{category}:{','.join(sorted(i... | train | APPS_structured |
You are standing near a very strange machine. If you put C cents in the machine, the remaining money in your purse will transform in an unusual way. If you have A dollars and B cents remaining in your purse after depositing the C cents, then after the transformation you will have B dollars and A cents. You can repeat t... | for _ in range(int(input())):
a, b, c = map(int, input().split())
ans, cur_max, cur, count = 0, [a, b], 0, 10000
while count > 0 and (b >= c or a > 0):
cur += 1
count -= 1
if b < c:
b += 100
a -= 1
b -= c
if cur_max < [b, a]... | for _ in range(int(input())):
a, b, c = map(int, input().split())
ans, cur_max, cur, count = 0, [a, b], 0, 10000
while count > 0 and (b >= c or a > 0):
cur += 1
count -= 1
if b < c:
b += 100
a -= 1
b -= c
if cur_max < [b, a]... | train | APPS_structured |
Take debugging to a whole new level:
Given a string, remove every *single* bug.
This means you must remove all instances of the word 'bug' from within a given string, *unless* the word is plural ('bugs').
For example, given 'obugobugobuoobugsoo', you should return 'ooobuoobugsoo'.
Another example: given 'obbugugo', you... | import re
def debug(string):
return re.sub("bug(?!s)", "", string) | import re
def debug(string):
return re.sub("bug(?!s)", "", string) | train | APPS_structured |
A Tic-Tac-Toe board is given as a string array board. Return True if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.
The board is a 3 x 3 array, and consists of characters " ", "X", and "O". The " " character represents an empty square.
Here are the rules of Tic-T... | class Solution:
def swimInWater(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
n = len(grid)
pq = [(grid[0][0], 0, 0)]
seen = set([(0, 0)])
res = 0
while True:
val, y, x = heapq.heappop(pq)
res ... | class Solution:
def swimInWater(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
n = len(grid)
pq = [(grid[0][0], 0, 0)]
seen = set([(0, 0)])
res = 0
while True:
val, y, x = heapq.heappop(pq)
res ... | train | APPS_structured |
Takaki Tono is a Computer Programmer in Tokyo. His boss at work shows him an online puzzle, which if solved would earn the solver a full expense paid trip to Los Angeles, California. Takaki really wants to solve this, as the love of his life, Akari, lives in Los Angeles and he hasn't met her since four years. Upon read... |
N = eval(input())
nodes = list(map(int, input().split(" ")))
edges = [set() for _ in range(N)]
for _ in range(N-1):
a, b = list(map(int, input().split(" ")))
edges[a-1].add(b-1)
edges[b-1].add(a-1)
path = [[] for _ in range(N)]
visited, tovisit = set(), [(0, 0)]
while tovisit:
p, v = tovisit.pop()
... |
N = eval(input())
nodes = list(map(int, input().split(" ")))
edges = [set() for _ in range(N)]
for _ in range(N-1):
a, b = list(map(int, input().split(" ")))
edges[a-1].add(b-1)
edges[b-1].add(a-1)
path = [[] for _ in range(N)]
visited, tovisit = set(), [(0, 0)]
while tovisit:
p, v = tovisit.pop()
... | train | APPS_structured |
Two tortoises named ***A*** and ***B*** must run a race. ***A*** starts with an average speed of ```720 feet per hour```.
Young ***B*** knows she runs faster than ***A***, and furthermore has not finished her cabbage.
When she starts, at last, she can see that ***A*** has a `70 feet lead` but ***B***'s speed is `850 fe... | def race(v1, v2, g):
if v1 >= v2: return None
t = float(g)/(v2-v1)*3600
mn, s = divmod(t, 60)
h, mn = divmod(mn, 60)
return [int(h), int(mn), int(s)] | def race(v1, v2, g):
if v1 >= v2: return None
t = float(g)/(v2-v1)*3600
mn, s = divmod(t, 60)
h, mn = divmod(mn, 60)
return [int(h), int(mn), int(s)] | train | APPS_structured |
The Binomial Form of a polynomial has many uses, just as the standard form does. For comparison, if p(x) is in Binomial Form and q(x) is in standard form, we might write
p(x) := a0 \* xC0 + a1 \* xC1 + a2 \* xC2 + ... + aN \* xCN
q(x) := b0 + b1 \* x + b2 \* x^(2) + ... + bN \* x^(N)
Both forms have tricks for evaluat... | def value_at(poly_spec, x):
leng = len(poly_spec)
ans = 0
for i, e in enumerate(poly_spec):
temp = 1
for j in range(leng-i-1):
temp *= (x-j)/(j+1)
ans += e*temp
return round(ans, 2) | def value_at(poly_spec, x):
leng = len(poly_spec)
ans = 0
for i, e in enumerate(poly_spec):
temp = 1
for j in range(leng-i-1):
temp *= (x-j)/(j+1)
ans += e*temp
return round(ans, 2) | train | APPS_structured |
Write a function that takes an integer and returns an array `[A, B, C]`, where `A` is the number of multiples of 3 (but not 5) below the given integer, `B` is the number of multiples of 5 (but not 3) below the given integer and `C` is the number of multiples of 3 and 5 below the given integer.
For example, `solution(2... | def solution(number):
number = number - 1
fizzbuzz = number // 15
fizz = number // 3 - fizzbuzz
buzz = number // 5 - fizzbuzz
return [fizz, buzz, fizzbuzz] | def solution(number):
number = number - 1
fizzbuzz = number // 15
fizz = number // 3 - fizzbuzz
buzz = number // 5 - fizzbuzz
return [fizz, buzz, fizzbuzz] | train | APPS_structured |
Consider the fraction, $a/b$, where $a$ and $b$ are positive integers. If $a < b$ and $GCD(a,b) = 1$, it is called a reduced proper fraction.
If we list the set of a reduced proper fraction for $d \leq 8$, (where $d$ is the denominator) in ascending order of size, we get:
$1/8$, $1/7$, $1/6$, $1/5$, $1/4$, $2/7$, $1/3$... | R1_HIGH, R1_LOW, R2_HIGH, R2_LOW = 0, 0, 0, 0
def cross_multiply(a, b, i):
nonlocal R1_HIGH
nonlocal R1_LOW
nonlocal R2_HIGH
nonlocal R2_LOW
if i == 1:
R1_HIGH = 6*a*b
R1_LOW = R1_HIGH // 2
elif i == 2:
R2_HIGH = 6*a*b
R2_LOW = R2_HIGH // 2
def isLes... | R1_HIGH, R1_LOW, R2_HIGH, R2_LOW = 0, 0, 0, 0
def cross_multiply(a, b, i):
nonlocal R1_HIGH
nonlocal R1_LOW
nonlocal R2_HIGH
nonlocal R2_LOW
if i == 1:
R1_HIGH = 6*a*b
R1_LOW = R1_HIGH // 2
elif i == 2:
R2_HIGH = 6*a*b
R2_LOW = R2_HIGH // 2
def isLes... | train | APPS_structured |
*Debug* function `getSumOfDigits` that takes positive integer to calculate sum of it's digits. Assume that argument is an integer.
### Example
```
123 => 6
223 => 7
1337 => 15
``` | def get_sum_of_digits(num):
digits = []
for i in str(num): digits.append(int(i))
return sum(digits) | def get_sum_of_digits(num):
digits = []
for i in str(num): digits.append(int(i))
return sum(digits) | train | APPS_structured |
Santa puts all the presents into the huge sack. In order to let his reindeers rest a bit, he only takes as many reindeers with him as he is required to do. The others may take a nap.
Two reindeers are always required for the sleigh and Santa himself. Additionally he needs 1 reindeer per 30 presents. As you know, Santa ... | from math import ceil
# Why is this 6 kyu?
def reindeer(presents):
if presents > 180: raise Exception("Too many presents")
return 2 + ceil(presents/30) | from math import ceil
# Why is this 6 kyu?
def reindeer(presents):
if presents > 180: raise Exception("Too many presents")
return 2 + ceil(presents/30) | train | APPS_structured |
Assume you are creating a webshop and you would like to help the user in the search. You have products with brands, prices and name. You have the history of opened products (the most recently opened being the first item).
Your task is to create a list of brands ordered by popularity, if two brands have the same popular... | from collections import Counter
def sorted_brands(history):
cnt = Counter(item["brand"] for item in history)
return sorted(cnt, key=cnt.get, reverse=True) | from collections import Counter
def sorted_brands(history):
cnt = Counter(item["brand"] for item in history)
return sorted(cnt, key=cnt.get, reverse=True) | train | APPS_structured |
You are the Dungeon Master for a public DnD game at your local comic shop and recently you've had some trouble keeping your players' info neat and organized so you've decided to write a bit of code to help keep them sorted!
The goal of this code is to create an array of objects that stores a player's name and contact n... | def player_manager(players):
return [{'player': a, 'contact': int(b)} for a, b in zip(*[iter(players.split(', '))] * 2)] if players else [] | def player_manager(players):
return [{'player': a, 'contact': int(b)} for a, b in zip(*[iter(players.split(', '))] * 2)] if players else [] | train | APPS_structured |
This kata is a continuation of [Part 1](http://www.codewars.com/kata/the-fibfusc-function-part-1). The `fibfusc` function is defined recursively as follows:
fibfusc(0) = (1, 0)
fibfusc(1) = (0, 1)
fibfusc(2n) = ((x + y)(x - y), y(2x + 3y)), where (x, y) = fibfusc(n)
fibfusc(2n + 1) = (-y(2x + 3y), (x + ... | def fibfusc(n, num_digits=None):
if n==0: return (1,0)
x,y=0,1
trunc=1 if num_digits==None else 10**(num_digits)
nbin=bin(n)[3:]
for i in nbin:
x,y=((x+y)*(x-y),y*(2*x+3*y)) if i=='0' else (-y*(2*x + 3*y),(x + 2*y)*(x + 4*y))
if trunc > 1 : x,y=(-(-x % trunc),y % trunc)
r... | def fibfusc(n, num_digits=None):
if n==0: return (1,0)
x,y=0,1
trunc=1 if num_digits==None else 10**(num_digits)
nbin=bin(n)[3:]
for i in nbin:
x,y=((x+y)*(x-y),y*(2*x+3*y)) if i=='0' else (-y*(2*x + 3*y),(x + 2*y)*(x + 4*y))
if trunc > 1 : x,y=(-(-x % trunc),y % trunc)
r... | train | APPS_structured |
Xorgon is an extremely delicious treat formed by the sequence $S$ of binary integers $s_1, s_2,..,s_N$. A really interesting property found in a Xorgon is that the xor of all elements in any contiguous subsequence of length $K$ in $S$ will result in $1$.
Chef has been asked to prepare a Xorgon. However, he has at hi... | # cook your dish here
from sys import stdin,stdout
a0=0
a1=1
n,k=stdin.readline().strip().split(' ')
n,k=int(n),int(k)
arr=list(map(int,stdin.readline().strip().split(' ')))
def solve(n,k,arr):
sol=[]
l=0;u=k;
while l!=u:
sol.append(arr[l:min(len(arr),u)])
l=min(l+k,len(arr))
u=min(u+k,len(arr))
... | # cook your dish here
from sys import stdin,stdout
a0=0
a1=1
n,k=stdin.readline().strip().split(' ')
n,k=int(n),int(k)
arr=list(map(int,stdin.readline().strip().split(' ')))
def solve(n,k,arr):
sol=[]
l=0;u=k;
while l!=u:
sol.append(arr[l:min(len(arr),u)])
l=min(l+k,len(arr))
u=min(u+k,len(arr))
... | train | APPS_structured |
You've came to visit your grandma and she straight away found you a job - her Christmas tree needs decorating!
She first shows you a tree with an identified number of branches, and then hands you a some baubles (or loads of them!).
You know your grandma is a very particular person and she would like the baubles to be d... | from itertools import cycle, islice
from collections import Counter
def baubles_on_tree(baubles, branches):
return [Counter(islice(cycle(range(branches)), baubles))[x] for x in range(branches)] or "Grandma, we will have to buy a Christmas tree first!" | from itertools import cycle, islice
from collections import Counter
def baubles_on_tree(baubles, branches):
return [Counter(islice(cycle(range(branches)), baubles))[x] for x in range(branches)] or "Grandma, we will have to buy a Christmas tree first!" | train | APPS_structured |
You are teaching a class of $N$ students. Today, during the morning prayer, all the students are standing in a line. You are given a string $s$ with length $N$; for each valid $i$, the $i$-th character of this string is 'b' if the $i$-th student in the line is a boy or 'g' if this student is a girl.
The awkwardness of ... | # cook your dish here
try:
T = int(input())
for i in range (0,T):
s = input()
p, q = s.count("b"), s.count("g")
d = 0
c = q - p
r = c // 2
if len(s) == 0:
print(d)
else:
if p == q:
d = (q*(2*(q**2)+1))/3
elif p>q:
d = (q*(2*(q**2)+1))/3
c = p - q
r = c // 2
d = d + (q*r*(2*q... | # cook your dish here
try:
T = int(input())
for i in range (0,T):
s = input()
p, q = s.count("b"), s.count("g")
d = 0
c = q - p
r = c // 2
if len(s) == 0:
print(d)
else:
if p == q:
d = (q*(2*(q**2)+1))/3
elif p>q:
d = (q*(2*(q**2)+1))/3
c = p - q
r = c // 2
d = d + (q*r*(2*q... | train | APPS_structured |
Initially, there is a Robot at position (0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place.
The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L (Left), U (Up) and D (down)... | class Solution:
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
pos = [0,0]
for i in moves:
if i == 'U':
pos[0] = pos[0] + 1
elif i == 'D':
pos[0] = pos[0] - 1
elif i =... | class Solution:
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
pos = [0,0]
for i in moves:
if i == 'U':
pos[0] = pos[0] + 1
elif i == 'D':
pos[0] = pos[0] - 1
elif i =... | train | APPS_structured |
Consider a sequence `u` where u is defined as follows:
1. The number `u(0) = 1` is the first one in `u`.
2. For each `x` in `u`, then `y = 2 * x + 1` and `z = 3 * x + 1` must be in `u` too.
3. There are no other numbers in `u`.
Ex:
`u = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...]`
1 gives 3 and 4, then 3 gives 7 ... | from collections import deque
def dbl_linear(n):
u, q2, q3 = 1, deque([]), deque([])
for _ in range(n):
q2.append(2 * u + 1)
q3.append(3 * u + 1)
u = min(q2[0], q3[0])
if u == q2[0]: q2.popleft()
if u == q3[0]: q3.popleft()
return u | from collections import deque
def dbl_linear(n):
u, q2, q3 = 1, deque([]), deque([])
for _ in range(n):
q2.append(2 * u + 1)
q3.append(3 * u + 1)
u = min(q2[0], q3[0])
if u == q2[0]: q2.popleft()
if u == q3[0]: q3.popleft()
return u | train | APPS_structured |
Today was a sad day. Having bought a new beard trimmer, I set it to the max setting and shaved away at my joyous beard. Stupidly, I hadnt checked just how long the max setting was, and now I look like Ive just started growing it!
Your task, given a beard represented as an arrayof arrays, is to trim the beard as follows... | def trim(beard):
return [[h.replace("J", "|") for h in b] for b in beard[:-1]] + [["..."]*len(beard[0])] | def trim(beard):
return [[h.replace("J", "|") for h in b] for b in beard[:-1]] + [["..."]*len(beard[0])] | train | APPS_structured |
Chef has a calculator which has two screens and two buttons. Initially, each screen shows the number zero. Pressing the first button increments the number on the first screen by 1, and each click of the first button consumes 1 unit of energy.
Pressing the second button increases the number on the second screen by the n... | # cook your dish here
for i in range(int(input())):
n,b=map(int,input().split())
ans=round(n/(2*b))*(n-b*round((n/(2*b))));
print(ans) | # cook your dish here
for i in range(int(input())):
n,b=map(int,input().split())
ans=round(n/(2*b))*(n-b*round((n/(2*b))));
print(ans) | train | APPS_structured |
We need you to implement a method of receiving commands over a network, processing the information and responding.
Our device will send a single packet to you containing data and an instruction which you must perform before returning your reply.
To keep things simple, we will be passing a single "packet" as a string.
... | import operator
funcs = {'0F12': operator.add, 'B7A2': operator.sub, 'C3D9': operator.mul}
def communication_module(packet):
instruction, one, two = packet[4:8], int(packet[8:12]), int(packet[12:16])
result = funcs[instruction](one, two)
if result > 9999:
result = 9999
elif result < ... | import operator
funcs = {'0F12': operator.add, 'B7A2': operator.sub, 'C3D9': operator.mul}
def communication_module(packet):
instruction, one, two = packet[4:8], int(packet[8:12]), int(packet[12:16])
result = funcs[instruction](one, two)
if result > 9999:
result = 9999
elif result < ... | train | APPS_structured |
## Overview
Resistors are electrical components marked with colorful stripes/bands to indicate both their resistance value in ohms and how tight a tolerance that value has. If you did my Resistor Color Codes kata, you wrote a function which took a string containing a resistor's band colors, and returned a string identi... | import re
import math
REGEX_NUMBERS = r"\d+\.?\d*"
RESISTOR_COLORS = {0: 'black', 1: 'brown', 2: 'red', 3: 'orange', 4: 'yellow', 5: 'green', 6: 'blue', 7: 'violet', 8: 'gray', 9: 'white'}
MULTIPLIER = {'k': 1000, 'M': 1000000}
def encode_resistor_colors(ohms_string):
retrieved_val = re.findall(REGEX_NUMBERS, ohm... | import re
import math
REGEX_NUMBERS = r"\d+\.?\d*"
RESISTOR_COLORS = {0: 'black', 1: 'brown', 2: 'red', 3: 'orange', 4: 'yellow', 5: 'green', 6: 'blue', 7: 'violet', 8: 'gray', 9: 'white'}
MULTIPLIER = {'k': 1000, 'M': 1000000}
def encode_resistor_colors(ohms_string):
retrieved_val = re.findall(REGEX_NUMBERS, ohm... | train | APPS_structured |
This kata is part one of precise fractions series (see pt. 2: http://www.codewars.com/kata/precise-fractions-pt-2-conversion).
When dealing with fractional values, there's always a problem with the precision of arithmetical operations. So lets fix it!
Your task is to implement class ```Fraction``` that takes care of si... | from fractions import Fraction
def to_string(self):
n, d = self.numerator, self.denominator
s, w, n = "-" if n < 0 else "", *divmod(abs(n), d)
r = " ".join((str(w) if w else "", f"{n}/{d}" if n else "")).strip()
return f"{s}{r}"
Fraction.__str__ = to_string
Fraction.to_decimal = lambda self: self.nume... | from fractions import Fraction
def to_string(self):
n, d = self.numerator, self.denominator
s, w, n = "-" if n < 0 else "", *divmod(abs(n), d)
r = " ".join((str(w) if w else "", f"{n}/{d}" if n else "")).strip()
return f"{s}{r}"
Fraction.__str__ = to_string
Fraction.to_decimal = lambda self: self.nume... | train | APPS_structured |
## Sum Even Fibonacci Numbers
* Write a func named SumEvenFibonacci that takes a parameter of type int and returns a value of type int
* Generate all of the Fibonacci numbers starting with 1 and 2 and ending on the highest number before exceeding the parameter's value
#### Each new number in the Fibonacci sequence is ... | def SumEvenFibonacci(limit):
a,b,s = 1,1,0
while a <= limit:
if not a%2: s += a
a,b = b, a+b
return s | def SumEvenFibonacci(limit):
a,b,s = 1,1,0
while a <= limit:
if not a%2: s += a
a,b = b, a+b
return s | train | APPS_structured |
In a forest, each rabbit has some color. Some subset of rabbits (possibly all of them) tell you how many other rabbits have the same color as them. Those answers are placed in an array.
Return the minimum number of rabbits that could be in the forest.
Examples:
Input: answers = [1, 1, 2]
Output: 5
Explanation:
The two ... | from collections import Counter
class Poly():
def __init__(self,v):
self.c = Counter()
self.c[''] = 0
if isinstance(v,int):
self.c[''] = v
elif isinstance(v,str):
self.c[v] = 1
elif isinstance(v,Counter):
self.c = v
... | from collections import Counter
class Poly():
def __init__(self,v):
self.c = Counter()
self.c[''] = 0
if isinstance(v,int):
self.c[''] = v
elif isinstance(v,str):
self.c[v] = 1
elif isinstance(v,Counter):
self.c = v
... | train | APPS_structured |
Chef is solving mathematics problems. He is preparing for Engineering Entrance exam. He's stuck in a problem.
$f(n)=1^n*2^{n-1}*3^{n-2} * \ldots * n^{1} $
Help Chef to find the value of $f(n)$.Since this number could be very large, compute it modulo $1000000007$.
-----Input:-----
- First line will contain $T$, number ... | #dt = {} for i in x: dt[i] = dt.get(i,0)+1
import sys;input = sys.stdin.readline
inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()]
M = 10**9+7
f = [1]*(1000001)
for i in range(2,1000001):
f[i] = (i*f[i-1])%M
for i in range(2,1000001):
f[i] = (f[i]*f[i-1])%M
for _ in range(inp()):
n = inp()
p... | #dt = {} for i in x: dt[i] = dt.get(i,0)+1
import sys;input = sys.stdin.readline
inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()]
M = 10**9+7
f = [1]*(1000001)
for i in range(2,1000001):
f[i] = (i*f[i-1])%M
for i in range(2,1000001):
f[i] = (f[i]*f[i-1])%M
for _ in range(inp()):
n = inp()
p... | train | APPS_structured |
# Remove Duplicates
You are to write a function called `unique` that takes an array of integers and returns the array with duplicates removed. It must return the values in the same order as first seen in the given array. Thus no sorting should be done, if 52 appears before 10 in the given array then it should also be t... | def unique(integers):
ans = []
for x in integers:
if x not in ans:
ans.append(x)
return ans | def unique(integers):
ans = []
for x in integers:
if x not in ans:
ans.append(x)
return ans | train | APPS_structured |
You are given a sequence of a journey in London, UK. The sequence will contain bus **numbers** and TFL tube names as **strings** e.g.
```python
['Northern', 'Central', 243, 1, 'Victoria']
```
Journeys will always only contain a combination of tube names and bus numbers. Each tube journey costs `£2.40` and each bus jour... | from itertools import groupby
def london_city_hacker(journey):
arr = list(map(type,journey))
s = 0
for k,g in groupby(arr):
g = len(list(g))
if k==str:
s += 2.4*g
else:
s += 1.5*(g//2+(1 if g%2 else 0) if g>1 else g)
return f'£{round(s,2):.2f}' | from itertools import groupby
def london_city_hacker(journey):
arr = list(map(type,journey))
s = 0
for k,g in groupby(arr):
g = len(list(g))
if k==str:
s += 2.4*g
else:
s += 1.5*(g//2+(1 if g%2 else 0) if g>1 else g)
return f'£{round(s,2):.2f}' | train | APPS_structured |
To give credit where credit is due: This problem was taken from the ACMICPC-Northwest Regional Programming Contest. Thank you problem writers.
You are helping an archaeologist decipher some runes. He knows that this ancient society used a Base 10 system, and that they never start a number with a leading zero. He's figu... | import re
def solve_runes(runes):
# 分解
m = re.match(r'(-?[0-9?]+)([-+*])(-?[0-9?]+)=(-?[0-9?]+)', runes)
nums = [m.group(1),m.group(3),m.group(4)]
op = m.group(2)
# 迭代尝试
for v in range(0,10):
# 同字校验
if str(v) in runes:
continue
testNums = [n... | import re
def solve_runes(runes):
# 分解
m = re.match(r'(-?[0-9?]+)([-+*])(-?[0-9?]+)=(-?[0-9?]+)', runes)
nums = [m.group(1),m.group(3),m.group(4)]
op = m.group(2)
# 迭代尝试
for v in range(0,10):
# 同字校验
if str(v) in runes:
continue
testNums = [n... | train | APPS_structured |
The chef was not happy with the binary number system, so he designed a new machine which is having 6 different states, i.e. in binary there is a total of 2 states as 0 and 1. Now, the chef is confused about how to correlate this machine to get an interaction with Integer numbers, when N(Integer number) is provided to t... | import sys
# cook your dish here
T=int(input())
system=[0,1]
new_multiplier=1
while(len(system)<110000):
new_multiplier*=6
new_list=list( int(x+new_multiplier) for x in system)
system+=new_list
for t in range(T):
N=int(input())
print(system[N])
| import sys
# cook your dish here
T=int(input())
system=[0,1]
new_multiplier=1
while(len(system)<110000):
new_multiplier*=6
new_list=list( int(x+new_multiplier) for x in system)
system+=new_list
for t in range(T):
N=int(input())
print(system[N])
| train | APPS_structured |
A category page displays a set number of products per page, with pagination at the bottom allowing the user to move from page to page.
Given that you know the page you are on, how many products are in the category in total, and how many products are on any given page, how would you output a simple string showing which ... | def pagination_text(page_number, page_size, total_products):
return "Showing %d to %d of %d Products." % (
page_size * (page_number - 1) + 1,
min(total_products, page_size * page_number),
total_products)
| def pagination_text(page_number, page_size, total_products):
return "Showing %d to %d of %d Products." % (
page_size * (page_number - 1) + 1,
min(total_products, page_size * page_number),
total_products)
| train | APPS_structured |
Vietnamese and Bengali as well.
An $N$-bonacci sequence is an infinite sequence $F_1, F_2, \ldots$ such that for each integer $i > N$, $F_i$ is calculated as $f(F_{i-1}, F_{i-2}, \ldots, F_{i-N})$, where $f$ is some function. A XOR $N$-bonacci sequence is an $N$-bonacci sequence for which $f(F_{i-1}, F_{i-2}, \ldots, F... | n,q=list(map(int,input().split()))
arr=[int(n) for n in input().split()]
x=arr[0]
arr1=[]
arr1.append(x)
for i in range(1,n):
x=x^arr[i]
arr1.append(x)
arr1.append(0)
while(q):
q=q-1
x=int(input())
r=x%(n+1)
print(arr1[r-1])
| n,q=list(map(int,input().split()))
arr=[int(n) for n in input().split()]
x=arr[0]
arr1=[]
arr1.append(x)
for i in range(1,n):
x=x^arr[i]
arr1.append(x)
arr1.append(0)
while(q):
q=q-1
x=int(input())
r=x%(n+1)
print(arr1[r-1])
| train | APPS_structured |
A startup office has an ongoing problem with its bin. Due to low budgets, they don't hire cleaners. As a result, the staff are left to voluntarily empty the bin. It has emerged that a voluntary system is not working and the bin is often overflowing. One staff member has suggested creating a rota system based upon the s... | def binRota(arr):
return [seat for row, seats in enumerate(arr) for seat in seats[::(-1)**row]]
| def binRota(arr):
return [seat for row, seats in enumerate(arr) for seat in seats[::(-1)**row]]
| train | APPS_structured |
Consider an array containing cats and dogs. Each dog can catch only one cat, but cannot catch a cat that is more than `n` elements away. Your task will be to return the maximum number of cats that can be caught.
For example:
```Haskell
solve(['D','C','C','D','C'], 2) = 2, because the dog at index 0 (D0) catches C1 and ... | def solve(arr,n):
c,l = 0,len(arr)
for i in range(l):
if arr[i] == 'C':
a = max(0,i-n)
b = min(l-1,i+n)
for j in range(a,b+1):
if arr[j] == 'D':
arr[j] = 'd'
c += 1
break
return c | def solve(arr,n):
c,l = 0,len(arr)
for i in range(l):
if arr[i] == 'C':
a = max(0,i-n)
b = min(l-1,i+n)
for j in range(a,b+1):
if arr[j] == 'D':
arr[j] = 'd'
c += 1
break
return c | train | APPS_structured |
Assume `"#"` is like a backspace in string. This means that string `"a#bc#d"` actually is `"bd"`
Your task is to process a string with `"#"` symbols.
## Examples
```
"abc#d##c" ==> "ac"
"abc##d######" ==> ""
"#######" ==> ""
"" ==> ""
``` | import re
def clean_string(s):
return clean_string(re.sub('[^#]{1}#', '', s).lstrip('#')) if '#' in s else s
| import re
def clean_string(s):
return clean_string(re.sub('[^#]{1}#', '', s).lstrip('#')) if '#' in s else s
| train | APPS_structured |
Chef works in a similar way to a travelling salesman ― he always travels to new cities in order to sell his delicious dishes.
Today, Chef is planning to visit $N$ cities (numbered $1$ through $N$). There is a direct way to travel between each pair of cities. Each city has a specific temperature; let's denote the temper... | def left(a, pos):
if pos == 0 or pos == len(a) - 1:
return True
for i in range(pos + 1, len(a)):
if a[i] - a[i - 2] > d:
return False
return True
def right(a ,pos):
for i in range(pos - 1, -1, -1):
if a[i + 2] - a[i] > d:
return False
return True
for _ in range(int(input())):
n, d = map(int, input(... | def left(a, pos):
if pos == 0 or pos == len(a) - 1:
return True
for i in range(pos + 1, len(a)):
if a[i] - a[i - 2] > d:
return False
return True
def right(a ,pos):
for i in range(pos - 1, -1, -1):
if a[i + 2] - a[i] > d:
return False
return True
for _ in range(int(input())):
n, d = map(int, input(... | train | APPS_structured |
Complete the method so that it formats the words into a single comma separated value. The last word should be separated by the word 'and' instead of a comma. The method takes in an array of strings and returns a single formatted string. Empty string values should be ignored. Empty arrays or null/nil values being passed... | def format_words(words):
words = [w for w in words if w] if words else ''
if not words:
return ''
return f'{", ".join(words[:-1])} and {words[-1]}' if len(words) !=1 else words[-1] | def format_words(words):
words = [w for w in words if w] if words else ''
if not words:
return ''
return f'{", ".join(words[:-1])} and {words[-1]}' if len(words) !=1 else words[-1] | train | APPS_structured |
Sort the given strings in alphabetical order, case **insensitive**. For example:
```
["Hello", "there", "I'm", "fine"] --> ["fine", "Hello", "I'm", "there"]
["C", "d", "a", "B"]) --> ["a", "B", "C", "d"]
``` | sortme=lambda w:sorted(w,key=lambda x:x.lower()) | sortme=lambda w:sorted(w,key=lambda x:x.lower()) | train | APPS_structured |
You have to write a function that describe Leo:
```python
def leo(oscar):
pass
```
if oscar was (integer) 88, you have to return "Leo finally won the oscar! Leo is happy".
if oscar was 86, you have to return "Not even for Wolf of wallstreet?!"
if it was not 88 or 86 (and below 88) you should return "When will you giv... | def leo(oscar):
return "Not even for Wolf of wallstreet?!" if oscar==86 else "When will you give Leo an Oscar?" if oscar<88 else "Leo finally won the oscar! Leo is happy" if oscar == 88 else "Leo got one already!" | def leo(oscar):
return "Not even for Wolf of wallstreet?!" if oscar==86 else "When will you give Leo an Oscar?" if oscar<88 else "Leo finally won the oscar! Leo is happy" if oscar == 88 else "Leo got one already!" | train | APPS_structured |
You are given array of integers, your task will be to count all pairs in that array and return their count.
**Notes:**
* Array can be empty or contain only one value; in this case return `0`
* If there are more pairs of a certain number, count each pair only once. E.g.: for `[0, 0, 0, 0]` the return value is `2` (= 2 ... | def duplicates(arr):
return sum((arr.count(n) // 2 for n in set(arr))) | def duplicates(arr):
return sum((arr.count(n) // 2 for n in set(arr))) | train | APPS_structured |
The Gray code (see wikipedia for more details) is a well-known concept.
One of its important properties is that every two adjacent numbers have exactly one different digit in their binary representation.
In this problem, we will give you n non-negative integers in a sequence A[1..n] (0<=A[i]<2^64), such that every two ... | n = int(input())
s = input()
s = s.split()
d = {}
flag = "No"
two,four = 0,0
for i in s:
if i in d:
d[i] += 1;
if d[i] == 2:
two += 1
elif d[i] == 4:
four += 1
else:
d[i] = 1;
if two>1 or four>0:
flag = "Yes"
else:
for i in range(n-1):
ex = int(s[i]) ^ int(s[i+1])
if ex in d:
d[ex].append(i)
... | n = int(input())
s = input()
s = s.split()
d = {}
flag = "No"
two,four = 0,0
for i in s:
if i in d:
d[i] += 1;
if d[i] == 2:
two += 1
elif d[i] == 4:
four += 1
else:
d[i] = 1;
if two>1 or four>0:
flag = "Yes"
else:
for i in range(n-1):
ex = int(s[i]) ^ int(s[i+1])
if ex in d:
d[ex].append(i)
... | train | APPS_structured |
Given a set of numbers, return the additive inverse of each. Each positive becomes negatives, and the negatives become positives.
~~~if-not:racket
```
invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5]
invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5]
invert([]) == []
```
~~~
```if:javascript,python,ruby,php,elixir,dart
You can assume that... | def invert(lst):
lstCopy = lst[:]
for i in range(len(lst)):
lstCopy[i]*=-1
return lstCopy | def invert(lst):
lstCopy = lst[:]
for i in range(len(lst)):
lstCopy[i]*=-1
return lstCopy | train | APPS_structured |
Mr. Wire Less is not that good at implementing circuit in a breadboard. In his Digital Logic Design course, he has to implement several boolean functions using the breadboard. In a breadboard, inputs are given through the switches and outputs are taken through the LEDs. Each input switch can be either in ground state o... | # cook your dish here
'''#include <bits/stdc++.h>
#include <math.h>
using namespace std;
main(){
long long a=pow(2,1000000000000000000,8589934592);
printf("%lld",a);
}'''
a=int(input())
for i in range(a):
b=int(input())
aa=pow(2,b,8589934592)
print("Case",str(i+1)+":",(aa-1)%(8589934592)) | # cook your dish here
'''#include <bits/stdc++.h>
#include <math.h>
using namespace std;
main(){
long long a=pow(2,1000000000000000000,8589934592);
printf("%lld",a);
}'''
a=int(input())
for i in range(a):
b=int(input())
aa=pow(2,b,8589934592)
print("Case",str(i+1)+":",(aa-1)%(8589934592)) | train | APPS_structured |
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).
You are given a target value to search. If found in the array return true, otherwise return false.
Example 1:
Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true
Exampl... | class Solution:
res = False
def searchR(self, nums, target, start, end):
if(start > end or self.res == True):
return self.res
else:
mid = int((start + end) / 2)
print("Mid index: %d, Mid val: %d, Target: %d" % (mid, nums[mid], target))
... | class Solution:
res = False
def searchR(self, nums, target, start, end):
if(start > end or self.res == True):
return self.res
else:
mid = int((start + end) / 2)
print("Mid index: %d, Mid val: %d, Target: %d" % (mid, nums[mid], target))
... | train | APPS_structured |
Passer ratings are the generally accepted standard for evaluating NFL quarterbacks.
I knew a rating of 100 is pretty good, but never knew what makes up the rating.
So out of curiosity I took a look at the wikipedia page and had an idea or my first kata: https://en.wikipedia.org/wiki/Passer_rating
## Formula
There are f... | def passer_rating(attempts, yards, completions, touchdowns, interceptions):
a = (completions / attempts - .3) * 5
b = (yards / attempts - 3) * .25
c = (touchdowns / attempts) * 20
d = 2.375 - (interceptions / attempts * 25)
a, b, c, d = (max(0, min(x, 2.375)) for x in (a, b, c, d))
return round(... | def passer_rating(attempts, yards, completions, touchdowns, interceptions):
a = (completions / attempts - .3) * 5
b = (yards / attempts - 3) * .25
c = (touchdowns / attempts) * 20
d = 2.375 - (interceptions / attempts * 25)
a, b, c, d = (max(0, min(x, 2.375)) for x in (a, b, c, d))
return round(... | train | APPS_structured |
Given a string s of lower and upper case English letters.
A good string is a string which doesn't have two adjacent characters s[i] and s[i + 1] where:
0 <= i <= s.length - 2
s[i] is a lower-case letter and s[i + 1] is the same letter but in upper-case or vice-versa.
To make the string good, you can choose two adjacent... | class Solution:
def makeGood(self, s: str) -> str:
if len(s) == 1:
return s
for i in range(len(s) - 2, -1, -1):
if s[i].lower() == s[i+1].lower() and s[i] != s[i+1]:
s = s[:i] + s[i+2:]
return self.makeGood(s)
... | class Solution:
def makeGood(self, s: str) -> str:
if len(s) == 1:
return s
for i in range(len(s) - 2, -1, -1):
if s[i].lower() == s[i+1].lower() and s[i] != s[i+1]:
s = s[:i] + s[i+2:]
return self.makeGood(s)
... | train | APPS_structured |
Given a string and an array of integers representing indices, capitalize all letters at the given indices.
For example:
* `capitalize("abcdef",[1,2,5]) = "aBCdeF"`
* `capitalize("abcdef",[1,2,5,100]) = "aBCdeF"`. There is no index 100.
The input will be a lowercase string with no spaces and an array of digits.
Good lu... | def capitalize(s, ind):
sy = list(s)
for i in ind:
try:
sy[i] = sy[i].upper()
except IndexError:
print("Index out of range")
return "".join(sy) | def capitalize(s, ind):
sy = list(s)
for i in ind:
try:
sy[i] = sy[i].upper()
except IndexError:
print("Index out of range")
return "".join(sy) | train | APPS_structured |
A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself).
Given a string s. Return the longest happy prefix of s .
Return an empty string if no such prefix exists.
Example 1:
Input: s = "level"
Output: "l"
Explanation: s contains 4 prefix excluding itself ("l", "le", "lev", "... | class Solution:
def longestPrefix(self, s: str) -> str:
def build(p):
m = len(p)
nxt = [0,0]
j = 0
for i in range(1,m):
while j > 0 and s[i] != s[j]:
j = nxt[j]
if s[i] == s[j]:
j += 1
... | class Solution:
def longestPrefix(self, s: str) -> str:
def build(p):
m = len(p)
nxt = [0,0]
j = 0
for i in range(1,m):
while j > 0 and s[i] != s[j]:
j = nxt[j]
if s[i] == s[j]:
j += 1
... | train | APPS_structured |
Vasya and Petya are playing a simple game. Vasya thought of number x between 1 and n, and Petya tries to guess the number.
Petya can ask questions like: "Is the unknown number divisible by number y?".
The game is played by the following rules: first Petya asks all the questions that interest him (also, he can ask no qu... | def main():
n = int(input()) + 1
a, res = [True] * n, []
for p in range(2, n):
if a[p]:
pp = 1
while pp * p < n:
pp *= p
res.append(pp)
a[p:n:p] = [False] * ((n - 1) // p)
print(len(res))
print(*res)
def __starting_point()... | def main():
n = int(input()) + 1
a, res = [True] * n, []
for p in range(2, n):
if a[p]:
pp = 1
while pp * p < n:
pp *= p
res.append(pp)
a[p:n:p] = [False] * ((n - 1) // p)
print(len(res))
print(*res)
def __starting_point()... | train | APPS_structured |
### Problem Context
The [Fibonacci](http://en.wikipedia.org/wiki/Fibonacci_number) sequence is traditionally used to explain tree recursion.
```python
def fibonacci(n):
if n in [0, 1]:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
```
This algorithm serves welll its educative purpose but it's [t... | from functools import lru_cache
@lru_cache()
def fibonacci(n):
if n in [0, 1]:
return n
return fibonacci(n - 1) + fibonacci(n - 2) | from functools import lru_cache
@lru_cache()
def fibonacci(n):
if n in [0, 1]:
return n
return fibonacci(n - 1) + fibonacci(n - 2) | train | APPS_structured |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.