problem_id
int64
80
5k
question
stringlengths
170
10.1k
solutions
stringlengths
0
675k
input_output
stringlengths
0
33.5k
difficulty
stringclasses
3 values
url
stringlengths
38
68
starter_code
stringlengths
0
315
4,491
In this Kata, you will be given two strings `a` and `b` and your task will be to return the characters that are not common in the two strings. For example: ```Haskell solve("xyab","xzca") = "ybzc" --The first string has 'yb' which is not in the second string. --The second string has 'zc' which is not in the first s...
["def solve(a,b):\n s = set(a)&set(b)\n return ''.join(c for c in a+b if c not in s)", "def solve(a,b):\n return \"\".join([c for c in a if not c in b]+[c for c in b if not c in a])", "def solve(a,b):\n unique=[]\n for i in a:\n if i not in b:\n unique.append(i)\n for i in b:\n ...
{"fn_name": "solve", "inputs": [["xyab", "xzca"], ["xyabb", "xzca"], ["abcd", "xyz"], ["xxx", "xzca"]], "outputs": [["ybzc"], ["ybbzc"], ["abcdxyz"], ["zca"]]}
introductory
https://www.codewars.com/kata/5a262cfb8f27f217f700000b
def solve(a,b):
4,493
As you probably know, Fibonacci sequence are the numbers in the following integer sequence: 1, 1, 2, 3, 5, 8, 13... Write a method that takes the index as an argument and returns last digit from fibonacci number. Example: getLastDigit(15) - 610. Your method must return 0 because the last digit of 610 is 0. Fibonacci ...
["def get_last_digit(index):\n a, b = 0, 1\n for _ in range(index):\n a, b = b, (a+b) % 10\n return a\n", "def get_last_digit(index):\n last, tmp, index = 0, 1, index % 60\n for i in range(index):\n last, tmp = tmp, (last + tmp) % 10\n return last\n", "def get_last_digit(index):\n ret...
{"fn_name": "get_last_digit", "inputs": [[193150], [300], [20001], [800], [1001], [100], [260], [1111], [1234], [99999], [10], [234], [193241], [79], [270]], "outputs": [[5], [0], [6], [5], [1], [5], [5], [9], [7], [6], [5], [2], [1], [1], [0]]}
introductory
https://www.codewars.com/kata/56b7251b81290caf76000978
def get_last_digit(index):
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,506
In your class, you have started lessons about geometric progression. Since you are also a programmer, you have decided to write a function that will print first `n` elements of the sequence with the given constant `r` and first element `a`. Result should be separated by comma and space. ### Example ```python geometr...
["def geometric_sequence_elements(a, r, n):\n return ', '.join(str(a * r ** i) for i in range(n))\n", "def geometric_sequence_elements(a, r, n):\n l = []\n for _ in range(n):\n l.append(str(a))\n a *= r\n return \", \".join(l)\n", "def geometric_sequence_elements(a, r, n):\n return \", \".j...
{"fn_name": "geometric_sequence_elements", "inputs": [[2, 3, 5], [2, 2, 10], [1, -2, 10]], "outputs": [["2, 6, 18, 54, 162"], ["2, 4, 8, 16, 32, 64, 128, 256, 512, 1024"], ["1, -2, 4, -8, 16, -32, 64, -128, 256, -512"]]}
introductory
https://www.codewars.com/kata/55caef80d691f65cb6000040
def geometric_sequence_elements(a, r, n):
4,508
A *Vampire number* is a positive integer `z` with a factorization `x * y = z` such that - `x` and `y` have the same number of digits and - the multiset of digits of `z` is equal to the multiset of digits of `x` and `y`. - Additionally, to avoid trivialities, `x` and `y` may not both end with `0`. In this case, `x` an...
["is_vampire = lambda x, y: sorted(f\"{x}{y}\") == sorted(f\"{x*y}\") and x%10 + y%10 > 0\nvampires = sorted({x*y for p in (1, 2) for x in range(10**p, 10**(p+1)) for y in range(x, 10**(p+1)) if is_vampire(x, y)})\n\ndef VampireNumber(k):\n return vampires[k-1]", "vampire_number = VampireNumber = (0, 1260, 1395, 143...
{"fn_name": "VampireNumber", "inputs": [[10], [100], [155]], "outputs": [[105210], [336960], [939658]]}
introductory
https://www.codewars.com/kata/558d5c71c68d1e86b000010f
def VampireNumber(k):
4,512
Consider the following series: `0,1,2,3,4,5,6,7,8,9,10,22,11,20,13,24...`There is nothing special between numbers `0` and `10`. Let's start with the number `10` and derive the sequence. `10` has digits `1` and `0`. The next possible number that does not have a `1` or a `0` is `22`. All other numbers between `10` and...
["masks = [0] * 10\nfor i in range(10 ** 4):\n for c in str(i):\n masks[int(c)] |= 1 << i\n\ndef find_num(n):\n seq, x = 1, 0\n for j in range(n):\n M = seq\n for m in masks:\n if x & m:\n M |= m\n x = ~M & (M+1)\n seq |= x\n return x.bit_length()...
{"fn_name": "find_num", "inputs": [[1], [5], [11], [100], [500]], "outputs": [[1], [5], [22], [103], [476]]}
introductory
https://www.codewars.com/kata/599688d0e2800dda4e0001b0
def find_num(n):
4,519
# Task **_Given_** *a number* , **_Return_** **_The Maximum number _** *could be formed from the digits of the number given* . ___ # Notes * **_Only Natural numbers_** *passed to the function , numbers Contain digits [0:9] inclusive* * **_Digit Duplications_** *could occur* , So also **_consider it when formin...
["def max_number(n):\n return int(''.join(sorted(str(n), reverse=True)))", "max_number = lambda n: int(\"\".join(sorted(str(n)))[::-1])", "def max_number(n):\n n = \"\".join(sorted(str(n), reverse=True))\n return int(n)", "max_number= lambda n : int(''.join(sorted(list(str(n)),reverse=True)))\n", "max_number=...
{"fn_name": "max_number", "inputs": [[213], [7389], [63792], [566797], [1000000]], "outputs": [[321], [9873], [97632], [977665], [1000000]]}
introductory
https://www.codewars.com/kata/5a4ea304b3bfa89a9900008e
def max_number(n):
4,522
**DESCRIPTION:** Your strict math teacher is teaching you about right triangles, and the Pythagorean Theorem --> a^2 + b^2 = c^2 whereas a and b are the legs of the right triangle and c is the hypotenuse of the right triangle. On the test however, the question asks: What are the possible integer lengths for the othe...
["def side_len(x, y):\n return [z for z in range(abs(x-y)+1,x+y) if z*z not in (abs(x*x-y*y), x*x+y*y)]", "def side_len(x, y):\n return [i for i in range(abs(x-y)+1, abs(x+y)) if i != (x*x+y*y)**0.5 and i != abs(y*y-x*x)**0.5]", "def side_len(x, y):\n return [i for i in range(y-x+1,x+y) if abs(i**2-y**2) != x*...
{"fn_name": "side_len", "inputs": [[1, 1], [3, 4], [4, 6], [5, 12], [8, 10]], "outputs": [[[1]], [[2, 3, 4, 6]], [[3, 4, 5, 6, 7, 8, 9]], [[8, 9, 10, 11, 12, 14, 15, 16]], [[3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]]]}
introductory
https://www.codewars.com/kata/5e81303e7bf0410025e01031
def side_len(x, y):
4,528
## Your task You are given a dictionary/hash/object containing some languages and your test results in the given languages. Return the list of languages where your test score is at least `60`, in descending order of the results. Note: the scores will always be unique (so no duplicate values) ## Examples ```python {...
["def my_languages(results):\n return sorted((l for l,r in results.items() if r>=60), reverse=True, key=results.get)", "# def my_languages(dict):\n# store = []\n# for key, value in dict.items():\n# if value >= 60:\n# store.append((key, value))\n# store.sort(key=lambda x: x[-1])\n# ...
{"fn_name": "my_languages", "inputs": [[{"Java": 10, "Ruby": 80, "Python": 65}], [{"Hindi": 60, "Greek": 71, "Dutch": 93}], [{"C++": 50, "ASM": 10, "Haskell": 20}]], "outputs": [[["Ruby", "Python"]], [["Dutch", "Greek", "Hindi"]], [[]]]}
introductory
https://www.codewars.com/kata/5b16490986b6d336c900007d
def my_languages(results):
4,529
Truncate the given string (first argument) if it is longer than the given maximum length (second argument). Return the truncated string with a `"..."` ending. Note that inserting the three dots to the end will add to the string length. However, if the given maximum string length num is less than or equal to 3, then t...
["def truncate_string(s,n):\n return s if len(s)<=n else s[:n if n<=3 else n-3]+'...'", "def truncate_string(s, n):\n return s if n>=len(s) else s[:n]+'...' if n<=3 else s[:n-3]+'...'", "def truncate_string(str,n):\n if len(str) <= n:\n return str\n if n <= 3:\n return str[0:n] + \"...\"\n ...
{"fn_name": "truncate_string", "inputs": [["pippi", 3], ["Peter Piper picked a peck of pickled peppers", 14], ["A-tisket a-tasket A green and yellow basket", 43], ["A-tisket a-tasket A green and yellow basket", 45], ["A-", 1], ["Chingel loves his Angel so much!!!", 27], ["I like ice-cream.Do you?", 19], ["Seems like yo...
introductory
https://www.codewars.com/kata/57af26297f75b57d1f000225
def truncate_string(str,n):
4,533
The image shows how we can obtain the Harmonic Conjugated Point of three aligned points A, B, C. - We choose any point L, that is not in the line with A, B and C. We form the triangle ABL - Then we draw a line from point C that intersects the sides of this triangle at points M and N respectively. - We draw the diago...
["def harmon_pointTrip(xA, xB, xC):\n a, b, c = list(map(float, [xA, xB, xC]))\n # Yay for algebra!\n d = ((a * c) + (b * c) - (2 * a * b)) / (2 * c - a - b)\n return round(d, 4)\n", "def harmon_pointTrip(xA, xB, xC):\n return round((xA*xC + xB*xC - 2*xA*xB) / (2*xC - xA - xB), 4)", "def harmon_pointTrip...
{"fn_name": "harmon_pointTrip", "inputs": [[2, 10, 20], [3, 9, 18], [6, 10, 11], [4, 12, 24], [5, 17, 20]], "outputs": [[7.1429], [6.75], [9.3333], [9.0], [15.0]]}
introductory
https://www.codewars.com/kata/5600e00e42bcb7b9dc00014e
def harmon_pointTrip(xA, xB, xC):
4,554
# Letterss of Natac In a game I just made up that doesn’t have anything to do with any other game that you may or may not have played, you collect resources on each turn and then use those resources to build things like roads, settlements and cities. If you would like to try other kata about this game, they can be foun...
["from collections import Counter\n\ndef play_if_enough(hand, play):\n h = Counter(hand)\n p = Counter(play)\n if p&h == p:\n h.subtract(p)\n return (True, \"\".join(h.elements()))\n return (False, hand)", "from collections import Counter\n\ndef play_if_enough(hand, play):\n hand, play = Co...
{"fn_name": "play_if_enough", "inputs": [["", "bw"]], "outputs": [[[false, ""]]]}
introductory
https://www.codewars.com/kata/59e0069781618a7950000995
def play_if_enough(hand, play):
4,557
# Scenario **_Several people_** are standing in *a row divided into two teams*. The **_first person_** goes into **_team 1_**, **_the second_** goes into **_team 2_**, **_the third_** goes into **_team 1_**, and so on. ___ # Task **_Given_** *an array of positive integers (the weights of the people)*, **_return_** ...
["def row_weights(array):\n return sum(array[::2]), sum(array[1::2])\n", "def row_weights(array):\n evens = sum(i for index, i in enumerate(array) if index%2==0)\n return (evens, sum(array)-evens)", "row_weights = lambda arr: (sum(arr[::2]), sum(arr[1::2]))", "def row_weights(array):\n a = array[::2]\n b...
{"fn_name": "row_weights", "inputs": [[[80]], [[100, 50]], [[50, 60, 70, 80]], [[13, 27, 49]], [[70, 58, 75, 34, 91]], [[29, 83, 67, 53, 19, 28, 96]], [[0]], [[100, 51, 50, 100]], [[39, 84, 74, 18, 59, 72, 35, 61]], [[0, 1, 0]]], "outputs": [[[80, 0]], [[100, 50]], [[120, 140]], [[62, 27]], [[236, 92]], [[211, 164]], [...
introductory
https://www.codewars.com/kata/5abd66a5ccfd1130b30000a9
def row_weights(array):
4,559
The [Ones' Complement](https://en.wikipedia.org/wiki/Ones%27_complement) of a binary number is the number obtained by swapping all the 0s for 1s and all the 1s for 0s. For example: ``` onesComplement(1001) = 0110 onesComplement(1001) = 0110 ``` For any given binary number,formatted as a string, return the Ones' Compl...
["def ones_complement(n):\n return n.translate(str.maketrans(\"01\",\"10\"))", "def ones_complement(binary_number):\n return binary_number.translate(str.maketrans('01', '10'))", "def ones_complement(binary_number):\n return \"\".join([ \"1\" if binary_number[x] == \"0\" else \"0\" for x in range(0, len(binary_nu...
{"fn_name": "ones_complement", "inputs": [["0"], ["1"], ["01"], ["10"], ["1101"]], "outputs": [["1"], ["0"], ["10"], ["01"], ["0010"]]}
introductory
https://www.codewars.com/kata/59b11f57f322e5da45000254
def ones_complement(binary_number):
4,568
*This is the advanced version of the [Minimum and Maximum Product of k Elements](https://www.codewars.com/kata/minimum-and-maximum-product-of-k-elements/) kata.* --- Given a list of **integers** and a positive integer `k` (> 0), find the minimum and maximum possible product of `k` elements taken from the list. If y...
["from functools import reduce\n\ndef find_min_max_product(arr, k): \n if k <= len(arr):\n arr = sorted(arr, key=abs)\n lasts = arr[-k:]\n v1 = reduce(int.__mul__, lasts)\n v0 = reduce(int.__mul__, arr[:k])\n \n first_SameOrOpp = [next((v for v in lasts ...
{"fn_name": "find_min_max_product", "inputs": [[[0, 1, 2, 3, 4], 2], [[0, -1, -2, -3, -4], 2], [[0, -1, -2, -3, -4], 3], [[-1, -2, -3, -4], 2], [[-1, -2, -3, -4], 3], [[], 2], [[-4, -10, -1], 2], [[0, 6, 3, 5, 4], 4], [[5, 4, 3, 3, 6], 2]], "outputs": [[[0, 12]], [[0, 12]], [[-24, 0]], [[2, 12]], [[-24, -6]], [null], [...
introductory
https://www.codewars.com/kata/5b05867c87566a947a00001c
def find_min_max_product(arr, k):
4,576
You are given two positive integer lists with a random number of elements (1 <= n <= 100). Create a [GCD](https://en.wikipedia.org/wiki/Greatest_common_divisor) matrix and calculate the average of all values. Return a float value rounded to 3 decimal places. ## Example ``` a = [1, 2, 3] b = [4, 5, 6] # a =...
["from fractions import gcd\nfrom itertools import product, starmap\nfrom statistics import mean\n\ndef gcd_matrix(a, b):\n return round(mean(starmap(gcd, product(a, b))), 3)", "from fractions import gcd\n\ndef gcd_matrix(a, b):\n return round(sum(gcd(x, y) for x in a for y in b) / (len(a) * len(b)), 3)\n", "from...
{"fn_name": "gcd_matrix", "inputs": [[[1, 2, 3], [4, 5, 6]], [[5, 5, 5], [10, 10, 10]], [[4, 7, 2, 10, 99, 4], [55, 32, 1, 344, 35234, 3]]], "outputs": [[1.444], [5.0], [2.0]]}
introductory
https://www.codewars.com/kata/58a30be22d5b6ca8d9000012
def gcd_matrix(a,b):
4,578
Your wizard cousin works at a Quidditch stadium and wants you to write a function that calculates the points for the Quidditch scoreboard! # Story Quidditch is a sport with two teams. The teams score goals by throwing the Quaffle through a hoop, each goal is worth **10 points**. The referee also deducts 30 points (...
["def quidditch_scoreboard(teams, actions):\n teams = {i:0 for i in teams.split(' vs ')}\n for i in actions.split(', '):\n team, action = i.split(': ')\n if 'goal' in action:\n teams[team] += 10\n elif 'foul' in action:\n teams[team] -= 30\n elif 'Snitch' in actio...
{"fn_name": "quidditch_scoreboard", "inputs": [["Appleby Arrows vs Montrose Magpies", "Montrose Magpies: Quaffle goal, Montrose Magpies: Quaffle goal, Appleby Arrows: Quaffle goal, Appleby Arrows: Quaffle goal, Montrose Magpies: Haverstacking foul, Appleby Arrows: Quaffle goal, Appleby Arrows: Quaffle goal, Appleby Arr...
introductory
https://www.codewars.com/kata/5b62f8a5b17883e037000136
def quidditch_scoreboard(teams, actions):
4,579
## Task: You have to write a function `pattern` which returns the following Pattern(See Examples) upto n number of rows. * Note:```Returning``` the pattern is not the same as ```Printing``` the pattern. ### Rules/Note: * The pattern should be created using only unit digits. * If `n < 1` then it should return "" i....
["def pattern(n):\n return \"\\n\".join(\n \"\".join(\n str((n - min(j, i)) % 10) for j in range(n)\n )\n for i in range(max(n, 0))\n )", "def pattern(n):\n return '\\n'.join(''.join(str((n - min(i, j))%10) for j in range(n)) for i in range(n))", "def pattern(n):\n return \"\...
{"fn_name": "pattern", "inputs": [[1], [2], [3], [7], [17], [27], [0], [-89]], "outputs": [["1"], ["22\n21"], ["333\n322\n321"], ["7777777\n7666666\n7655555\n7654444\n7654333\n7654322\n7654321"], ["77777777777777777\n76666666666666666\n76555555555555555\n76544444444444444\n76543333333333333\n76543222222222222\n76543211...
introductory
https://www.codewars.com/kata/55ae997d1c40a199e6000018
def pattern(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,596
Write a function that takes a number or a string and gives back the number of **permutations without repetitions** that can generated using all of its element.; more on permutations [here](https://en.wikipedia.org/wiki/Permutation). For example, starting with: ``` 1 45 115 "abc" ``` You could respectively generate: `...
["from operator import mul\nfrom math import factorial\nfrom functools import reduce\nfrom collections import Counter\n\ndef perms(inp):\n return factorial(len(str(inp))) // reduce(mul, map(factorial, Counter(str(inp)).values()), 1)", "from math import factorial\ndef perms(e):\n e = str(e)\n n = factorial(len(...
{"fn_name": "perms", "inputs": [[2], [25], [342], [1397], [76853], ["a"], ["ab"], ["abc"], [737], [66666]], "outputs": [[1], [2], [6], [24], [120], [1], [2], [6], [3], [1]]}
introductory
https://www.codewars.com/kata/571bff6082661c8a11000823
def perms(element):
4,621
--- # Story The Pied Piper has been enlisted to play his magical tune and coax all the rats out of town. But some of the rats are deaf and are going the wrong way! # Kata Task How many deaf rats are there? # Legend * ```P``` = The Pied Piper * ```O~``` = Rat going left * ```~O``` = Rat going right # Example * ...
["def count_deaf_rats(town):\n return town.replace(' ', '')[::2].count('O')", "import re\ndef count_deaf_rats(town):\n return re.findall(r\"O~|~O\",town.split(\"P\")[0]).count(\"O~\") + re.findall(r\"O~|~O\",town.split(\"P\")[1]).count(\"~O\")", "import re\n\ndef count_deaf_rats(town):\n town = re.sub(\"(~O|O~...
{"fn_name": "count_deaf_rats", "inputs": [["~O~O~O~O P"], ["P O~ O~ ~O O~"], ["~O~O~O~OP~O~OO~"], ["O~~OO~~OO~~OO~P~OO~~OO~~OO~~O"], ["~OP"], ["PO~"], ["O~P"], ["P~O"], [" P"], ["P "], [" P "], ["P"]], "outputs": [[0], [1], [2], [8], [0], [0], [1], [1], [0], [0], [0], [0]]}
introductory
https://www.codewars.com/kata/598106cb34e205e074000031
def count_deaf_rats(town):
4,624
The four bases found in DNA are adenine (A), cytosine (C), guanine (G) and thymine (T). In genetics, GC-content is the percentage of Guanine (G) and Cytosine (C) bases on a DNA molecule that are either guanine or cytosine. Given a DNA sequence (a string) return the GC-content in percent, rounded up to 2 decimal digi...
["def gc_content(seq):\n if not seq :\n return 0.0\n else:\n res = seq.count(\"C\")+seq.count(\"G\")\n return round(res*100/len(seq),2)\n", "def gc_content(seq):\n if not seq:\n return 0\n gc_cnt = total_chars = 0\n for a in seq:\n if a in 'GC':\n gc_cnt += 1...
{"fn_name": "gc_content", "inputs": [[""], ["A"], ["C"], ["CA"]], "outputs": [[0.0], [0.0], [100.0], [50.0]]}
introductory
https://www.codewars.com/kata/5747a9bbe2fab9a0c400012f
def gc_content(seq):
4,628
## Objective Given a number `n` we will define it's sXORe to be `0 XOR 1 XOR 2 ... XOR n` where `XOR` is the [bitwise XOR operator](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). Write a function that takes `n` and returns it's sXORe. ## Examples | n | sXORe n |---------|-------- | 0 | 0 ...
["def sxore(n):\n return [n, 1, n + 1, 0][n % 4]", "def sxore(n):\n return (n,1,n+1,0)[n%4]", "def sxore(n):\n res = {0: n, 1: 1, 2: n + 1, 3: 0}\n return res[n % 4]", "sxore=lambda n:{n%4==0:n,n%4==1:1,n%4==2:n+1}.get(True,0)", "sxore=lambda n:(n,1,n+1,0)[n%4]", "def sxore(n):\n return (n >> 1) & 1 ^ ( ...
{"fn_name": "sxore", "inputs": [[0], [1], [2], [50], [1000000], [1000001], [9999999999999999999999999]], "outputs": [[0], [1], [3], [51], [1000000], [1], [0]]}
introductory
https://www.codewars.com/kata/56d3e702fc231fdf72001779
def sxore(n):
4,634
# Task Pac-Man got lucky today! Due to minor performance issue all his enemies have frozen. Too bad Pac-Man is not brave enough to face them right now, so he doesn't want any enemy to see him. Given a gamefield of size `N` x `N`, Pac-Man's position(`PM`) and his enemies' positions(`enemies`), your task is to count...
["def pac_man(size, pacman, enemies):\n px, py = pacman\n mx, my, Mx, My = -1, -1, size, size\n for x, y in enemies:\n if x < px and x > mx: mx = x\n if y < py and y > my: my = y\n if x > px and x < Mx: Mx = x\n if y > py and y < My: My = y\n return (Mx - mx - 1) * (My - my - 1) ...
{"fn_name": "pac_man", "inputs": [[1, [0, 0], []], [2, [0, 0], []], [3, [0, 0], []], [3, [1, 1], []], [2, [0, 0], [[1, 1]]], [3, [2, 0], [[1, 1]]], [3, [2, 0], [[0, 2]]], [10, [4, 6], [[0, 2], [5, 2], [5, 5]]], [8, [1, 1], [[5, 4]]], [8, [1, 5], [[5, 4]]], [8, [6, 1], [[5, 4]]]], "outputs": [[0], [3], [8], [8], [0], [0...
introductory
https://www.codewars.com/kata/58ad0e0a154165a1c80000ea
def pac_man(N, PM, enemies):
4,635
# YOUR MISSION An [octahedron](https://en.wikipedia.org/wiki/Octahedron) is an 8-sided polyhedron whose faces are triangles. Create a method that outputs a 3-dimensional array of an octahedron in which the height, width, and depth are equal to the provided integer `size`, which is equal to the length from one vertex...
["def create_octahedron(size):\n if size <= 1 or size % 2 == 0:\n return []\n m = size // 2\n return [[[int(abs(x - m) + abs(y - m) + abs(z - m) <= m)\n for z in range(size)]\n for y in range(size)]\n for x in range(size)]", "def face(size, m, n):\n return [\n [abs(r-m) + ...
{"fn_name": "create_octahedron", "inputs": [[7], [0], [-7]], "outputs": [[[[[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]], [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1,...
introductory
https://www.codewars.com/kata/5bfb0d9b392c5bf79a00015a
def create_octahedron(size):
4,639
Complete the function `power_of_two`/`powerOfTwo` (or equivalent, depending on your language) that determines if a given non-negative integer is a [power of two](https://en.wikipedia.org/wiki/Power_of_two). From the corresponding Wikipedia entry: > *a power of two is a number of the form 2^(n) where **n** is an integ...
["def power_of_two(x):\n return x != 0 and ((x & (x - 1)) == 0)", "def power_of_two(num):\n return bin(num).count('1') == 1\n", "def power_of_two(x):\n return x and (not(x&(x-1)))", "def power_of_two(x):\n # your code here\n return x > 0 and (x & (x-1)) == 0", "def power_of_two(x):\n # your code here\n ret...
{"fn_name": "power_of_two", "inputs": [[0], [1], [536870912]], "outputs": [[false], [true], [true]]}
introductory
https://www.codewars.com/kata/534d0a229345375d520006a0
def power_of_two(x):
4,645
> If you've finished this kata, you can try the [more difficult version](https://www.codewars.com/kata/5b256145a454c8a6990000b5). ## Taking a walk A promenade is a way of uniquely representing a fraction by a succession of “left or right” choices. For example, the promenade `"LRLL"` represents the fraction `4/7`. ...
["def promenade(choices):\n \n def compute(): return l+r,m+s\n \n l,m, r,s = 1,0, 0,1\n for c in choices:\n if c=='L': l,m = compute()\n else: r,s = compute()\n \n return compute()", "def promenade(choices):\n l, m = (1, 0)\n r, s = (0, 1)\n for choice in choices:\n ...
{"fn_name": "promenade", "inputs": [[""], ["L"], ["R"], ["LRLL"], ["LLRLR"], ["RRRLRRR"], ["LLLLRLLLL"], ["LLLLLLLLLL"], ["RLRLRLRRLRLL"], ["LLRRLRRLRLLL"], ["LRRLLRLLRLRR"], ["LRRLRLLLLRLL"], ["LLLRRRLLLRLL"], ["RRLRRRLLRLRR"], ["RRRRLLRLLRLR"], ["LLRLRLLRLLRL"], ["LRLLRRRRLLRR"], ["RLRRLRRRRRRR"]], "outputs": [[[1, 1...
introductory
https://www.codewars.com/kata/5b254b2225c2bb99c500008d
def promenade(choices):
4,647
This kata is the second part of a series: [Neighbourhood kata collection](https://www.codewars.com/collections/5b2f4db591c746349d0000ce). If this one is to easy you can try out the harder Katas.;) ___ The neighbourhood of a cell (in a matrix) are cells that are near to it. There are two popular types: - The [Moore nei...
["def get_neighbourhood(typ, arr, coordinates):\n \n def isInside(x,y): return 0 <= x < len(arr) and 0 <= y < len(arr[0])\n \n x,y = coordinates\n if not isInside(x,y): return []\n \n neigh = ( [(dx, dy) for dx in range(-1,2) for dy in range(-1,2) if (dx,dy) != (0,0)]\n if typ == '...
{"fn_name": "get_neighbourhood", "inputs": [["moore", [[]], [0, 0]], ["von_neumann", [[]], [0, 0]], ["moore", [[], [], []], [0, 0]], ["von_neumann", [[], [], []], [0, 0]]], "outputs": [[[]], [[]], [[]], [[]]]}
introductory
https://www.codewars.com/kata/5b2e5a02a454c82fb9000048
def get_neighbourhood(n_type, mat, coordinates):
4,648
# Definition A **number** is called **_Automorphic number_** if and only if *its square ends in the same digits as the number itself*. ___ # Task **_Given_** a **number** *determine if it Automorphic or not* . ___ # Warm-up (Highly recommended) # [Playing With Numbers Series](https://www.codewars.com/collections/p...
["def automorphic(n):\n return \"Automorphic\" if str(n*n).endswith(str(n)) else \"Not!!\"", "def automorphic(n):\n return \"Automorphic\" if str(n**2).endswith(str(n)) else \"Not!!\"", "def automorphic(n):\n return ('Not!!', 'Automorphic')[str(n ** 2).endswith(str(n))]", "def automorphic(n):\n return \"Aut...
{"fn_name": "automorphic", "inputs": [[1], [3], [6], [9], [25], [53], [76], [95], [625], [225]], "outputs": [["Automorphic"], ["Not!!"], ["Automorphic"], ["Not!!"], ["Automorphic"], ["Not!!"], ["Automorphic"], ["Not!!"], ["Automorphic"], ["Not!!"]]}
introductory
https://www.codewars.com/kata/5a58d889880385c2f40000aa
def automorphic(n):
4,652
Given a number `n` we will define its scORe to be `0 | 1 | 2 | 3 | ... | n`, where `|` is the [bitwise OR operator](https://en.wikipedia.org/wiki/Bitwise_operation#OR). Write a function that takes `n` and finds its scORe. --------------------- | n | scORe n | |---------|-------- | | 0 | 0 | | 1 ...
["score=lambda n:2**n.bit_length()-1", "score=lambda n:(1<<n.bit_length())-1", "def score(n):\n # Good Luck!\n return 2**n.bit_length()-1", "def score(n):\n res = n\n while n:\n res, n = res | n, n >> 1\n return res", "def score(n):\n return 0 if n == 0 else n | int(n.bit_length() * '1', 2)", "...
{"fn_name": "score", "inputs": [[0], [1], [49], [1000000], [10000000], [1000000000000000000]], "outputs": [[0], [1], [63], [1048575], [16777215], [1152921504606846975]]}
introductory
https://www.codewars.com/kata/56cafdabc8cfcc3ad4000a2b
def score(n):
4,656
# Task Christmas is coming. In the [previous kata](https://www.codewars.com/kata/5a405ba4e1ce0e1d7800012e), we build a custom Christmas tree with the specified characters and the specified height. Now, we are interested in the center of the Christmas tree. Please imagine that we build a Christmas tree with `chars =...
["def center_of(chars):\n if not chars:\n return \"\"\n total=0\n res=[]\n for i in range(1,len(chars)*2+1): \n if i%2==1:\n res.append((i+1)//2+total)\n res[-1]=chars[(res[-1]-1)%len(chars)]\n total+=i\n res=\"\".join(res)\n for i in range(len(res)//2+...
{"fn_name": "center_of", "inputs": [[""], ["a"], ["ab"], ["abc"], ["abab"], ["abcde"], ["aaaaaaaaaaaaaa"], ["abaabaaab"], ["dbdbebedbddbedededeeddbbdeddbeddeebdeddeebbbb"], ["vttussvutvuvvtustsvsvtvu"]], "outputs": [[""], ["a"], ["a"], ["aba"], ["a"], ["aecea"], ["a"], ["aba"], ["deededebddeebeddeddeddbddeddeddebeeddbe...
introductory
https://www.codewars.com/kata/5a4076f3e1ce0ee6d4000010
def center_of(chars):
4,658
### 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/list [] of integers* , **_Find the product of the k maximal_** numbers. ___ ### Notes * **_Array/list_** size is *at leas...
["def max_product(lst, n_largest_elements):\n lst_largest = sorted(lst)[-n_largest_elements:]\n prod = 1\n for number in lst_largest:\n prod *= number\n return prod", "def max_product(lst, n):\n from functools import reduce\n return reduce(lambda x,y: x*y, sorted(lst, reverse=True)[:n])", "def ...
{"fn_name": "max_product", "inputs": [[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 5], [[4, 3, 5], 2], [[10, 8, 7, 9], 3], [[8, 6, 4, 6], 3], [[10, 2, 3, 8, 1, 10, 4], 5], [[13, 12, -27, -302, 25, 37, 133, 155, -1], 5], [[-4, -27, -15, -6, -1], 2], [[-17, -8, -102, -309], 2], [[10, 3, -27, -1], 3], [[14, 29, -28, 39, -16, -48], 4]...
introductory
https://www.codewars.com/kata/5a63948acadebff56f000018
def max_product(lst, n_largest_elements):
4,662
Consider an array that has no prime numbers, and none of its elements has any prime digit. It would start with: `[1,4,6,8,9,10,14,16,18,..]`. `12` and `15` are not in the list because `2` and `5` are primes. You will be given an integer `n` and your task will be return the number at that index in the array. For exa...
["n,forbid = 100000, set(\"2357\")\nsieve, notPrimes = [0]*(n+1), [1]\nfor i in range(2, n+1):\n if sieve[i]:\n if not (forbid & set(str(i))): notPrimes.append(i)\n else:\n for j in range(i**2, n+1, i): sieve[j] = 1\n\ndef solve(n): return notPrimes[n]", "solve=lambda n: [1,4,6,8,9,10,14,16,18,40,4...
{"fn_name": "solve", "inputs": [[10], [50], [100], [150], [200], [300], [400], [500], [1000], [2000], [3000]], "outputs": [[44], [169], [644], [896], [1060], [1668], [4084], [4681], [9110], [18118], [46166]]}
introductory
https://www.codewars.com/kata/59f8750ac374cba8f0000033
def solve(n):
4,669
Born a misinterpretation of [this kata](https://www.codewars.com/kata/simple-fun-number-334-two-beggars-and-gold/), your task here is pretty simple: given an array of values and an amount of beggars, you are supposed to return an array with the sum of what each beggar brings home, assuming they all take regular turns, ...
["def beggars(values, n):\n return [sum(values[i::n]) for i in range(n)]", "def beggars(a, n): \n return [sum(a[i::n]) for i in range(n)]", "def beggars(values, n):\n if n == 0:\n return []\n i=0\n take=[]\n for x in range(n):\n take.append(0)\n for val in values:\n take[i%n...
{"fn_name": "beggars", "inputs": [[[1, 2, 3, 4, 5], 1], [[1, 2, 3, 4, 5], 2], [[1, 2, 3, 4, 5], 3], [[1, 2, 3, 4, 5], 6], [[1, 2, 3, 4, 5], 0]], "outputs": [[[15]], [[9, 6]], [[5, 7, 3]], [[1, 2, 3, 4, 5, 0]], [[]]]}
introductory
https://www.codewars.com/kata/59590976838112bfea0000fa
def beggars(values, n):
4,670
Note: This kata is inspired by [Convert a Number to a String!](http://www.codewars.com/kata/convert-a-number-to-a-string/). Try that one too. ## Description We need a function that can transform a string into a number. What ways of achieving this do you know? Note: Don't worry, all inputs will be strings, and every ...
["def string_to_number(s):\n return int(s)", "string_to_number = int", "string_to_number = lambda n: int(n)", "string_to_number=lambda s:int(s)", "def string_to_number(s):\n # ... your code here\n s = int(s)\n return s", "def string_to_number(s):\n i = int(s)\n return i", "def string_to_number(s):\n ...
{"fn_name": "string_to_number", "inputs": [["4"]], "outputs": [[4]]}
introductory
https://www.codewars.com/kata/544675c6f971f7399a000e79
def string_to_number(s):
4,677
Given is a md5 hash of a five digits long PIN. It is given as string. Md5 is a function to hash your password: "password123" ===> "482c811da5d5b4bc6d497ffa98491e38" Why is this useful? Hash functions like md5 can create a hash from string in a short time and it is impossible to find out the password, if you only got t...
["import hashlib\ndef crack(hash):\n for i in range(100000):\n if hashlib.md5(str(i).zfill(5).encode()).hexdigest() == hash:\n return str(i).zfill(5)", "from hashlib import md5\nfrom itertools import product\n\ndef crack(hash):\n for bs in map(bytes, product(b'0123456789', repeat=5)):\n i...
{"fn_name": "crack", "inputs": [["827ccb0eea8a706c4c34a16891f84e7b"], ["86aa400b65433b608a9db30070ec60cd"]], "outputs": [["12345"], ["00078"]]}
introductory
https://www.codewars.com/kata/5efae11e2d12df00331f91a6
def crack(hash):
4,680
# Making Change Complete the method that will determine the minimum number of coins needed to make change for a given amount in American currency. Coins used will be half-dollars, quarters, dimes, nickels, and pennies, worth 50¢, 25¢, 10¢, 5¢ and 1¢, respectively. They'll be represented by the symbols `H`, `Q`, `D`, ...
["BASE = {\"H\": 50, \"Q\": 25, \"D\": 10, \"N\": 5, \"P\": 1}\n\ndef make_change(n):\n r = {}\n for x, y in BASE.items():\n if n >= y:\n r[x], n = divmod(n, y)\n return r", "def make_change(amount):\n H = 50\n Q = 25\n D = 10\n N = 5\n P = 1\n change = {}\n while amount ...
{"fn_name": "make_change", "inputs": [[0], [1], [5], [43], [91], [101], [239]], "outputs": [[{}], [{"P": 1}], [{"N": 1}], [{"Q": 1, "D": 1, "N": 1, "P": 3}], [{"H": 1, "Q": 1, "D": 1, "N": 1, "P": 1}], [{"H": 2, "P": 1}], [{"H": 4, "Q": 1, "D": 1, "P": 4}]]}
introductory
https://www.codewars.com/kata/5365bb5d5d0266cd010009be
def make_change(amount):
4,681
The alphabetized kata --------------------- Re-order the characters of a string, so that they are concatenated into a new string in "case-insensitively-alphabetical-order-of-appearance" order. Whitespace and punctuation shall simply be removed! The input is restricted to contain no numerals and only words containing ...
["def alphabetized(s):\n return \"\".join(sorted(filter(str.isalpha, s),key=str.lower))\n", "import re\n\ndef alphabetized(s):\n return ''.join(sorted(re.sub(r'[^A-Za-z]','',s), key=str.lower))", "alphabetized = lambda s: \"\".join(sorted(filter(str.isalpha, s), key=str.lower))", "def xx_key(a):\n if a.islower...
{"fn_name": "alphabetized", "inputs": [[""], [" "], [" a"], ["a "], [" a "], ["A b B a"], [" a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"], ["!@$%^&*()_+=-`,"], ["The Holy Bible"], ["CodeWars can't Load Today"]], "outputs": [[""], [""], ["a"], ["a"], ["a"], ["...
introductory
https://www.codewars.com/kata/5970df092ef474680a0000c9
def alphabetized(s):
4,683
The aim of the kata is to try to show how difficult it can be to calculate decimals of an irrational number with a certain precision. We have chosen to get a few decimals of the number "pi" using the following infinite series (Leibniz 1646–1716): PI / 4 = 1 - 1/3 + 1/5 - 1/7 + ... which gives an approximation of PI /...
["from math import pi\n\ndef iter_pi(epsilon):\n n = 1\n approx = 4\n while abs(approx - pi) > epsilon:\n n += 1\n approx += (-4, 4)[n % 2] / (n * 2 - 1.0)\n return [n, round(approx, 10)]", "from math import pi\n\ndef iter_pi(epsilon):\n pi_4 = 0\n k = 0\n while abs(pi_4 * 4 - pi) > e...
{"fn_name": "iter_pi", "inputs": [[0.1], [0.01], [0.001], [0.0001], [1e-05], [1e-06]], "outputs": [[[10, 3.0418396189]], [[100, 3.1315929036]], [[1000, 3.1405926538]], [[10000, 3.1414926536]], [[100001, 3.1416026535]], [[1000001, 3.1415936536]]]}
introductory
https://www.codewars.com/kata/550527b108b86f700000073f
def iter_pi(epsilon):
4,688
# Write Number in Expanded Form - Part 2 This is version 2 of my ['Write Number in Exanded Form' Kata](https://www.codewars.com/kata/write-number-in-expanded-form). You will be given a number and you will need to return it as a string in [Expanded Form](https://www.mathplacementreview.com/arithmetic/decimals.php#writ...
["def expanded_form(num):\n integer_part, fractional_part = str(num).split('.')\n\n result = [str(int(num) * (10 ** i)) for i, num in enumerate(integer_part[::-1]) if num != '0'][::-1]\n result += [str(num) + '/' + str(10 ** (i + 1)) for i, num in enumerate(fractional_part) if num != '0']\n\n return ' + '.j...
{"fn_name": "expanded_form", "inputs": [[1.24], [7.304], [0.04], [1.04], [7.3004], [0.004], [693.230459]], "outputs": [["1 + 2/10 + 4/100"], ["7 + 3/10 + 4/1000"], ["4/100"], ["1 + 4/100"], ["7 + 3/10 + 4/10000"], ["4/1000"], ["600 + 90 + 3 + 2/10 + 3/100 + 4/10000 + 5/100000 + 9/1000000"]]}
introductory
https://www.codewars.com/kata/58cda88814e65627c5000045
def expanded_form(num):
4,699
Imagine two rings with numbers on them. The inner ring spins clockwise (decreasing by 1 each spin) and the outer ring spins counter clockwise (increasing by 1 each spin). We start with both rings aligned on 0 at the top, and on each move we spin each ring one increment. How many moves will it take before both rings sho...
["from itertools import count\n\ndef spinning_rings(inner_max, outer_max):\n return next(i for i in count(1) if i % (outer_max + 1) == -i % (inner_max + 1))", "def spinning_rings(inner_max, outer_max):\n a,b,res = inner_max,1,1\n while a != b:\n a = (a + inner_max) % (inner_max+1)\n b = (b + 1) %...
{"fn_name": "spinning_rings", "inputs": [[2, 3], [3, 2], [1, 1], [2, 2], [3, 3]], "outputs": [[5], [2], [1], [3], [2]]}
introductory
https://www.codewars.com/kata/59afff65f1c8274f270020f5
def spinning_rings(inner_max, outer_max):
4,703
The medians of a triangle are the segments that unit the vertices with the midpoint of their opposite sides. The three medians of a triangle intersect at the same point, called the barycenter or the centroid. Given a triangle, defined by the cartesian coordinates of its vertices we need to localize its barycenter or ce...
["def bar_triang(a, b, c):\n return [round(sum(x)/3.0, 4) for x in zip(a, b, c)]", "def bar_triang(pointA, pointB, pointC): \n a = (pointA[0] + pointB[0] + pointC[0]) / 3.0\n b = (pointA[1] + pointB[1] + pointC[1]) / 3.0\n return [round(a, 4), round(b, 4)]", "def bar_triang(pointA, pointB, pointC): # points...
{"fn_name": "bar_triang", "inputs": [[[4, 6], [12, 4], [10, 10]], [[4, 2], [12, 2], [6, 10]], [[4, 8], [8, 2], [16, 6]]], "outputs": [[[8.6667, 6.6667]], [[7.3333, 4.6667]], [[9.3333, 5.3333]]]}
introductory
https://www.codewars.com/kata/5601c5f6ba804403c7000004
def bar_triang(pointA, pointB, pointC):
4,705
This is the simple version of Fastest Code series. If you need some challenges, please try the [Performance version](http://www.codewars.com/kata/5714594d2817ff681c000783) ## Task: Give you a number array ```numbers``` and a number ```c```. Find out a pair of numbers(we called them number a and number b) from t...
["def find_a_b(numbers,c):\n for i, a in enumerate(numbers, 1):\n for b in numbers[i:]:\n if a * b == c: return [a, b]", "from itertools import combinations\n\ndef find_a_b(numbers,c):\n return next(([a,b] for a,b in combinations(numbers,2) if a*b==c),None)", "def find_a_b(numbers, c):\n for ...
{"fn_name": "find_a_b", "inputs": [[[1, 2, 3], 3], [[1, 2, 3], 6], [[1, 2, 3], 7], [[1, 2, 3, 6], 6], [[1, 2, 3, 4, 5, 6], 15], [[0, 0, 2], 4], [[0, 0, 2, 2], 4], [[-3, -2, -2, -1, 0, 1, 2, 3, 4], 4], [[-3, -2, -2, -1, 0, 1, 2, 3, 4], 0], [[-3, -2, -1, 0, 1, 2, 3, 4], 4]], "outputs": [[[1, 3]], [[2, 3]], [null], [[1, 6...
introductory
https://www.codewars.com/kata/5714803d2817ffce17000a35
def find_a_b(numbers,c):
4,708
# Kata Task I have a cat and a dog. I got them at the same time as kitten/puppy. That was `humanYears` years ago. Return their respective ages now as [`humanYears`,`catYears`,`dogYears`] NOTES: * humanYears >= 1 * humanYears are whole numbers only ## Cat Years * `15` cat years for first year * `+9` cat years for ...
["def human_years_cat_years_dog_years(x):\n return [x, 24+(x-2)*4 if (x != 1) else 15, 24+(x-2)*5 if (x != 1) else 15]", "def human_years_cat_years_dog_years(human_years):\n catYears = 0\n dogYears = 0\n if human_years == 1:\n catYears += 15\n dogYears += 15\n return [human_years, catYe...
{"fn_name": "human_years_cat_years_dog_years", "inputs": [[1], [2], [10]], "outputs": [[[1, 15, 15]], [[2, 24, 24]], [[10, 56, 64]]]}
introductory
https://www.codewars.com/kata/5a6663e9fd56cb5ab800008b
def human_years_cat_years_dog_years(human_years):
4,711
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 ...
["def zeros(n):\n \"\"\"\n No factorial is going to have fewer zeros than the factorial of a smaller\n number.\n\n Each multiple of 5 adds a 0, so first we count how many multiples of 5 are\n smaller than `n` (`n // 5`).\n\n Each multiple of 25 adds two 0's, so next we add another 0 for each multiple\...
{"fn_name": "zeros", "inputs": [[0], [6], [30], [100], [1000], [100000], [1000000000]], "outputs": [[0], [1], [7], [24], [249], [24999], [249999998]]}
introductory
https://www.codewars.com/kata/52f787eb172a8b4ae1000a34
def zeros(n):
4,721
Write a function ```convert_temp(temp, from_scale, to_scale)``` converting temperature from one scale to another. Return converted temp value. Round converted temp value to an integer(!). Reading: http://en.wikipedia.org/wiki/Conversion_of_units_of_temperature ``` possible scale inputs: "C" for Celsius "F...
["TO_KELVIN = {\n 'C': (1, 273.15),\n 'F': (5.0 / 9, 459.67 * 5.0 / 9),\n 'R': (5.0 / 9, 0),\n 'De': (-2.0 / 3, 373.15),\n 'N': (100.0 / 33, 273.15),\n 'Re': (5.0 / 4, 273.15),\n 'Ro': (40.0 / 21, -7.5 * 40 / 21 + 273.15),\n}\n\ndef convert_temp(temp, from_scale, to_scale):\n if from_scale == to...
{"fn_name": "convert_temp", "inputs": [[100, "C", "F"], [-30, "De", "K"], [40, "Re", "C"], [60, "De", "F"], [373.15, "K", "N"], [666, "K", "K"], [60, "C", "F"], [60, "De", "C"], [128.25, "Ro", "C"], [-273.15, "C", "R"], [0, "K", "R"]], "outputs": [[212], [393], [50], [140], [33], [666], [140], [60], [230], [0], [0]]}
introductory
https://www.codewars.com/kata/54ce9497975ca65e1a0008c6
def convert_temp(temp, from_scale, to_scale):
4,722
# Challenge : Write a function that takes a single argument `n` that is a string representation of a simple mathematical expression and evaluates it as a floating point value. # Commands : - positive or negative decimal numbers - `+, -, *, /, ( / ).` --- Expressions use [infix notation](https://en.wikipedia.org/...
["def e(s):return f([*s,'+'])\ndef f(s,r=0,o=0,x='',c=0):\n while s and')'!=c:\n c=s.pop(0);i='+-*/)('.find(c)\n if c=='-'>x or i<0:x+=c\n elif c=='(':x=str(f(s))\n elif i>-1:a=float(x);r=[r+a,r-a,r*a,r/a][o];o=i;x=''\n return r", "def e(s,t=[],x=0,o='+',m=')*+-/'):\n if s:t+=list(s.replace(' ','')+')')\n while o!=...
{"fn_name": "e", "inputs": [["2*3*4*5+99"]], "outputs": [[219]]}
introductory
https://www.codewars.com/kata/5b05a8dd91cc5739df0000aa
def e(s):
4,731
It is 2050 and romance has long gone, relationships exist solely for practicality. MatchMyHusband is a website that matches busy working women with perfect house husbands. You have been employed by MatchMyHusband to write a function that determines who matches!! The rules are... a match occurs providing the husband's...
["def match(usefulness, months):\n return \"Match!\" if sum(usefulness) >= 0.85**months * 100 else \"No match!\"", "def match(usefulness, months):\n return 'Match!' if sum(usefulness) >= 100*0.85**months else 'No match!'", "def current(usefulness):\n return sum(usefulness)\n\ndef needed(months):\n if months...
{"fn_name": "match", "inputs": [[[15, 24, 12], 4], [[26, 23, 19], 3], [[11, 25, 36], 1], [[22, 9, 24], 5], [[8, 11, 4], 10], [[17, 31, 21], 2], [[34, 25, 36], 1], [[35, 35, 29], 0], [[35, 35, 30], 0], [[35, 35, 31], 0]], "outputs": [["No match!"], ["Match!"], ["No match!"], ["Match!"], ["Match!"], ["No match!"], ["Matc...
introductory
https://www.codewars.com/kata/5750699bcac40b3ed80001ca
def match(usefulness, months):
4,735
#### Task: Your job here is to write a function (`keepOrder` in JS/CoffeeScript, `keep_order` in Ruby/Crystal/Python, `keeporder` in Julia), which takes a sorted array `ary` and a value `val`, and returns the lowest index where you could insert `val` to maintain the sorted-ness of the array. The input array will alway...
["from bisect import bisect_left as keep_order", "from bisect import bisect_left\n\ndef keep_order(arr, val):\n return bisect_left(arr, val)", "def keep_order(ary, val):\n for i, x in enumerate(ary):\n if x >= val:\n return i\n return len(ary)", "def keep_order(arr, val):\n for i in range(...
{"fn_name": "keep_order", "inputs": [[[1, 2, 3, 4, 7], 5], [[1, 2, 3, 4, 7], 0], [[1, 1, 2, 2, 2], 2], [[1, 2, 3, 4], 5], [[1, 2, 3, 4], -1], [[1, 2, 3, 4], 2], [[1, 2, 3, 4], 0], [[1, 2, 3, 4], 1], [[1, 2, 3, 4], 3], [[], 1], [[], 0], [[1, 1, 1, 1], 2], [[1, 1, 1, 1], 1], [[1, 1, 1, 1], 0], [[1, 3, 5, 6], 0], [[1, 3, ...
introductory
https://www.codewars.com/kata/582aafca2d44a4a4560000e7
def keep_order(ary, val):
4,751
For a given two numbers your mission is to derive a function that evaluates whether two given numbers are **abundant**, **deficient** or **perfect** and whether together they are **amicable**. ### Abundant Numbers An abundant number or excessive number is a number for which the sum of its proper divisors is greater ...
["def deficiently_abundant_amicable_numbers(a,b):\n c,d = list(map(sumOfDivs,(a,b)))\n return f'{ kind(a,c)} { kind(b,d) } { \"not \"*(a!=d or b!=c or a==b) }amicable'\n\ndef kind(n,sD): return 'abundant' if sD>n else 'perfect' if sD==n else 'deficient'\ndef sumOfDivs(n): return sum(d for d in range(1,int(n/2+1...
{"fn_name": "deficiently_abundant_amicable_numbers", "inputs": [[220, 284], [220, 280], [1184, 1210], [220221, 282224], [10744, 10856], [299920, 9284], [999220, 2849], [139815, 122265], [496, 28], [8128, 8128]], "outputs": [["abundant deficient amicable"], ["abundant abundant not amicable"], ["abundant deficient amicab...
introductory
https://www.codewars.com/kata/56bc7687e8936faed5000c09
def deficiently_abundant_amicable_numbers(n1, n2):
4,752
Similar to the [previous kata](https://www.codewars.com/kata/string-subpattern-recognition-ii/), but this time you need to operate with shuffled strings to identify if they are composed repeating a subpattern Since there is no deterministic way to tell which pattern was really the original one among all the possible p...
["from collections import Counter\nfrom functools import reduce\nfrom fractions import gcd\n\ndef has_subpattern(s):\n c = Counter(s)\n m = reduce(gcd, c.values())\n return ''.join(sorted(k*(v//m) for k,v in c.items()))", "from collections import Counter\nfrom functools import reduce\nfrom math import gcd\n\n\...
{"fn_name": "has_subpattern", "inputs": [["a"], ["aaaa"], ["abcd"], ["babababababababa"], ["bbabbaaabbaaaabb"], ["123a123a123a"], ["123A123a123a"], ["12aa13a21233"], ["12aa13a21233A"], ["abcdabcaccd"]], "outputs": [["a"], ["a"], ["abcd"], ["ab"], ["ab"], ["123a"], ["111222333Aaa"], ["123a"], ["111222333Aaaa"], ["aaabbc...
introductory
https://www.codewars.com/kata/5a4a2973d8e14586c700000a
def has_subpattern(string):
4,755
Every non-negative integer N has a binary representation.  For example, 5 can be represented as "101" in binary, 11 as "1011" in binary, and so on.  Note that except for N = 0, there are no leading zeroes in any binary representation. The complement of a binary representation is the number in binary you get when changi...
["class Solution:\n def bitwiseComplement(self, N: int) -> int:\n return (1 << len(bin(N))-2) - N - 1", "class Solution:\n def bitwiseComplement(self, N: int) -> int:\n \n if N==0:\n return 1\n \n dummy_num=N\n \n n=0\n while(dummy_num):\n ...
{"fn_name": "bitwiseComplement", "inputs": [[5]], "outputs": [2]}
introductory
https://leetcode.com/problems/complement-of-base-10-integer/
class Solution: def bitwiseComplement(self, N: int) -> int:
4,756
=====Function Descriptions===== re.findall() The expression re.findall() returns all the non-overlapping matches of patterns in a string as a list of strings. Code >>> import re >>> re.findall(r'\w','http://www.hackerrank.com/') ['h', 't', 't', 'p', 'w', 'w', 'w', 'h', 'a', 'c', 'k', 'e', 'r', 'r', 'a', 'n', 'k', 'c'...
["import re\ns = input()\nresult = re.findall(r'(?<=[QWRTYPSDFGHJKLZXCVBNMqwrtypsdfghjklzxcvbnm])([AEIOUaeiou]{2,})(?=[QWRTYPSDFGHJKLZXCVBNMqwrtypsdfghjklzxcvbnm])',s)\nif result:\n for i in result:\n print(i)\nelse:\n print((-1))\n", "#!/usr/bin/env python3\n\nimport re\n\ncons = 'QWRTYPSDFGHJKLZXCVBNMqwr...
{"inputs": ["rabcdeefgyYhFjkIoomnpOeorteeeeet"], "outputs": ["ee\nIoo\nOeo\neeeee"]}
introductory
https://www.hackerrank.com/challenges/re-findall-re-finditer/problem
# Enter your code here. Read input from STDIN. Print output to STDOUT
4,760
A [binary search tree](https://en.wikipedia.org/wiki/Binary_search_tree) is a binary tree that is ordered. This means that if you were to convert the tree to an array using an in-order traversal, the array would be in sorted order. The benefit gained by this ordering is that when the tree is balanced, searching is a lo...
["class T:\n def __init__(self,value,left=None,right=None):\n self.value=value\n self.left=left\n self.right=right\n\n\ndef is_bst(node):\n\n def extract(node):\n if node is not None:\n yield from extract(node.left)\n yield node.value\n yield from extra...
{"fn_name": "__init__", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/588534713472944a9e000029
def __init__(self,value,left=None,right=None):
4,762
The business has been suffering for years under the watch of Homie the Clown. Every time there is a push to production it requires 500 hands-on deck, a massive manual process, and the fire department is on stand-by along with Fire Marshall Bill the king of manual configuration management. He is called a Fire Marshall b...
["def nkotb_vs_homie(requirements):\n return [\"{}! Homie dont play that!\".format(a[8:-5].title())\n for b in requirements for a in b] + \\\n [\"{} monitoring objections, {} automation, {} deployment pipeline, {} cloud, and {} microservices.\".\n format(*(len(x) for x in requirements...
{"fn_name": "nkotb_vs_homie", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/58b497914c5d0af407000049
def nkotb_vs_homie(requirements):
4,766
This the second part part of the kata: https://www.codewars.com/kata/the-sum-and-the-rest-of-certain-pairs-of-numbers-have-to-be-perfect-squares In this part we will have to create a faster algorithm because the tests will be more challenging. The function ```n_closestPairs_tonum()```, (Javascript: ```nClosestPairsT...
["def n_closestPairs_tonum(upper_lim, k):\n square_lim = int((2 * upper_lim) ** .5) + 1\n squares = [n*n for n in range(1, square_lim)]\n p, s = [], set(squares)\n for m in range(upper_lim - 1, 1, -1):\n for b in squares:\n if b >= m: break\n if 2*m - b in s:\n p....
{"fn_name": "n_closestPairs_tonum", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/57aaaada72292d3b8f0001b4
def n_closestPairs_tonum(num, k):
4,770
# Kata Task A bird flying high above a mountain range is able to estimate the height of the highest peak. Can you? # Example ## The birds-eye view ^^^^^^ ^^^^^^^^ ^^^^^^^ ^^^^^ ^^^^^^^^^^^ ^^^^^^ ^^^^ ## The bird-brain calculations 111111 1^^^^111 1^^^^11 1^^^1 1^^^^111111 1^^^11 1111 ...
["def peak_height(mountain):\n M = {(r, c) for r, l in enumerate(mountain) for c in range(len(l)) if l[c] == '^'}\n h = 0\n while M:\n M -= {(r, c) for r, c in M if {(r, c+1), (r, c-1), (r+1, c), (r-1, c)} - M}\n h += 1\n return h", "from scipy.ndimage.morphology import binary_erosion as erode...
{"fn_name": "peak_height", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5c09ccc9b48e912946000157
def peak_height(mountain):
4,771
Caesar Ciphers are one of the most basic forms of encryption. It consists of a message and a key, and it shifts the letters of the message for the value of the key. Read more about it here: https://en.wikipedia.org/wiki/Caesar_cipher ## Your task Your task is to create a function encryptor that takes 2 arguments -...
["from string import maketrans as mt, ascii_lowercase as lc, ascii_uppercase as uc\ndef encryptor(key, message):\n key %= 26\n return message.translate(mt(lc+uc, lc[key:]+lc[:key]+uc[key:]+uc[:key]))", "def encryptor(key, message):\n upper_alpha = list(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\")\n lower_alpha = list(\"...
{"fn_name": "encryptor", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/546937989c0b6ab3c5000183
def encryptor(key, message):
4,775
The fusc function is defined recursively as follows: 1. fusc(0) = 0 2. fusc(1) = 1 3. fusc(2 * n) = fusc(n) 4. fusc(2 * n + 1) = fusc(n) + fusc(n + 1) The 4 rules above are sufficient to determine the value of `fusc` for any non-negative input `n`. For example, let's say you want to compute `fusc...
["def fusc(n):\n assert type(n) == int and n >= 0\n \n if n < 2:\n return n\n \n if n % 2 == 0:\n return fusc(n//2)\n else:\n return fusc(n//2) + fusc(n//2 + 1)", "\ndef fusc(n):\n f = [0, 1]\n for i in range(1, n + 1):\n f.append(f[i])\n f.append(f[i] + f[i+1]) \n return f[n]",...
{"fn_name": "fusc", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/570409d3d80ec699af001bf9
def fusc(n):
4,785
#Task: Write a function `get_member_since` which accepts a username from someone at Codewars and returns an string containing the month and year separated by a space that they joined CodeWars. ###If you want/don't want your username to be in the tests, ask me in the discourse area. There can't be too many though becau...
["from urllib.request import urlopen\nfrom bs4 import BeautifulSoup as bs\ndef get_member_since(username):\n html = urlopen(f'https://www.codewars.com/users/{username}')\n soup = bs(html.read(), \"html.parser\")\n tags = soup.find_all(\"div\", {\"class\": \"stat\"})\n member_tag = [x.text for x in tags if '...
{"fn_name": "get_member_since", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/58ab2ed1acbab2eacc00010e
def get_member_since(username):
4,786
*** Nova polynomial derivative*** This kata is from a series on polynomial handling. ( [#1](http://www.codewars.com/kata/nova-polynomial-1-add-1) [#2](http://www.codewars.com/kata/570eb07e127ad107270005fe) [#3](http://www.codewars.com/kata/5714041e8807940ff3001140 ) [#4](http://www.codewars.com/kata/571a2e2df24b...
["def poly_derivative(p):\n return [i * x for i, x in enumerate(p)][1:]\n", "def poly_derivative(p):\n return [i * n for i, n in enumerate(p[1:], 1)]", "def poly_derivative(p):\n return [ n*d for d,n in enumerate(p[1:], 1)]", "def poly_derivative(p):\n return [i * p[i] for i in range(1, len(p))]", "def poly...
{"fn_name": "poly_derivative", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/571a2e2df24bdfd4e20001f5
def poly_derivative(p):
4,788
My 5th kata, and 1st in a planned series of rock climbing themed katas. In rock climbing ([bouldering](https://en.wikipedia.org/wiki/Bouldering) specifically), the V/Vermin (USA) climbing grades start at `'VB'` (the easiest grade), and then go `'V0'`, `'V0+'`, `'V1'`, `'V2'`, `'V3'`, `'V4'`, `'V5'` etc. up to `'V17'` ...
["def sort_grades(gs):\n return sorted(gs, key=grade)\n\ndef grade(v):\n if v == 'VB': return -2\n if v == 'V0': return -1\n if v == 'V0+': return 0\n return int(v[1:])", "# G is just a dict mapping string after `V` to int.\nG = {str(k):k for k in range(1, 18)}; G['B'] = -2; G['0'] = -1; G['0+'] = 0\ndef sort_g...
{"fn_name": "sort_grades", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/58a08e622e7fb654a300000e
def sort_grades(lst):
4,799
Let us define a function `f`such as: - (1) for k positive odd integer > 2 : - (2) for k positive even integer >= 2 : - (3) for k positive integer > 1 : where `|x|` is `abs(x)` and Bk the kth Bernoulli number. `f` is not defined for `0, 1, -1`. These values will not be tested. # Guidelines for Bernoulli ...
["from math import factorial,pi\nfrom fractions import Fraction\n\ndef comb(n,k):\n return factorial(n)//(factorial(n-k)*factorial(k))\n\ndef bernoulli(m):\n b=[1]\n for i in range(1,m+1):\n n=0\n for k in range(0,i):\n n+=comb(i+1,k)*b[k]\n b.append(Fraction(-n,i+1))\n retur...
{"fn_name": "comb", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5a02cf76c9fc0ee71d0000d5
def comb(n,k):
4,800
The Collatz conjecture (also known as 3n+1 conjecture) is a conjecture that applying the following algorithm to any number we will always eventually reach one: ``` [This is writen in pseudocode] if(number is even) number = number / 2 if(number is odd) number = 3*number + 1 ``` #Task Your task is to make a function `...
["def hotpo(n):\n cnt = 0\n while n != 1:\n n = 3 * n + 1 if n % 2 else n / 2\n cnt += 1\n return cnt", "def hotpo(num, count=0):\n return count if num == 1 else hotpo(num / 2 if num % 2 == 0 else num * 3 + 1 ,count + 1)", "def hotpo(n):\n def even_odd(m):\n return [3*m+1, m/2][m%2==0]...
{"fn_name": "hotpo", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/577a6e90d48e51c55e000217
def hotpo(n):
4,801
DevOps legacy roasting! Save the business from technological purgatory. Convert IT to DevOps, modernize application workloads, take it all to the Cloud……. You will receive a string of workloads represented by words….some legacy and some modern mixed in with complaints from the business….your job is to burn the legac...
["complaints = [\"slow!\", \"expensive!\", \"manual!\", \"down!\", \"hostage!\", \"security!\"]\n\nlegacy = {\n \"cobol\": 1000,\n \"nonobject\": 500,\n \"monolithic\": 500,\n \"fax\": 100,\n \"modem\": 100,\n \"thickclient\": 50,\n \"tape\": 50,\n \"floppy\": 50,\n \"oldschoolit\": 50\n}\n\n...
{"fn_name": "roast_legacy", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/58ade79f3c97367977000274
def roast_legacy(workloads):
4,802
# Task Follow the instructions in each failing test case to write logic that calculates the total price when ringing items up at a cash register. # Purpose Practice writing maintainable and extendable code. # Intent This kata is meant to emulate the real world where requirements change over time. This kata does not ...
["import re\nclass Checkout(object):\n def __init__(self, d={}):\n self.pricing,self.total,self.fruits,self.free = d,0,{},{}\n \n def scan(self, n, qty=1):\n item = get_price(n)\n for i in range(qty):\n if not self.free.get(n, 0) : self.total += item ; self.fruits[n] = self.frui...
{"fn_name": "__init__", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/57c8d7f8484cf9c1550000ff
def __init__(self, d={}):
4,803
Write a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in a tuple like so: `(index1, index2)`. For the purposes of this kata, some ...
["def two_sum(nums, t):\n for i, x in enumerate(nums):\n for j, y in enumerate(nums):\n if i != j and x + y == t:\n return [i, j]", "def two_sum(nums, target):\n d = {}\n for i, num in enumerate(nums):\n diff = target - num\n if diff in d:\n return [d[d...
{"fn_name": "two_sum", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/52c31f8e6605bcc646000082
def two_sum(numbers, target):
4,806
The [Linear Congruential Generator (LCG)](https://en.wikipedia.org/wiki/Linear_congruential_generator) is one of the oldest pseudo random number generator functions. The algorithm is as follows: ## Xn+1=(aXn + c) mod m where: * `a`/`A` is the multiplier (we'll be using `2`) * `c`/`C` is the increment (we'll be using ...
["class LCG(object):\n def __init__(self, x):\n self._seed = x\n def random(self):\n self._seed = (2 * self._seed + 3) % 10\n return self._seed / 10", "class LCG(object):\n a = 2\n c = 3\n m = 10\n \n def __init__(self, seed):\n self.seed = seed\n self.x = self.seed\n \n def g(self):\n...
{"fn_name": "__init__", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/594979a364becbc1ab00003a
def __init__(self, seed):
4,807
While developing a website, you detect that some of the members have troubles logging in. Searching through the code you find that all logins ending with a "\_" make problems. So you want to write a function that takes an array of pairs of login-names and e-mails, and outputs an array of all login-name, e-mails-pairs f...
["def search_names(logins):\n return list(filter(lambda a: a[0].endswith('_'), logins))", "def search_names(logins):\n return filter(lambda x: x[0][-1] == \"_\", logins)", "def search_names(logins):\n return [l for l in logins if l[0].endswith('_')]", "def search_names(logins):\n return list(filter(lambda l...
{"fn_name": "search_names", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/525d9b1a037b7a9da7000905
def search_names(logins):
4,810
# Idea In the world of graphs exists a structure called "spanning tree". It is unique because it's created not on its own, but based on other graphs. To make a spanning tree out of a given graph you should remove all the edges which create cycles, for example: ``` This can become this or this or ...
["from operator import itemgetter\nfrom numpy import delete\n\ndef make_spanning_tree(edges, t):\n memo, result = [], []\n for v in sorted(edges, key=itemgetter(1), reverse=(t==\"max\")):\n (x,y), w = v\n \n if x == y: continue\n \n i = next((i for i,s in enumerate(memo) if x in...
{"fn_name": "make_spanning_tree", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5ae8e14c1839f14b2c00007a
def make_spanning_tree(edges, t):
4,812
The [Floyd's triangle](https://en.wikipedia.org/wiki/Floyd%27s_triangle) is a right-angled triangular array of natural numbers listing them in order, in lines of increasing length, so a Floyds triangle of size 6 looks like: ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 ... ``` In this kata you'r...
["def nth_floyd(n):\n return ((1+8*(n-1))**0.5+1)//2", "from math import ceil\n\ndef nth_floyd(n):\n return ceil(((8*n + 1) ** 0.5 - 1) / 2)", "def nth_floyd(n):\n s=i=0\n while s<n:\n i+=1\n s+=i\n return i", "def nth_floyd(n):\n return round((n * 2)**(.5))", "from math import sqrt\n\ndef nth_floyd(n...
{"fn_name": "nth_floyd", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5b096efeaf15bef812000010
def nth_floyd(n):
4,820
Classy Extensions Classy Extensions, this kata is mainly aimed at the new JS ES6 Update introducing extends keyword. You will be preloaded with the Animal class, so you should only edit the Cat class. Task Your task is to complete the Cat class which Extends Animal and replace the speak method to return the cats name ...
["class Cat(Animal):\n def __init__(self, name):\n self.name = name\n def speak(self):\n return '{} meows.'.format(self.name)", "class Cat(Animal):\n def __init__(self, name, *args, **kwargs):\n assert isinstance(name, str)\n self.name = name\n \n def speak(self):\n ret...
{"fn_name": "__init__", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/55a14aa4817efe41c20000bc
def __init__(self, name):
4,826
``` ------------------------------------------------------------------ we are programmed just to do anything you want us to w e a r e t h e r o b o t s -----------------------------------------------------------[ d[(0)(0)]b] ``` Task..... You will receieve an array of strings su...
["import re\nfrom collections import Counter\nfrom itertools import chain\n\np = re.compile('{legs}{body}{body}0{body}{body}0{body}{body}{legs}'.format(\n legs='[a-z]',\n body=r'[[\\]|};&#/><()*]',\n))\ndef count_robots(a):\n cnt = Counter(chain.from_iterable(\n ['d' if 'mechanik' in line else 'w' if 'a...
{"fn_name": "count_robots", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/587ae98e2ab0ef32ef00004c
def count_robots(a):
4,829
__Function composition__ is a mathematical operation that mainly presents itself in lambda calculus and computability. It is explained well [here](http://www.mathsisfun.com/sets/functions-composition.html), but this is my explanation, in simple mathematical notation: ``` f3 = compose( f1 f2 ) Is equivalent to... f3...
["def compose(f,g):\n return lambda *x: f(g(*x))", "def pow(x, y):\n return x**y\n\n# assuming python 3 where print is a function\nprintPow = compose(print, pow)\n# compose would return\nlambda *x: print(pow(*x))\n# because f is bound to print and g is bound to pow.\n\nprintPow(2, 3)\n# this would call the lambda wit...
{"fn_name": "compose", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5421c6a2dda52688f6000af8
def compose(f,g):
4,830
Part 2/3 of my kata series. [Part 1](http://www.codewars.com/kata/riemann-sums-i-left-side-rule) The description changes little in this second part. Here we simply want to improve our approximation of the integral by using trapezoids instead of rectangles. The left/right side rules have a serious bias and the trapezoi...
["def riemann_trapezoidal(f, n, a, b):\n dx = (b - a) / n\n return round(dx * sum((f(a + i*dx) + f(a + (i+1)*dx)) / 2 for i in range(n)), 2)\n", "def riemann_trapezoidal(f, n, a, b):\n dx = (b - a) / n\n return round(sum(dx * (f(a + i * dx) + f(a + (i+1) * dx)) / 2 for i in range(n)), 2)", "def riemann_trapezoi...
{"fn_name": "riemann_trapezoidal", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5562b6de2f508f1adc000089
def riemann_trapezoidal(f, n, a, b):
4,831
Tired of those repetitive javascript challenges? Here's a unique hackish one that should keep you busy for a while ;) There's a mystery function which is already available for you to use. It's a simple function called `mystery`. It accepts a string as a parameter and outputs a string. The exercise depends on guessing ...
["def solved(s):\n if len(s)&1:\n s = s[:len(s)//2]+s[len(s)//2+1:]\n return ''.join(sorted(s))", "def solved(string):\n b = str((len(string)-1)/2)\n b = int(b[:-2])\n if len(string)%2==1:\n c = string[:b] + string[b+1:]\n return ''.join(sorted(c))\n return ''.join(sorted(string))...
{"fn_name": "solved", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/531963f82dde6fc8c800048a
def solved(string):
4,832
Your task is to find all the elements of an array that are non consecutive. A number is non consecutive if it is not exactly one larger than the previous element in the array. The first element gets a pass and is never considered non consecutive. ~~~if:javascript,haskell,swift Create a function named `allNonConsecuti...
["def all_non_consecutive(a):\n return [{\"i\": i, \"n\": y} for i, (x, y) in enumerate(zip(a, a[1:]), 1) if x != y - 1]", "def all_non_consecutive(arr):\n answer = []\n for i in range(len(arr)-1):\n if arr[i + 1] - arr[i] != 1:\n answer.append({'i': i + 1, 'n': arr[i + 1]})\n return answe...
{"fn_name": "all_non_consecutive", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/58f8b35fda19c0c79400020f
def all_non_consecutive(arr):
4,837
Time to build a crontab parser... https://en.wikipedia.org/wiki/Cron A crontab command is made up of 5 fields in a space separated string: ``` minute: 0-59 hour: 0-23 day of month: 1-31 month: 1-12 day of week: 0-6 (0 == Sunday) ``` Each field can be a combination of the following values: * a wildcard `*` which equ...
["RANGES = {\n 'minute': (0, 59),\n 'hour': (0, 23),\n 'day of month': (1, 31),\n 'month': (1, 12),\n 'day of week': (0, 6),\n}\n\nALIASES = {\n 'month': ' JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC'.split(' '),\n 'day of week': 'SUN MON TUE WED THU FRI SAT'.split(),\n}\n\ndef get_alias(field,...
{"fn_name": "parse", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5d7b9ed14cd01b000e7ebb41
def parse(crontab):
4,840
This Kata is the first in the [Rubiks Cube collection](https://www.codewars.com/collections/rubiks-party). [This](https://ruwix.com/the-rubiks-cube/notation/) or [this](https://ruwix.com/the-rubiks-cube/notation/advanced/) websites will be very usefull for this kata, if there will be some lack of understanding after t...
["f,g=lambda X:[list(x) for x in zip(*X[::-1])],lambda X:[list(x) for x in zip(*X)][::-1]\n\ndef ROTF(U,L,F,R,B,D):\n U[2],(L[0][2],L[1][2],L[2][2]),(R[0][0],R[1][0],R[2][0]),D[0]=([L[0][2],L[1][2],L[2][2]][::-1],list(D[0]),list(U[2]),[R[0][0],R[1][0],R[2][0]][::-1])\n return (U,L,f(F),R,B,D)\n \ndef ROTS(U,L,...
{"fn_name": "ROTF", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5b3bec086be5d8893000002e
def ROTF(U,L,F,R,B,D):
4,842
Mutation is a genetic operator used to maintain genetic diversity from one generation of a population of genetic algorithm chromosomes to the next. ![Mutation](http://i.imgur.com/HngmxNN.gif) A mutation here may happen on zero or more positions in a chromosome. It is going to check every position and by a given proba...
["from random import random\ndef mutate(chromosome, p):\n res = ''\n for s in chromosome:\n res += str(1 - int(s)) if random() < p else s\n return res\n", "from random import random\n\n\ndef mutate(chromosome, p):\n return ''.join((a, '01'[a == '0'])[random() <= p] for a in chromosome)\n", "from rand...
{"fn_name": "mutate", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/567b39b27d0a4606a5000057
def mutate(chromosome, p):
4,854
A circle is defined by three coplanar points that are not aligned. You will be given a list of circles and a point [xP, yP]. You have to create a function, ```count_circles()``` (Javascript ```countCircles()```), that will count the amount of circles that contains the point P inside (the circle border line is included...
["def circum_curvat(points):\n A, B, C = [complex(*p) for p in points]\n BC, CA, AB = B - C, C - A, A - B\n D = 2. * (A.real * BC + B.real * CA + C.real * AB).imag\n if not D: return D, D\n U = (abs(A)**2 * BC + abs(B)**2 * CA + abs(C)**2 * AB) / D\n radius = (abs(BC) * abs(CA) * abs(AB)) / abs(D)\n ...
{"fn_name": "count_circles", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/57b840b2a6fdc7be02000123
def count_circles(list_of_circles, point):
4,877
According to Gary Chapman, marriage counselor and the author of ["The Five Love Languages"](https://en.wikipedia.org/wiki/The_Five_Love_Languages) books, there are five major ways to express our love towards someone: *words of affirmation, quality time, gifts, acts of service,* and *physical touch*. These are called th...
["import random\n\ndef love_language(partner, weeks):\n rst = [0,0,0,0,0]\n for i in range (0, weeks*7):\n if(partner.response(LOVE_LANGUAGES[i%5]) == 'positive'):\n rst[i%5]+=1\n return LOVE_LANGUAGES[rst.index(max(rst))]\n", "def love_language(partner, weeks):\n n = len(LOVE_LANGUAGES)\n...
{"fn_name": "love_language", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5aa7a581fd8c06b552000177
def love_language(partner, weeks):
4,878
My third kata, write a function `check_generator` that examines the status of a Python generator expression `gen` and returns `'Created'`, `'Started'` or `'Finished'`. For example: `gen = (i for i in range(1))` >>> returns `'Created'` (the generator has been initiated) `gen = (i for i in range(1)); next(gen, None)` >...
["def check_generator(gen):\n if gen.gi_frame is None:\n return \"Finished\"\n if gen.gi_frame.f_lasti == -1:\n return \"Created\"\n return \"Started\"", "from inspect import getgeneratorstate as gt\nd = {'GEN_CREATED':'Created', 'GEN_SUSPENDED':'Started'}\ndef check_generator(gen):\n return d.get(gt(gen), ...
{"fn_name": "check_generator", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/585e6eb2eec14124ea000120
def check_generator(gen):
4,880
What is the answer to life the universe and everything Create a function that will make anything true ```python anything({}) != [], 'True' anything('Hello') < 'World', 'True' anything(80) > 81, 'True' anything(re) >= re, 'True' anything(re) <= math, 'True' an...
["class anything(object):\n def __init__(self, foo): pass\n def __eq__(self, other): return True\n __ne__ = __lt__ = __le__ = __gt__ = __ge__ = __eq__", "class anything:\n def __init__(self,*args,**kwargs):\n pass\n\nanything.__eq__ = anything.__neq__ = anything.__gt__ = anything.__ge__ = anything.__...
{"fn_name": "__init__", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/557d9e4d155e2dbf050000aa
def __init__(self, foo):
4,887
The date is March 24, 2437 and the the Earth has been nearly completely destroyed by the actions of its inhabitants. Our last hope in this disaster lies in a shabby time machine built from old toasters and used microwave parts. The World Time Agency requires you to travel back in time to prevent disaster. You are o...
["import datetime\n\ndef days(date, month, year):\n x = datetime.datetime(year, month, date)\n y = datetime.datetime(2437, 3, 24)\n delta = y-x\n t = delta.days\n if year < 1752 or (year == 1752 and month < 9) or (year == 1752 and month == 9 and date < 14):\n t -= 11\n if year < 1752 :\n ...
{"fn_name": "days", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5c1556f37f0627f75b0000d5
def days(date, month, year):
4,888
Return the `n`th term of the Recamán's sequence. ``` a(0) = 0; a(n-1) - n, if this value is positive and not yet in the sequence / a(n) < \ a(n-1) + n, otherwise ``` ___ A video about Recamán's sequence by Numberphile: https://www.youtube.com/watch?v=FGC5TdIiT9U
["def recaman(n):\n series, last = {0}, 0\n for i in range(1, n+1): \n test = last - i\n last = last + i if test < 0 or test in series else test\n series.add(last) \n\n return last", "inseq, seq = {0}, [0]\nfor n in range(1, 10 ** 6):\n x = seq[-1] - n\n if x < 0 or x in inseq: x...
{"fn_name": "recaman", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5c3f31c2460e9b4020780aa2
def recaman(n):
4,892
We need a function that may receive a list of an unknown amount of points in the same plane, having each of them, cartesian coordinates of the form (x, y) and may find the biggest triangle (the one with the largest area) formed by all of the possible combinations of groups of three points of that given list. Of course...
["from itertools import combinations\n\ndef area(t):\n (a,b),(c,d),(e,f) = t\n return abs(a*d+b*e+c*f-d*e-a*f-b*c)/2\n\ndef find_biggTriang(lst):\n tris = list(combinations(lst,3))\n areas = list(map(area,tris))\n m = max(areas)\n mTris = [list(map(list,t)) for t,v in zip(tris,areas) if v==m]\n ...
{"fn_name": "find_biggTriang", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/55f0a7d8c44c6f1438000013
def find_biggTriang(points):
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,896
The goal of this kata is to implement [trie](https://en.wikipedia.org/wiki/Trie) (or prefix tree) using dictionaries (aka hash maps or hash tables), where: 1. the dictionary keys are the prefixes 2. the value of a leaf node is `None` in Python, `nil` in Ruby and `null` in Groovy, JavaScript and Java. 3. the value for ...
["def build_trie(*words):\n root = {}\n for word in words:\n branch = root\n length = len(word)\n for i in range(1, length+1):\n length -= 1\n key = word[:i]\n if key not in branch: \n branch[key] = None\n if length and not branch[key...
{"fn_name": "build_trie", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5b65c47cbedf7b69ab00066e
def build_trie(*words):
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,906
**See Also** * [Traffic Lights - one car](.) * [Traffic Lights - multiple cars](https://www.codewars.com/kata/5d230e119dd9860028167fa5) --- # Overview A character string represents a city road. Cars travel on the road obeying the traffic lights.. Legend: * `.` = Road * `C` = Car * `G` = GREEN traffic light * `O` =...
["def traffic_lights(road, n):\n lightsIdx = [ (i, 6*(c!='G')) for i,c in enumerate(road) if c in 'RG' ]\n car, ref = road.find('C'), road.replace('C','.')\n mut, out = list(ref), [road]\n \n for turn in range(1,n+1):\n \n for i,delta in lightsIdx: # Update al...
{"fn_name": "traffic_lights", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5d0ae91acac0a50232e8a547
def traffic_lights(road, n):
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,910
This kata is part one of precise fractions series (see pt. 2: http://www.codewars.com/kata/precise-fractions-pt-2-conversion). When dealing with fractional values, there's always a problem with the precision of arithmetical operations. So lets fix it! Your task is to implement class ```Fraction``` that takes care of ...
["from fractions import Fraction\n\ndef to_string(self):\n n, d = self.numerator, self.denominator\n s, w, n = \"-\" if n < 0 else \"\", *divmod(abs(n), d)\n r = \" \".join((str(w) if w else \"\", f\"{n}/{d}\" if n else \"\")).strip()\n return f\"{s}{r}\"\n\nFraction.__str__ = to_string\nFraction.to_decimal...
{"fn_name": "to_string", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/54cf4fc26b85dc27bf000a6b
def to_string(self):
4,913
# Our Setup Alice and Bob work in an office. When the workload is light and the boss isn't looking, they often play simple word games for fun. This is one of those days! # This Game Today Alice and Bob are playing what they like to call _Mutations_, where they take turns trying to "think up" a new four-letter word i...
["import re\n\ndef genMask(w):\n x = list(w)\n for i in range(len(w)):\n x[i] = '.'\n yield ''.join(x)\n x[i] = w[i]\n\ndef mutations(alice, bob, word, first):\n players, seen = [alice,bob], {word}\n win, failed, i = -1, -1, first^1\n while 1:\n i ^= 1\n lst = pla...
{"fn_name": "mutations", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5cb5eb1f03c3ff4778402099
def mutations(alice, bob, word, first):
4,915
Help Suzuki rake his garden! The monastery has a magnificent Zen garden made of white gravel and rocks and it is raked diligently everyday by the monks. Suzuki having a keen eye is always on the lookout for anything creeping into the garden that must be removed during the daily raking such as insects or moss. You wi...
["VALID = {'gravel', 'rock'}\n\n\ndef rake_garden(garden):\n return ' '.join(a if a in VALID else 'gravel' for a in garden.split())\n", "def rake_garden(garden):\n return \" \".join(w if w == \"rock\" else \"gravel\" for w in garden.split())\n", "import re\n\ndef rake_garden(garden):\n return re.sub(r'(?<!\\S)...
{"fn_name": "rake_garden", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/571c1e847beb0a8f8900153d
def rake_garden(garden):
4,917
Write a function that takes a string of braces, and determines if the order of the braces is valid. It should return `true` if the string is valid, and `false` if it's invalid. This Kata is similar to the [Valid Parentheses](https://www.codewars.com/kata/valid-parentheses) Kata, but introduces new characters: brackets...
["def validBraces(string):\n braces = {\"(\": \")\", \"[\": \"]\", \"{\": \"}\"}\n stack = []\n for character in string:\n if character in braces.keys():\n stack.append(character)\n else:\n if len(stack) == 0 or braces[stack.pop()] != character:\n return False...
{"fn_name": "validBraces", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5277c8a221e209d3f6000b56
def validBraces(string):
4,921
In this kata, we're going to create the function `nato` that takes a `word` and returns a string that spells the word using the [NATO phonetic alphabet](https://en.wikipedia.org/wiki/NATO_phonetic_alphabet). There should be a space between each word in the returned string, and the first letter of each word should be c...
["letters = {\n \"A\": \"Alpha\", \"B\": \"Bravo\", \"C\": \"Charlie\",\n \"D\": \"Delta\", \"E\": \"Echo\", \"F\": \"Foxtrot\",\n \"G\": \"Golf\", \"H\": \"Hotel\", \"I\": \"India\",\n \"J\": \"Juliett\",\"K\": \"Kilo\", \"L\": \"Lima\",\n \"M\": \"Mike\", \"N\": \"November\",\"O\": \"O...
{"fn_name": "nato", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/54530f75699b53e558002076
def nato(word):
4,925
## Preface A collatz sequence, starting with a positive integern, is found by repeatedly applying the following function to n until n == 1 : `$f(n) = \begin{cases} n/2, \text{ if $n$ is even} \\ 3n+1, \text{ if $n$ is odd} \end{cases}$` ---- A more detailed description of the collatz conjecture may be found [on...
["def collatz(n):\n l = [str(n)]\n while n > 1:\n n = 3 * n + 1 if n % 2 else n / 2\n l.append(str(n))\n return '->'.join(l)", "def collatz_step(n):\n if n % 2 == 0:\n return n//2\n else:\n return n*3 + 1\n\ndef collatz_seq(n):\n while n != 1:\n yield n\n n = ...
{"fn_name": "collatz", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5286b2e162056fd0cb000c20
def collatz(n):
4,927
Given an array `A` and an integer `x`, map each element in the array to `F(A[i],x)` then return the xor sum of the resulting array. where F(n,x) is defined as follows: F(n, x) = ^(x)Cx **+** ^(x+1)Cx **+** ^(x+2)Cx **+** ... **+** ^(n)Cx and ^(n)Cx represents [Combination](https://en.m.wikipedia.org/wiki/Combination...
["from functools import reduce\nfrom gmpy2 import comb\nfrom operator import xor\n\ndef transform(a, x):\n return reduce(xor, (comb(n + 1, x + 1) for n in a))", "def transform(A, x):\n c, i, f, r = 1, x, 0, None\n for n in sorted(A):\n while i <= n:\n c *= i\n c //= i-x or x\n ...
{"fn_name": "transform", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5bb9053a528b29a970000113
def transform(A, x):
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):