Datasets:

Modalities:
Text
Libraries:
Datasets
License:
Dataset Viewer
Auto-converted to Parquet Duplicate
input
stringlengths
50
13.9k
output_program
stringlengths
5
655k
output_answer
stringlengths
5
655k
split
stringclasses
1 value
dataset
stringclasses
1 value
Shivam is the youngest programmer in the world, he is just 12 years old. Shivam is learning programming and today he is writing his first program. Program is very simple, Given two integers A and B, write a program to add these two numbers. -----Input----- The first line contains an integer T, the total number of test...
L = [] l = [] x = int(input()) for i in range(x): y = input() z = y.split() a = z[0] b = z[1] L.append(a) l.append(b) for j in range(x): c = int(L[j])+ int(l[j]) print(c)
L = [] l = [] x = int(input()) for i in range(x): y = input() z = y.split() a = z[0] b = z[1] L.append(a) l.append(b) for j in range(x): c = int(L[j])+ int(l[j]) print(c)
train
APPS_structured
Back in 2015, Usain Bolt announced that he'll be retiring after the 2017 World Championship. Though his final season did not end gloriously, we all know that he is a true legend and we witnessed his peak during 2008 - 2013. Post retirement, Usain Bolt is still leading an adventurous life. He's exploring the unexplored...
import math def func(): t=int(input()) for _ in range(t): fn,dst,ta,bs = map(int,input().split(' ')) t1=fn/bs t2=math.sqrt(2*(fn+dst)/ta) if t1<t2: print("Bolt") else: print("Tiger") func()
import math def func(): t=int(input()) for _ in range(t): fn,dst,ta,bs = map(int,input().split(' ')) t1=fn/bs t2=math.sqrt(2*(fn+dst)/ta) if t1<t2: print("Bolt") else: print("Tiger") func()
train
APPS_structured
Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and r...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ stack = [] ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ stack = [] ...
train
APPS_structured
In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.) Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty. Example : Input: [1,2,3,4,5,6,7,8] Output...
from functools import lru_cache class Solution: def splitArraySameAverage(self, A: List[int]) -> bool: # TLE # avg = sum(A) / len(A) # for k in range(1, len(A) // 2 + 1): # for comb in combinations(A, k): # if abs(sum(comb) / k - avg) < 1e-5: # ...
from functools import lru_cache class Solution: def splitArraySameAverage(self, A: List[int]) -> bool: # TLE # avg = sum(A) / len(A) # for k in range(1, len(A) // 2 + 1): # for comb in combinations(A, k): # if abs(sum(comb) / k - avg) < 1e-5: # ...
train
APPS_structured
If we write out the digits of "60" as English words we get "sixzero"; the number of letters in "sixzero" is seven. The number of letters in "seven" is five. The number of letters in "five" is four. The number of letters in "four" is four: we have reached a stable equilibrium. Note: for integers larger than 9, write out...
t = {'1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine', '0': 'zero'} def numbers_of_letters(n): x = [''.join([t[i] for i in str(n)])] while int(n) != len(x[-1]): n = len(x[-1]) x.append(''.join([t[i] for i in str(n)])) return...
t = {'1': 'one', '2': 'two', '3': 'three', '4': 'four', '5': 'five', '6': 'six', '7': 'seven', '8': 'eight', '9': 'nine', '0': 'zero'} def numbers_of_letters(n): x = [''.join([t[i] for i in str(n)])] while int(n) != len(x[-1]): n = len(x[-1]) x.append(''.join([t[i] for i in str(n)])) return...
train
APPS_structured
# Task A lock has `n` buttons in it, numbered from `1 to n`. To open the lock, you have to press all buttons in some order, i.e. a key to the lock is a permutation of the first `n` integers. If you push the right button in the right order, it will be pressed into the lock. Otherwise all pressed buttons will pop out. W...
def press_button(n): return n*(n**2 + 5)/6
def press_button(n): return n*(n**2 + 5)/6
train
APPS_structured
# Description: Find the longest successive exclamation marks and question marks combination in the string. A successive exclamation marks and question marks combination must contains two part: a substring of "!" and a substring "?", they are adjacent. If more than one result are found, return the one which at left s...
def find(s): if s == '' or '!' not in s or '?' not in s: return '' s += ' ' counts = [] curr = s[0] count = 0 for i in s: if i == curr: count += 1 else: counts.append(count) count = 1 curr = i n = [] for i in range(l...
def find(s): if s == '' or '!' not in s or '?' not in s: return '' s += ' ' counts = [] curr = s[0] count = 0 for i in s: if i == curr: count += 1 else: counts.append(count) count = 1 curr = i n = [] for i in range(l...
train
APPS_structured
Pirates have notorious difficulty with enunciating. They tend to blur all the letters together and scream at people. At long last, we need a way to unscramble what these pirates are saying. Write a function that will accept a jumble of letters as well as a dictionary, and output a list of words that the pirate might ha...
def grabscrab(w, pw): return [i for i in pw if all(w.count(j)==i.count(j) for j in w)]
def grabscrab(w, pw): return [i for i in pw if all(w.count(j)==i.count(j) for j in w)]
train
APPS_structured
Your task is to return how many times a string contains a given character. The function takes a string(inputS) as a paremeter and a char(charS) which is the character that you will have to find and count. For example, if you get an input string "Hello world" and the character to find is "o", return 2.
def string_counter(string, char): return string.count(char)
def string_counter(string, char): return string.count(char)
train
APPS_structured
We have a sandglass consisting of two bulbs, bulb A and bulb B. These bulbs contain some amount of sand. When we put the sandglass, either bulb A or B lies on top of the other and becomes the upper bulb. The other bulb becomes the lower bulb. The sand drops from the upper bulb to the lower bulb at a rate of 1 gram per ...
def main(): import sys from operator import itemgetter input = sys.stdin.readline X = int(input()) K = int(input()) R = list(map(int, input().split())) Q = [] for r in R: Q.append((r, -1)) q = int(input()) for _ in range(q): t, a = list(map(int, input().split()))...
def main(): import sys from operator import itemgetter input = sys.stdin.readline X = int(input()) K = int(input()) R = list(map(int, input().split())) Q = [] for r in R: Q.append((r, -1)) q = int(input()) for _ in range(q): t, a = list(map(int, input().split()))...
train
APPS_structured
In this kata you will be given an **integer n**, which is the number of times that is thown a coin. You will have to return an array of string for all the possibilities (heads[H] and tails[T]). Examples: ```coin(1) should return {"H", "T"}``` ```coin(2) should return {"HH", "HT", "TH", "TT"}``` ```coin(3) should return...
from itertools import product def coin(n): return list(map(''.join, product('HT', repeat=n)))
from itertools import product def coin(n): return list(map(''.join, product('HT', repeat=n)))
train
APPS_structured
-----Problem----- Suppose there is a circle. There are N Juice shops on that circle. Juice shops are numbered 0 to N-1 (both inclusive). You have two pieces of information corresponding to each of the juice shop: (1) the amount of Juice that a particular Juice shop can provide and (2) the distance from that juice shop...
a = 0 ans = None for t in range(int(input())): j, d = list(map(int,input().split())) a+=j a-=d if (ans is None): ans = t if (a <= 0): a = 0 ans = None if (ans is None): print(0) else: print(ans)
a = 0 ans = None for t in range(int(input())): j, d = list(map(int,input().split())) a+=j a-=d if (ans is None): ans = t if (a <= 0): a = 0 ans = None if (ans is None): print(0) else: print(ans)
train
APPS_structured
You are given an $array$ of size $N$ and an integer $K$ ( $N > 1 , K > 0$ ). Each element in the array can be incremented by $K$ or decremented by $K$ $at$ $most$ $once$. So there will be $3^n$ possible combinations of final array. (As there are 3 options for every element). Out of these combinations, you have to sele...
# cook your dish here try: for _ in range(int(input())): n,k=map(int,input().split()) li=list(map(int,input().split())) a=max(li) b=min(li) c=a+k d=b-k print(c-d) except: pass
# cook your dish here try: for _ in range(int(input())): n,k=map(int,input().split()) li=list(map(int,input().split())) a=max(li) b=min(li) c=a+k d=b-k print(c-d) except: pass
train
APPS_structured
=====Problem Statement===== ABCXYZ company has up to 100 employees. The company decides to create a unique identification number (UID) for each of its employees. The company has assigned you the task of validating all the randomly generated UIDs. A valid UID must follow the rules below: It must contain at least 2 upper...
import re def __starting_point(): t = int(input().strip()) for _ in range(t): uid = "".join(sorted(input())) if (len(uid) == 10 and re.match(r'', uid) and re.search(r'[A-Z]{2}', uid) and re.search(r'\d\d\d', uid) and not re.search(r'[^a-zA-Z...
import re def __starting_point(): t = int(input().strip()) for _ in range(t): uid = "".join(sorted(input())) if (len(uid) == 10 and re.match(r'', uid) and re.search(r'[A-Z]{2}', uid) and re.search(r'\d\d\d', uid) and not re.search(r'[^a-zA-Z...
train
APPS_structured
You have a collection of lovely poems. Unfortuantely they aren't formatted very well. They're all on one line, like this: ``` Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. ``` What you want is to present each sentence on a new line, s...
def format_poem(poem): poem = poem.split('. ') result = '.\n'.join(poem) return result
def format_poem(poem): poem = poem.split('. ') result = '.\n'.join(poem) return result
train
APPS_structured
Bandwidth of a matrix A is defined as the smallest non-negative integer K such that A(i, j) = 0 for |i - j| > K. For example, a matrix with all zeros will have its bandwith equal to zero. Similarly bandwith of diagonal matrix will also be zero. For example, for the below given matrix, the bandwith of this matrix is 2. ...
from sys import stdin T = int(stdin.readline()) for i in range(0, T): n = int(stdin.readline()) A = [] for i in range(0, n): A.append([int(i) for i in stdin.readline().split(' ')]) ones = sum([sum(i) for i in A]) compare = n ans = 0 for i in range(0, n): if ones <= compare:...
from sys import stdin T = int(stdin.readline()) for i in range(0, T): n = int(stdin.readline()) A = [] for i in range(0, n): A.append([int(i) for i in stdin.readline().split(' ')]) ones = sum([sum(i) for i in A]) compare = n ans = 0 for i in range(0, n): if ones <= compare:...
train
APPS_structured
# Bubblesort Algorithm ## Overview The Bubblesort Algorithm is one of many algorithms used to sort a list of similar items (e.g. all numbers or all letters) into either ascending order or descending order. Given a list (e.g.): ```python [9, 7, 5, 3, 1, 2, 4, 6, 8] ``` To sort this list in ascending order using Bubbles...
def bubblesort_once(L): if len(L)<=1 : return L if L[0]<=L[1]: return [L[0]] + bubblesort_once(L[1:]) return [L[1]] + bubblesort_once([L[0]]+L[2:])
def bubblesort_once(L): if len(L)<=1 : return L if L[0]<=L[1]: return [L[0]] + bubblesort_once(L[1:]) return [L[1]] + bubblesort_once([L[0]]+L[2:])
train
APPS_structured
Shivam owns a gambling house, which has a special wheel called The Wheel of Fortune. This wheel is meant for giving free coins to people coming in the house. The wheel of fortune is a game of chance. It uses a spinning wheel with exactly N numbered pockets and a coin is placed in between every consecutive pocket. The...
t=int(input()) for _ in range(t): n=int(input()) arr=list(map(int,input().split())) d={} for i in range(n): if arr[i] in d: d[arr[i]].append(i) else: d[arr[i]]=[i] q=int(input()) for i in range(q): m=int(input()) if len(d[m])==...
t=int(input()) for _ in range(t): n=int(input()) arr=list(map(int,input().split())) d={} for i in range(n): if arr[i] in d: d[arr[i]].append(i) else: d[arr[i]]=[i] q=int(input()) for i in range(q): m=int(input()) if len(d[m])==...
train
APPS_structured
Every Friday and Saturday night, farmer counts amount of sheep returned back to his farm (sheep returned on Friday stay and don't leave for a weekend). Sheep return in groups each of the days -> you will be given two arrays with these numbers (one for Friday and one for Saturday night). Entries are always positive ints...
def lostSheep(friday,saturday,total): sheeps = friday + saturday return total - sum(sheeps)
def lostSheep(friday,saturday,total): sheeps = friday + saturday return total - sum(sheeps)
train
APPS_structured
## Number of people in the bus There is a bus moving in the city, and it takes and drop some people in each bus stop. You are provided with a list (or array) of integer arrays (or tuples). Each integer array has two items which represent number of people get into bus (The first item) and number of people get off the bu...
def number(bus_stops): # Good Luck! return sum((peoplein - peopleout) for peoplein,peopleout in (bus_stops))
def number(bus_stops): # Good Luck! return sum((peoplein - peopleout) for peoplein,peopleout in (bus_stops))
train
APPS_structured
You are given n strings s_1, s_2, ..., s_{n} consisting of characters 0 and 1. m operations are performed, on each of them you concatenate two existing strings into a new one. On the i-th operation the concatenation s_{a}_{i}s_{b}_{i} is saved into a new string s_{n} + i (the operations are numbered starting from 1). A...
# -*- coding: utf-8 -*- import math import collections import bisect import heapq import time import random """ created by shhuan at 2017/10/5 15:00 """ N = int(input()) S = [''] for i in range(N): S.append(input()) M = int(input()) # t0 = time.time() # N = 3 # S = ["", "00010110000", "110101110101101010101101...
# -*- coding: utf-8 -*- import math import collections import bisect import heapq import time import random """ created by shhuan at 2017/10/5 15:00 """ N = int(input()) S = [''] for i in range(N): S.append(input()) M = int(input()) # t0 = time.time() # N = 3 # S = ["", "00010110000", "110101110101101010101101...
train
APPS_structured
Mohit's girlfriend is playing a game with Nicky. The description of the game is as follows: - Initially on a table Player 1 will put N gem-stones. - Players will play alternatively, turn by turn. - At each move a player can take at most M gem-stones (at least 1 gem-stone must be taken) from the available gem-stones on ...
read = lambda: list(map(int, input().split())) read_s = lambda: list(map(str, input().split())) n, m = read() ans = 0 while True: if n > m: ans += m n -= 2*m else: break print(ans)
read = lambda: list(map(int, input().split())) read_s = lambda: list(map(str, input().split())) n, m = read() ans = 0 while True: if n > m: ans += m n -= 2*m else: break print(ans)
train
APPS_structured
# Task In the field, two beggars A and B found some gold at the same time. They all wanted the gold, and they decided to use simple rules to distribute gold: ``` They divided gold into n piles and be in line. The amount of each pile and the order of piles all are randomly. They took turns to take away a pile of gold f...
def distribution_of(golds): a,b,i=0,0,0 golds_c=golds[:] while golds_c: m=golds_c.pop(0) if golds_c[0]>=golds_c[-1] else golds_c.pop() if i%2:b+=m else:a+=m i+=1 return [a,b]
def distribution_of(golds): a,b,i=0,0,0 golds_c=golds[:] while golds_c: m=golds_c.pop(0) if golds_c[0]>=golds_c[-1] else golds_c.pop() if i%2:b+=m else:a+=m i+=1 return [a,b]
train
APPS_structured
# Task Write a function `deNico`/`de_nico()` that accepts two parameters: - `key`/`$key` - string consists of unique letters and digits - `message`/`$message` - string with encoded message and decodes the `message` using the `key`. First create a numeric key basing on the provided `key` by assigning each letter posi...
def de_nico(key,msg): num_key = ''.join([str(id) for i in key for id, item in enumerate(sorted(key), 1) if item == i]) cut_msg = [msg[i:i+len(num_key)] for i in range(0, len(msg), len(num_key))] d_msg = [''.join([item for i in num_key for id, item in enumerate(list(x), 1) if id == int(i)]) for x in cut_msg]...
def de_nico(key,msg): num_key = ''.join([str(id) for i in key for id, item in enumerate(sorted(key), 1) if item == i]) cut_msg = [msg[i:i+len(num_key)] for i in range(0, len(msg), len(num_key))] d_msg = [''.join([item for i in num_key for id, item in enumerate(list(x), 1) if id == int(i)]) for x in cut_msg]...
train
APPS_structured
Write a function that calculates the *least common multiple* of its arguments; each argument is assumed to be a non-negative integer. In the case that there are no arguments (or the provided array in compiled languages is empty), return `1`. ~~~if:objc NOTE: The first (and only named) argument of the function `n` speci...
from functools import reduce def lcm(*args): return reduce(lcms, args) if args else 1 def gcd(a,b): """Euclidean Algorithm""" return b if a == 0 else gcd(b % a, a) def lcms(a, b): return (a*b) // gcd(a,b)
from functools import reduce def lcm(*args): return reduce(lcms, args) if args else 1 def gcd(a,b): """Euclidean Algorithm""" return b if a == 0 else gcd(b % a, a) def lcms(a, b): return (a*b) // gcd(a,b)
train
APPS_structured
Given a string text, we are allowed to swap two of the characters in the string. Find the length of the longest substring with repeated characters. Example 1: Input: text = "ababa" Output: 3 Explanation: We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the longest repeated characte...
import itertools from collections import Counter class Solution: def maxRepOpt1(self, text: str) -> int: ref = [ [letter,len(list(s))] for letter,s in itertools.groupby(text)] count = Counter(text) res = max( [ min(count.get(i), k + 1) for i , k in ref] ) for i in range(1,len(ref) -...
import itertools from collections import Counter class Solution: def maxRepOpt1(self, text: str) -> int: ref = [ [letter,len(list(s))] for letter,s in itertools.groupby(text)] count = Counter(text) res = max( [ min(count.get(i), k + 1) for i , k in ref] ) for i in range(1,len(ref) -...
train
APPS_structured
Write a program to check whether a triangle is valid or not, when the three angles of the triangle are the inputs. A triangle is valid if the sum of all the three angles is equal to 180 degrees. -----Input----- The first line contains an integer T, the total number of testcases. Then T lines follow, each line contains ...
N=int(input()) for i in range(N): a,b,c=list(map(int,input().split())) if(a+b+c==180): print('YES') else: print('NO')
N=int(input()) for i in range(N): a,b,c=list(map(int,input().split())) if(a+b+c==180): print('YES') else: print('NO')
train
APPS_structured
A number is simply made up of digits. The number 1256 is made up of the digits 1, 2, 5, and 6. For 1256 there are 24 distinct permutations of the digits: 1256, 1265, 1625, 1652, 1562, 1526, 2156, 2165, 2615, 2651, 2561, 2516, 5126, 5162, 5216, 5261, 5621, 5612, 6125, 6152, 6251, 6215, 6521, 6512. Your goal is ...
from itertools import permutations from math import factorial def permutation_average(n): return round(sum(int(''.join(x)) for x in permutations(str(n))) / float(factorial(len(str(n)))))
from itertools import permutations from math import factorial def permutation_average(n): return round(sum(int(''.join(x)) for x in permutations(str(n))) / float(factorial(len(str(n)))))
train
APPS_structured
Given an 2D board, count how many battleships are in it. The battleships are represented with 'X's, empty slots are represented with '.'s. You may assume the following rules: You receive a valid board, made of only battleships or empty slots. Battleships can only be placed horizontally or vertically. In other words, th...
class Solution: def countBattleships(self, board): """ :type board: List[List[str]] :rtype: int """ ans = 0 for r, row in enumerate(board): for c, val in enumerate(row): if val == 'X': ans += 1 ...
class Solution: def countBattleships(self, board): """ :type board: List[List[str]] :rtype: int """ ans = 0 for r, row in enumerate(board): for c, val in enumerate(row): if val == 'X': ans += 1 ...
train
APPS_structured
Write a program to obtain a number $(N)$ from the user and display whether the number is a one digit number, 2 digit number, 3 digit number or more than 3 digit number -----Input:----- - First line will contain the number $N$, -----Output:----- Print "1" if N is a 1 digit number. Print "2" if N is a 2 digit number. Pri...
# cook your dish here s=input() if len(s)==1: print(1) if len(s)==2: print(2) if len(s)==3: print(3) elif len(s)>3: print( "More than 3 digits")
# cook your dish here s=input() if len(s)==1: print(1) if len(s)==2: print(2) if len(s)==3: print(3) elif len(s)>3: print( "More than 3 digits")
train
APPS_structured
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Example 1: Input: [1,3,5,6], 5 Output: 2 Example 2: Input: [1,3,5,6], 2 Output: 1 Example 3: Input: [1,3,5,6], 7 Output: 4...
class Solution: def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ i = 0 n = len(nums) if n == 0: return 0 if nums[0] >= target else 1 else: if nums[n-...
class Solution: def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ i = 0 n = len(nums) if n == 0: return 0 if nums[0] >= target else 1 else: if nums[n-...
train
APPS_structured
=====Problem Statement===== The itertools module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an iterator algebra making it possible to construct specialized tools succinctly and efficiently in pure Python. You are given a list of N lowerca...
#!/usr/bin/env python3 import string symbols = string.ascii_lowercase from itertools import combinations def __starting_point(): n = int(input().strip()) arr = list(map(str, input().strip().split(' '))) times = int(input().strip()) cmbts = list(combinations(sorted(arr), times)) print(("{:.4f...
#!/usr/bin/env python3 import string symbols = string.ascii_lowercase from itertools import combinations def __starting_point(): n = int(input().strip()) arr = list(map(str, input().strip().split(' '))) times = int(input().strip()) cmbts = list(combinations(sorted(arr), times)) print(("{:.4f...
train
APPS_structured
Given an integer array arr, remove a subarray (can be empty) from arr such that the remaining elements in arr are non-decreasing. A subarray is a contiguous subsequence of the array. Return the length of the shortest subarray to remove. Example 1: Input: arr = [1,2,3,10,4,2,3,5] Output: 3 Explanation: The shortest suba...
class Solution: def findLengthOfShortestSubarray(self, arr: List[int]) -> int: l = [] for x in arr: if not l or x >= l[-1]: l.append(x) else: break r = [] for i in range(len(arr)-1, -1, -1): if not r or arr[i] <= r[-...
class Solution: def findLengthOfShortestSubarray(self, arr: List[int]) -> int: l = [] for x in arr: if not l or x >= l[-1]: l.append(x) else: break r = [] for i in range(len(arr)-1, -1, -1): if not r or arr[i] <= r[-...
train
APPS_structured
For this exercise you will create a global flatten method. The method takes in any number of arguments and flattens them into a single array. If any of the arguments passed in are an array then the individual objects within the array will be flattened so that they exist at the same level as the other arguments. Any nes...
def flatten(*a): r, s = [], [iter(a)] while s: it = s.pop() for v in it: if isinstance(v, list): s.extend((it, iter(v))) break else: r.append(v) return r
def flatten(*a): r, s = [], [iter(a)] while s: it = s.pop() for v in it: if isinstance(v, list): s.extend((it, iter(v))) break else: r.append(v) return r
train
APPS_structured
There are N robots and M exits on a number line. The N + M coordinates of these are all integers and all distinct. For each i (1 \leq i \leq N), the coordinate of the i-th robot from the left is x_i. Also, for each j (1 \leq j \leq M), the coordinate of the j-th exit from the left is y_j. Snuke can repeatedly perform t...
from bisect import bisect from collections import defaultdict class Bit: def __init__(self, n, MOD): self.size = n self.tree = [0] * (n + 1) self.depth = n.bit_length() self.mod = MOD def sum(self, i): s = 0 while i > 0: s += self.tree[i] ...
from bisect import bisect from collections import defaultdict class Bit: def __init__(self, n, MOD): self.size = n self.tree = [0] * (n + 1) self.depth = n.bit_length() self.mod = MOD def sum(self, i): s = 0 while i > 0: s += self.tree[i] ...
train
APPS_structured
Write a program to take two numbers as input and print their difference if the first number is greater than the second number otherwise$otherwise$ print their sum. -----Input:----- - First line will contain the first number (N1$N1$) - Second line will contain the second number (N2$N2$) -----Output:----- Output a single...
from sys import * def main(): nbre1 = int(stdin.readline().strip()) nbre2 = int(stdin.readline().strip()) if nbre1 > nbre2: difference = nbre1 - nbre2 stdout.write(str(difference)) else: somme = nbre1 + nbre2 stdout.write(str(somme)) def __starting_point(): main(...
from sys import * def main(): nbre1 = int(stdin.readline().strip()) nbre2 = int(stdin.readline().strip()) if nbre1 > nbre2: difference = nbre1 - nbre2 stdout.write(str(difference)) else: somme = nbre1 + nbre2 stdout.write(str(somme)) def __starting_point(): main(...
train
APPS_structured
Now you have to write a function that takes an argument and returns the square of it.
def square(n): squares = int(n **2) return squares
def square(n): squares = int(n **2) return squares
train
APPS_structured
Today, Chef decided to cook some delicious meals from the ingredients in his kitchen. There are $N$ ingredients, represented by strings $S_1, S_2, \ldots, S_N$. Chef took all the ingredients, put them into a cauldron and mixed them up. In the cauldron, the letters of the strings representing the ingredients completely ...
# cook your dish here for _ in range(int(input())): N = int(input()) s = '' for i in range(N): s += input() c = [] for i in list('codehf'): c.append(s.count(i)) c[0] /= 2 c[3] /= 2 print(int(min(c)))
# cook your dish here for _ in range(int(input())): N = int(input()) s = '' for i in range(N): s += input() c = [] for i in list('codehf'): c.append(s.count(i)) c[0] /= 2 c[3] /= 2 print(int(min(c)))
train
APPS_structured
# Right in the Center _This is inspired by one of Nick Parlante's exercises on the [CodingBat](https://codingbat.com/java) online code practice tool._ Given a sequence of characters, does `"abc"` appear in the CENTER of the sequence? The sequence of characters could contain more than one `"abc"`. To define CENTER, the ...
def in_centre(s,i): return s[i] == "a" and s[i+1] == "b" and s[i+2] == "c" def is_in_middle(s): if "abc" not in s or len(s) < 3: return False l = len(s) if l % 2 == 1: i = (l+1)//2-2; return in_centre(s,i) else: i1 = l//2 -2; i2 = l//2 -1; return in_centre(s,i1) or in_centre(s,i2)
def in_centre(s,i): return s[i] == "a" and s[i+1] == "b" and s[i+2] == "c" def is_in_middle(s): if "abc" not in s or len(s) < 3: return False l = len(s) if l % 2 == 1: i = (l+1)//2-2; return in_centre(s,i) else: i1 = l//2 -2; i2 = l//2 -1; return in_centre(s,i1) or in_centre(s,i2)
train
APPS_structured
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (x_{i}, y_{i}). They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan con...
from collections import defaultdict, Counter n = int(input()) w = [] for i in range(n): w.append(tuple(map(int, input().split()))) dx = Counter() dy = Counter() for x, y in w: dx[x] += 1 dy[y] += 1 count = sum((v * (v-1) / 2) for v in list(dx.values())) + \ sum((v * (v-1) / 2) for v in list(dy.v...
from collections import defaultdict, Counter n = int(input()) w = [] for i in range(n): w.append(tuple(map(int, input().split()))) dx = Counter() dy = Counter() for x, y in w: dx[x] += 1 dy[y] += 1 count = sum((v * (v-1) / 2) for v in list(dx.values())) + \ sum((v * (v-1) / 2) for v in list(dy.v...
train
APPS_structured
We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job.  Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i].  Every worker can be assigned at most one job, but one ...
from bisect import bisect_right class Solution: def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int: dp = [(d, p) for d, p in zip(difficulty, profit)] dp.sort() G = [] C = [] for x, y in dp: if not G or G[-1] < x: ...
from bisect import bisect_right class Solution: def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int: dp = [(d, p) for d, p in zip(difficulty, profit)] dp.sort() G = [] C = [] for x, y in dp: if not G or G[-1] < x: ...
train
APPS_structured
Mr. Pr and Ms. Ad are at $a$ and $b$ respectively on an infinite number line. Mr. Pr wants to meet Ms. Ad. Mr. Pr can choose to move $c$ or $d$ units in 1 second. If Mr. Pr moves $c$ units then Ms. Ad will move $d$ units and vice versa. (Both of them always moved in positive x-direction) You have to determine if Mr. P...
T=int(input()) while T>0: T-=1 A,B,C,D=map(int,input().split()) res1=max(C,D) res2=min(C,D) val1=B-A val2=res2-res1 val1=abs(val1) val2=abs(val2) if val2!=0: if val1%val2==0: print("YES") else: print("NO") elif val1==0 and val2==0: ...
T=int(input()) while T>0: T-=1 A,B,C,D=map(int,input().split()) res1=max(C,D) res2=min(C,D) val1=B-A val2=res2-res1 val1=abs(val1) val2=abs(val2) if val2!=0: if val1%val2==0: print("YES") else: print("NO") elif val1==0 and val2==0: ...
train
APPS_structured
You are standing on top of an amazing Himalayan mountain. The view is absolutely breathtaking! you want to take a picture on your phone, but... your memory is full again! ok, time to sort through your shuffled photos and make some space... Given a gallery of photos, write a function to sort through your pictures. You g...
def key(pic): parts = pic.split('.') return parts[0], int(parts[1][3:]) def sort_photos(pics): pics.sort(key=key) pics = pics[-5:] last_key = key(pics[-1]) pics.append(last_key[0] + '.img' + str(last_key[1] + 1)) return pics
def key(pic): parts = pic.split('.') return parts[0], int(parts[1][3:]) def sort_photos(pics): pics.sort(key=key) pics = pics[-5:] last_key = key(pics[-1]) pics.append(last_key[0] + '.img' + str(last_key[1] + 1)) return pics
train
APPS_structured
Bob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game. Initially, Bob chooses integer m, bit depth of the game, which means that all numbers in the game will consist of m bits. Then he asks Peter to choose some m-bit number. After that, B...
def sumBin(a, b, varMap): lhs = varMap[a] rhs = varMap[b] return bin(int(lhs, 2) + int(rhs, 2))[2:] def andBin(a, b, varMap): lhs = varMap[a] rhs = varMap[b] return bin(int(lhs, 2) & int(rhs, 2))[2:] def orBin(a, b, varMap): lhs = varMap[a] rhs = varMap[b] return bin(int(lhs, 2) | int(rhs, 2))[2:] ...
def sumBin(a, b, varMap): lhs = varMap[a] rhs = varMap[b] return bin(int(lhs, 2) + int(rhs, 2))[2:] def andBin(a, b, varMap): lhs = varMap[a] rhs = varMap[b] return bin(int(lhs, 2) & int(rhs, 2))[2:] def orBin(a, b, varMap): lhs = varMap[a] rhs = varMap[b] return bin(int(lhs, 2) | int(rhs, 2))[2:] ...
train
APPS_structured
Create a class Vector that has simple (3D) vector operators. In your class, you should support the following operations, given Vector ```a``` and Vector ```b```: ```python a + b # returns a new Vector that is the resultant of adding them a - b # same, but with subtraction a == b # returns true if they have the same mag...
import math import operator class Vector: def __init__(self, *args): self.x, self.y, self.z = self.args = tuple(args[0] if len(args) == 1 else args) self.magnitude = math.sqrt(sum(i ** 2 for i in self.args)) def __str__(self): return '<{}>'.format(', '.join(map(str, self.args))) ...
import math import operator class Vector: def __init__(self, *args): self.x, self.y, self.z = self.args = tuple(args[0] if len(args) == 1 else args) self.magnitude = math.sqrt(sum(i ** 2 for i in self.args)) def __str__(self): return '<{}>'.format(', '.join(map(str, self.args))) ...
train
APPS_structured
# Introduction and Warm-up (Highly recommended) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) ___ # Task **_Given_** an **_array of integers_** , **_Find the minimum sum_** which is obtained *from summing each Two integers product* . ___ # Notes * **_Array/l...
def min_sum(arr): arr = sorted(arr) n = 0 while len(arr)>0: n += arr.pop(0)*arr.pop() return n
def min_sum(arr): arr = sorted(arr) n = 0 while len(arr)>0: n += arr.pop(0)*arr.pop() return n
train
APPS_structured
#Detail [Countdown](https://en.wikipedia.org/wiki/Countdown_(game_show) is a British game show with number and word puzzles. The letters round consists of the contestant picking 9 shuffled letters - either picking from the vowel pile or the consonant pile. The contestants are given 30 seconds to try to come up with the...
def longest_word(letters): try: word_list = [w for w in words if all(w.count(c) <= letters.count(c) for c in w)] largest = sorted([w for w in word_list if len(w) == len(max(word_list, key=len))]) return largest if largest else None except: return None
def longest_word(letters): try: word_list = [w for w in words if all(w.count(c) <= letters.count(c) for c in w)] largest = sorted([w for w in word_list if len(w) == len(max(word_list, key=len))]) return largest if largest else None except: return None
train
APPS_structured
In this Kata, you will implement the [Luhn Algorithm](http://en.wikipedia.org/wiki/Luhn_algorithm), which is used to help validate credit card numbers. Given a positive integer of up to 16 digits, return ```true``` if it is a valid credit card number, and ```false``` if it is not. Here is the algorithm: * Double every ...
import numpy as np def validate(cc_number): # split integer into array of digits arr = np.array([int(i) for i in str(cc_number)]) # double every second digit from the right arr[-2::-2] *= 2 # substract 9 from digits greater than 9 arr[arr>9] -= 9 # sum up all the digits and check the modulus...
import numpy as np def validate(cc_number): # split integer into array of digits arr = np.array([int(i) for i in str(cc_number)]) # double every second digit from the right arr[-2::-2] *= 2 # substract 9 from digits greater than 9 arr[arr>9] -= 9 # sum up all the digits and check the modulus...
train
APPS_structured
# Longest Palindromic Substring (Linear) A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g., 'madam' or 'racecar'. Even the letter 'x' is considered a palindrome. For this Kata, you are given a string ```s```. Write a function that returns the longest _contiguous_ palindromic sub...
''' Write a function that returns the longest contiguous palindromic substring in s. In the event that there are multiple longest palindromic substrings, return the first to occur. ''' # TODO: Complete in linear time xDD def longest_palindrome(s): if is_palindrome(s): return s ma...
''' Write a function that returns the longest contiguous palindromic substring in s. In the event that there are multiple longest palindromic substrings, return the first to occur. ''' # TODO: Complete in linear time xDD def longest_palindrome(s): if is_palindrome(s): return s ma...
train
APPS_structured
Jem is famous for his laziness at school. He always leaves things to last minute. Now Jem has N problems in the assignment of "Advanced topics in algorithm" class to solved. The assignment is due tomorrow and as you may guess he hasn't touch any of the problems. Fortunately he got a plan as always. The first step will ...
# cook your code here t= int(input()) while (t>0): t=t-1 T=0 N,B,M = list(map(int,input().split())) while(N!=0): T=T+ int((N+1)/2) *M + B M=2*M N= int(N/2) print(T-B)
# cook your code here t= int(input()) while (t>0): t=t-1 T=0 N,B,M = list(map(int,input().split())) while(N!=0): T=T+ int((N+1)/2) *M + B M=2*M N= int(N/2) print(T-B)
train
APPS_structured
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n. Example: Input: 3 Output: [   [1,null,3,2],   [3,2,null,1],   [3,1,null,null,2],   [2,1,3],   [1,null,2,null,3] ] Explanation: The above output corresponds to the 5 unique BST's shown below: 1 3 3 ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def generateTrees(self, n): """ :type n: int :rtype: List[TreeNode] """ if n <= 0: ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def generateTrees(self, n): """ :type n: int :rtype: List[TreeNode] """ if n <= 0: ...
train
APPS_structured
Similar setting of the [previous](https://www.codewars.com/kata/progressive-spiral-number-position/), this time you are called to identify in which "branch" of the spiral a given number will end up. Considering a square of numbers disposed as the 25 items in [the previous kata](https://www.codewars.com/kata/progressive...
k, li = 1, [0] for i in range(1, 1000000): li.append(k) k += 8 * i def branch(n): a,b = next([i,li[i-1]+1] for i,j in enumerate(li) if j>=n) step = a*2-2 for i in range(4): if b<=n<b+step : return i b += step return 0
k, li = 1, [0] for i in range(1, 1000000): li.append(k) k += 8 * i def branch(n): a,b = next([i,li[i-1]+1] for i,j in enumerate(li) if j>=n) step = a*2-2 for i in range(4): if b<=n<b+step : return i b += step return 0
train
APPS_structured
Do you know that The Chef has a special interest in palindromes? Yes he does! Almost all of the dishes in his restaurant is named by a palindrome strings. The problem is that a name of a dish should not be too long, so The Chef has only limited choices when naming a new dish. For the given positive integer N, your task...
mod=1000000007 for _ in range(int(input())): n=int(input()) if n==1: print(26) elif n==2: print(52) else: k=-(-n//2) if n%2==0: ans=26*(1+26*(pow(26,k-1,mod)-1)*pow(26-1,mod-2,mod))+26*(1+26*(pow(26,k-1,mod)-1)*pow(26-1,mod-2,mod)) else: ...
mod=1000000007 for _ in range(int(input())): n=int(input()) if n==1: print(26) elif n==2: print(52) else: k=-(-n//2) if n%2==0: ans=26*(1+26*(pow(26,k-1,mod)-1)*pow(26-1,mod-2,mod))+26*(1+26*(pow(26,k-1,mod)-1)*pow(26-1,mod-2,mod)) else: ...
train
APPS_structured
We define the "unfairness" of a list/array as the *minimal* difference between max(x1,x2,...xk) and min(x1,x2,...xk), for all possible combinations of k elements you can take from the list/array; both minimum and maximum of an empty list/array are considered to be 0. **More info and constraints:** * lists/arrays can co...
min_unfairness=lambda a,k:a.sort()or k>0<len(a)and min(b-a for a,b in zip(a,a[k-1:]))
min_unfairness=lambda a,k:a.sort()or k>0<len(a)and min(b-a for a,b in zip(a,a[k-1:]))
train
APPS_structured
Write the following function: ```python def area_of_polygon_inside_circle(circle_radius, number_of_sides): ``` It should calculate the area of a regular polygon of `numberOfSides`, `number-of-sides`, or `number_of_sides` sides inside a circle of radius `circleRadius`, `circle-radius`, or `circle_radius` which passes th...
import math def area_of_polygon_inside_circle(circle_radius, number_of_sides): r = circle_radius s = number_of_sides a = (s * (r ** 2) * math.sin(2*math.pi/s))/2 return round(a, 3)
import math def area_of_polygon_inside_circle(circle_radius, number_of_sides): r = circle_radius s = number_of_sides a = (s * (r ** 2) * math.sin(2*math.pi/s))/2 return round(a, 3)
train
APPS_structured
You are given set of n points in 5-dimensional space. The points are labeled from 1 to n. No two points coincide. We will call point a bad if there are different points b and c, not equal to a, from the given set such that angle between vectors $\vec{ab}$ and $\vec{ac}$ is acute (i.e. strictly less than $90^{\circ}$). ...
from math import acos,sqrt,pi def norm(x): if x==0: return 0 else: return sqrt(scalar(x,x)) def scalar(x,y): return sum([x[i]*y[i] for i in range(5)]) def vector(p,q): return ([ (q[i]-p[i]) for i in range(5) ]) number=0 good_points=[] n=int(input()) liste=[] for _ in range(n): x=...
from math import acos,sqrt,pi def norm(x): if x==0: return 0 else: return sqrt(scalar(x,x)) def scalar(x,y): return sum([x[i]*y[i] for i in range(5)]) def vector(p,q): return ([ (q[i]-p[i]) for i in range(5) ]) number=0 good_points=[] n=int(input()) liste=[] for _ in range(n): x=...
train
APPS_structured
Write a function that accepts two square matrices (`N x N` two dimensional arrays), and return the sum of the two. Both matrices being passed into the function will be of size `N x N` (square), containing only integers. How to sum two matrices: Take each cell `[n][m]` from the first matrix, and add it with the same `[n...
import numpy as np def matrix_addition(a, b): S = np.array(a) + np.array(b) return S.tolist()
import numpy as np def matrix_addition(a, b): S = np.array(a) + np.array(b) return S.tolist()
train
APPS_structured
AtCoDeer the deer found N rectangle lying on the table, each with height 1. If we consider the surface of the desk as a two-dimensional plane, the i-th rectangle i(1≤i≤N) covers the vertical range of [i-1,i] and the horizontal range of [l_i,r_i], as shown in the following figure: AtCoDeer will move these rectangles hor...
# seishin.py N = int(input()) P = [list(map(int, input().split())) for i in range(N)] INF = 10**18 from heapq import heappush, heappop l0, r0 = P[0] L = [-l0+1] R = [l0-1] s = t = 0 def debug(L, s, t, R): L0 = L[:] Q1 = []; Q2 = [] while L0: Q1.append(-s-heappop(L0)) R0 = R[:] while R0:...
# seishin.py N = int(input()) P = [list(map(int, input().split())) for i in range(N)] INF = 10**18 from heapq import heappush, heappop l0, r0 = P[0] L = [-l0+1] R = [l0-1] s = t = 0 def debug(L, s, t, R): L0 = L[:] Q1 = []; Q2 = [] while L0: Q1.append(-s-heappop(L0)) R0 = R[:] while R0:...
train
APPS_structured
We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i. Vertex i has an integer a_i written on it. For every integer k from 1 through N, solve the following problem: - We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k...
import math import bisect n = int(input()) alist = [0]+list(map(int,input().split())) uv_list = [] for i in range(n-1): u,v = list(map(int,input().split())) if u > v: u, v = v, u uv_list.append([u,v]) tree = [[] for _ in range(n+1)] for i in range(n-1): uv = uv_list[i] tree[uv[0]].append(...
import math import bisect n = int(input()) alist = [0]+list(map(int,input().split())) uv_list = [] for i in range(n-1): u,v = list(map(int,input().split())) if u > v: u, v = v, u uv_list.append([u,v]) tree = [[] for _ in range(n+1)] for i in range(n-1): uv = uv_list[i] tree[uv[0]].append(...
train
APPS_structured
=====Function Descriptions===== collections.deque() A deque is a double-ended queue. It can be used to add or remove elements from both ends. Deques support thread safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction. Example Code >>> fro...
#!/usr/bin/env python3 from collections import deque def __starting_point(): num = int(input().strip()) deq = deque() for _ in range(num): args = input().strip().split() if args[0] == 'append': deq.append(args[1]) elif args[0] == 'appendleft': ...
#!/usr/bin/env python3 from collections import deque def __starting_point(): num = int(input().strip()) deq = deque() for _ in range(num): args = input().strip().split() if args[0] == 'append': deq.append(args[1]) elif args[0] == 'appendleft': ...
train
APPS_structured
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). Example: Input: S = "ADOBECODEBANC", T = "ABC" Output: "BANC" Note: If there is no such window in S that covers all characters in T, return the empty string "". If there is such win...
class Solution: def minWindow(self, s, t): """ :type s: str :type t: str :rtype: str """ # assume t doesn't have duplicated chars left=-1 right = 0 result = "" totalMatch = 0 d = {} for c in t: ...
class Solution: def minWindow(self, s, t): """ :type s: str :type t: str :rtype: str """ # assume t doesn't have duplicated chars left=-1 right = 0 result = "" totalMatch = 0 d = {} for c in t: ...
train
APPS_structured
In a given 2D binary array A, there are two islands.  (An island is a 4-directionally connected group of 1s not connected to any other 1s.) Now, we may change 0s to 1s so as to connect the two islands together to form 1 island. Return the smallest number of 0s that must be flipped.  (It is guaranteed that the answer is...
class Solution: def shortestBridge(self, A: List[List[int]]) -> int: N, M = len(A), len(A[0]) def labelIsland(i, j): stack = [(i,j)] visited = {(i,j)} while stack: x, y = stack.pop() A[x][y] = 2 for nx, ny in [(x-1,y...
class Solution: def shortestBridge(self, A: List[List[int]]) -> int: N, M = len(A), len(A[0]) def labelIsland(i, j): stack = [(i,j)] visited = {(i,j)} while stack: x, y = stack.pop() A[x][y] = 2 for nx, ny in [(x-1,y...
train
APPS_structured
Given an array which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these m subarrays. Note: If n is the length of array, assume the following constraints are satisfied: 1 ≤ n ≤ 1000 1 ≤ m ≤ min(50, ...
class Solution: def splitArray(self, nums, m): """ :type nums: List[int] :type m: int :rtype: int """ accum = [0] N = len(nums) mmm = max(nums) if m >= N: return mmm res = 0 for i in nums: r...
class Solution: def splitArray(self, nums, m): """ :type nums: List[int] :type m: int :rtype: int """ accum = [0] N = len(nums) mmm = max(nums) if m >= N: return mmm res = 0 for i in nums: r...
train
APPS_structured
Chef has just started Programming, he is in first year of Engineering. Chef is reading about Relational Operators. Relational Operators are operators which check relatioship between two values. Given two numerical values A and B you need to help chef in finding the relationship between them that is, - First one is gr...
N=int(input()) for i in range(N): a,b=list(map(int,input().split())) if(a<b): print('<') elif(a>b): print('>') else: print('=')
N=int(input()) for i in range(N): a,b=list(map(int,input().split())) if(a<b): print('<') elif(a>b): print('>') else: print('=')
train
APPS_structured
Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them. We repeatedly make duplicate removals on S until we no longer can. Return the final string after all such duplicate removals have been made.  It is guaranteed the answer is unique. Example ...
class Solution: def removeDuplicates(self, S: str) -> str: ## stack application stack = [] for i in S: if not stack: stack.append(i) elif i == stack[-1]: stack.pop() else: stack.append(i) ret...
class Solution: def removeDuplicates(self, S: str) -> str: ## stack application stack = [] for i in S: if not stack: stack.append(i) elif i == stack[-1]: stack.pop() else: stack.append(i) ret...
train
APPS_structured
Assume that you started to store items in progressively expanding square location, like this for the first 9 numbers: ``` 05 04 03 06 01 02 07 08 09 ``` And like this for the expanding to include up to the first 25 numbers: ``` 17 16 15 14 13 18 05 04 03 12 19 06 01 02 11 20 07 08 09 10 21 22 23 24 25 ``` You might eas...
def layers(n): return int(((n - 1)**0.5 + 1) // 2) + 1
def layers(n): return int(((n - 1)**0.5 + 1) // 2) + 1
train
APPS_structured
Given two arrays nums1 and nums2. Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remai...
class Solution: def maxDotProduct(self, nums1, nums2): if all(x >= 0 for x in nums1) and all(y <= 0 for y in nums2): return min(nums1) * max(nums2) if all(x <= 0 for x in nums1) and all(y >= 0 for y in nums2): return max(nums1) * min(nums2) a, b = len(nums1), len(nums...
class Solution: def maxDotProduct(self, nums1, nums2): if all(x >= 0 for x in nums1) and all(y <= 0 for y in nums2): return min(nums1) * max(nums2) if all(x <= 0 for x in nums1) and all(y >= 0 for y in nums2): return max(nums1) * min(nums2) a, b = len(nums1), len(nums...
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...
# cook your dish here for _ in range(int(input())): n=int(input()) print("0") for i in range(1,n+1): for j in range(i): print("*",end="") print(i)
# cook your dish here for _ in range(int(input())): n=int(input()) print("0") for i in range(1,n+1): for j in range(i): print("*",end="") print(i)
train
APPS_structured
In this Kata, you will be given an integer `n` and your task will be to return `the largest integer that is <= n and has the highest digit sum`. For example: ``` solve(100) = 99. Digit Sum for 99 = 9 + 9 = 18. No other number <= 100 has a higher digit sum. solve(10) = 9 solve(48) = 48. Note that 39 is also an option, b...
def solve(n): b = [int(str(n)[0]) - 1] + [9 for x in str(n)[1:]] digsum = sum(b) if digsum <= sum([int(x) for x in str(n)]): return n for i in range(len(str(n))-1, -1, -1): a = [int(x) for x in str(n)[:i]] + [int(str(n)[i]) - 1] + [9 for x in str(n)[i+1:]] print((i,a)) if...
def solve(n): b = [int(str(n)[0]) - 1] + [9 for x in str(n)[1:]] digsum = sum(b) if digsum <= sum([int(x) for x in str(n)]): return n for i in range(len(str(n))-1, -1, -1): a = [int(x) for x in str(n)[:i]] + [int(str(n)[i]) - 1] + [9 for x in str(n)[i+1:]] print((i,a)) if...
train
APPS_structured
The chef was playing with numbers and he found that natural number N can be obtained by sum various unique natural numbers, For challenging himself chef wrote one problem statement, which he decided to solve in future. Problem statement: N can be obtained as the sum of Kth power of integers in multiple ways, find total...
for _ in range(int(input())): x,n = map(int,input().split()) reach = [0]*(x+1) reach[0] = 1 i=1 while i**n<=x: j = 1 while j+i**n<=x: j+=1 j-=1 while j>=0: if reach[j]>0: reach[j+i**n]+=reach[j] j-=1 i+=1 ...
for _ in range(int(input())): x,n = map(int,input().split()) reach = [0]*(x+1) reach[0] = 1 i=1 while i**n<=x: j = 1 while j+i**n<=x: j+=1 j-=1 while j>=0: if reach[j]>0: reach[j+i**n]+=reach[j] j-=1 i+=1 ...
train
APPS_structured
Write a program that will calculate the number of trailing zeros in a factorial of a given number. `N! = 1 * 2 * 3 * ... * N` Be careful `1000!` has 2568 digits... For more info, see: http://mathworld.wolfram.com/Factorial.html ## Examples ```python zeros(6) = 1 # 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing zero ...
def zeros(n): # Initialize result count = 0 # Keep dividing n by # powers of 5 and # update Count i=5 while (n/i>=1): count += int(n/i) i *= 5 return int(count)
def zeros(n): # Initialize result count = 0 # Keep dividing n by # powers of 5 and # update Count i=5 while (n/i>=1): count += int(n/i) i *= 5 return int(count)
train
APPS_structured
Bit Vectors/Bitmaps A bitmap is one way of efficiently representing sets of unique integers using single bits. To see how this works, we can represent a set of unique integers between `0` and `< 20` using a vector/array of 20 bits: ``` var set = [3, 14, 2, 11, 16, 4, 6];``` ``` var bitmap = [0, 0, 1, 1, 1, 0, 1, 0, 0, ...
def to_bits(string): input=sorted([int(x) for x in string.split("\n")]) bitmap=[0]*5000 for i in input: bitmap[i]=1 return bitmap
def to_bits(string): input=sorted([int(x) for x in string.split("\n")]) bitmap=[0]*5000 for i in input: bitmap[i]=1 return bitmap
train
APPS_structured
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth. Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!). $8$ illustration by 猫屋 https://twitter.com/nekoyaliu ...
# IAWT s = input() ans = 0 for i in range(len(s)): for j in range(i+1, len(s)): for k in range(j+1, len(s)): if s[i] == 'Q' and s[j] == 'A' and s[k] == 'Q': ans += 1 print(ans)
# IAWT s = input() ans = 0 for i in range(len(s)): for j in range(i+1, len(s)): for k in range(j+1, len(s)): if s[i] == 'Q' and s[j] == 'A' and s[k] == 'Q': ans += 1 print(ans)
train
APPS_structured
The function is not returning the correct values. Can you figure out why? ```python get_planet_name(3) # should return 'Earth' ```
def get_planet_name(id): # a dictionary also can work as a switch case switcher = { 1:"Mercury", 2:"Venus", 3:"Earth", 4:"Mars", 5:"Jupiter", 6:"Saturn", 7:"Uranus", 8:"Neptune" } return switcher.get(id)
def get_planet_name(id): # a dictionary also can work as a switch case switcher = { 1:"Mercury", 2:"Venus", 3:"Earth", 4:"Mars", 5:"Jupiter", 6:"Saturn", 7:"Uranus", 8:"Neptune" } return switcher.get(id)
train
APPS_structured
## Task Implement a function which finds the numbers less than `2`, and the indices of numbers greater than `1` in the given sequence, and returns them as a pair of sequences. Return a nested array or a tuple depending on the language: * The first sequence being only the `1`s and `0`s from the original sequence. * Th...
def binary_cleaner(seq): return [x for x in seq if x in [0, 1]], [i for i, x in enumerate(seq) if x > 1]
def binary_cleaner(seq): return [x for x in seq if x in [0, 1]], [i for i, x in enumerate(seq) if x > 1]
train
APPS_structured
Slime and his $n$ friends are at a party. Slime has designed a game for his friends to play. At the beginning of the game, the $i$-th player has $a_i$ biscuits. At each second, Slime will choose a biscuit randomly uniformly among all $a_1 + a_2 + \ldots + a_n$ biscuits, and the owner of this biscuit will give it to a r...
MOD = 998244353 n = int(input()) a = list(map(int, input().split())) tot = sum(a) def inv(x): return pow(x, MOD - 2, MOD) l = [0, pow(n, tot, MOD) - 1] for i in range(1, tot): aC = i cC = (n - 1) * (tot - i) curr = (aC + cC) * l[-1] curr -= tot * (n - 1) curr -= aC * l[-2] curr *= inv(c...
MOD = 998244353 n = int(input()) a = list(map(int, input().split())) tot = sum(a) def inv(x): return pow(x, MOD - 2, MOD) l = [0, pow(n, tot, MOD) - 1] for i in range(1, tot): aC = i cC = (n - 1) * (tot - i) curr = (aC + cC) * l[-1] curr -= tot * (n - 1) curr -= aC * l[-2] curr *= inv(c...
train
APPS_structured
Given an array of integers as strings and numbers, return the sum of the array values as if all were numbers. Return your answer as a number.
def sum_mix(arr): sum = 0 for i in range(len(arr)): if isinstance(arr[i], str): sum += int(arr[i]) else: sum += arr[i] return sum
def sum_mix(arr): sum = 0 for i in range(len(arr)): if isinstance(arr[i], str): sum += int(arr[i]) else: sum += arr[i] return sum
train
APPS_structured
Indraneel's student has given him data from two sets of experiments that the student has performed. Indraneel wants to establish a correlation between the two sets of data. Each data set is a sequence of $N$ numbers. The two data sets do not match number for number, but Indraneel believes that this is because data has ...
# cook your dish here ans = [] mxlen = 0 def lcs(a,b,d,mxlen): L = [0]*(n+1) for i in range(n+1): L[i] = [0]*(n+1) #print("#",L,a,b) for i in range(1,n+1): for j in range(1,n+1): if a[i-1] == b[j-1]: L[i][j] = L[i-1][j-1] + 1 else: ...
# cook your dish here ans = [] mxlen = 0 def lcs(a,b,d,mxlen): L = [0]*(n+1) for i in range(n+1): L[i] = [0]*(n+1) #print("#",L,a,b) for i in range(1,n+1): for j in range(1,n+1): if a[i-1] == b[j-1]: L[i][j] = L[i-1][j-1] + 1 else: ...
train
APPS_structured
Everyone knows passphrases. One can choose passphrases from poems, songs, movies names and so on but frequently they can be guessed due to common cultural references. You can get your passphrases stronger by different means. One is the following: choose a text in capital letters including or not digits and non alphabe...
from string import ascii_uppercase as letters, digits def play_pass(s, n): return "".join(c.lower() if i & 1 else c for i, c in enumerate(s.upper().translate( str.maketrans(letters + digits, letters[n:] + letters[:n] + digits[::-1]) )))[::-1]
from string import ascii_uppercase as letters, digits def play_pass(s, n): return "".join(c.lower() if i & 1 else c for i, c in enumerate(s.upper().translate( str.maketrans(letters + digits, letters[n:] + letters[:n] + digits[::-1]) )))[::-1]
train
APPS_structured
# Write this function ![](http://i.imgur.com/mlbRlEm.png) `for i from 1 to n`, do `i % m` and return the `sum` f(n=10, m=5) // returns 20 (1+2+3+4+0 + 1+2+3+4+0) *You'll need to get a little clever with performance, since n can be a very large number*
def f(n, m): times = n // m extra = n % m sum_mini_series = (m - 1) * (m - 1 + 1) // 2 sum_extra = (extra) * (extra + 1) // 2 return sum_mini_series * times + sum_extra
def f(n, m): times = n // m extra = n % m sum_mini_series = (m - 1) * (m - 1 + 1) // 2 sum_extra = (extra) * (extra + 1) // 2 return sum_mini_series * times + sum_extra
train
APPS_structured
Given a square matrix of size N×N, calculate the absolute difference between the sums of its diagonals. -----Input----- The first line contains a single integer N. The next N lines denote the matrix's rows, with each line containing N space-separated integers describing the columns. -----Output----- Print the absolute...
def diagonal_difference(matrix): l = sum(matrix[i][i] for i in range(N)) r = sum(matrix[i][N-i-1] for i in range(N)) return abs(l - r) matrix = [] N = eval(input()) for _ in range(N): matrix.append(list(map(int, input().split()))) print(diagonal_difference(matrix))
def diagonal_difference(matrix): l = sum(matrix[i][i] for i in range(N)) r = sum(matrix[i][N-i-1] for i in range(N)) return abs(l - r) matrix = [] N = eval(input()) for _ in range(N): matrix.append(list(map(int, input().split()))) print(diagonal_difference(matrix))
train
APPS_structured
In this kata, you will make a function that converts between `camelCase`, `snake_case`, and `kebab-case`. You must write a function that changes to a given case. It must be able to handle all three case types: ```python py> change_case("snakeCase", "snake") "snake_case" py> change_case("some-lisp-name", "camel") "someL...
def change_case(identifier, targetCase): # kebab make dashes after all capital, snake underscore after capital # camel makes kebab to caps #account for if isBad(identifier): return None if targetCase == 'snake': return snake(identifier) elif targetCase == 'camel': return camel(ident...
def change_case(identifier, targetCase): # kebab make dashes after all capital, snake underscore after capital # camel makes kebab to caps #account for if isBad(identifier): return None if targetCase == 'snake': return snake(identifier) elif targetCase == 'camel': return camel(ident...
train
APPS_structured
You're about to go on a trip around the world! On this trip you're bringing your trusted backpack, that anything fits into. The bad news is that the airline has informed you, that your luggage cannot exceed a certain amount of weight. To make sure you're bringing your most valuable items on this journey you've decided ...
def pack_bagpack(scores, weights, capacity): dp=[[0,[]] for i in range(capacity+1)] for j in range(1,len(scores)+1): r = [[0,[]] for i in range(capacity+1)] for i in range(1,capacity+1): c,p = weights[j-1], scores[j-1] if c<=i and p+dp[i-c][0]>dp[i][0]: r[i]=[p+dp[i-c][0]...
def pack_bagpack(scores, weights, capacity): dp=[[0,[]] for i in range(capacity+1)] for j in range(1,len(scores)+1): r = [[0,[]] for i in range(capacity+1)] for i in range(1,capacity+1): c,p = weights[j-1], scores[j-1] if c<=i and p+dp[i-c][0]>dp[i][0]: r[i]=[p+dp[i-c][0]...
train
APPS_structured
Complete the method which returns the number which is most frequent in the given input array. If there is a tie for most frequent number, return the largest number among them. Note: no empty arrays will be given. ## Examples ``` [12, 10, 8, 12, 7, 6, 4, 10, 12] --> 12 [12, 10, 8, 12, 7, 6, 4, 10, 12, 10] ...
from collections import Counter def highest_rank(arr): return max(Counter(arr).items(), key=lambda x: [x[1], x[0]])[0]
from collections import Counter def highest_rank(arr): return max(Counter(arr).items(), key=lambda x: [x[1], x[0]])[0]
train
APPS_structured
=====Function Descriptions===== HTML Hypertext Markup Language is a standard markup language used for creating World Wide Web pages. Parsing Parsing is the process of syntactic analysis of a string of symbols. It involves resolving a string into its component parts and describing their syntactic roles. HTMLParser An HT...
import re from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print("Start".ljust(6) + ":", tag) for at in attrs: print("-> {} > {}".format(at[0], at[1])) def handle_endtag(self, tag): print("End".ljust(6) + ":", tag) ...
import re from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print("Start".ljust(6) + ":", tag) for at in attrs: print("-> {} > {}".format(at[0], at[1])) def handle_endtag(self, tag): print("End".ljust(6) + ":", tag) ...
train
APPS_structured
Given a binary tree, find the leftmost value in the last row of the tree. Example 1: Input: 2 / \ 1 3 Output: 1 Example 2: Input: 1 / \ 2 3 / / \ 4 5 6 / 7 Output: 7 Note: You may assume the tree (i.e., the given root node) is not NULL.
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def findBottomLeftValue(self, root): """ :type root: TreeNode :rtype: int """ q = [r...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def findBottomLeftValue(self, root): """ :type root: TreeNode :rtype: int """ q = [r...
train
APPS_structured
End of preview. Expand in Data Studio

Lila: A Unified Benchmark for Mathematical Reasoning

Licensing Information

Creative Commons Attribution 4.0 International

Citation Information

Cite this dataset and the source datasets (see sources.bib).

@INPROCEEDINGS{Mishra2022Lila,
  author = {
    Swaroop Mishra 
      and Matthew Finlayson 
      and Pan Lu 
      and Leonard Tang 
      and Sean Welleck 
      and Chitta Baral 
      and Tanmay Rajpurohit 
      and Oyvind Tafjord 
      and Ashish Sabharwal 
      and Peter Clark 
      and Ashwin Kalyan},
  title = {Lila: A Unified Benchmark for Mathematical Reasoning},
  booktitle = {Proceedings of the 2022 Conference on Empirical Methods in Natural Language Processing (EMNLP)},
  year = {2022}
}
Downloads last month
352

Models trained or fine-tuned on allenai/lila