problem_id
int64
174
4.99k
question
stringlengths
170
5.3k
solutions
stringlengths
0
333k
input_output
stringlengths
45
25.4k
difficulty
stringclasses
3 values
url
stringlengths
39
57
starter_code
stringlengths
0
77
174
Suppose we abstract our file system by a string in the following manner: The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents: dir subdir1 subdir2 file.ext The directory dir contains an empty sub-directory subdir1 and a sub-directory subdir2 containing a file file.ext. The string "dir\n\...
["class Solution:\n def lengthLongestPath(self, input):\n \"\"\"\n :type input: str\n :rtype: int\n \"\"\"\n dict={0:0}\n maxlen=0\n line=input.split(\"\\n\")\n for i in line:\n name=i.lstrip('\\t')\n print(name)\n p...
{"fn_name": "lengthLongestPath", "inputs": [["\"dir\\n\\tsubdir1\\n\\tsubdir2\\n\\t\\tfile.ext\""]], "outputs": [41]}
interview
https://leetcode.com/problems/longest-absolute-file-path/
class Solution: def lengthLongestPath(self, input: str) -> int:
752
Many internet protocols these days include the option of associating a media type with the content being sent. The type is usually inferred from the file extension. You are to write a program that facilitates the lookup of media types for a number of files. You will be given a table of media type associations that asso...
["# cook your dish here\nn,m=list(map(int,input().split()))\na={}\nfor i in range(n):\n x,y=input().split()\n a[x]=y\nfor i in range(m):\n c=input().strip()\n if '.' not in c:\n print(\"unknown\")\n else:\n h=c.split('.')[-1]\n if h in a:\n print(a[h])\n else:\n print('unknown')\n \n \n", "# cook your dish her...
{"inputs": [["5 6", "html text/html", "htm text/html", "png image/png", "svg image/svg+xml", "txt text/plain", "index.html", "this.file.has.lots.of.dots.txt", "nodotsatall", "virus.exe", "dont.let.the.png.fool.you", "case.matters.TXT"]], "outputs": [["text/html", "text/plain", "unknown", "unknown", "unknown", "unknown"...
interview
https://www.codechef.com/problems/MIME2
1,649
Automatons, or Finite State Machines (FSM), are extremely useful to programmers when it comes to software design. You will be given a simplistic version of an FSM to code for a basic TCP session. The outcome of this exercise will be to return the correct state of the TCP FSM based on the array of events given. ------...
["STATE_TO_COMMANDS = {\n 'CLOSED': {\n 'APP_PASSIVE_OPEN': 'LISTEN',\n 'APP_ACTIVE_OPEN': 'SYN_SENT'\n },\n 'LISTEN': {\n 'RCV_SYN': 'SYN_RCVD',\n 'APP_SEND': 'SYN_SENT',\n 'APP_CLOSE': 'CLOSED'\n },\n 'SYN_RCVD': {\n 'APP_CLOSE': 'FIN_WAIT_1',\n 'RCV_ACK': 'ESTABLISHED'\n },\n 'SYN_SENT': ...
{"fn_name": "traverse_TCP_states", "inputs": [[["APP_PASSIVE_OPEN", "RCV_SYN", "RCV_ACK", "APP_CLOSE"]], [["APP_PASSIVE_OPEN", "RCV_SYN", "RCV_ACK"]], [["APP_PASSIVE_OPEN", "RCV_SYN"]], [["APP_PASSIVE_OPEN"]], [["APP_ACTIVE_OPEN", "APP_CLOSE"]], [["APP_ACTIVE_OPEN", "RCV_SYN", "APP_CLOSE", "RCV_FIN", "RCV_ACK"]], [["AP...
interview
https://www.codewars.com/kata/54acc128329e634e9a000362
def traverse_TCP_states(events):
1,655
```if:java ___Note for Java users:___ Due to type checking in Java, inputs and outputs are formated quite differently in this language. See the footnotes of the description. ``` You have the following lattice points with their corresponding coordinates and each one with an specific colour. ``` Point [x , y] ...
["from itertools import combinations\n\ndef count_col_triang(a):\n p, r = {}, {}\n for xy, col in a:\n p[col] = p.get(col, []) + [xy]\n for k in p:\n r[k] = sum(1 for c in combinations(p[k], 3) if triangle(*c))\n mx = max(r.values())\n return [len(a), len(p), sum(r.values()), sorted(k for k...
{"fn_name": "count_col_triang", "inputs": [[[[[3, -4], "blue"], [[-7, -1], "red"], [[7, -6], "yellow"], [[2, 5], "yellow"], [[1, -5], "red"], [[-1, 4], "red"], [[1, 7], "red"], [[-3, 5], "red"], [[-3, -5], "blue"], [[4, 1], "blue"]]], [[[[3, -4], "blue"], [[-7, -1], "red"], [[7, -6], "yellow"], [[2, 5], "yellow"], [[1,...
interview
https://www.codewars.com/kata/57cebf1472f98327760003cd
def count_col_triang(a):
1,664
# Task An `amazon` (also known as a queen+knight compound) is an imaginary chess piece that can move like a `queen` or a `knight` (or, equivalently, like a `rook`, `bishop`, or `knight`). The diagram below shows all squares which the amazon attacks from e4 (circles represent knight-like moves while crosses correspond ...
["from itertools import count\n\nALL_MOVES = [(1,1), (0,1), ( 1,0), (-1,0), (0,-1), (-1,1), ( 1,-1), (-1,-1)] # Natural directions of moves for king or queen (one step)\nAMA_MOVES = [(1,2), (2,1), (-1,2), (2,-1), (1,-2), (-2,1), (-1,-2), (-2,-1)] # Knight moves for amazon queen\n\n\ndef amazon_check_mate(...
{"fn_name": "amazon_check_mate", "inputs": [["a1", "g5"], ["a3", "e4"], ["f3", "f2"], ["b7", "a8"], ["f7", "d3"], ["g2", "c3"], ["f3", "c1"], ["d4", "h8"], ["h6", "a7"], ["a6", "g3"], ["e1", "b4"], ["f4", "c4"], ["c3", "e8"], ["b5", "e5"], ["c8", "g8"], ["a6", "b5"], ["b3", "e2"], ["b7", "c3"], ["b5", "b3"], ["a4", "a6...
interview
https://www.codewars.com/kata/5897f30d948beb78580000b2
def amazon_check_mate(king, amazon):
1,710
![alt text](https://2.bp.blogspot.com/-DNNiOXduuvQ/Vh-FR-qbKXI/AAAAAAAAEOA/HT0IzJ36zW4/s1600/voz.jpg) Create a class called `Warrior` which calculates and keeps track of their level and skills, and ranks them as the warrior they've proven to be. Business Rules: - A warrior starts at level 1 and can progress all the ...
["class Warrior():\n \n def __init__(self):\n self._experience = 100\n self.rs = [\"Pushover\", \"Novice\", \"Fighter\", \"Warrior\", \"Veteran\", \"Sage\", \"Elite\", \"Conqueror\", \"Champion\", \"Master\", \"Greatest\"]\n self.achievements = []\n def training(self, train):\n if(t...
{"fn_name": "__init__", "inputs": [], "outputs": []}
interview
https://www.codewars.com/kata/5941c545f5c394fef900000c
def __init__(self):
1,714
### The Problem Consider a flat board with pegs sticking out of one side. If you stretched a rubber band across the outermost pegs what is the set of pegs such that all other pegs are contained within the shape formed by the rubber band? ![alt text](https://upload.wikimedia.org/wikipedia/commons/b/bc/ConvexHull.png) ...
["def hull_method(points):\n sorted_points = sorted(points)\n return half_hull(sorted_points) + half_hull(reversed(sorted_points))\n\ndef half_hull(sorted_points):\n hull = []\n for p in sorted_points:\n while len(hull) > 1 and not is_ccw_turn(hull[-2], hull[-1], p):\n hull.pop()\n ...
{"fn_name": "hull_method", "inputs": [], "outputs": []}
interview
https://www.codewars.com/kata/5657d8bdafec0a27c800000f
def hull_method(pointlist):
1,767
### **[Mahjong Series](/collections/mahjong)** **Mahjong** is based on draw-and-discard card games that were popular in 18th and 19th century China and some are still popular today. In each deck, there are three different suits numbered `1` to `9`, which are called **Simple tiles**. To simplify the problem, we talk a...
["from collections import Counter\n\ndef solution(tiles):\n return \"\".join(\n tile for tile in \"123456789\"\n if tiles.count(tile) < 4\n and list(meld(meld(meld(meld(pair(Counter(map(int, tiles+tile))))))))\n )\n\ndef pair(c):\n yield from (c - Counter([t,t]) for t in c if c[t] ...
{"fn_name": "solution", "inputs": [], "outputs": []}
interview
https://www.codewars.com/kata/56ad7a4978b5162445000056
def solution(tiles):
1,777
# Task IONU Satellite Imaging, Inc. records and stores very large images using run length encoding. You are to write a program that reads a compressed image, finds the edges in the image, as described below, and outputs another compressed image of the detected edges. A simple edge detection algorithm sets an output...
["'''\nChallenge Fun #20: Edge Detection\nhttps://www.codewars.com/kata/58bfa40c43fadb4edb0000b5/train/python\n\nFor a rectangular image given in run-length encoding (RLE) as\ndescribed below, return a RLE of the image processed by replacing\neach pixel by the maximum absolute value of the difference between\nit and ea...
{"fn_name": "edge_detection", "inputs": [], "outputs": []}
interview
https://www.codewars.com/kata/58bfa40c43fadb4edb0000b5
def edge_detection(image):
2,858
# Task Miss X has only two combs in her possession, both of which are old and miss a tooth or two. She also has many purses of different length, in which she carries the combs. The only way they fit is horizontally and without overlapping. Given teeth' positions on both combs, find the minimum length of the purse she ...
["def combs(a, b):\n return min(mesh(a, b), mesh(b, a))\n\ndef mesh(a, b):\n for i in range(len(a)):\n for j, k in zip(a[i:], b):\n if j + k == '**': break\n else:\n return max(i + len(b), len(a))\n return len(a) + len(b) ", "def combs(comb1, comb2):\n options ...
{"fn_name": "combs", "inputs": [["*..*", "*.*"], ["*...*", "*.*"], ["*..*.*", "*.***"], ["*.*", "*.*"], ["*.**", "*.*"]], "outputs": [[5], [5], [9], [4], [5]]}
introductory
https://www.codewars.com/kata/58898b50b832f8046a0000ec
def combs(comb1, comb2):
2,921
Just another day in the world of Minecraft, Steve is working on his new project -- building a beacon pyramid in front of his house. ![Beacon pyramid](http://www.minecraft101.net/reference/images/beacon_pyramid_thb.jpg) Steve has already obtained the beacon (the glass wrapped blue thingy on the top), he just needs to ...
["def blocks_to_collect(level):\n answer = {\n 'total': sum([(i+3+i)**2 for i in range(level)]),\n 'gold': sum([(i+3+i)**2 for i in range(0,level,4)]),\n 'diamond': sum([(i+3+i)**2 for i in range(1,level,4)]),\n 'emerald': sum([(i+3+i)**2 for i in range(2,level,4)]),\n 'iron': sum([(i+3+i)**2 for i in...
{"fn_name": "blocks_to_collect", "inputs": [[1], [2], [3]], "outputs": [[{"total": 9, "gold": 9, "diamond": 0, "emerald": 0, "iron": 0}], [{"total": 34, "gold": 9, "diamond": 25, "emerald": 0, "iron": 0}], [{"total": 83, "gold": 9, "diamond": 25, "emerald": 49, "iron": 0}]]}
introductory
https://www.codewars.com/kata/5839cd780426f5d0ec00009a
def blocks_to_collect(level):
2,958
# Your Task You have a cuboid with dimensions x,y,z ∈ ℕ. A subcuboid of this cuboid has dimensions length, width, height ∈ ℕ where 1≤length≤x, 1≤width≤y, 1≤height≤z. If two subcuboids have the same length, width, and height, but they are at different positions within the cuboid, they are distinct. Find the total number...
["def subcuboids(x,y,z):\n return x*y*z*(x+1)*(y+1)*(z+1)//8", "def n(x):\n return x * (x+1) // 2\n\ndef subcuboids(x, y, z):\n return n(x) * n(y) * n(z)", "def subcuboids(x,y,z):\n return (x*(x+1)//2)*(y*(y+1)//2)*(z*(z+1)//2)", "def subcuboids(x,y,z):\n return (x + 1) * (y + 1) * (z + 1) * x * y * z //...
{"fn_name": "subcuboids", "inputs": [[1, 1, 1], [2, 2, 2], [2, 3, 3], [4, 5, 6], [3, 7, 11]], "outputs": [[1], [27], [108], [3150], [11088]]}
introductory
https://www.codewars.com/kata/5b9e29dc1d5ed219910000a7
def subcuboids(x,y,z):
2,985
## **Task** Four mirrors are placed in a way that they form a rectangle with corners at coordinates `(0, 0)`, `(max_x, 0)`, `(0, max_y)`, and `(max_x, max_y)`. A light ray enters this rectangle through a hole at the position `(0, 0)` and moves at an angle of 45 degrees relative to the axes. Each time it hits one of th...
["def reflections(n, m):\n x = y = 0\n dx = dy = 1\n while 1:\n x += dx\n y += dy\n if x == y == 0 or x == n and y == m: return 1\n if 0 in (x, y) and (x == n or y == m): return 0\n if x in (0, n): dx *= -1\n if y in (0, m): dy *= -1", "from math import gcd\n\ndef refl...
{"fn_name": "reflections", "inputs": [[10, 10], [10, 20], [12, 23], [5, 25]], "outputs": [[true], [false], [false], [true]]}
introductory
https://www.codewars.com/kata/5eaf88f92b679f001423cc66
def reflections(max_x, max_y):
3,051
The idea for this Kata came from 9gag today.[here](http://9gag.com/gag/amrb4r9) [screen]:("http://img-9gag-fun.9cache.com/photo/amrb4r9_700b.jpg") You'll have to translate a string to Pilot's alphabet (NATO phonetic alphabet) [wiki](https://en.wikipedia.org/wiki/NATO_phonetic_alphabet). Like this: **Input:** `If, ...
["import string\n\ndb = { 'A':'Alfa','B':'Bravo','C':'Charlie','D':'Delta','E':'Echo',\n 'F':'Foxtrot','G':'Golf','H':'Hotel','I':'India','J':'Juliett',\n 'K':'Kilo','L':'Lima','M':'Mike','N':'November','O':'Oscar',\n 'P':'Papa','Q':'Quebec','R':'Romeo','S':'Sierra','T':'Tango',\n 'U':'Uniform',...
{"fn_name": "to_nato", "inputs": [["If you can read"], ["Did not see that coming"]], "outputs": [["India Foxtrot Yankee Oscar Uniform Charlie Alfa November Romeo Echo Alfa Delta"], ["Delta India Delta November Oscar Tango Sierra Echo Echo Tango Hotel Alfa Tango Charlie Oscar Mike India November Golf"]]}
introductory
https://www.codewars.com/kata/586538146b56991861000293
def to_nato(words):
3,099
Based on [this kata, Connect Four.](https://www.codewars.com/kata/connect-four-1) In this kata we play a modified game of connect four. It's connect X, and there can be multiple players. Write the function ```whoIsWinner(moves,connect,size)```. ```2 <= connect <= 10``` ```2 <= size <= 52``` Each column is identifi...
["from itertools import compress\nfrom string import ascii_uppercase, ascii_lowercase\nD = {c:i for i,c in enumerate(ascii_uppercase + ascii_lowercase)}\n\ndef whoIsWinner(moves, con, sz):\n def gen(i, j):\n for x in range(1, con):\n yield ((i, j-x), (i-x, j), (i+x, j), (i-x, j-x), (i+x, j+x), (i+x...
{"fn_name": "whoIsWinner", "inputs": [[["A_R", "B_Y", "A_R"], 2, 2], [["B_R", "A_Y", "A_R", "D_Y", "B_R", "D_Y", "B_R", "D_Y", "C_R", "D_Y"], 4, 4], [["A_R", "C_Y", "C_R", "B_Y", "A_R", "C_Y", "B_R", "B_Y", "D_R", "A_Y", "D_R", "A_Y"], 2, 4], [["H_R", "A_Y", "A_R", "C_Y", "H_R", "E_Y", "G_R", "C_Y", "D_R", "F_Y", "E_R"...
introductory
https://www.codewars.com/kata/5b442a063da310049b000047
def whoIsWinner(moves, con, sz):
3,122
# Task Consider a `bishop`, a `knight` and a `rook` on an `n × m` chessboard. They are said to form a `triangle` if each piece attacks exactly one other piece and is attacked by exactly one piece. Calculate the number of ways to choose positions of the pieces to form a triangle. Note that the bishop attacks piec...
["def chess_triangle(n, m):\n return sum( 8 * (n-x+1)*(m-y+1) for dims in {(3,4), (3,3), (2,4), (2,3)} for x,y in [dims, dims[::-1]] if x <= n and y <= m )\n", "def chess_triangle(n, m):\n if n>m:\n n,m=m,n\n if m<=2 or n<2:\n return 0\n elif n==2:\n return (m*2-5)*8\n else:\n ...
{"fn_name": "chess_triangle", "inputs": [[2, 3], [1, 30], [3, 3], [2, 2], [5, 2], [40, 40]], "outputs": [[8], [0], [48], [0], [40], [92400]]}
introductory
https://www.codewars.com/kata/5897eebff3d21495a70000df
def chess_triangle(n, m):
3,163
# Task `Triangular numbers` are defined by the formula `n * (n + 1) / 2` with `n` starting from 1. They count the number of objects that can form an equilateral triangle as shown in the picture below: ![](https://i.gyazo.com/eec11cc9e17a31324338edc4eb7bb746.png) So the sequence of triangular numbers begins as follows...
["triangular_sum=lambda n: (-0.5+(1+8*n)**0.5/2.0)**0.5%1==0", "from math import sqrt\n\ndef triangular_sum(n):\n return sqrt(2 * (sqrt(8*n + 1) - 1)) % 2 == 0", "def triangular_sum(n):\n r = int((n*2)**0.5)\n return r * (r+1) / 2 == n and round(r**0.5)**2 == r", "triangular_sum = lambda n: ((((1+8*n)**0.5 - 1...
{"fn_name": "triangular_sum", "inputs": [[6], [28], [45], [105], [136], [190], [210], [5050], [300], [2080]], "outputs": [[false], [false], [true], [false], [true], [false], [false], [true], [false], [true]]}
introductory
https://www.codewars.com/kata/591404294ef3051cbe000035
def triangular_sum(n):
3,236
## MTV Cribs is back! ![](https://s-media-cache-ak0.pinimg.com/236x/1b/cf/f4/1bcff4f4621644461103576e40bde4ed.jpg) _If you haven't solved it already I recommend trying [this kata](https://www.codewars.com/kata/5834a44e44ff289b5a000075) first._ ## Task Given `n` representing the number of floors build a penthouse li...
["def my_crib(n):\n wide = 4 + 3 + 6 * (n - 1)\n door = 2 + n - 1\n roof = 3 + 2 * (n - 1)\n r = '{0}{1}{0}\\n'.format(' ' * (wide // 2 - n), '_' * (3 + 2 * (n - 1)))\n for i in range(1, roof):\n r += '{0}/{1}\\\\{0}\\n'.format(' ' * (wide // 2 - n - i), '_' * (3 + 2 * (n - 1) + 2 * (i -1)))\n ...
{"fn_name": "my_crib", "inputs": [[1], [2], [3]], "outputs": [[" ___ \n /___\\ \n/_____\\\n| _ |\n|_|_|_|"], [" _____ \n /_____\\ \n /_______\\ \n /_________\\ \n/___________\\\n| |\n| ___ |\n| | | |\n|___|___|___|"], [" _______ \n /_______\\ \n /_________\\ ...
introductory
https://www.codewars.com/kata/58360d112fb0ba255300008b
def my_crib(n):
3,239
# Task Four men, `a, b, c and d` are standing in a line, one behind another. There's a wall between the first three people (a, b and c) and the last one (d). a, b and c are lined up in order of height, so that person a can see the backs of b and c, person b can see the back of c, and c can see just the wall. ...
["def guess_hat_color(a,b,c,d):\n return 1 if b == c else 2", "guess_hat_color=lambda a,b,c,d:2-(b==c)", "guess_hat_color=lambda a,b,c,d:1+(b!=c)", "def guess_hat_color(a,b,c,d):\n if a == d:\n return 1\n else:\n return 2", "def guess_hat_color(a,b,c,d):\n return (b != c) + 1", "guess_hat_colo...
{"fn_name": "guess_hat_color", "inputs": [["white", "black", "white", "black"], ["white", "black", "black", "white"]], "outputs": [[2], [1]]}
introductory
https://www.codewars.com/kata/58c21c4ff130b7cab400009e
def guess_hat_color(a,b,c,d):
3,283
Your aged grandfather is tragically optimistic about Team GB's chances in the upcoming World Cup, and has enlisted you to help him make [Union Jack](https://en.wikipedia.org/wiki/Union_Jack) flags to decorate his house with. ## Instructions * Write a function which takes as a parameter a number which represents the d...
["from math import ceil\n\ndef union_jack(n):\n if not isinstance(n, (int, float)):\n return False\n n = max(7, ceil(n))\n h, m = divmod(n-1, 2)\n flag = [[\"X\" if len({i, n-j-1, j, h, h+m}) < 4+m else \"-\" for i in range(n)] for j in range(n)] \n return \"\\n\".join(\"\".join(row) for row in fl...
{"fn_name": "union_jack", "inputs": [[4.5], [7.1], [19.00384], [109.1], [66.4], ["pippi"], [{}]], "outputs": [["X--X--X\n-X-X-X-\n--XXX--\nXXXXXXX\n--XXX--\n-X-X-X-\nX--X--X"], ["X--XX--X\n-X-XX-X-\n--XXXX--\nXXXXXXXX\nXXXXXXXX\n--XXXX--\n-X-XX-X-\nX--XX--X"], ["X--------XX--------X\n-X-------XX-------X-\n--X------XX--...
introductory
https://www.codewars.com/kata/5620281f0eeee479cd000020
def union_jack(n):
3,297
A stick is balanced horizontally on a support. Will it topple over or stay balanced? (This is a physics problem: imagine a real wooden stick balanced horizontally on someone's finger or on a narrow table, for example). The stick is represented as a list, where each entry shows the mass in that part of the stick. The...
["from math import ceil\n\ndef will_it_balance(stick, gnd):\n gravPt = sum(v*i for i,v in enumerate(stick)) / sum(stick)\n return gnd[int(gravPt)] == gnd[ceil(gravPt)] == 1", "def will_it_balance(stick, terrain):\n com = sum(i*w for i,w in enumerate(stick))/sum(stick)\n return terrain.index(1)<=com<=max(i f...
{"fn_name": "will_it_balance", "inputs": [[[2, 3, 2], [0, 1, 0]], [[5, 1, 1], [0, 1, 0]], [[3, 3, 4], [0, 1, 0]], [[9, 7, 1, 1], [1, 1, 0, 0]], [[9, 1, 1, 7], [1, 1, 0, 0]]], "outputs": [[true], [false], [false], [true], [false]]}
introductory
https://www.codewars.com/kata/5a8328fefd57777fa3000072
def will_it_balance(stick, terrain):
3,397
# Introduction A grille cipher was a technique for encrypting a plaintext by writing it onto a sheet of paper through a pierced sheet (of paper or cardboard or similar). The earliest known description is due to the polymath Girolamo Cardano in 1550. His proposal was for a rectangular stencil allowing single letters, ...
["def grille(msg, code):\n return ''.join(msg[-1-i] for i,c in enumerate(bin(code)[::-1]) if c == '1' and i < len(msg))[::-1]", "def grille(message, code):\n binary = bin(code)[2:][-len(message):].zfill(len(message))\n return ''.join(char for char, code in zip(message, binary) if code == '1')", "def grille(m, ...
{"fn_name": "grille", "inputs": [["abcdef", 5], ["", 5], ["abcd", 1], ["0abc", 2], ["ab", 255], ["ab", 256], ["abcde", 32], ["tcddoadepwweasresd", 77098]], "outputs": [["df"], [""], ["d"], ["b"], ["ab"], [""], [""], ["codewars"]]}
introductory
https://www.codewars.com/kata/595b3f0ad26b2d817400002a
def grille(message, code):
3,425
A [Word Square](https://en.wikipedia.org/wiki/Word_square) is a set of words written out in a square grid, such that the same words can be read both horizontally and vertically. The number of words, equal to the number of letters in each word, is known as the *order* of the square. For example, this is an *order* `5` ...
["from collections import Counter\ndef word_square(ls):\n n = int(len(ls)**0.5)\n return n*n==len(ls) and sum(i%2 for i in list(Counter(ls).values())) <= n\n", "def word_square(letters):\n root = int(len(letters)**0.5)\n return len(letters)**0.5 == root and sum([ letters.count(i)%2 for i in set(letters) ]) ...
{"fn_name": "word_square", "inputs": [["SATORAREPOTENETOPERAROTAS"], ["NOTSQUARE"], ["BITICETEN"], ["CARDAREAREARDART"], ["CODEWARS"], ["AAAAACEEELLRRRTT"], ["AAACCEEEEHHHMMTT"], ["AAACCEEEEHHHMMTTXXX"], ["ABCD"], ["GHBEAEFGCIIDFHGG"], ["AAHHFDKIHHFCXZBFDERRRTXXAA"], ["AABBCCDDEEFFGGGG"], ["ABCABCABC"], ["FRACTUREOUTLI...
introductory
https://www.codewars.com/kata/578e07d590f2bb8d3300001d
def word_square(letters):
3,571
You're laying out a rad pixel art mural to paint on your living room wall in homage to [Paul Robertson](http://68.media.tumblr.com/0f55f7f3789a354cfcda7c2a64f501d1/tumblr_o7eq3biK9s1qhccbco1_500.png), your favorite pixel artist. You want your work to be perfect down to the millimeter. You haven't decided on the dimens...
["def is_divisible(wall_length, pixel_size):\n return wall_length % pixel_size == 0", "def is_divisible(wall_length, pixel_size):\n return not wall_length % pixel_size", "def is_divisible(a, b):\n return a % b == 0", "def is_divisible(wall_length, pixel_size):\n return divmod(wall_length,pixel_size)[1] == 0...
{"fn_name": "is_divisible", "inputs": [[4050, 27], [4066, 27], [10000, 20], [10005, 20]], "outputs": [[true], [false], [true], [false]]}
introductory
https://www.codewars.com/kata/58630e2ae88af44d2b0000ea
def is_divisible(wall_length, pixel_size):
3,591
In the morning all the doors in the school are closed. The school is quite big: there are **N** doors. Then pupils start coming. It might be hard to believe, but all of them want to study! Also, there are exactly **N** children studying in this school, and they come one by one. When these strange children pass by some...
["def doors(n):\n return int(n ** .5)", "def doors(n):\n doors = [False] * n\n for i in range(0, n):\n for j in range(i, n, i + 1):\n doors[j] = not doors[j]\n return doors.count(True)", "def doors(n):\n return int(n**0.5)", "def doors(n):\n from math import sqrt\n return int(sqrt...
{"fn_name": "doors", "inputs": [[5], [10], [100]], "outputs": [[2], [3], [10]]}
introductory
https://www.codewars.com/kata/57c15d314677bb2bd4000017
def doors(n):
3,605
In the drawing below we have a part of the Pascal's triangle, lines are numbered from **zero** (top). The left diagonal in pale blue with only numbers equal to 1 is diagonal **zero**, then in dark green (1, 2, 3, 4, 5, 6, 7) is diagonal 1, then in pale green (1, 3, 6, 10, 15, 21) is diagonal 2 and so on. We want to c...
["def diagonal(n, p):\n # your code\n res = 0\n for base in range(p, max(n,p) + 1):\n value = 1\n for i in range(base-p+1,base+1):\n value *= i\n for i in range(1,p+1):\n value //= i\n res += int(value)\n return res\n", "import math\n\ndef diagonal(n, p):\n ...
{"fn_name": "diagonal", "inputs": [[20, 3], [20, 4], [20, 5], [20, 15], [100, 0], [1291, 5], [1291, 56], [1291, 1234], [12910, 15], [129100, 5]], "outputs": [[5985], [20349], [54264], [20349], [101], [6385476296235036], [154789835867995789816056814507354264440830262370837552235265352527754232996260833330144856388410192...
introductory
https://www.codewars.com/kata/559b8e46fa060b2c6a0000bf
def diagonal(n, p):
3,637
# Definition (Primorial Of a Number) *Is similar to factorial of a number*, **_In primorial_**, not all the natural numbers get multiplied, **_only prime numbers are multiplied to calculate the primorial of a number_**. It's denoted with **_P_****_#_** and it is the product of the first n prime numbers. ___ # Task ...
["def num_primorial(n):\n primorial, x, n = 2, 3, n-1\n while n:\n if all(x % d for d in range(3, int(x ** .5) + 1, 2)):\n primorial *= x\n n -= 1\n x += 2\n return primorial", "def num_primorial(n):\n primNums = [\n 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ...
{"fn_name": "num_primorial", "inputs": [[3], [4], [5], [8], [9]], "outputs": [[30], [210], [2310], [9699690], [223092870]]}
introductory
https://www.codewars.com/kata/5a99a03e4a6b34bb3c000124
def num_primorial(n):
3,768
Naming multiple files can be a pain sometimes. #### Task: Your job here is to create a function that will take three parameters, `fmt`, `nbr` and `start`, and create an array of `nbr` elements formatted according to `frm` with the starting index `start`. `fmt` will have `` inserted at various locations; this is where...
["def name_file(fmt, nbr, start):\n try:\n return [fmt.replace('<index_no>', '{0}').format(i)\n for i in range(start, start + nbr)]\n except TypeError:\n return []", "def name_file(fmt, n, start):\n return [fmt.replace('<index_no>', str(i)) for i in range(start, start+n)] if n > 0 and is...
{"fn_name": "name_file", "inputs": [["IMG <index_no>", 4, 1], ["image #<index_no>.jpg", 3, 7], ["#<index_no> #<index_no>", 3, -2], ["<file> number <index_no>", 5, 0], ["<file_no> number <index_no>", 2, -1], ["file", 2, 3], ["<file_no> number <index_no>", -1, 0], ["file <index_no>", 2, 0.1], ["file <index_no>", 0.2, 0],...
introductory
https://www.codewars.com/kata/5829994cd04efd4373000468
def name_file(fmt, nbr, start):
3,776
# Task Given some points(array `A`) on the same line, determine the minimum number of line segments with length `L` needed to cover all of the given points. A point is covered if it is located inside some segment or on its bounds. # Example For `A = [1, 3, 4, 5, 8]` and `L = 3`, the output should be `2`. Check ou...
["def segment_cover(A, L):\n n=1\n s=min(A)\n for i in sorted(A):\n if s+L<i:\n s=i\n n+=1\n return n", "def segment_cover(a, l):\n a, n = set(a), 0\n while a:\n a -= set(range(min(a), min(a) + l + 1))\n n += 1\n return n\n", "def segment_cover(A, L):\n A = sorted(A)...
{"fn_name": "segment_cover", "inputs": [[[1, 3, 4, 5, 8], 3], [[-7, -2, 0, -1, -6, 7, 3, 4], 4], [[1, 5, 2, 4, 3], 1], [[1, 10, 100, 1000], 1]], "outputs": [[2], [3], [3], [4]]}
introductory
https://www.codewars.com/kata/589ac16a0cccbff11d000115
def segment_cover(A, L):
3,806
# Task In a black and white image we can use `1` instead of black pixels and `0` instead of white pixels. For compression image file we can reserve pixels by consecutive pixels who have the same color. Your task is to determine how much of black and white pixels is in each row sorted by place of those. # Exa...
["def black_and_white(height, width, compressed):\n res, left, i, color = [], 0, 0, 0\n for h in range(height):\n tot, tmp = 0, []\n if color == 1: tmp.append(0)\n while tot < width and i < len(compressed):\n if left:\n if left <= width:\n tmp.appe...
{"fn_name": "black_and_white", "inputs": [[2, 100, [40, 120, 40, 0]], [2, 100, [0, 180, 20, 0]]], "outputs": [[[[40, 60], [0, 60, 40, 0]]], [[[0, 100], [0, 80, 20, 0]]]]}
introductory
https://www.codewars.com/kata/58a6a56942fd72afdd000161
def black_and_white(height, width, compressed):
3,878
Adapted from here, with less terrible instructions and a couple tweaks. Two kangaroos are jumping on a line. They start out at different points on the line, and jump in the same direction at different speeds. Your task is to determine whether or not they'll ever land in the same spot at the same time (you'll just have...
["def kangaroo(k1, r1, k2, r2):\n if r1==r2: return k1==k2\n cross, r = divmod(k1-k2, r2-r1)\n return cross >= 0 and not r", "def kangaroo(x1, v1, x2, v2):\n if x1 > x2 and v1 > v2:\n return False\n if (v1 > v2 and (x2-x1)%(v1-v2)==0):\n return True\n else:\n return False", "def k...
{"fn_name": "kangaroo", "inputs": [[0, 3, 4, 2], [0, 9, 16, 4], [-1, 3, 0, 2], [-1571, 4240, 9023, 4234], [-7855, 4240, 9023, 4234], [43, 5, 49, 3], [9023, 4240, 1571, 4234], [129, 15, 147, 9], [129, 15, 147, 90], [0, 2, 100000, 1], [72893, 11125, 24432, 4202], [13613, 299, 65130, 73]], "outputs": [[true], [false], [tr...
introductory
https://www.codewars.com/kata/5ae7e1522c5061beb7000051
def kangaroo(kanga1, rate1, kanga2, rate2):
3,884
# RegExp Fun #1 - When I miss few days of gym ## Disclaimer The background story of this Kata is 100% fiction. Any resemblance to real people or real events is **nothing more than a coincidence** and should be regarded as such. ## Background Story You are a person who loves to go to the gym everyday with the squad...
["import re\n\ndef gym_slang(phrase):\n phrase = re.sub(r'([pP])robably', r'\\1rolly', phrase)\n phrase = re.sub(r'([iI]) am', r\"\\1'm\", phrase)\n phrase = re.sub(r'([iI])nstagram', r'\\1nsta', phrase)\n phrase = re.sub(r'([dD])o not', r\"\\1on't\", phrase)\n phrase = re.sub(r'([gG])oing to', r'\\1onna...
{"fn_name": "gym_slang", "inputs": [["When I miss few days of gym"], ["Squad probably think I am fake"], ["Whole squad probably bigger than me now"], ["No selfie to post on Instagram either"], ["Gym crush probably found someone else"], ["What if I die fat"], ["What if I do not fit in my clothes now"], ["Going to feel l...
introductory
https://www.codewars.com/kata/5720a81309e1f9b232001c5b
def gym_slang(phrase):
3,939
# Rock Paper Scissors Let's play! You have to return which player won! In case of a draw return `Draw!`. Examples: ![rockpaperscissors](http://i.imgur.com/aimOQVX.png)
["def rps(p1, p2):\n beats = {'rock': 'scissors', 'scissors': 'paper', 'paper': 'rock'}\n if beats[p1] == p2:\n return \"Player 1 won!\"\n if beats[p2] == p1:\n return \"Player 2 won!\"\n return \"Draw!\"", "def rps(p1, p2):\n hand = {'rock':0, 'paper':1, 'scissors':2}\n results = ['Draw...
{"fn_name": "rps", "inputs": [["rock", "scissors"], ["scissors", "paper"], ["paper", "rock"], ["scissors", "rock"], ["paper", "scissors"], ["rock", "paper"], ["rock", "rock"], ["scissors", "scissors"], ["paper", "paper"]], "outputs": [["Player 1 won!"], ["Player 1 won!"], ["Player 1 won!"], ["Player 2 won!"], ["Player ...
introductory
https://www.codewars.com/kata/5672a98bdbdd995fad00000f
def rps(p1, p2):
3,994
Two Joggers === Description --- Bob and Charles are meeting for their weekly jogging tour. They both start at the same spot called "Start" and they each run a different lap, which may (or may not) vary in length. Since they know each other for a long time already, they both run at the exact same speed. Illustration -...
["from fractions import gcd\n\ndef nbr_of_laps(x, y):\n return (y / gcd(x,y), x / gcd(x,y))", "from fractions import gcd\n\ndef nbr_of_laps(x, y):\n lcm = x / gcd(x, y) * y\n return lcm/x, lcm/y", "def nbr_of_laps(x, y):\n for i in range(min(x, y), 0, -1):\n if x % i == 0 and y % i == 0:\n ...
{"fn_name": "nbr_of_laps", "inputs": [[5, 3], [4, 6], [5, 5]], "outputs": [[[3, 5]], [[3, 2]], [[1, 1]]]}
introductory
https://www.codewars.com/kata/5274d9d3ebc3030802000165
def nbr_of_laps(x, y):
4,011
# How many urinals are free? In men's public toilets with urinals, there is this unwritten rule that you leave at least one urinal free between you and the next person peeing. For example if there are 3 urinals and one person is already peeing in the left one, you will choose the urinal on the right and not the one in...
["def get_free_urinals(urinals):\n return -1 if '11' in urinals else sum(((len(l)-1)//2 for l in f'0{urinals}0'.split('1')))", "def get_free_urinals(urinals):\n if '11' in urinals: return -1\n if urinals == '0': return 1\n free = 0\n i = 0\n while (i < len(urinals)):\n if i == 0 and urinals[i:i...
{"fn_name": "get_free_urinals", "inputs": [["10001"], ["1001"], ["00000"], ["0000"], ["01000"], ["00010"], ["10000"], ["1"], ["0"], ["10"], ["110"], ["1011000001"]], "outputs": [[1], [0], [3], [2], [1], [1], [2], [0], [1], [0], [-1], [-1]]}
introductory
https://www.codewars.com/kata/5e2733f0e7432a000fb5ecc4
def get_free_urinals(urinals):
4,038
# Task Given a position of a knight on the standard chessboard, find the number of different moves the knight can perform. The knight can move to a square that is two squares horizontally and one square vertically, or two squares vertically and one square horizontally away from it. The complete move therefore looks ...
["def chess_knight(cell):\n x, y = (ord(c) - ord(origin) for c, origin in zip(cell, 'a1'))\n return sum(0 <= x + dx < 8 and 0 <= y + dy < 8 for dx, dy in (\n (-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)))", "moves = {(-2, -1), (-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2), (-...
{"fn_name": "chess_knight", "inputs": [["a1"], ["c2"], ["d4"], ["g6"]], "outputs": [[2], [6], [8], [6]]}
introductory
https://www.codewars.com/kata/589433358420bf25950000b6
def chess_knight(cell):
4,042
You have the `radius` of a circle with the center in point `(0,0)`. Write a function that calculates the number of points in the circle where `(x,y)` - the cartesian coordinates of the points - are `integers`. Example: for `radius = 2` the result should be `13`. `0 <= radius <= 1000` ![](http://i.imgur.com/1SMov3s....
["def points(R):\n from math import sqrt\n point = sum(int(sqrt(R * R - x * x)) for x in range(0,R+1)) * 4 + 1\n return point", "from math import floor, sqrt\n\ndef points(n):\n # solution is \n # A000328 Number of points of norm <= n^2 in square lattice.\n # which can be calculated as \n # a...
{"fn_name": "points", "inputs": [[1], [2], [3], [5], [1000], [55], [33], [15], [42], [0], [99], [17]], "outputs": [[5], [13], [29], [81], [3141549], [9477], [3409], [709], [5525], [1], [30757], [901]]}
introductory
https://www.codewars.com/kata/5b55c49d4a317adff500015f
def points(n):
4,059
# Task `N` candles are placed in a row, some of them are initially lit. For each candle from the 1st to the Nth the following algorithm is applied: if the observed candle is lit then states of this candle and all candles before it are changed to the opposite. Which candles will remain lit after applying the algorithm ...
["def switch_lights(initial_states):\n states = list(initial_states)\n parity = 0\n for i in reversed(range(len(states))):\n parity ^= initial_states[i]\n states[i] ^= parity\n return states", "def switch_lights(a):\n n = sum(a)\n for i, x in enumerate(a):\n if n % 2:\n ...
{"fn_name": "switch_lights", "inputs": [[[1, 1, 1, 1, 1]], [[0, 0]], [[1, 0, 0, 1, 0, 1, 0, 1]], [[1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1]]], "outputs": [[[0, 1, 0, 1, 0]], [[0, 0]], [[1, 1, 1, 0, 0, 1, 1, 0]], [[1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0]]]}
introductory
https://www.codewars.com/kata/5888145122fe8620950000f0
def switch_lights(a):
4,071
# Scenario *You're saying good-bye your best friend* , **_See you next happy year_** . **_Happy Year_** *is the year with only distinct digits* , (e.g) **_2018_** ___ # Task **_Given_** a year, **_Find_** **_The next happy year_** or **_The closest year You'll see your best friend_** ![!alt](https://i.imgur....
["def next_happy_year(year):\n year += 1\n \n while len(set(str(year))) != 4:\n year += 1\n \n return year", "def next_happy_year(year):\n for n in range(year+1, 9999):\n if len(set(str(n))) == 4:\n return n", "def next_happy_year(year):\n while True:\n year+=1\n ...
{"fn_name": "next_happy_year", "inputs": [[1001], [1123], [2001], [2334], [3331], [1987], [5555], [7712], [8088], [8999]], "outputs": [[1023], [1203], [2013], [2340], [3401], [2013], [5601], [7801], [8091], [9012]]}
introductory
https://www.codewars.com/kata/5ae7e3f068e6445bc8000046
def next_happy_year(year):
4,116
*Are you a file extension master? Let's find out by checking if Bill's files are images or audio files. Please use regex if available natively for your language.* You will create 2 string methods: - **isAudio/is_audio**, matching 1 or + uppercase/lowercase letter(s) (combination possible), with the extension .mp3, .f...
["def is_audio(filename):\n name, ext = filename.split('.')\n return name.isalpha() and ext in {'mp3', 'flac', 'alac', 'aac'}\n\n\ndef is_img(filename):\n name, ext = filename.split('.')\n return name.isalpha() and ext in {'jpg', 'jpeg', 'png', 'bmp', 'gif'}", "import re\ndef is_audio(file_name):\n retur...
{"fn_name": "is_audio", "inputs": [["Nothing Else Matters.mp3"], ["NothingElseMatters.mp3"], ["DaftPunk.FLAC"], ["DaftPunk.flac"], ["AmonTobin.aac"], [" Amon Tobin.alac"], ["tobin.alac"]], "outputs": [[false], [true], [false], [true], [true], [false], [true]]}
introductory
https://www.codewars.com/kata/574bd867d277832448000adf
def is_audio(file_name):
4,136
# Task A cake is sliced with `n` straight lines. Your task is to calculate the maximum number of pieces the cake can have. # Example For `n = 0`, the output should be `1`. For `n = 1`, the output should be `2`. For `n = 2`, the output should be `4`. For `n = 3`, the output should be `7`. See the followin...
["def cake_slice(n):\n return (n ** 2 + n + 2) // 2", "def cake_slice(n):\n return 0.5*n**2+0.5*n+1", "def cake_slice(n):\n return (n**2 + n) // 2 + 1", "cake_slice = lambda n: sum(range(n + 1)) + 1", "def cake_slice(n):\n #coding and coding...\n sum = 1\n for i in range(n):\n sum += i+1\n ret...
{"fn_name": "cake_slice", "inputs": [[0], [1], [2], [3], [10]], "outputs": [[1], [2], [4], [7], [56]]}
introductory
https://www.codewars.com/kata/58c8a41bedb423240a000007
def cake_slice(n):
4,177
# Scenario *Now that the competition gets tough it will* **_Sort out the men from the boys_** . **_Men_** are the **_Even numbers_** and **_Boys_** are the **_odd_** ![!alt](https://i.imgur.com/mdX8dJP.png) ![!alt](https://i.imgur.com/mdX8dJP.png) ___ # Task **_Given_** an *array/list [] of n integers* , **_Se...
["def men_from_boys(arr):\n men = []\n boys = []\n for i in sorted(set(arr)):\n if i % 2 == 0:\n men.append(i)\n else:\n boys.append(i)\n return men + boys[::-1]", "def men_from_boys(arr):\n return sorted(set(arr), key=lambda n: (n%2, n * (-1)**(n%2)))", "def men_from_...
{"fn_name": "men_from_boys", "inputs": [[[7, 3, 14, 17]], [[2, 43, 95, 90, 37]], [[20, 33, 50, 34, 43, 46]], [[82, 91, 72, 76, 76, 100, 85]], [[2, 15, 17, 15, 2, 10, 10, 17, 1, 1]], [[-32, -39, -35, -41]], [[-64, -71, -63, -66, -65]], [[-94, -99, -100, -99, -96, -99]], [[-53, -26, -53, -27, -49, -51, -14]], [[-17, -45,...
introductory
https://www.codewars.com/kata/5af15a37de4c7f223e00012d
def men_from_boys(arr):
4,198
### What is simplifying a square root? If you have a number, like 80, for example, you would start by finding the greatest perfect square divisible by 80. In this case, that's 16. Find the square root of 16, and multiply it by 80 / 16. Answer = 4 √5. ##### The above example: ![simplify_roots_example.png](https://i....
["def simplify(n):\n for d in range(int(n ** .5), 0, -1):\n if not n % d ** 2: break\n if d*d == n: return '%d' % d\n elif d == 1: return 'sqrt %d' % n\n else: return '%d sqrt %d' % (d, n // d ** 2)\n\ndef desimplify(s):\n x, _, y = s.partition('sqrt')\n return int(x or '1') ** 2 * int(y or '1'...
{"fn_name": "simplify", "inputs": [[1], [2], [3], [8], [15], [16], [18], [20], [24], [32], [4], [7], [9], [10], [12], [13], [14], [50], [80], [200]], "outputs": [["1"], ["sqrt 2"], ["sqrt 3"], ["2 sqrt 2"], ["sqrt 15"], ["4"], ["3 sqrt 2"], ["2 sqrt 5"], ["2 sqrt 6"], ["4 sqrt 2"], ["2"], ["sqrt 7"], ["3"], ["sqrt 10"]...
introductory
https://www.codewars.com/kata/5850e85c6e997bddd300005d
def simplify(n):
4,242
# Task You're standing at the top left corner of an `n × m` grid and facing towards the `right`. Then you start walking one square at a time in the direction you are facing. If you reach the border of the grid or if the next square you are about to visit has already been visited, you turn right. You stop w...
["def direction_in_grid(n, m):\n return \"LR\"[n%2] if m >= n else \"UD\"[m%2]\n", "def direction_in_grid(n,m):\n return \"LRUD\"[n%2 if m>=n else 2+m%2]\n", "NEXT = {'R': 'D', 'D': 'L', 'L': 'U', 'U': 'R'}\n\ndef direction_in_grid(n, m, d='R'):\n while n > 1:\n n, m, d = m, n-1, NEXT[d]\n return d", "...
{"fn_name": "direction_in_grid", "inputs": [[1, 1], [2, 2], [2, 3], [2, 4], [3, 1], [3, 2], [3, 3], [3, 4], [3, 5], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [5, 4], [5, 5], [5, 6], [100, 100]], "outputs": [["R"], ["L"], ["L"], ["L"], ["D"], ["U"], ["R"], ["R"], ["R"], ["U"], ["D"], ["L"], ["L"], ["L"], ["U"], ["R"], ["R...
introductory
https://www.codewars.com/kata/58bcd7f2f6d3b11fce000025
def direction_in_grid(n,m):
4,261
# Task A robot is standing at the `(0, 0)` point of the Cartesian plane and is oriented towards the vertical (y) axis in the direction of increasing y values (in other words, he's facing up, or north). The robot executes several commands each of which is a single positive integer. When the robot is given a positive in...
["def robot_walk(a):\n i=3\n while(i<len(a) and a[i] < a[i-2]): i+=1\n return i<len(a)\n", "def robot_walk(a):\n return any(x <= y for x,y in zip(a[1:], a[3:]))", "def robot_walk(a):\n if len(set(a)) == 1:\n return True\n movings = []\n p = (0, 0) # x, y\n dir = (0, 1)\n for k in a: \n ...
{"fn_name": "robot_walk", "inputs": [[[4, 4, 3, 2, 2, 3]], [[7, 5, 4, 5, 2, 3]], [[10, 3, 10, 2, 5, 1, 2]], [[11, 8, 6, 6, 4, 3, 7, 2, 1]], [[5, 5, 5, 5]], [[34241, 23434, 2341]], [[9348, 2188, 9348]]], "outputs": [[true], [true], [false], [true], [true], [false], [false]]}
introductory
https://www.codewars.com/kata/58a64b48586e9828df000109
def robot_walk(a):
4,281
To introduce the problem think to my neighbor who drives a tanker truck. The level indicator is down and he is worried because he does not know if he will be able to make deliveries. We put the truck on a horizontal ground and measured the height of the liquid in the tank. Fortunately the tank is a perfect cylinder ...
["import math\ndef tankvol(h, d, vt):\n r = d/2.0\n if h == r: return vt/2 # is the tank half full?\n half = h>r # is it more than half full\n h = d-h if half else h # adjust h accordingly\n a = r-h # perpendicular intercept of the chord\n b = math.sqrt(r**2-...
{"fn_name": "tankvol", "inputs": [[5, 7, 3848], [2, 7, 3848], [2, 8, 5026], [4, 9, 6361], [3, 10, 7853], [3, 5, 1963], [4, 7, 3848], [0, 7, 3848], [7, 7, 3848], [2, 5, 1963], [2, 4, 1256], [4, 10, 7853], [3, 9, 6361], [2, 10, 7853], [5, 9, 6361], [5, 6, 2827], [1, 4, 1256]], "outputs": [[2940], [907], [982], [2731], [1...
introductory
https://www.codewars.com/kata/55f3da49e83ca1ddae0000ad
def tankvol(h, d, vt):
4,301
The Menger Sponge is a three-dimensional fractal, first described by Karl Menger in 1926. ![Mengers Sponge (Level 0-3)](http://i.imgur.com/V6Rb4Za.jpg) ###### _An illustration of the iterative construction of a Menger sponge_ A method of constructing a Menger Sponge can be visualized as follows: 1. Start from a cube ...
["def calc_ms(n):\n return 20 ** n", "def calc_ms(n):\n return pow(20,n)", "calc_ms = (20).__pow__", "from functools import partial\n\ncalc_ms = partial(pow, 20)", "from functools import partial\nfrom operator import pow\n\ncalc_ms = partial(pow, 20)", "def calc_ms(n):\n a = n * '0'\n return int(str(pow(2, n)) + ...
{"fn_name": "calc_ms", "inputs": [[0], [1], [2], [3], [4], [5], [6]], "outputs": [[1], [20], [400], [8000], [160000], [3200000], [64000000]]}
introductory
https://www.codewars.com/kata/59d28768a25c8c51a6000057
def calc_ms(n):
4,314
# Task In ChessLand there is a small but proud chess bishop with a recurring dream. In the dream the bishop finds itself on an `n × m` chessboard with mirrors along each edge, and it is not a bishop but a ray of light. This ray of light moves only along diagonals (the bishop can't imagine any other types of moves ...
["def chess_bishop_dream(b,p,d,k):\n yq,yr=divmod(p[0]+k*d[0],2*b[0])\n xq,xr=divmod(p[1]+k*d[1],2*b[1])\n return [min(yr, 2*b[0]-yr-1), min(xr, 2*b[1]-xr-1)]", "chess_bishop_dream=lambda b,p,d,k:[c-abs((q+k*e)%(2*c)-c+.5)-.5for c,q,e in zip(b,p,d)]", "def chess_bishop_dream(board_size, init_position, init_dir...
{"fn_name": "chess_bishop_dream", "inputs": [[[3, 7], [1, 2], [-1, 1], 13], [[1, 2], [0, 0], [1, 1], 6], [[2, 2], [1, 0], [1, 1], 12], [[1, 1], [0, 0], [1, -1], 1000000000], [[2, 3], [1, 2], [-1, -1], 41], [[17, 19], [14, 8], [1, -1], 239239], [[17, 19], [16, 18], [1, 1], 239239239]], "outputs": [[[0, 1]], [[0, 1]], [[...
introductory
https://www.codewars.com/kata/5897ea323387497f460001a0
def chess_bishop_dream(board_size, init_position, init_direction, k):
4,316
# Do you speak retsec? You and your friends want to play undercover agents. In order to exchange your *secret* messages, you've come up with the following system: you take the word, cut it in half, and place the first half behind the latter. If the word has an uneven number of characters, you leave the middle at its pr...
["def reverse_by_center(s):n=len(s)//2;return s[-n:]+s[n:-n]+s[:n]", "import re\n\ndef reverse_by_center(s):\n half = len(s) // 2\n return re.sub(\"(.{%s})(.?)(.{%s})\" % (half, half), r\"\\3\\2\\1\", s)", "def reverse_by_center(s):\n q, r = divmod(len(s), 2)\n return s[-q:] + s[q:q+r] + s[:q]", "def revers...
{"fn_name": "reverse_by_center", "inputs": [["secret"], ["agent"], ["raw"], ["onion"]], "outputs": [["retsec"], ["nteag"], ["war"], ["onion"]]}
introductory
https://www.codewars.com/kata/5516ab668915478845000780
def reverse_by_center(s):
4,336
*Shamelessly stolen from Here :)* Your server has sixteen memory banks; each memory bank can hold any number of blocks. You must write a routine to balance the blocks between the memory banks. The reallocation routine operates in cycles. In each cycle, it finds the memory bank with the most blocks (ties won by the lo...
["def mem_alloc(banks):\n seen = set()\n while tuple(banks) not in seen:\n seen.add(tuple(banks))\n number = max(banks)\n index = banks.index(number)\n banks[index] = 0\n while number:\n index = (index + 1) % 16\n banks[index] += 1\n number -= 1\...
{"fn_name": "mem_alloc", "inputs": [[[5, 1, 10, 0, 1, 7, 13, 14, 3, 12, 8, 10, 7, 12, 0, 600]], [[53, 21, 10, 0, 1, 7, 13, 14, 3, 12, 8, 10, 7, 12, 0, 60]], [[14, 21, 10, 0, 1, 7, 0, 14, 3, 12, 8, 10, 17, 12, 0, 19]], [[5, 1, 10, 0, 1, 7, 13, 14, 3, 12, 8, 10, 7, 12, 0, 6]], [[17, 17, 3, 5, 1, 10, 6, 2, 0, 12, 8, 11, 1...
introductory
https://www.codewars.com/kata/5ad927c932d79e34fb000091
def mem_alloc(banks):
4,348
Just another day in the world of Minecraft, Steve is getting ready to start his next exciting project -- building a railway system! ![Alt text](http://static.planetminecraft.com/files/resource_media/screenshot/1506/2015-02-02_0156508603066.jpg) But first, Steve needs to melt some iron ores in the furnace to get the m...
["t = ((800, \"lava\"), (120, \"blaze rod\"), (80, \"coal\"), (15, \"wood\"), (1, \"stick\"))\n\n\ndef calc_fuel(n):\n s, r = n * 11, {}\n for d, e in t:\n r[e], s = divmod(s, d)\n return r", "def calc_fuel(n):\n time = n * 11\n lava, blaze = divmod(time, 800)\n blaze, coal = divmod(blaze, 120)...
{"fn_name": "calc_fuel", "inputs": [[37], [21], [123]], "outputs": [[{"lava": 0, "blaze rod": 3, "coal": 0, "wood": 3, "stick": 2}], [{"lava": 0, "blaze rod": 1, "coal": 1, "wood": 2, "stick": 1}], [{"lava": 1, "blaze rod": 4, "coal": 0, "wood": 4, "stick": 13}]]}
introductory
https://www.codewars.com/kata/583a02740b0a9fdf5900007c
def calc_fuel(n):
4,355
## Euler's Method We want to calculate the shape of an unknown curve which starts at a given point with a given slope. This curve satisfies an ordinary differential equation (ODE): ```math \frac{dy}{dx} = f(x, y);\\ y(x_0) = y_0 ``` The starting point `$ A_0 (x_0, y_0) $` is known as well as the slope to the curve ...
["from math import floor, exp\n \ndef ex_euler(n):\n # fct to study\n F = lambda t,y : 2 - exp(-4 * t) - 2 * y\n # initial conditions\n t0 = 0; y0 = 1; # pt A0\n T = 1; \n # variables\n h = T / float(n); X = [t0]; Y = [y0]; Z = []; R = []\n # points A1 ... An\n for k in range(0, n):\n ...
{"fn_name": "ex_euler", "inputs": [[1], [10], [17], [50], [100], [200], [400], [800], [1000], [1200], [1500], [2000]], "outputs": [[0.5], [0.026314], [0.015193], [0.005073], [0.002524], [0.001259], [0.000628], [0.000314], [0.000251], [0.000209], [0.000167], [0.000125]]}
introductory
https://www.codewars.com/kata/56347fcfd086de8f11000014
def ex_euler(n):
4,390
![](http://www.grindtv.com/wp-content/uploads/2015/08/drone.jpg) The other day I saw an amazing video where a guy hacked some wifi controlled lightbulbs by flying a drone past them. Brilliant. In this kata we will recreate that stunt... sort of. You will be given two strings: `lamps` and `drone`. `lamps` represents ...
["def fly_by(lamps, drone):\n return lamps.replace('x', 'o', drone.count('=') + 1)", "def fly_by(lamps, drone):\n l = len(lamps)\n d = len(drone)\n if d >= l:\n return 'o'* l\n return ('o' * d) + ('x' * (l - d))", "def fly_by(lamps, drone):\n newlamps = []\n for x in lamps:\n newlamps...
{"fn_name": "fly_by", "inputs": [["xxxxxx", "====T"], ["xxxxxxxxx", "==T"], ["xxxxxxxxxxxxxxx", "=========T"]], "outputs": [["ooooox"], ["oooxxxxxx"], ["ooooooooooxxxxx"]]}
introductory
https://www.codewars.com/kata/58356a94f8358058f30004b5
def fly_by(lamps, drone):
4,499
# Convergents of e The square root of 2 can be written as an infinite continued fraction. ![img](http://img0.ph.126.net/x1Hyc4iHQg0Jz2EInmT3ag==/6597639313681841979.png) The infinite continued fraction can be written, √2 = [1;(2)], (2) indicates that 2 repeats ad infinitum. In a similar way, √23 = [4;(1,3,1,8)]. It ...
["e = [1, 2]\nfor n in range(1, 10 ** 4):\n for f in 1, 2 * n, 1:\n e.append(f * e[-1] + e[-2])\nconvergents_of_e = lambda n: sum(map(int, str(e[n])))", "def convergents_of_e(n):\n def b(n):\n return n // 3 * 2 if n % 3 == 0 else 1\n x, y = b(n), 1\n for k in range(n - 1, 0, -1):\n x, y...
{"fn_name": "convergents_of_e", "inputs": [[57], [125], [298], [938], [3756], [18287], [2132], [9999], [788], [8787]], "outputs": [[125], [298], [938], [3756], [18287], [108346], [9469], [55534], [3151], [48461]]}
introductory
https://www.codewars.com/kata/5a8d63930025e92f4c000086
def convergents_of_e(n):
4,595
# Task In the Land Of Chess, bishops don't really like each other. In fact, when two bishops happen to stand on the same diagonal, they immediately rush towards the opposite ends of that same diagonal. Given the initial positions (in chess notation) of two bishops, `bishop1` and `bishop2`, calculate their future pos...
["def bishop_diagonal(a, b):\n a, b = sorted([['abcdefgh'.index(f), '12345678'.index(r)] for f, r in [a, b]])\n m = int((b[1] - a[1])/(b[0] - a[0])) if abs(a[1] - b[1]) == abs(a[0] - b[0]) and abs(a[1] - b[1]) else 0\n if m:\n while all(0 < e < 7 for e in a): a = [a[0] - 1, a[1] - m]\n while all(...
{"fn_name": "bishop_diagonal", "inputs": [["d7", "f5"], ["d8", "b5"], ["a1", "h8"], ["g3", "e1"], ["b4", "e7"]], "outputs": [[["c8", "h3"]], [["b5", "d8"]], [["a1", "h8"]], [["e1", "h4"]], [["a3", "f8"]]]}
introductory
https://www.codewars.com/kata/5897e394fcc4b9c310000051
def bishop_diagonal(bishop1, bishop2):
4,821
Task: This kata requires you to write an object that receives a file path and does operations on it. NOTE FOR PYTHON USERS: You cannot use modules os.path, glob, and re The purpose of this kata is to use string parsing, so you're not supposed to import external libraries. I could only enforce this in python. Testing: ...
["class FileMaster():\n def __init__(self, filepath):\n lk = filepath.rfind('.')\n ls = filepath.rfind('/')\n self.ext = filepath[lk+1:]\n self.file = filepath[ls+1:lk]\n self.path = filepath[:ls+1]\n def extension(self):\n return self.ext\n def filename(self):\n ...
{"fn_name": "__init__", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5844e0890d3bedc5c5000e54
def __init__(self, filepath):
4,895
[XKCD 1609]( http://xkcd.com/1609/) provides us with the following fun fact: ![If anyone tries this on you, the best reply is a deadpan "Oh yeah, that's a common potato chip flavor in Canada."](http://imgs.xkcd.com/comics/food_combinations.png) ### Task: Given an array containing a list of good foods, return a strin...
["OUTPUT = 'You know what\\'s actually really good? {}'.format\n\n\ndef actually_really_good(foods):\n foods = list(set(foods))\n length = len(foods)\n if length == 0:\n return OUTPUT('Nothing!')\n return OUTPUT('{} and more {}.'.format(\n foods[0].capitalize(), foods[0 if length == 1 else 1]....
{"fn_name": "actually_really_good", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/565f448e6e0190b0a40000cc
def actually_really_good(foods):
4,899
An architect wants to construct a vaulted building supported by a family of arches Cn. fn(x) = -nx - xlog(x) is the equation of the arch Cn where `x` is a positive real number (0 < x <= 1), `log(x)` is the natural logarithm (base e), `n` a non negative integer. Let fn(0) = 0. Be An the point of Cn where the tangent t...
["weight=lambda n,w,e=__import__('math').exp(-2):(1-3*e)/(1-e)/4*(1-e**n)*w", "# i0 = 0.14849853757254047\nfrom math import e\ndef weight(n, w):\n total = 1\n for i in range(1, n + 1): \n total += e ** (-2 * i)\n return w * 0.14849853757254047 * total\n", "def weight(n, w):\n from math import e\n ...
{"fn_name": "weight", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5db19d503ec3790012690c11
def weight(n, w):
4,908
In 1978 the British Medical Journal reported on an outbreak of influenza at a British boarding school. There were `1000` students. The outbreak began with one infected student. We want to study the spread of the disease through the population of this school. The total population may be divided into three: the infecte...
["def epidemic(tm, n, s, i, b, a):\n def f(s, i, r): \n dt = tm / n\n for t in range(n):\n s, i, r = s-dt*b*s*i, i+dt*(b*s*i-a*i), r+dt*i*a\n yield i\n return int(max(f(s, i, 0)))", "def epidemic(tm, n, s0, i0, b, a):\n timing = 0\n dt = tm/n\n r0 = 0\n i_max = i0\...
{"fn_name": "epidemic", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/566543703c72200f0b0000c9
def epidemic(tm, n, s0, i0, b, a):
4,928
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):\n return [name for i, row in enumerate(arr) for name in row[::-1 if i % 2 else 1]]", "def binRota(arr):\n rota = []\n for i, row in enumerate(arr):\n if i % 2: row = reversed(row)\n rota.extend(row)\n return rota", "def binRota(arr):\n res = []\n for i in range(len(ar...
{"fn_name": "binRota", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/578fdcfc75ffd1112c0001a1
def binRota(arr):
4,949
Robinson Crusoe decides to explore his isle. On a sheet of paper he plans the following process. His hut has coordinates `origin = [0, 0]`. From that origin he walks a given distance `d` on a line that has a given angle `ang` with the x-axis. He gets to a point A. (Angles are measured with respect to the x-axis) Fro...
["from math import cos, sin, radians\n\ndef crusoe(n, d, ang, dist_mult, ang_mult):\n x, y, a = 0, 0, radians(ang)\n for i in range(n):\n x += d * cos(a)\n y += d * sin(a)\n d *= dist_mult\n a *= ang_mult\n return x, y", "from math import sin,cos,pi\ndef crusoe(n, d, ang, dis_tmult,...
{"fn_name": "crusoe", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5d95b7644a336600271f52ba
def crusoe(n, d, ang, dist_mult, ang_mult):
4,986
# 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):\n re, c = divmod(n,m) \n return m*(m-1)/2*re + (c+1)*c/2", "def f(n, m):\n # Function to return the sum of the remnainders when n is divided by m for all n from 1 to n\n # The remainders cycle from 0, 1, 2, 3,... m-1. This happens n // m times, with a final sequnce \n # up to n % m. The ...
{"fn_name": "f", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/54c2fc0552791928c9000517
def f(n, m):
3,423
Modern operating system distributions have tools to manage installed software, making it easy to keep the software up-to-date. Putting different pieces of software into ‘packages’ that can be installed separately keeps things simple and avoids duplicate effort and code. But this means that a package may depend on other...
{ "inputs": [ "14\nlibattr\nvim-X11 vim-common gtk2 libattr\nvim-common\ngtk2 libtiff atk pango glib2\nlibtiff zlib libjpeg\natk\npango xorg-x11-libs freetype glib2\nglib2\nzlib\nlibjpeg\nxorg-x11-libs grep freetype\ngrep pcre\npcre\nfreetype\n3\nemacs xorg-x11 lisp\nxorg-x11\nlisp emacs\n0\n", "4\n...
competition
https://open.kattis.com/problems/managingpackaging