problem_id
int64
2.36k
5k
question
stringlengths
52
14k
solutions
stringlengths
79
675k
input_output
stringlengths
37
505k
difficulty
stringclasses
1 value
url
stringlengths
36
94
starter_code
stringlengths
0
952
3,064
Transpose means is to interchange rows and columns of a two-dimensional array matrix. [A^(T)]ij=[A]ji ie: Formally, the i th row, j th column element of AT is the j th row, i th column element of A: Example : ``` [[1,2,3],[4,5,6]].transpose() //should return [[1,4],[2,5],[3,6]] ``` Write a prototype transpose to...
["import numpy as np\n\ndef transpose(A):\n if len(A) == 0:\n return []\n return np.array(A, dtype = 'O').T.tolist() if len(A[0]) > 0 else [[]]", "def transpose(arr):\n if arr and not any(map(bool,arr)): return [[]]\n return list(map(list,zip(*arr)))", "def transpose(arr):\n tran_each = []\n tr...
{"fn_name": "transpose", "inputs": [[[]], [[[1]]], [[[0, 1]]], [[[1, 2, 3], [4, 5, 6]]], [[[1, 2, 3, 4, 5, 6]]], [[[1], [2], [3], [4], [5], [6]]], [[["a", "b", "c"], ["d", "e", "f"]]], [[[true, false, true], [false, true, false]]], [[[]]], [[[], [], [], [], [], []]]], "outputs": [[[]], [[[1]]], [[[0], [1]]], [[[1, 4], ...
introductory
https://www.codewars.com/kata/559656796d8fb52e17000003
def transpose(arr):
3,065
We like parsed SQL or PL/SQL blocks... You need to write function that return list of literals indices from source block, excluding "in" comments, OR return empty list if no literals found. input: some fragment of sql or pl/sql code output: list of literals indices [(start, end), ...] OR empty list Sample: ``` get_...
["import re\n\nSKIPERS = re.compile(r'|'.join([\"\\\\\\*.*?\\*/\", \"--.*?(\\n|$)\", \"''\"]))\n\ndef get_textliterals(code):\n code = SKIPERS.sub(lambda m: \"x\"*len(m.group()) , code.rstrip())\n if code.count(\"'\") % 2: code += \"'\"\n return [(m.start(), m.end()) for m in re.finditer(r\"'.+?'\", code, flag...
{"fn_name": "get_textliterals", "inputs": [["select 'text' into row from table where a = 'value'"], ["if a>'data'and b<'nnn' then c:='test'; end if;"], ["select aaa, bbb, ccc, /*'ddd'?*/ into row from table;"], ["a:='data''s';"]], "outputs": [[[[7, 13], [44, 51]]], [[[5, 11], [17, 22], [31, 37]]], [[]], [[[3, 12]]]]}
introductory
https://www.codewars.com/kata/5536552b372553087d000086
def get_textliterals(pv_code):
3,066
In this Kata, you will be given a mathematical string and your task will be to remove all braces as follows: ```Haskell solve("x-(y+z)") = "x-y-z" solve("x-(y-z)") = "x-y+z" solve("u-(v-w-(x+y))-z") = "u-v+w+x+y-z" solve("x-(-y-z)") = "x+y+z" ``` There are no spaces in the expression. Only two operators are given: `"...
["from functools import reduce\n\ndef solve(st):\n res, s, k = [], \"\", 1\n for ch in st:\n if ch == '(': res.append(k); k = 1\n elif ch == ')': res.pop(); k = 1\n elif ch == '-': k = -1\n elif ch == '+': k = 1\n else: s+= '-'+ch if (reduce(lambda a,b: a * b,res,1) * (1 if k ==...
{"fn_name": "solve", "inputs": [["a-(b)"], ["a-(-b)"], ["a+(b)"], ["a+(-b)"], ["(((((((((-((-(((n))))))))))))))"], ["(((a-((((-(-(f)))))))))"], ["((((-(-(-(-(m-g))))))))"], ["(((((((m-(-(((((t)))))))))))))"], ["-x"], ["-(-(x))"], ["-((-x))"], ["-(-(-x))"], ["-(-(x-y))"], ["-(x-y)"], ["x-(y+z)"], ["x-(y-z)"], ["x-(-y-z)...
introductory
https://www.codewars.com/kata/5a3bedd38f27f246c200005f
def solve(s):
3,067
Bob needs a fast way to calculate the volume of a cuboid with three values: `length`, `width` and the `height` of the cuboid. Write a function to help Bob with this calculation. ```if:shell In bash the script is ran with the following 3 arguments: `length` `width` `height` ```
["def get_volume_of_cuboid(length, width, height):\n return length * width * height\n\n\n# PEP8: kata function name should use snake_case not mixedCase\ngetVolumeOfCubiod = get_volume_of_cuboid", "def getVolumeOfCubiod(l, w, h):\n return l * w * h", "def getVolumeOfCubiod(length, width, height):\n return lengt...
{"fn_name": "getVolumeOfCubiod", "inputs": [[2, 5, 6], [6.3, 3, 5]], "outputs": [[60], [94.5]]}
introductory
https://www.codewars.com/kata/58261acb22be6e2ed800003a
def getVolumeOfCubiod(length, width, height):
3,068
You need to play around with the provided string (s). Move consonants forward 9 places through the alphabet. If they pass 'z', start again at 'a'. Move vowels back 5 places through the alphabet. If they pass 'a', start again at 'z'. For our Polish friends this kata does not count 'y' as a vowel. Exceptions: If the ...
["def vowel_back(st):\n return st.translate(str.maketrans(\"abcdefghijklmnopqrstuvwxyz\", \"vkbaafpqistuvwnyzabtpvfghi\"))", "def vowel_back(s):\n return s.translate(str.maketrans(\"abcdeghjklmnopqrsuwxyz\", \"vkbaapqstuvwnyzabpfghi\"))", "from string import ascii_lowercase as abc\n\ndef vowel_back(st): return st...
{"fn_name": "vowel_back", "inputs": [["testcase"], ["codewars"], ["exampletesthere"], ["returnofthespacecamel"], ["bringonthebootcamp"], ["weneedanofficedog"]], "outputs": [["tabtbvba"], ["bnaafvab"], ["agvvyuatabtqaaa"], ["aatpawnftqabyvbabvvau"], ["kaiwpnwtqaknntbvvy"], ["fawaaavwnffibaanp"]]}
introductory
https://www.codewars.com/kata/57cfd92c05c1864df2001563
def vowel_back(st):
3,069
Your start-up's BA has told marketing that your website has a large audience in Scandinavia and surrounding countries. Marketing thinks it would be great to welcome visitors to the site in their own language. Luckily you already use an API that detects the user's location, so this is an easy win. ### The Task - Think...
["def greet(language):\n return {\n 'czech': 'Vitejte',\n 'danish': 'Velkomst',\n 'dutch': 'Welkom',\n 'english': 'Welcome',\n 'estonian': 'Tere tulemast',\n 'finnish': 'Tervetuloa',\n 'flemish': 'Welgekomen',\n 'french': 'Bienvenue',\n 'german': 'Willko...
{"fn_name": "greet", "inputs": [["english"], ["dutch"], ["IP_ADDRESS_INVALID"], [""], [2]], "outputs": [["Welcome"], ["Welkom"], ["Welcome"], ["Welcome"], ["Welcome"]]}
introductory
https://www.codewars.com/kata/577ff15ad648a14b780000e7
def greet(language):
3,070
Given a list of integers values, your job is to return the sum of the values; however, if the same integer value appears multiple times in the list, you can only count it once in your sum. For example: ```python [ 1, 2, 3] ==> 6 [ 1, 3, 8, 1, 8] ==> 12 [ -1, -1, 5, 2, -7] ==> -1 [] ==> None ``` Good Luck!
["def unique_sum(lst):\n return sum(set(lst)) if lst else None\n", "def unique_sum(lst):\n if lst:\n return sum(set(lst)) ", "def unique_sum(lst):\n s = set(lst)\n \n return sum(s) if len(s) != 0 else None", "unique_sum = lambda l: sum(set(l)) if l else None", "def unique_sum(lst):\n if lst:\n ...
{"fn_name": "unique_sum", "inputs": [[[]], [[0, 1, -1]]], "outputs": [[null], [0]]}
introductory
https://www.codewars.com/kata/56b1eb19247c01493a000065
def unique_sum(lst):
3,071
Define a function that takes in two non-negative integers `$a$` and `$b$` and returns the last decimal digit of `$a^b$`. Note that `$a$` and `$b$` may be very large! For example, the last decimal digit of `$9^7$` is `$9$`, since `$9^7 = 4782969$`. The last decimal digit of `$({2^{200}})^{2^{300}}$`, which has over `$...
["def last_digit(n1, n2):\n return pow( n1, n2, 10 )", "rules = {\n 0: [0,0,0,0], \n 1: [1,1,1,1],\n 2: [2,4,8,6],\n 3: [3,9,7,1],\n 4: [4,6,4,6], \n 5: [5,5,5,5], \n 6: [6,6,6,6], \n 7: [7,9,3,1], \n 8: [8,4,2,6], \n 9: [9,1,9,1],\n}\ndef last_digit(n1, n2):\n ruler = rules[int(st...
{"fn_name": "last_digit", "inputs": [[4, 1], [4, 2], [9, 7], [10, 1000000000], [38710248912497124917933333333284108412048102948908149081409204712406, 226628148126342643123641923461846128214626], [3715290469715693021198967285016729344580685479654510946723, 68819615221552997273737174557165657483427362207517952651]], "out...
introductory
https://www.codewars.com/kata/5511b2f550906349a70004e1
def last_digit(n1, n2):
3,072
Well, those numbers were right and we're going to feed their ego. Write a function, isNarcissistic, that takes in any amount of numbers and returns true if all the numbers are narcissistic. Return false for invalid arguments (numbers passed in as strings are ok). For more information about narcissistic numbers (and b...
["def get_digits(n):\n return [int(x) for x in list(str(n))]\n\n\ndef is_narc(n):\n return n == sum([x**len(get_digits(n)) for x in get_digits(n)])\n\n\ndef is_narcissistic(*values):\n try:\n return all(type(n) in [int,str] and is_narc(int(n)) for n in values)\n except ValueError:\n return Fal...
{"fn_name": "is_narcissistic", "inputs": [[11], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 22, 9], ["4"], ["4", 7, "9"], ["words"], [[1, 2]], [407, 8208], [-1], [""], ["", 407], [407, ""], [5, "", 407], [9474], [{}]], "outputs": [[false], [true], [false], [true], [true], [false], [false], [true], [false],...
introductory
https://www.codewars.com/kata/565225029bcf176687000022
def is_narcissistic(*args):
3,073
An `non decreasing` number is one containing no two consecutive digits (left to right), whose the first is higer than the second. For example, 1235 is an non decreasing number, 1229 is too, but 123429 isn't. Write a function that finds the number of non decreasing numbers up to `10**N` (exclusive) where N is the input...
["def increasing_numbers(d):\n s = 1\n for i in range(1,10): s=s*(i+d)//i\n return s", "from functools import lru_cache\n\n\n@lru_cache(maxsize=None)\ndef f(ndigits, starting_digit):\n if ndigits == 0:\n return 1\n return sum(f(ndigits-1, i) for i in range(starting_digit, 10))\n \ndef increasin...
{"fn_name": "increasing_numbers", "inputs": [[0], [1], [2], [3], [4], [5], [6], [10], [20], [50]], "outputs": [[1], [10], [55], [220], [715], [2002], [5005], [92378], [10015005], [12565671261]]}
introductory
https://www.codewars.com/kata/57698ec6dd8944888e000110
def increasing_numbers(n):
3,074
### Task Each day a plant is growing by `upSpeed` meters. Each night that plant's height decreases by `downSpeed` meters due to the lack of sun heat. Initially, plant is 0 meters tall. We plant the seed at the beginning of a day. We want to know when the height of the plant will reach a certain level. ### Example F...
["from math import ceil\n\ndef growing_plant(up, down, h):\n return max(ceil((h - down) / (up - down)), 1)", "def growing_plant(upSpeed, downSpeed, desiredHeight):\n days = 1\n height = upSpeed\n while (height < desiredHeight):\n height += upSpeed - downSpeed\n days += 1\n return days;\n", ...
{"fn_name": "growing_plant", "inputs": [[100, 10, 910], [10, 9, 4], [5, 2, 5], [5, 2, 6]], "outputs": [[10], [1], [1], [2]]}
introductory
https://www.codewars.com/kata/58941fec8afa3618c9000184
def growing_plant(upSpeed, downSpeed, desiredHeight):
3,075
Array inversion indicates how far the array is from being sorted. Inversions are pairs of elements in array that are out of order. ## Examples ``` [1, 2, 3, 4] => 0 inversions [1, 3, 2, 4] => 1 inversion: 2 and 3 [4, 1, 2, 3] => 3 inversions: 4 and 1, 4 and 2, 4 and 3 [4, 3, 2, 1] => 6 inversions: 4 and 3, 4...
["def count_inversions(array):\n inv_count = 0\n for i in range(len(array)):\n for j in range(i, len(array)):\n if array[i] > array[j]:\n inv_count += 1\n return inv_count", "def count_inversions(array):\n return sum(x > y for i,x in enumerate(array) for y in array[i+1:])", ...
{"fn_name": "count_inversions", "inputs": [[[]], [[1, 2, 3]], [[2, 1, 3]], [[6, 5, 4, 3, 2, 1]], [[6, 5, 4, 3, 3, 3, 3, 2, 1]]], "outputs": [[0], [0], [1], [15], [30]]}
introductory
https://www.codewars.com/kata/537529f42993de0e0b00181f
def count_inversions(array):
3,076
In this Kata, you will be given directions and your task will be to find your way back. ```Perl solve(["Begin on Road A","Right on Road B","Right on Road C","Left on Road D"]) = ['Begin on Road D', 'Right on Road C', 'Left on Road B', 'Left on Road A'] solve(['Begin on Lua Pkwy', 'Right on Sixth Alley', 'Right on 1st ...
["DIRS = {'Left': 'Right', 'Right': 'Left'}\n\ndef solve(arr):\n lst,prevDir = [], 'Begin'\n for cmd in arr[::-1]:\n d, r = cmd.split(' on ')\n follow = DIRS.get(prevDir, prevDir)\n prevDir = d\n lst.append(f'{follow} on {r}')\n return lst", "def solve(arr):\n go_moves, go_pl...
{"fn_name": "solve", "inputs": [[["Begin on 3rd Blvd", "Right on First Road", "Left on 9th Dr"]], [["Begin on Road A", "Right on Road B", "Right on Road C", "Left on Road D"]], [["Begin on Road A"]]], "outputs": [[["Begin on 9th Dr", "Right on First Road", "Left on 3rd Blvd"]], [["Begin on Road D", "Right on Road C", "...
introductory
https://www.codewars.com/kata/5b94d7eb1d5ed297680000ca
def solve(arr):
3,077
##Task: You have to write a function **pattern** which creates the following pattern upto n number of rows. *If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string.* ##Examples: pattern(4): 1234 234 34 4 pattern(6): 123456 23456 3456 456 5...
["pattern = lambda n: \"\\n\".join([\"\".join([str(y) for y in range(x + 1, n + 1)]) for x in range(n)]);", "def pattern(n):\n return '\\n'.join( ''.join(str(j) for j in range(i,n+1)) for i in range(1,n+1) )", "def pattern(n):\n return '\\n'.join(''.join(str(i + 1) for i in range(n)[j:]) for j in range(n))\n", "d...
{"fn_name": "pattern", "inputs": [[1], [2], [5], [0], [-25]], "outputs": [["1"], ["12\n2"], ["12345\n2345\n345\n45\n5"], [""], [""]]}
introductory
https://www.codewars.com/kata/55736129f78b30311300010f
def pattern(n):
3,078
# Task Consider an array of integers `a`. Let `min(a)` be its minimal element, and let `avg(a)` be its mean. Define the center of the array `a` as array `b` such that: ``` - b is formed from a by erasing some of its elements. - For each i, |b[i] - avg(a)| < min(a). - b has the maximum number of elements among all the...
["def array_center(lst):\n return [i for i in lst if abs(i - sum(lst)*1.0/len(lst)) < min(lst)]", "from statistics import mean\n\ndef array_center(arr):\n low, avg = min(arr), mean(arr)\n return [b for b in arr if abs(b - avg) < low]", "from statistics import mean\n\ndef array_center(a):\n n, m = min(a), me...
{"fn_name": "array_center", "inputs": [[[8, 3, 4, 5, 2, 8]], [[1, 3, 2, 1]], [[10, 11, 12, 13, 14]]], "outputs": [[[4, 5]], [[1, 2, 1]], [[10, 11, 12, 13, 14]]]}
introductory
https://www.codewars.com/kata/590bdaa251ab8267b800005b
def array_center(arr):
3,079
Given a certain integer ```n```, we need a function ```big_primefac_div()```, that give an array with the highest prime factor and the highest divisor (not equal to n). Let's see some cases: ```python big_primefac_div(100) == [5, 50] big_primefac_div(1969) == [179, 179] ``` If n is a prime number the function will out...
["def big_primefac_div(n):\n bpf, bd = 0, 1\n frac = []\n \n if n % 1 != 0:\n return \"The number has a decimal part. No Results\"\n else:\n n = abs(int(n))\n n_copy = n\n \n i = 2\n while i * i <= n:\n if n % i == 0:\n n //= i\n frac.append(i)\n ...
{"fn_name": "big_primefac_div", "inputs": [[100], [1969], [997], [-1800], [-1800.1]], "outputs": [[[5, 50]], [[179, 179]], [[]], [[5, 900]], ["The number has a decimal part. No Results"]]}
introductory
https://www.codewars.com/kata/5646ac68901dc5c31a000022
def big_primefac_div(n):
3,080
Don Drumphet lives in a nice neighborhood, but one of his neighbors has started to let his house go. Don Drumphet wants to build a wall between his house and his neighbor’s, and is trying to get the neighborhood association to pay for it. He begins to solicit his neighbors to petition to get the association to build ...
["who_is_paying = lambda n: [n, n[:2]] if len(n)>2 else [n]", "def who_is_paying(name):\n if len(name) > 2:\n return [name, name[0:2]]\n else:\n return [name[0:len(name)]]", "def who_is_paying(name):\n return [name,name[0:2]] if len(name)>2 else [name]", "def who_is_paying(name):\n return [nam...
{"fn_name": "who_is_paying", "inputs": [["Mexico"], ["Melania"], ["Melissa"], ["Me"], [""], ["I"]], "outputs": [[["Mexico", "Me"]], [["Melania", "Me"]], [["Melissa", "Me"]], [["Me"]], [[""]], [["I"]]]}
introductory
https://www.codewars.com/kata/58bf9bd943fadb2a980000a7
def who_is_paying(name):
3,081
Following on from [Part 1](http://www.codewars.com/kata/filling-an-array-part-1/), part 2 looks at some more complicated array contents. So let's try filling an array with... ## ...square numbers The numbers from `1` to `n*n` ## ...a range of numbers A range of numbers starting from `start` and increasing by `step` ...
["import random\ndef squares(n):\n return [i**2 for i in range(1, n+1)]\n\ndef num_range(n, start, step):\n return [i for i in range(start, start+step*n, step)]\n\ndef rand_range(n, mn, mx):\n return [random.randint(mn, mx) for i in range(n)]\ndef primes(n):\n return [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31,...
{"fn_name": "squares", "inputs": [[5]], "outputs": [[[1, 4, 9, 16, 25]]]}
introductory
https://www.codewars.com/kata/571e9af407363dbf5700067c
def squares(n):
3,082
In this kata you will create a function to check a non-negative input to see if it is a prime number. The function will take in a number and will return True if it is a prime number and False if it is not. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. ### Ex...
["import math\ndef is_prime(n):\n if n < 2: \n return False\n return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))", "def is_prime(n):\n 'Return True if n is a prime number otherwise return False'\n # 0 and 1 are not primes\n if n < 2: \n return False\n \n # 2 is only even pr...
{"fn_name": "is_prime", "inputs": [[0], [1], [2], [11], [12], [61], [571], [573], [25]], "outputs": [[false], [false], [true], [true], [false], [true], [true], [false], [false]]}
introductory
https://www.codewars.com/kata/53daa9e5af55c184db00025f
def is_prime(n):
3,083
Most of this problem is by the original author of [the harder kata](https://www.codewars.com/kata/556206664efbe6376700005c), I just made it simpler. I read a book recently, titled "Things to Make and Do in the Fourth Dimension" by comedian and mathematician Matt Parker ( [Youtube](https://www.youtube.com/user/standupm...
["def polydivisible(x):\n for i in range(1, len(str(x)) + 1):\n if int(str(x)[:i]) % i != 0:\n return False\n return True", "def polydivisible(x):\n s = str(x)\n return all(int(s[:i]) % i == 0 for i in range(1, len(s) + 1))", "def polydivisible(x):\n return all(int(str(x)[:i+1])%(i+1)==...
{"fn_name": "polydivisible", "inputs": [[1232], [123220], [0], [1], [141], [1234], [21234], [81352], [987654], [1020005], [9876545], [381654729], [1073741823]], "outputs": [[true], [false], [true], [true], [true], [false], [false], [false], [true], [true], [true], [true], [false]]}
introductory
https://www.codewars.com/kata/5e4217e476126b000170489b
def polydivisible(x):
3,084
Your task is to write a function that takes two or more objects and returns a new object which combines all the input objects. All input object properties will have only numeric values. Objects are combined together so that the values of matching keys are added together. An example: ```python objA = { 'a': 10, 'b':...
["def combine(*bs):\n c = {}\n for b in bs:\n for k, v in list(b.items()):\n c[k] = v + c.get(k, 0)\n return c\n", "from collections import Counter\n\n\ndef combine(*args):\n return sum((Counter(a) for a in args), Counter())\n", "def combine(*dictionaries):\n result = {}\n for dict i...
{"fn_name": "combine", "inputs": [[{}, {}, {}], [{}]], "outputs": [[{}], [{}]]}
introductory
https://www.codewars.com/kata/56bd9e4b0d0b64eaf5000819
def combine(*args):
3,085
The AKS algorithm for testing whether a number is prime is a polynomial-time test based on the following theorem: A number p is prime if and only if all the coefficients of the polynomial expansion of `(x − 1)^p − (x^p − 1)` are divisible by `p`. For example, trying `p = 3`: (x − 1)^3 − (x^3 − 1) = (x^3 − 3x^2...
["def aks_test(p):\n lst = []\n for i in range(2, p+1):\n for j in lst:\n if i % j == 0:\n break\n else:\n lst.append(i)\n if p in lst:\n return True\n else:\n return False", "import math\ndef aks_test(p):\n center = (math.factorial(p//2)*m...
{"fn_name": "aks_test", "inputs": [[3], [4], [5], [7], [10], [33], [101], [1], [2], [11213], [8191], [8192]], "outputs": [[true], [false], [true], [true], [false], [false], [true], [false], [true], [true], [true], [false]]}
introductory
https://www.codewars.com/kata/5416d02d932c1df3a3000492
def aks_test(p):
3,086
#Unflatten a list (Easy) There are several katas like "Flatten a list". These katas are done by so many warriors, that the count of available list to flattin goes down! So you have to build a method, that creates new arrays, that can be flattened! #Shorter: You have to unflatten a list/an array. You get an array of...
["def unflatten(flat_array):\n arr = flat_array[:]\n for i, v in enumerate(arr):\n if v > 2:\n arr[i], arr[i+1:i+v] = arr[i:i+v], []\n return arr", "def unflatten(flat):\n if not flat : return []\n if flat[0]<3 : return [flat[0]] + unflatten(flat[1:])\n else: return [ flat[...
{"fn_name": "unflatten", "inputs": [[[3, 5, 2, 1]], [[1, 4, 5, 2, 1, 2, 4, 5, 2, 6, 2, 3, 3]], [[1, 1, 1, 1]], [[1]], [[99, 1, 1, 1]], [[3, 1, 1, 3, 1, 1]]], "outputs": [[[[3, 5, 2], 1]], [[1, [4, 5, 2, 1], 2, [4, 5, 2, 6], 2, [3, 3]]], [[1, 1, 1, 1]], [[1]], [[[99, 1, 1, 1]]], [[[3, 1, 1], [3, 1, 1]]]]}
introductory
https://www.codewars.com/kata/57e2dd0bec7d247e5600013a
def unflatten(flat_array):
3,087
You will be given a string and you task is to check if it is possible to convert that string into a palindrome by removing a single character. If the string is already a palindrome, return `"OK"`. If it is not, and we can convert it to a palindrome by removing one character, then return `"remove one"`, otherwise return...
["def solve(s):\n isOK = lambda x: x == x[::-1]\n \n return (\"OK\" if isOK(s) else\n \"remove one\" if any( isOK(s[:i]+s[i+1:]) for i in range(len(s)) ) else\n \"not possible\")", "def solve(s):\n if s == s[::-1]:\n return 'OK'\n for i in range(len(s)):\n if s[:i] + ...
{"fn_name": "solve", "inputs": [["abba"], ["abbaa"], ["abbaab"], ["madmam"], ["raydarm"], ["hannah"], ["baba"], ["babab"], ["bababa"], ["abcbad"], ["abcdba"], ["dabcba"], ["abededba"], ["abdcdeba"], ["abcdedba"], ["abbcdedba"]], "outputs": [["OK"], ["remove one"], ["not possible"], ["remove one"], ["not possible"], ["O...
introductory
https://www.codewars.com/kata/5a2c22271f7f709eaa0005d3
def solve(s):
3,088
An NBA game runs 48 minutes (Four 12 minute quarters). Players do not typically play the full game, subbing in and out as necessary. Your job is to extrapolate a player's points per game if they played the full 48 minutes. Write a function that takes two arguments, ppg (points per game) and mpg (minutes per game) and ...
["def nba_extrap(ppg, mpg):\n return round(48.0 / mpg * ppg, 1) if mpg > 0 else 0", "def nba_extrap(ppg, mpg):\n return round(ppg * 48.0 / mpg, 1) if mpg else 0", "def nba_extrap(ppg, mpg):\n try:\n return round(ppg/(mpg * 1.0)*48, 1) \n except ZeroDivisionError:\n return 0\n", "def nba_extrap...
{"fn_name": "nba_extrap", "inputs": [[2, 5], [3, 9], [16, 27], [11, 19], [14, 33], [1, 7.5], [6, 13]], "outputs": [[19.2], [16.0], [28.4], [27.8], [20.4], [6.4], [22.2]]}
introductory
https://www.codewars.com/kata/587c2d08bb65b5e8040004fd
def nba_extrap(ppg, mpg):
3,089
Given a number, return a string with dash``` '-' ```marks before and after each odd integer, but do not begin or end the string with a dash mark. Ex:
["import re\ndef dashatize(num):\n try:\n return ''.join(['-'+i+'-' if int(i)%2 else i for i in str(abs(num))]).replace('--','-').strip('-')\n except:\n return 'None'", "import re\n\ndef dashatize(num):\n return 'None' if num is None else '-'.join(w for w in re.split(r'([13579])', str(abs(num))) if...
{"fn_name": "dashatize", "inputs": [[274], [5311], [86320], [974302]], "outputs": [["2-7-4"], ["5-3-1-1"], ["86-3-20"], ["9-7-4-3-02"]]}
introductory
https://www.codewars.com/kata/58223370aef9fc03fd000071
def dashatize(num):
3,090
Find the 2nd largest integer in array If the array has no 2nd largest integer then return nil. Reject all non integers elements and then find the 2nd largest integer in array find_2nd_largest([1,2,3]) => 2 find_2nd_largest([1,1,1,1,1]) => nil because all elements are same. Largest no. is 1. and there is no 2nd larges...
["def find_2nd_largest(arr):\n arr = sorted(i for i in set(arr) if type(i) == int)\n return arr[-2] if len(arr) > 1 else None", "def find_2nd_largest(arr): \n newarr = sorted(list({x for x in arr if type(x) == int})) # remove duplicates and non-int objects, sort\n return newarr[-2] if len(newarr) > 1 else N...
{"fn_name": "find_2nd_largest", "inputs": [[[1, 2, 3]], [[1, 1, 1, 1, 1, 1, 1]], [[1, "a", "2", 3, 3, 4, 5, "b"]], [[1, "a", "2", 3, 3, 3333333333333333333334, 544444444444444444444444444444, "b"]]], "outputs": [[2], [null], [4], [3333333333333333333334]]}
introductory
https://www.codewars.com/kata/55a58505cb237a076100004a
def find_2nd_largest(arr):
3,091
The local transport authority is organizing an online picture contest. Participants must take pictures of transport means in an original way, and then post the picture on Instagram using a specific ```hashtag```. The local transport authority needs your help. They want you to take out the ```hashtag``` from the posted...
["def omit_hashtag(message, hashtag):\n return message.replace(hashtag, \"\", 1)", "omit_hashtag = lambda message, hashtag: message.replace(hashtag, '', 1)", "def omit_hashtag(message, hashtag):\n return message.replace(hashtag, '' , 1) if hashtag in message else message", "omit_hashtag = lambda m, h: m.replace(h...
{"fn_name": "omit_hashtag", "inputs": [["Sunny day! #lta #vvv", "#lta"], ["#lta #picture_contest", "#lta"], ["#lta #picture_contest #lta", "#lta"]], "outputs": [["Sunny day! #vvv"], [" #picture_contest"], [" #picture_contest #lta"]]}
introductory
https://www.codewars.com/kata/5a06238a80171f824300003c
def omit_hashtag(message, hashtag):
3,092
You have to rebuild a string from an enumerated list. For this task, you have to check if input is correct beforehand. * Input must be a list of tuples * Each tuple has two elements. * Second element is an alphanumeric character. * First element is the index of this character into the reconstructed string. * Indexes s...
["def denumerate(enum_list):\n try:\n nums = dict(enum_list)\n maximum = max(nums) + 1\n result = ''.join(nums[a] for a in range(maximum))\n if result.isalnum() and len(result) == maximum:\n return result\n except (KeyError, TypeError, ValueError):\n pass\n return ...
{"fn_name": "denumerate", "inputs": [[1], ["a"], [[0]], [[["a", 0]]], [[[1, "a"]]], [[[0, ""]]]], "outputs": [[false], [false], [false], [false], [false], [false]]}
introductory
https://www.codewars.com/kata/57197be09906af7c830016de
def denumerate(enum_list):
3,093
Write a function `insertDash(num)`/`InsertDash(int num)` that will insert dashes ('-') between each two odd numbers in num. For example: if num is 454793 the output should be 4547-9-3. Don't count zero as an odd number. Note that the number will always be non-negative (>= 0).
["import re\n\ndef insert_dash(num):\n #your code here\n return re.sub(r'([13579])(?=[13579])', r'\\1-', str(num))", "import re\ndef insert_dash(num): return re.sub(r'[13579](?=[13579])', \"\\g<0>-\", str(num))", "\n \ndef insert_dash(num):\n odd = False\n result = []\n for n in str(num):\n ...
{"fn_name": "insert_dash", "inputs": [[454793], [123456], [1003567], [24680], [13579]], "outputs": [["4547-9-3"], ["123456"], ["1003-567"], ["24680"], ["1-3-5-7-9"]]}
introductory
https://www.codewars.com/kata/55960bbb182094bc4800007b
def insert_dash(num):
3,094
Sum all the numbers of the array (in F# and Haskell you get a list) except the highest and the lowest element (the value, not the index!). (The highest/lowest element is respectively only one element at each edge, even if there are more than one with the same value!) Example: ``` { 6, 2, 1, 8, 10 } => 16 { 1, 1, 11, 2,...
["def sum_array(arr):\n if arr == None or len(arr) < 3:\n return 0\n return sum(arr) - max(arr) - min(arr)", "def sum_array(arr):\n return sum(sorted(arr)[1:-1]) if arr and len(arr) > 1 else 0", "def sum_array(arr):\n return sum(sorted(arr)[1:-1]) if arr else 0\n", "def sum_array(arr):\n return 0 ...
{"fn_name": "sum_array", "inputs": [[null], [[]], [[3]], [[-3]], [[3, 5]], [[-3, -5]], [[6, 2, 1, 8, 10]], [[6, 0, 1, 10, 10]], [[-6, -20, -1, -10, -12]], [[-6, 20, -1, 10, -12]]], "outputs": [[0], [0], [0], [0], [0], [0], [16], [17], [-28], [3]]}
introductory
https://www.codewars.com/kata/576b93db1129fcf2200001e6
def sum_array(arr):
3,095
You like the way the Python `+` operator easily handles adding different numeric types, but you need a tool to do that kind of addition without killing your program with a `TypeError` exception whenever you accidentally try adding incompatible types like strings and lists to numbers. You decide to write a function `my...
["def my_add(a, b):\n try:\n return a + b\n except TypeError:\n return None\n", "def my_add(*a):\n try:\n return sum(a)\n except:\n pass", "def my_add(a, b):\n try:\n ans = a + b\n return ans\n except:\n return None\n", "def my_add(a, b):\n # Your co...
{"fn_name": "my_add", "inputs": [[1, 3.414], [42, " is the answer."], [10, "2"]], "outputs": [[4.414], [null], [null]]}
introductory
https://www.codewars.com/kata/58659b1261cbfc8bfc00020a
def my_add(a, b):
3,096
This problem takes its name by arguably the most important event in the life of the ancient historian Josephus: according to his tale, he and his 40 soldiers were trapped in a cave by the Romans during a siege. Refusing to surrender to the enemy, they instead opted for mass suicide, with a twist: **they formed a circl...
["def josephus(xs, k):\n i, ys = 0, []\n while len(xs) > 0:\n i = (i + k - 1) % len(xs)\n ys.append(xs.pop(i))\n return ys", "def josephus(n,k):\n i, ans = 0, []\n while n: i = (i + k - 1) % len(n); ans.append(n.pop(i))\n return ans", "from collections import deque\n\ndef josephus(items,...
{"fn_name": "josephus", "inputs": [[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 1], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2], [["C", "o", "d", "e", "W", "a", "r", "s"], 4], [["C", 0, "d", 3, "W", 4, "r", 5], 4], [[1, 2, 3, 4, 5, 6, 7], 3], [[], 3], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 2...
introductory
https://www.codewars.com/kata/5550d638a99ddb113e0000a2
def josephus(items,k):
3,097
Comprised of a team of five incredibly brilliant women, "The ladies of ENIAC" were the first “computors” working at the University of Pennsylvania’s Moore School of Engineering (1945). Through their contributions, we gained the first software application and the first programming classes! The ladies of ENIAC were induc...
["import re\ndef rad_ladies(name):\n return \"\".join(re.findall(\"[A-Z\\s!]+\", name.upper()))", "from string import ascii_uppercase\n\nVALID = set(ascii_uppercase + ' !')\n\n\ndef rad_ladies(name):\n return ''.join(a for a in name.upper() if a in VALID)\n", "import re\ndef rad_ladies(name):\n return re.sub(\...
{"fn_name": "rad_ladies", "inputs": [["k?%35a&&/y@@@5599 m93753&$$$c$n///79u??@@%l?975$t?%5y%&$3$1!"], ["9?9?9?m335%$@a791%&$r$$$l@53$&y&n%$5@ $5577w&7e931%s$c$o%%%f351f??%!%%"], ["%&$557f953//1/$@%r%935$$a@3111$@???%n???5 $%157b%///$i%55&31@l?%&$$a%@$s5757!$$%%%%53"], ["///$%&$553791r357%??@$%u?$%@7993111@$%t$h3% 3$l$...
introductory
https://www.codewars.com/kata/56d31aaefd3a52902a000d66
def rad_ladies(name):
3,098
The `depth` of an integer `n` is defined to be how many multiples of `n` it is necessary to compute before all `10` digits have appeared at least once in some multiple. example: ``` let see n=42 Multiple value digits comment 42*1 42 2,4 42*2 84 8 ...
["def compute_depth(n):\n i = 0\n digits = set()\n while len(digits) < 10:\n i += 1\n digits.update(str(n * i))\n return i", "def compute_depth(n):\n s, i = set(str(n)), 1\n while len(s) < 10:\n i += 1\n s |= set(str(n*i))\n return i\n", "from itertools import count\n\nd...
{"fn_name": "compute_depth", "inputs": [[8], [13], [7], [25], [42], [1]], "outputs": [[12], [8], [10], [36], [9], [10]]}
introductory
https://www.codewars.com/kata/59b401e24f98a813f9000026
def compute_depth(n):
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,100
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said # Description: Given two array of integers(`arr1`,`arr2`). Your task is going to find a pair of numbers(an element in arr1, and another element in arr2), their difference...
["def max_and_min(arr1,arr2):\n diffs = [abs(x-y) for x in arr1 for y in arr2]\n return [max(diffs), min(diffs)]\n", "def max_and_min(arr1,arr2):\n max_min = [abs(y-x) for x in arr1 for y in arr2]\n \n return [max(max_min), min(max_min)]", "def max_and_min(arr1, arr2):\n return [op(a...
{"fn_name": "max_and_min", "inputs": [[[3, 10, 5], [20, 7, 15, 8]], [[3], [20]], [[3, 10, 5], [3, 10, 5]], [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]], "outputs": [[[17, 2]], [[17, 17]], [[7, 0]], [[9, 1]]]}
introductory
https://www.codewars.com/kata/583c5469977933319f000403
def max_and_min(arr1,arr2):
3,101
Given a list of unique words. Find all pairs of distinct indices (i, j) in the given list so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome. Examples: Non-string inputs should be converted to strings. Return an array of arrays containing pairs of distinct indices that form palindro...
["def palindrome_pairs(w):\n return [[i, j] for i in range(len(w)) for j in range(len(w)) if str(w[i])+str(w[j])==(str(w[i])+str(w[j]))[::-1] and i!=j]", "def is_palindrome(word):\n return word == word[::-1]\n\n\ndef palindrome_pairs(words):\n words = [str(word) for word in words]\n return [\n [i, j]\n...
{"fn_name": "palindrome_pairs", "inputs": [[["bat", "tab", "cat"]], [["dog", "cow", "tap", "god", "pat"]], [["abcd", "dcba", "lls", "s", "sssll"]], [[]], [["adgdfsh", "wertewry", "zxcbxcb", "efveyn"]], [[5, 2, "abc", true, [false]]], [[5777, "dog", "god", true, 75]]], "outputs": [[[[0, 1], [1, 0]]], [[[0, 3], [2, 4], [...
introductory
https://www.codewars.com/kata/5772ded6914da62b4b0000f8
def palindrome_pairs(words):
3,102
Johnny is a boy who likes to open and close lockers. He loves it so much that one day, when school was out, he snuck in just to play with the lockers. Each locker can either be open or closed. If a locker is closed when Johnny gets to it, he opens it, and vice versa. The lockers are numbered sequentially, starting at...
["from math import floor\n#Pretty sure this is the fastest implementation; only one square root, and sqrt(n) multiplications.\n#Plus, no booleans, because they're super slow.\nlocker_run = lambda l: [i * i for i in range(1, int(floor(l ** .5)) + 1)]", "def locker_run(lockers):\n return [n*n for n in range(1,int(lock...
{"fn_name": "locker_run", "inputs": [[1], [5], [10], [20]], "outputs": [[[1]], [[1, 4]], [[1, 4, 9]], [[1, 4, 9, 16]]]}
introductory
https://www.codewars.com/kata/55a5085c1a3d379fbb000062
def locker_run(lockers):
3,103
# Remove Duplicates You are to write a function called `unique` that takes an array of integers and returns the array with duplicates removed. It must return the values in the same order as first seen in the given array. Thus no sorting should be done, if 52 appears before 10 in the given array then it should also be ...
["from collections import OrderedDict\ndef unique(integers):\n return list(OrderedDict.fromkeys(integers))", "def unique(integers):\n l = []\n for i in integers:\n if not i in l: l.append(i)\n return l", "def unique(integers):\n ans = []\n for x in integers:\n if x not in ans:\n ...
{"fn_name": "unique", "inputs": [[[]], [[-1]], [[-1, 5, 10, -100, 3, 2]], [[1, 2, 3, 3, 2, 1, 2, 3, 1, 1, 3, 2]], [[1, 3, 2, 3, 2, 1, 2, 3, 1, 1, 3, 2]], [[3, 2, 3, 3, 2, 1, 2, 3, 1, 1, 3, 2]]], "outputs": [[[]], [[-1]], [[-1, 5, 10, -100, 3, 2]], [[1, 2, 3]], [[1, 3, 2]], [[3, 2, 1]]]}
introductory
https://www.codewars.com/kata/53e30ec0116393fe1a00060b
def unique(integers):
3,104
Santa puts all the presents into the huge sack. In order to let his reindeers rest a bit, he only takes as many reindeers with him as he is required to do. The others may take a nap. Two reindeers are always required for the sleigh and Santa himself. Additionally he needs 1 reindeer per 30 presents. As you know, Santa...
["from math import ceil\ndef reindeer(presents):\n if presents > 180: raise ValueError(\"Too many presents\")\n return ceil(presents / 30.0) + 2", "def reindeer(presents):\n assert presents <= 180\n return 2+presents//30+(1 if presents % 30 else 0)", "from math import ceil\ndef reindeer(presents):\n assert pre...
{"fn_name": "reindeer", "inputs": [[0], [1], [5], [30], [31], [60], [61], [90], [91], [120], [121], [150], [151], [180]], "outputs": [[2], [3], [3], [3], [4], [4], [5], [5], [6], [6], [7], [7], [8], [8]]}
introductory
https://www.codewars.com/kata/52ad1db4b2651f744d000394
def reindeer(presents):
3,105
If you can't sleep, just count sheep!! ## Task: Given a non-negative integer, `3` for example, return a string with a murmur: `"1 sheep...2 sheep...3 sheep..."`. Input will always be valid, i.e. no negative integers.
["def count_sheep(n):\n return ''.join(f\"{i} sheep...\" for i in range(1,n+1))", "def count_sheep(n):\n sheep=\"\"\n for i in range(1, n+1):\n sheep+=str(i) + \" sheep...\"\n return sheep", "def count_sheep(n):\n return \"\".join(\"{} sheep...\".format(i) for i in range(1, n+1))", "def count_shee...
{"fn_name": "count_sheep", "inputs": [[3]], "outputs": [["1 sheep...2 sheep...3 sheep..."]]}
introductory
https://www.codewars.com/kata/5b077ebdaf15be5c7f000077
def count_sheep(n):
3,106
You have a set of four (4) balls labeled with different numbers: ball_1 (1), ball_2 (2), ball_3 (3) and ball(4) and we have 3 equal boxes for distribute them. The possible combinations of the balls, without having empty boxes, are: ``` (1) (2) (3)(4) ______ ______ _______ ```...
["# Stirling numbers of second kind\n# http://mathworld.wolfram.com/StirlingNumberoftheSecondKind.html\n# S(n,k)=1/(k!)sum_(i=0)^k(-1)^i(k; i)(k-i)^n\nfrom math import factorial as fact\n\ndef combs_non_empty_boxes(n,k):\n if k<0 or k>n: return 'It cannot be possible!'\n return sum([1,-1][i%2]*(k-i)**n*fact(k)//(...
{"fn_name": "combs_non_empty_boxes", "inputs": [[4, 3], [4, 2], [4, 4], [4, 1], [4, 0], [4, 5], [20, 8]], "outputs": [[6], [7], [1], [1], [0], ["It cannot be possible!"], [15170932662679]]}
introductory
https://www.codewars.com/kata/5b5f7f7607a266914200007c
def combs_non_empty_boxes(n,k):
3,107
Program the function distance(p1, p2) which returns the distance between the points p1 and p2 in n-dimensional space. p1 and p2 will be given as arrays. Your program should work for all lengths of arrays, and should return -1 if the arrays aren't of the same length or if both arrays are empty sets. If you don't know ...
["def distance(p1, p2):\n return sum((a - b) ** 2 for a, b in zip(p1, p2)) ** 0.5 if len(p1) == len(p2) > 0 else -1", "def distance(p1, p2):\n from functools import reduce\n from math import hypot\n if not p1 or len(p1) != len(p2): return -1\n return reduce(hypot, (x-y for x,y in zip(p1, p2)))", "def dis...
{"fn_name": "distance", "inputs": [[[], []], [[1], [1, 1, 1, 1, 1, 1, 1, 1, 1]]], "outputs": [[-1], [-1]]}
introductory
https://www.codewars.com/kata/5a0b72484bebaefe60001867
def distance(p1, p2):
3,108
Your goal is to return multiplication table for ```number``` that is always an integer from 1 to 10. For example, a multiplication table (string) for ```number == 5``` looks like below: ``` 1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25 6 * 5 = 30 7 * 5 = 35 8 * 5 = 40 9 * 5 = 45 10 * 5 = 50 ``` P. S. You can...
["def multi_table(number):\n return '\\n'.join(f'{i} * {number} = {i * number}' for i in range(1, 11))", "def multi_table(number):\n table = [\"{0} * {1} = {2}\".format(i, number, i * number) for i in range(1, 11)]\n return '\\n'.join(table)", "def multi_table(number):\n return \"\\n\".join([\"{1} * {0} = {...
{"fn_name": "multi_table", "inputs": [[5], [1]], "outputs": [["1 * 5 = 5\n2 * 5 = 10\n3 * 5 = 15\n4 * 5 = 20\n5 * 5 = 25\n6 * 5 = 30\n7 * 5 = 35\n8 * 5 = 40\n9 * 5 = 45\n10 * 5 = 50"], ["1 * 1 = 1\n2 * 1 = 2\n3 * 1 = 3\n4 * 1 = 4\n5 * 1 = 5\n6 * 1 = 6\n7 * 1 = 7\n8 * 1 = 8\n9 * 1 = 9\n10 * 1 = 10"]]}
introductory
https://www.codewars.com/kata/5a2fd38b55519ed98f0000ce
def multi_table(number):
3,109
Background There is a message that is circulating via public media that claims a reader can easily read a message where the inner letters of each words is scrambled, as long as the first and last letters remain the same and the word contains all the letters. Another example shows that it is quite difficult to read the...
["import re\n\ndef scramble_words(words):\n def sort_letters(match):\n s = match.group()\n letters = iter(sorted(filter(str.isalpha, s[1:-1])))\n return s[0] + \"\".join(next(letters) if c.isalpha() else c for c in s[1:-1]) + s[-1]\n return re.sub(r'[a-z][^\\s]*[a-z]', sort_letters, words)", ...
{"fn_name": "scramble_words", "inputs": [["professionals"], ["i"], [""], ["me"], ["you"], ["card-carrying"], ["shan't"], ["-dcba"], ["dcba."], ["you've gotta dance like there's nobody watching, love like you'll never be hurt, sing like there's nobody listening, and live like it's heaven on earth."]], "outputs": [["paef...
introductory
https://www.codewars.com/kata/55953e906851cf2441000032
def scramble_words(words):
3,110
Each number should be formatted that it is rounded to two decimal places. You don't need to check whether the input is a valid number because only valid numbers are used in the tests. ``` Example: 5.5589 is rounded 5.56 3.3424 is rounded 3.34 ```
["def two_decimal_places(n):\n return round(n, 2)\n", "def two_decimal_places(n):\n return round(n* 100) / 100", "from decimal import Decimal, ROUND_HALF_UP\n\ndef two_decimal_places(n):\n dn = Decimal(str(n)).quantize(Decimal('.01'), rounding=ROUND_HALF_UP)\n return float(dn)\n", "def two_decimal_places(n):\n ...
{"fn_name": "two_decimal_places", "inputs": [[4.659725356], [173735326.37837327], [4.653725356]], "outputs": [[4.66], [173735326.38], [4.65]]}
introductory
https://www.codewars.com/kata/5641a03210e973055a00000d
def two_decimal_places(n):
3,111
Format any integer provided into a string with "," (commas) in the correct places. **Example:** ``` csharp Kata.NumberFormat(100000); // return "100,000" Kata.NumberFormat(5678545); // return "5,678,545" Kata.NumberFormat(-420902); // return "-420,902" ``` ``` javascript numberFormat(100000); // return '100,000' numbe...
["def number_format(n):\n return f'{n:,}'", "def number_format(n):\n return format(n, ',')", "number_format='{:,}'.format", "def number_format(n):\n return str('{:,.3f}'.format(n)).rstrip('0').rstrip('.')", "import re\n\ndef number_format(n):\n return re.sub(r'\\B(?=(\\d{3})+(?!\\d))', r',', str(n))", "numb...
{"fn_name": "number_format", "inputs": [[100000], [5678545], [-420902], [-3], [-1003]], "outputs": [["100,000"], ["5,678,545"], ["-420,902"], ["-3"], ["-1,003"]]}
introductory
https://www.codewars.com/kata/565c4e1303a0a006d7000127
def number_format(n):
3,112
# Task You are given an array of integers `arr` that representing coordinates of obstacles situated on a straight line. Assume that you are jumping from the point with coordinate 0 to the right. You are allowed only to make jumps of the same length represented by some integer. Find the minimal length of the jump e...
["def avoid_obstacles(arr):\n n=2\n while 1: \n if all([x%n for x in arr]): return n\n n+=1", "def avoid_obstacles(a):\n for j in range(2, max(a) + 2): \n if all(e % j != 0 for e in a): return j", "def avoid_obstacles(arr):\n s = set(arr)\n m = max(arr)\n for i in range(1, m+2):\n ...
{"fn_name": "avoid_obstacles", "inputs": [[[5, 3, 6, 7, 9]], [[2, 3]], [[1, 4, 10, 6, 2]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, ...
introductory
https://www.codewars.com/kata/5894045b8a8a230d0c000077
def avoid_obstacles(arr):
3,113
There are some candies that need to be distributed to some children as fairly as possible (i.e. the variance of result needs to be as small as possible), but I don't know how to distribute them, so I need your help. Your assignment is to write a function with signature `distribute(m, n)` in which `m` represents how man...
["def distribute(m, n):\n if n <= 0:\n return []\n q, r = divmod(max(m, 0), n)\n return [q + (i < r) for i in range(n)]", "def distribute(m, n):\n lst = []\n if n > 0:\n lst = [0 for i in range(n)]\n if m > 0:\n for j in range(m):\n lst[j % n] += 1\n retu...
{"fn_name": "distribute", "inputs": [[-5, 0], [10, 0], [15, 0], [-5, -5], [10, -5], [15, -5]], "outputs": [[[]], [[]], [[]], [[]], [[]], [[]]]}
introductory
https://www.codewars.com/kata/59901cd68fc658ab6c000025
def distribute(m, n):
3,114
A variation of determining leap years, assuming only integers are used and years can be negative and positive. Write a function which will return the days in the year and the year entered in a string. For example 2000, entered as an integer, will return as a string 2000 has 366 days There are a few assumptions we wi...
["def year_days(year):\n days = 365\n if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:\n days += 1\n return \"%d has %d days\" % (year, days)", "from calendar import isleap\ndef year_days(year):\n return \"{} has {} days\".format(year, isleap(year) + 365)", "def year_days(year):\n return '...
{"fn_name": "year_days", "inputs": [[0], [-64], [2016], [1974], [-10], [666], [1857], [2000], [-300], [-1]], "outputs": [["0 has 366 days"], ["-64 has 366 days"], ["2016 has 366 days"], ["1974 has 365 days"], ["-10 has 365 days"], ["666 has 365 days"], ["1857 has 365 days"], ["2000 has 366 days"], ["-300 has 365 days"]...
introductory
https://www.codewars.com/kata/56d6c333c9ae3fc32800070f
def year_days(year):
3,115
Given a square matrix (i.e. an array of subarrays), find the sum of values from the first value of the first array, the second value of the second array, the third value of the third array, and so on... ## Examples ``` array = [[1, 2], [3, 4]] diagonal sum: 1 + 4 = 5 ``` ``` array = [[5, 9,...
["def diagonal_sum(array):\n return sum(row[i] for i, row in enumerate(array))", "from numpy import trace as diagonal_sum", "def diagonal_sum(array):\n \n return sum([array[a][a] for a in range(len(array))])", "def diagonal_sum(array):\n return sum( row[idx] for idx, row in enumerate(array) )", "def diagona...
{"fn_name": "diagonal_sum", "inputs": [[[[1, 2], [3, 4]]], [[[1, 2, 3], [4, 5, 6], [7, 8, 9]]], [[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]]], "outputs": [[5], [15], [34]]}
introductory
https://www.codewars.com/kata/5497a3c181dd7291ce000700
def diagonal_sum(array):
3,116
There are several (or no) spiders, butterflies, and dragonflies. In this kata, a spider has eight legs. A dragonfly or a butterfly has six legs. A __dragonfly__ has __two__ pairs of wings, while a __butterfly__ has __one__ pair of wings. __I am not sure whether they are biologically correct, but the values apply here...
["def cal_n_bug(n_head, n_leg, n_wing):\n spider = (n_leg-n_head*6)//(8-6)\n butterfly = (n_wing-(n_head-spider))\n dragonfly = n_head-spider-butterfly\n return [spider,butterfly,dragonfly] if spider>=0 and butterfly>=0 and dragonfly>=0 else [-1,-1,-1]", "def cal_n_bug(n_head, n_leg, n_wing):\n s = (n_le...
{"fn_name": "cal_n_bug", "inputs": [[3, 20, 3]], "outputs": [[[1, 1, 1]]]}
introductory
https://www.codewars.com/kata/58cf479f87c2e967250000e4
def cal_n_bug(n_head, n_leg, n_wing):
3,117
The vowel substrings in the word `codewarriors` are `o,e,a,io`. The longest of these has a length of 2. Given a lowercase string that has alphabetic characters only (both vowels and consonants) and no spaces, return the length of the longest vowel substring. Vowels are any of `aeiou`. ```if:csharp Documentation: Kat...
["def solve(s):\n return max(map(len, ''.join(c if c in 'aeiou' else ' ' for c in s).split()))", "import re\n\ndef solve(s):\n return max(len(x.group(0)) for x in re.finditer(r'[aeiou]+', s))", "from re import findall\n\ndef solve(s):\n return max(map(len, findall(\"[aeiou]+\", s)))", "def solve(s):\n vowel...
{"fn_name": "solve", "inputs": [["codewarriors"], ["suoidea"], ["ultrarevolutionariees"], ["strengthlessnesses"], ["cuboideonavicuare"], ["chrononhotonthuooaos"], ["iiihoovaeaaaoougjyaw"]], "outputs": [[2], [3], [3], [1], [2], [5], [8]]}
introductory
https://www.codewars.com/kata/59c5f4e9d751df43cf000035
def solve(s):
3,118
###Lucky number Write a function to find if a number is lucky or not. If the sum of all digits is 0 or multiple of 9 then the number is lucky. `1892376 => 1+8+9+2+3+7+6 = 36`. 36 is divisble by 9, hence number is lucky. Function will return `true` for lucky numbers and `false` for others.
["def is_lucky(n):\n return n % 9 == 0", "def is_lucky(n):\n sume=0\n for i in str(n):\n sume+=int(i)\n return True if sume%9==0 else False ", "def is_lucky(n):\n digits = list(str(n))\n return sum(list(map(int, digits)))%9==0", "def is_lucky(n):\n return sum([int(i) for i in str(n)]) % ...
{"fn_name": "is_lucky", "inputs": [[1892376], [189237], [18922314324324234423437], [189223141324324234423437], [1892231413243242344321432142343423437], [0]], "outputs": [[true], [false], [false], [true], [true], [true]]}
introductory
https://www.codewars.com/kata/55afed09237df73343000042
def is_lucky(n):
3,119
< PREVIOUS KATA NEXT KATA > ## Task: You have to write a function `pattern` which returns the following Pattern(See Examples) upto desired number of rows. * Note:`Returning` the pattern is not the same as `Printing` the pattern. ## Parameters: pattern( n , y ); ...
["def pattern(n, *y):\n if n < 1:\n return \"\"\n y = y[0] if y and y[0] > 0 else 1\n result = []\n for j in range(1, n + 1):\n line = \" \" * (j - 1) + str(j % 10) + \" \" * (n - j)\n result.append(line + line[::-1][1:])\n return \"\\n\".join(((result + result[::-1][1:-1]) * y)) + \...
{"fn_name": "pattern", "inputs": [[0]], "outputs": [[""]]}
introductory
https://www.codewars.com/kata/559379505c859be5a9000034
def pattern(n, y=1, *_):
3,120
So you've found a meeting room - phew! You arrive there ready to present, and find that someone has taken one or more of the chairs!! You need to find some quick.... check all the other meeting rooms to see if all of the chairs are in use. Your meeting room can take up to 8 chairs. `need` will tell you how many have b...
["def meeting(rooms, need):\n if need == 0: return \"Game On\"\n \n result = []\n for people, chairs in rooms:\n taken = min(max(chairs - len(people), 0), need)\n result.append(taken)\n need -= taken\n if need == 0: return result\n \n return \"Not enough!\"", "def meeti...
{"fn_name": "meeting", "inputs": [[[["XXX", 3], ["XXXXX", 6], ["XXXXXX", 9]], 4], [[["XXX", 1], ["XXXXXX", 6], ["X", 2], ["XXXXXX", 8], ["X", 3], ["XXX", 1]], 5], [[["XX", 2], ["XXXX", 6], ["XXXXX", 4]], 0], [[["XX", 2], ["XXXX", 6], ["XXXXX", 4]], 8], [[["XX", 2], ["XXXX", 6], ["XXXXX", 4]], 2]], "outputs": [[[0, 1, 3...
introductory
https://www.codewars.com/kata/57f6051c3ff02f3b7300008b
def meeting(rooms, number):
3,121
In this Kata, you will be given an array of integers whose elements have both a negative and a positive value, except for one integer that is either only negative or only positive. Your task will be to find that integer. Examples: `[1, -1, 2, -2, 3] => 3` `3` has no matching negative appearance `[-3, 1, 2, 3, -1, ...
["def solve(arr): return sum(set(arr))\n", "def solve(arr):\n for a in arr:\n if -a not in arr:\n return a\n", "def solve(a):\n return sum(set(a))", "def solve(arr):\n return [i for i in arr if -i not in arr][0]", "\ndef solve(arr):\n for n in arr:\n if -n not in arr: return n\n", "...
{"fn_name": "solve", "inputs": [[[1, -1, 2, -2, 3]], [[-3, 1, 2, 3, -1, -4, -2]], [[1, -1, 2, -2, 3, 3]], [[-110, 110, -38, -38, -62, 62, -38, -38, -38]], [[-9, -105, -9, -9, -9, -9, 105]]], "outputs": [[3], [-4], [3], [-38], [-9]]}
introductory
https://www.codewars.com/kata/5a092d9e46d843b9db000064
def solve(arr):
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,123
Write a function that returns the count of characters that have to be removed in order to get a string with no consecutive repeats. *Note:* This includes any characters ## Examples ```python 'abbbbc' => 'abc' # answer: 3 'abbcca' => 'abca' # answer: 2 'ab cca' => 'ab ca' # answer: 1 ```
["from itertools import groupby\ndef count_repeats(s):\n return len(s) - len(list(groupby(s)))", "def count_repeats(str):\n return sum(a == b for a, b in zip(str, str[1:]))", "from itertools import groupby\n\ndef count_repeats(txt):\n return len(txt) - sum(1 for _ in groupby(txt))", "import re\n\ndef count_rep...
{"fn_name": "count_repeats", "inputs": [["abcdefg"], ["aabbccddeeffgg"], ["abcdeefee"], ["122453124"], ["@*$##^^^*)*"], ["abmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmvxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxaaaaaaaaaaaaaaa...
introductory
https://www.codewars.com/kata/598ee7b6ec6cb90dd6000061
def count_repeats(txt):
3,124
Write a method named `getExponent(n,p)` that returns the largest integer exponent `x` such that p^(x) evenly divides `n`. if `p<=1` the method should return `null`/`None` (throw an `ArgumentOutOfRange` exception in C#).
["def get_exponent(n, p):\n if p > 1:\n x = 0\n while not n % p:\n x += 1\n n //= p\n return x", "def get_exponent(n, p, i = 0):\n if p <= 1: return None\n return get_exponent(n / p, p, i + 1) if n / p == n // p else i", "from itertools import count\n\ndef get_exponen...
{"fn_name": "get_exponent", "inputs": [[27, 3]], "outputs": [[3]]}
introductory
https://www.codewars.com/kata/59b139d69c56e8939700009d
def get_exponent(n, p):
3,125
In this Kata, you will be given a number `n` (`n > 0`) and your task will be to return the smallest square number `N` (`N > 0`) such that `n + N` is also a perfect square. If there is no answer, return `-1` (`nil` in Clojure, `Nothing` in Haskell, `None` in Rust). ```clojure solve 13 = 36 ; because 36 is the smalles...
["def solve(n):\n for i in range(int(n**0.5), 0, -1):\n x = n - i**2\n if x > 0 and x % (2*i) == 0:\n return ((n - i ** 2) // (2 * i)) ** 2\n return -1", "def solve(n):\n#Imagine a table, 1 to n on the top, and 1 to n on the side.\n#The contents of the table are the difference between the...
{"fn_name": "solve", "inputs": [[1], [2], [3], [4], [5], [7], [8], [9], [10], [11], [13], [17], [88901], [290101]], "outputs": [[-1], [-1], [1], [-1], [4], [9], [1], [16], [-1], [25], [36], [64], [5428900], [429235524]]}
introductory
https://www.codewars.com/kata/5edc8c53d7cede0032eb6029
def solve(n):
3,126
# Task Given a string `s`, find out if its characters can be rearranged to form a palindrome. # Example For `s = "aabb"`, the output should be `true`. We can rearrange `"aabb"` to make `"abba"`, which is a palindrome. # Input/Output - `[input]` string `s` A string consisting of lowercase English letters....
["def palindrome_rearranging(s):\n return sum(s.count(c) % 2 for c in set(s)) < 2", "from collections import Counter\n\ndef palindrome_rearranging(s):\n return sum(n % 2 for n in Counter(s).values()) <= 1", "def palindrome_rearranging(s):\n d = {}\n c = 0\n for x in s:\n if x not in d:\n ...
{"fn_name": "palindrome_rearranging", "inputs": [["aabb"], ["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaabc"], ["abbcabb"], ["zyyzzzzz"], ["aaabbb"]], "outputs": [[true], [false], [true], [true], [false]]}
introductory
https://www.codewars.com/kata/5893fa478a8a23ef82000031
def palindrome_rearranging(s):
3,127
You should write a function that takes a string and a positive integer `n`, splits the string into parts of length `n` and returns them in an array. It is ok for the last element to have less than `n` characters. If `n` is not a valid size (`> 0`) (or is absent), you should return an empty array. If `n` is greater th...
["def string_chunk(string, n=0):\n return [string[i:i+n] for i in range(0,len(string), n)] if isinstance(n, int) and n > 0 else []\n", "def string_chunk(s, n=0):\n if not isinstance(n, int) or n == 0:\n return []\n return [s[i:i+n] for i in range(0, len(s), n)]", "def string_chunk(string, n=None):\n ...
{"fn_name": "string_chunk", "inputs": [["codewars", 2]], "outputs": [[["co", "de", "wa", "rs"]]]}
introductory
https://www.codewars.com/kata/55b4f9906ac454650900007d
def string_chunk(string, n=0):
3,128
# Task A media access control address (MAC address) is a unique identifier assigned to network interfaces for communications on the physical network segment. The standard (IEEE 802) format for printing MAC-48 addresses in human-friendly form is six groups of two hexadecimal digits (0 to 9 or A to F), separated by hy...
["import re\ndef is_mac_48_address(address):\n return bool(re.match(\"^([0-9A-F]{2}[-]){5}([0-9A-F]{2})$\", address.upper()))", "def is_mac_48_address(address):\n chunks = address.split('-')\n for chunk in chunks:\n try:\n int(chunk, 16)\n except ValueError:\n return False\n ...
{"fn_name": "is_mac_48_address", "inputs": [["00-1B-63-84-45-E6"], ["Z1-1B-63-84-45-E6"], ["not a MAC-48 address"], ["FF-FF-FF-FF-FF-FF"], ["00-00-00-00-00-00"], ["G0-00-00-00-00-00"], ["12-34-56-78-9A-BC"], ["02-03-04-05-06-07-"], ["02-03-04-05"], ["02-03-04-FF-00-F0"]], "outputs": [[true], [false], [false], [true], [...
introductory
https://www.codewars.com/kata/5886faac54a7111c21000072
def is_mac_48_address(address):
3,129
A trick I learned in elementary school to determine whether or not a number was divisible by three is to add all of the integers in the number together and to divide the resulting sum by three. If there is no remainder from dividing the sum by three, then the original number is divisible by three as well. Given a seri...
["def divisible_by_three(s): \n return int(s) % 3 == 0\n\n", "def divisible_by_three(st):\n return (sum([int(i) for i in st]) % 3) == 0\n", "def divisible_by_three(st): \n return sum([int(c) for c in st]) % 3 == 0", "import re\ndef divisible_by_three(st):\n return re.match(\"(((((0|3)|6)|9)|((2|5)|8)((((0|3...
{"fn_name": "divisible_by_three", "inputs": [["123"], ["19254"], ["88"], ["1"], ["963210456"], ["10110101011"], ["9"], ["6363"], ["10987654321"], ["9876543211234567890009"], ["9876543211234567890002"]], "outputs": [[true], [true], [false], [false], [true], [false], [true], [true], [false], [true], [false]]}
introductory
https://www.codewars.com/kata/59f7fc109f0e86d705000043
def divisible_by_three(st):
3,130
In this kata you need to build a function to return either `true/True` or `false/False` if a string can be seen as the repetition of a simpler/shorter subpattern or not. For example: ```cpp,java hasSubpattern("a") == false; //no repeated pattern hasSubpattern("aaaa") == true; //created repeating "a" hasSubpattern("ab...
["def has_subpattern(string):\n return (string * 2).find(string, 1) != len(string)", "import re\n\ndef has_subpattern(string):\n return bool(re.match(r'(.+)\\1+$', string))", "def has_subpattern(string):\n s = len(string)\n for i in range(1,s//2+1):\n if s % i == 0:\n q = s//i\n ...
{"fn_name": "has_subpattern", "inputs": [["a"], ["aaaa"], ["abcd"], ["abababab"], ["ababababa"], ["123a123a123a"], ["123A123a123a"], ["abbaabbaabba"], ["abbabbabba"], ["abcdabcabcd"]], "outputs": [[false], [true], [false], [true], [false], [true], [false], [true], [false], [false]]}
introductory
https://www.codewars.com/kata/5a49f074b3bfa89b4c00002b
def has_subpattern(string):
3,131
# Task Let's call `product(x)` the product of x's digits. Given an array of integers a, calculate `product(x)` for each x in a, and return the number of distinct results you get. # Example For `a = [2, 8, 121, 42, 222, 23]`, the output should be `3`. Here are the products of the array's elements: ``` 2: product(2...
["from operator import mul\nfrom functools import reduce\n\n\ndef unique_digit_products(nums):\n return len({reduce(mul, (int(a) for a in str(num))) for num in nums})\n", "from functools import reduce\nfrom operator import mul\n\ndef unique_digit_products(a):\n return len({reduce(mul, map(int, str(x))) for x in a...
{"fn_name": "unique_digit_products", "inputs": [[[2, 8, 121, 42, 222, 23]], [[239]], [[100, 101, 111]], [[100, 23, 42, 239, 22339, 9999999, 456, 78, 228, 1488]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]]], "outputs": [[3], [1], [2], [10], [10]]}
introductory
https://www.codewars.com/kata/5897d94dd07028546c00009d
def unique_digit_products(a):
3,132
Write a function ```python alternate_sort(l) ``` that combines the elements of an array by sorting the elements ascending by their **absolute value** and outputs negative and non-negative integers alternatingly (starting with the negative value, if any). E.g. ```python alternate_sort([5, -42, 2, -3, -4, 8, -9,]) == [-...
["from itertools import chain, zip_longest\n\ndef alternate_sort(l):\n l=sorted(l,key=abs)\n p,n=[n for n in l if n>=0],[n for n in l if n<0]\n return [n for n in chain(*zip_longest(n,p)) if n is not None]", "def alternate_sort(l):\n a = sorted([i for i in l if i >= 0])[::-1]\n b = sorted([i for i in l i...
{"fn_name": "alternate_sort", "inputs": [[[5, 2, -3, -9, -4, 8]], [[5, -42, 2, -3, -4, 8, 9]], [[5, -42, 8, 2, -3, -4, 9]], [[5, -42, -8, 2, -3, -4, -9]], [[5, 2, 3, 4, 8, 9]], [[-5, -2, -3, -4, -8, -9]], [[-5, -2, 3, 4, -8, 0, -9]], [[-5, -2, 3, 9, 4, -2, -8, 0, 9, -9]]], "outputs": [[[-3, 2, -4, 5, -9, 8]], [[-3, 2, ...
introductory
https://www.codewars.com/kata/5ac49156376b11767f00060c
def alternate_sort(l):
3,133
### Vaccinations for children under 5 You have been put in charge of administrating vaccinations for children in your local area. Write a function that will generate a list of vaccines for each child presented for vaccination, based on the child's age and vaccination history, and the month of the year. #### The functio...
["from itertools import chain\n\nTOME = {\n '8 weeks': ['fiveInOne', 'pneumococcal', 'rotavirus', 'meningitisB'],\n '12 weeks': ['fiveInOne', 'rotavirus'],\n '16 weeks': ['fiveInOne', 'pneumococcal', 'meningitisB'],\n '12 months': ['meningitisB', 'hibMenC', 'measlesMumpsRubella'],\n '40 months': ['me...
{"fn_name": "vaccine_list", "inputs": [["12 weeks", "up-to-date", "december"], ["12 months", "16 weeks", "june"], ["40 months", "12 months", "october"]], "outputs": [[["fiveInOne", "rotavirus"]], [["fiveInOne", "hibMenC", "measlesMumpsRubella", "meningitisB", "pneumococcal"]], [["hibMenC", "measlesMumpsRubella", "menin...
introductory
https://www.codewars.com/kata/577d0a117a3dbd36170001c2
def vaccine_list(age, status, month):
3,134
Given a string, determine if it's a valid identifier. ## Here is the syntax for valid identifiers: * Each identifier must have at least one character. * The first character must be picked from: alpha, underscore, or dollar sign. The first character cannot be a digit. * The rest of the characters (besides the first) ca...
["import re\n\ndef is_valid(idn):\n return re.compile('^[a-z_\\$][a-z0-9_\\$]*$', re.IGNORECASE).match(idn) != None", "import re\nis_valid = lambda id: bool(re.match('^[a-z_$][\\w$]*$', id, re.I))", "import re\n\ndef is_valid(identifier):\n return bool(re.fullmatch(r\"[a-z_$][\\w$]*\", identifier, flags=re.IGNORE...
{"fn_name": "is_valid", "inputs": [["okay_ok1"], ["$ok"], ["___"], ["str_STR"], ["myIdentf"], ["1ok0okay"], ["!Ok"], [""], ["str-str"], ["no no"]], "outputs": [[true], [true], [true], [true], [true], [false], [false], [false], [false], [false]]}
introductory
https://www.codewars.com/kata/563a8656d52a79f06c00001f
def is_valid(idn):
3,135
Two moving objects A and B are moving accross the same orbit (those can be anything: two planets, two satellites, two spaceships,two flying saucers, or spiderman with batman if you prefer). If the two objects start to move from the same point and the orbit is circular, write a function that gives the time the two objec...
["def meeting_time(Ta, Tb, r):\n if Ta == 0:\n return \"{:.2f}\".format(abs(Tb))\n elif Tb == 0:\n return \"{:.2f}\".format(abs(Ta))\n else:\n return \"{:.2f}\".format(abs(Ta * Tb / (Tb - Ta)))", "def meeting_time(Ta, Tb, r):\n return str(abs(Tb))+'.00' if Ta == 0 else str(abs(Ta))+'.00...
{"fn_name": "meeting_time", "inputs": [[12, 15, 5], [12, -15, 6], [-14, -5, 5], [23, 16, 5], [0, 0, 7], [12, 0, 10], [0, 15, 17], [-24, 0, 10], [0, -18, 14], [32, -14, 14]], "outputs": [["60.00"], ["6.67"], ["7.78"], ["52.57"], ["0.00"], ["12.00"], ["15.00"], ["24.00"], ["18.00"], ["9.74"]]}
introductory
https://www.codewars.com/kata/58dc420210d162048a000085
def meeting_time(Ta, Tb, r):
3,136
- Kids drink toddy. - Teens drink coke. - Young adults drink beer. - Adults drink whisky. Make a function that receive age, and return what they drink. **Rules:** - Children under 14 old. - Teens under 18 old. - Young under 21 old. - Adults have 21 or more. **Examples:** ```python people_with_age_drink(13) == "dri...
["def people_with_age_drink(age):\n if age > 20: return 'drink whisky'\n if age > 17: return 'drink beer'\n if age > 13: return 'drink coke'\n return 'drink toddy'", "def people_with_age_drink(age):\n if age <= 13:\n beverage = 'toddy'\n elif age > 13 and age <= 17:\n beverage = 'coke'\n...
{"fn_name": "people_with_age_drink", "inputs": [[13], [0], [17], [15], [14], [20], [18], [22], [21]], "outputs": [["drink toddy"], ["drink toddy"], ["drink coke"], ["drink coke"], ["drink coke"], ["drink beer"], ["drink beer"], ["drink whisky"], ["drink whisky"]]}
introductory
https://www.codewars.com/kata/56170e844da7c6f647000063
def people_with_age_drink(age):
3,137
From this lesson, we learn about JS static object: ```Math```. It mainly helps us to carry out mathematical calculations. It has a lot of properties and methods. Some of the properties and methods we rarely used. So we only learn some common methods. The properties of the Math object are some constants, such as PI, on...
["from math import ceil\n\ndef round_it(n):\n left, right = (len(part) for part in str(n).split(\".\"))\n return ceil(n) if left < right else int(n) if left > right else round(n)", "from math import floor, ceil\n\ndef round_it(n):\n l, r = [len(x) for x in str(n).split('.')]\n if r > l:\n return ceil...
{"fn_name": "round_it", "inputs": [[3.45], [34.5], [34.56]], "outputs": [[4], [34], [35]]}
introductory
https://www.codewars.com/kata/5732d3c9791aafb0e4001236
def round_it(n):
3,138
For every positive integer N, there exists a unique sequence starting with 1 and ending with N and such that every number in the sequence is either the double of the preceeding number or the double plus 1. For example, given N = 13, the sequence is [1, 3, 6, 13], because . . . : ``` 3 = 2*1 +1 6 = 2*3 13 = 2*6 +...
["def climb(n):\n return [1] if n == 1 else climb(int(n/2)) + [n]", "# If we write the decision tree for the problem we can see\n# that we can traverse upwards from any node simply by\n# dividing by two and taking the floor. This would require\n# a reversal of the list generated since we're building it\n# backwards....
{"fn_name": "climb", "inputs": [[1], [100], [12345], [54321]], "outputs": [[[1]], [[1, 3, 6, 12, 25, 50, 100]], [[1, 3, 6, 12, 24, 48, 96, 192, 385, 771, 1543, 3086, 6172, 12345]], [[1, 3, 6, 13, 26, 53, 106, 212, 424, 848, 1697, 3395, 6790, 13580, 27160, 54321]]]}
introductory
https://www.codewars.com/kata/559760bae64c31556c00006b
def climb(n):
3,139
This kata is from check py.checkio.org You are given an array with positive numbers and a number N. You should find the N-th power of the element in the array with the index N. If N is outside of the array, then return -1. Don't forget that the first element has the index 0. Let's look at a few examples: * array = [...
["def index(array, n):\n try:\n return array[n]**n\n except:\n return -1", "def index(array, n):\n return array[n]**n if n < len(array) else -1", "def index(array, n):\n try:\n return pow(array[n],n)\n except IndexError:\n return -1", "def index(array, n):\n if n < len(arra...
{"fn_name": "index", "inputs": [[[1, 2, 3, 4], 2], [[1, 3, 10, 100], 3], [[0, 1], 0], [[0, 1], 1], [[1, 2], 2], [[1, 2], 3], [[0], 0], [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 9], [[1, 1, 1, 1, 1, 1, 1, 1, 1, 100], 9], [[29, 82, 45, 10], 3], [[6, 31], 3], [[75, 68, 35, 61, 9, 36, 89, 0, 30], 10]], "outputs": [[9], [1000000], [...
introductory
https://www.codewars.com/kata/57d814e4950d8489720008db
def index(array, n):
3,140
Math geeks and computer nerds love to anthropomorphize numbers and assign emotions and personalities to them. Thus there is defined the concept of a "happy" number. A happy number is defined as an integer in which the following sequence ends with the number 1. * Start with the number itself. * Calculate the sum of the...
["def is_happy(n):\n seen = set()\n while n not in seen:\n seen.add(n)\n n = sum( int(d)**2 for d in str(n) )\n return n == 1\n\n\ndef happy_numbers(n): \n return [x for x in range(1, n+1) if is_happy(x)]", "# Code reuse: https://www.codewars.com/kata/reviews/5ac53889cd661be6ee0013ff/groups...
{"fn_name": "happy_numbers", "inputs": [[10], [50], [100]], "outputs": [[[1, 7, 10]], [[1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49]], [[1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100]]]}
introductory
https://www.codewars.com/kata/59d53c3039c23b404200007e
def happy_numbers(n):
3,141
# Task John is an orchard worker. There are `n` piles of fruits waiting to be transported. Each pile of fruit has a corresponding weight. John's job is to combine the fruits into a pile and wait for the truck to take them away. Every time, John can combine any two piles(`may be adjacent piles, or not`), and the ener...
["from heapq import heappop, heappush\n\ndef comb(fruits):\n total, heap = 0, sorted(fruits)\n while len(heap) > 1:\n cost = heappop(heap) + heappop(heap)\n heappush(heap, cost)\n total += cost\n return total", "import bisect\nfrom collections import deque\ndef comb(fruits):\n energy = ...
{"fn_name": "comb", "inputs": [[[1, 2, 9]], [[100]], [[1, 2]], [[4, 3, 5, 6, 10, 20]], [[87, 84, 42, 34, 24, 81, 60, 48, 75]], [[11, 9, 20, 10, 21, 35, 15, 34, 48, 76, 94, 28, 79, 16, 4, 41, 98, 30, 35, 92, 93, 33, 100, 93, 64, 23, 37, 6, 86, 27, 48, 16, 66, 99, 61, 83, 3, 5, 95]]], "outputs": [[15], [0], [3], [111], [...
introductory
https://www.codewars.com/kata/5c2ab63b1debff404a46bd12
def comb(fruits):
3,142
Write a function that removes every lone 9 that is inbetween 7s. ```python seven_ate9('79712312') => '7712312' seven_ate9('79797') => '777' ``` Input: String Output: String
["def seven_ate9(str_):\n while str_.find('797') != -1:\n str_ = str_.replace('797','77')\n return str_", "import re\n\ndef seven_ate9(str_):\n return re.sub(r'79(?=7)', r'7', str_)", "def seven_ate9(str_):\n while \"797\" in str_:\n str_ = str_.replace(\"797\", \"77\")\n return str_", "def se...
{"fn_name": "seven_ate9", "inputs": [["165561786121789797"], ["797"], ["7979797"], ["16797"], ["77"], ["7927"], ["1779"], ["a779"], ["17797a"], ["797 9 7"]], "outputs": [["16556178612178977"], ["77"], ["7777"], ["1677"], ["77"], ["7927"], ["1779"], ["a779"], ["1777a"], ["77 9 7"]]}
introductory
https://www.codewars.com/kata/559f44187fa851efad000087
def seven_ate9(str_):
3,143
# Hey You ! Sort these integers for me ... By name ... Do it now ! --- ## Input * Range is ```0```-```999``` * There may be duplicates * The array may be empty ## Example * Input: 1, 2, 3, 4 * Equivalent names: "one", "two", "three", "four" * Sorted by name: "four", "one", "three", "two" * Output: 4, 1, 3, 2...
["def int_to_word(num):\n d = { 0 : 'zero', 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five',\n 6 : 'six', 7 : 'seven', 8 : 'eight', 9 : 'nine', 10 : 'ten',\n 11 : 'eleven', 12 : 'twelve', 13 : 'thirteen', 14 : 'fourteen',\n 15 : 'fifteen', 16 : 'sixteen', 17 : 'seventeen', 18 : '...
{"fn_name": "sort_by_name", "inputs": [[[0, 1, 2, 3]], [[]], [[8, 8, 9, 9, 10, 10]], [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]], [[99, 100, 200, 300, 999]], [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 3...
introductory
https://www.codewars.com/kata/56f4ff45af5b1f8cd100067d
def sort_by_name(arr):
3,144
Pair of gloves ============= Winter is coming, you must prepare your ski holidays. The objective of this kata is to determine the number of pair of gloves you can constitute from the gloves you have in your drawer. A pair of gloves is constituted of two gloves of the same color. You are given an array containing the...
["from collections import Counter\n\ndef number_of_pairs(gloves):\n return sum(c // 2 for c in Counter(gloves).values())", "def number_of_pairs(gloves):\n return sum(gloves.count(color)//2 for color in set(gloves))", "def number_of_pairs(gloves):\n unique = set(gloves)\n return sum(gloves.count(i)//2 for i ...
{"fn_name": "number_of_pairs", "inputs": [[["red", "red"]], [["red", "green", "blue"]], [["gray", "black", "purple", "purple", "gray", "black"]], [[]], [["red", "green", "blue", "blue", "red", "green", "red", "red", "red"]]], "outputs": [[1], [0], [3], [0], [4]]}
introductory
https://www.codewars.com/kata/58235a167a8cb37e1a0000db
def number_of_pairs(gloves):
3,145
Make a function that will return a greeting statement that uses an input; your program should return, `"Hello, how are you doing today?"`. SQL: return results in a column named ```greeting``` *[Make sure you type the exact thing I wrote or the program may not execute properly]*
["def greet(name):\n return \"Hello, {} how are you doing today?\".format(name)", "def greet(name):\n return f'Hello, {name} how are you doing today?'", "def greet(name):\n return \"Hello, %s how are you doing today?\" % name", "def greet(name):\n return \"Hello, \" + name + \" how are you doing today?\"", ...
{"fn_name": "greet", "inputs": [["Ryan"], ["Shingles"]], "outputs": [["Hello, Ryan how are you doing today?"], ["Hello, Shingles how are you doing today?"]]}
introductory
https://www.codewars.com/kata/55a70521798b14d4750000a4
def greet(name):
3,146
Unicode Transformation Format – 8-bit As the name suggests UTF-8 was designed to encode data in a stream of bytes. It works by splitting the bits up in multiples of eight. This is achieved by inserting headers to mark in how many bytes the bits were split. If the bits need to be split in two, the header `110` is added...
["from textwrap import wrap\n\ndef to_utf8_binary(string):\n return ''.join(format(x, 'b').rjust(8, '0') for x in bytearray(string, 'utf-8'))\n \ndef from_utf8_binary(bitstring):\n return bytearray([int(t, 2) for t in wrap(bitstring, 8)]).decode()\n", "def to_utf8_binary(string):\n return ''.join('{:08b}'.form...
{"fn_name": "to_utf8_binary", "inputs": [["\u0080"], ["\u07ff"], ["\u0800"], ["\uffff"]], "outputs": [["1100001010000000"], ["1101111110111111"], ["111000001010000010000000"], ["111011111011111110111111"]]}
introductory
https://www.codewars.com/kata/5f5fffc4f6b3390029a6b277
def to_utf8_binary(string):
3,147
*This is the advanced version of the [Total Primes](https://www.codewars.com/kata/total-primes/) kata.* --- The number `23` is the smallest prime that can be "cut" into **multiple** primes: `2, 3`. Another such prime is `6173`, which can be cut into `61, 73` or `617, 3` or `61, 7, 3` (all primes). A third one is `557...
["import numpy as np\nfrom itertools import accumulate\ndef sieve_primes(n):\n sieve = np.ones(n // 2, dtype = np.bool)\n limit = 1 + int(n ** 0.5)\n\n for a in range(3, limit, 2):\n if sieve[a // 2]:\n sieve[a * a // 2::a] = False\n\n prime_indexes = 2 * np.nonzero(sieve)[0].astype(int) +...
{"fn_name": "total_primes", "inputs": [[10, 100], [500, 600], [23, 37], [0, 20], [113, 197], [199, 299], [1, 2273], [11703, 13330], [312232, 312311], [967335, 967871]], "outputs": [[[23, 37, 53, 73]], [[523, 541, 547, 557, 571, 577, 593]], [[23, 37]], [[]], [[113, 137, 173, 193, 197]], [[211, 223, 227, 229, 233, 241, 2...
introductory
https://www.codewars.com/kata/5d2351b313dba8000eecd5ee
def total_primes(a, b):
3,148
# Story John found a path to a treasure, and while searching for its precise location he wrote a list of directions using symbols `"^"`, `"v"`, `"<"`, `">"` which mean `north`, `east`, `west`, and `east` accordingly. On his way John had to try many different paths, sometimes walking in circles, and even missing the tr...
["def simplify(p):\n new_p=[(0,0)]\n new_str=''\n x=0\n y=0\n for i in p:\n if i == '<':\n x-=1\n elif i == '>':\n x+=1\n elif i == '^':\n y+=1\n elif i == 'v':\n y-=1\n if (x,y) not in new_p:\n new_p.append((x,y))\...
{"fn_name": "simplify", "inputs": [["<>>"], [""], ["v>^<"], [">>>>"], ["^>>>>v"], ["<^^>v<^^^"], ["<^>>v<"], ["<^<<^^>>vv<<<>^^^v^"], ["v<<<<<^^^^^v>v>v>v>v>>"], [">^>^>^>^>^>^>v>v>v>v>v>v>v>v<"], ["^^^>>>>>>^^^<<<vvv<<<vvv"], ["^^^>>>>>>^^^<<<vvv<<<vv"], [">vv<<<^^^^>>>>>vvvvvv<<<<<<^^^^^^^^>>>>vv"], [">vv<<<^^^^>>>>>...
introductory
https://www.codewars.com/kata/56bcafba66a2ab39e6001226
def simplify(path):
3,149
The sports centre needs repair. Vandals have been kicking balls so hard into the roof that some of the tiles have started sticking up. The roof is represented by r. As a quick fix, the committee have decided to place another old roof over the top, if they can find one that fits. This is your job. A 'new' roof (f) wil...
["def roof_fix(new, old):\n return all(patch == ' ' for patch, tile in zip(new, old) if tile in '\\/')", "def roof_fix(f, r):\n return all(x == ' ' or y == '_' for x,y in zip(f, r))", "def roof_fix(f,r):\n return all(b == ' ' for a, b in zip(r, f) if a in '\\//')", "def roof_fix(f,r):\n return all(b not in ...
{"fn_name": "roof_fix", "inputs": [[" l f l k djmi k", "___\\_____//_____/_"], [" ikm il h llmmc a i", "__\\_______________________"], [" h c ", "__/____"], ["q h", "_/_"], [" cg dg em lfh cdam", "_______/____\\_____/_/"]], "outputs": [[false], [true], [true], [true], [false]]}
introductory
https://www.codewars.com/kata/57d15a03264276aaf000007f
def roof_fix(f,r):
3,150
## Task Implement a function which finds the numbers less than `2`, and the indices of numbers greater than `1` in the given sequence, and returns them as a pair of sequences. Return a nested array or a tuple depending on the language: * The first sequence being only the `1`s and `0`s from the original sequence. *...
["def binary_cleaner(seq): \n res = ([], [])\n for i,x in enumerate(seq):\n if x < 2: res[0].append(x)\n else: res[1].append(i)\n return res", "def binary_cleaner(lst):\n return [n for n in lst if n < 2], [i for i, n in enumerate(lst) if n > 1]", "def binary_cleaner(seq): \n return list(fil...
{"fn_name": "binary_cleaner", "inputs": [[[0, 1, 2, 1, 0, 2, 1, 1, 1, 0, 4, 5, 6, 2, 1, 1, 0]], [[0, 1, 1, 2, 0]], [[2, 2, 0]], [[0, 1, 2, 1, 0, 2, 1, 1]], [[1]], [[3, 0, 7, 0, 2, 0]]], "outputs": [[[[0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0], [2, 5, 10, 11, 12, 13]]], [[[0, 1, 1, 0], [3]]], [[[0], [0, 1]]], [[[0, 1, 1, 0, 1, 1...
introductory
https://www.codewars.com/kata/5b5097324a317afc740000fe
def binary_cleaner(seq):
3,151
Your task is to return the number of visible dots on a die after it has been rolled(that means the total count of dots that would not be touching the table when rolled) 6, 8, 10, 12, 20 sided dice are the possible inputs for "numOfSides" topNum is equal to the number that is on top, or the number that was rolled. f...
["def totalAmountVisible(topNum, numOfSides):\n return numOfSides*(numOfSides+1)/2-(numOfSides-topNum+1)\n", "totalAmountVisible=lambda n,s:s*~-s//2-1+n", "def totalAmountVisible(top, sides):\n return sides * (sides + 1 ) / 2 + top - sides - 1", "def totalAmountVisible(topNum, numOfSides):\n return numOfSides*...
{"fn_name": "totalAmountVisible", "inputs": [[5, 6], [19, 20], [6, 20], [15, 20], [8, 20], [9, 8], [4, 10], [12, 12], [7, 10], [4, 12]], "outputs": [[19], [208], [195], [204], [197], [36], [48], [77], [51], [69]]}
introductory
https://www.codewars.com/kata/5a39724945ddce2223000800
def totalAmountVisible(topNum, numOfSides):
3,152
# Task: This kata asks you to make a custom esolang interpreter for the language [MiniBitMove](https://esolangs.org/wiki/MiniBitMove). MiniBitMove has only two commands and operates on a array of bits. It works like this: - `1`: Flip the bit at the current cell - `0`: Move selector by 1 It takes two inputs, the progr...
["from itertools import cycle\ndef interpreter(tape, array):\n idx, result = 0, list(map(int, array))\n for cmd in cycle(map(int, tape)):\n if idx == len(array): break\n if cmd: result[idx] = 1-result[idx]\n else: idx += 1\n return ''.join(map(str, result))", "def interpreter(tape, code): ...
{"fn_name": "interpreter", "inputs": [["10", "1100101"], ["100", "1111111111"], ["110", "1010"], ["0", "100010001"], ["101010", "111"]], "outputs": [["0011010"], ["0101010101"], ["1010"], ["100010001"], ["000"]]}
introductory
https://www.codewars.com/kata/587c0138110b20624e000253
def interpreter(tape, array):
3,153
Let's imagine we have a popular online RPG. A player begins with a score of 0 in class E5. A1 is the highest level a player can achieve. Now let's say the players wants to rank up to class E4. To do so the player needs to achieve at least 100 points to enter the qualifying stage. Write a script that will check to see...
["def playerRankUp(pts):\n msg = \"Well done! You have advanced to the qualifying stage. Win 2 out of your next 3 games to rank up.\" \n return msg if pts >=100 else False", "def playerRankUp(pts):\n return \"Well done! You have advanced to the qualifying stage. Win 2 out of your next 3 games to rank up.\" if ...
{"fn_name": "playerRankUp", "inputs": [[-1], [0], [45], [59], [64], [100], [105], [111], [118], [332532105]], "outputs": [[false], [false], [false], [false], [false], ["Well done! You have advanced to the qualifying stage. Win 2 out of your next 3 games to rank up."], ["Well done! You have advanced to the qualifying st...
introductory
https://www.codewars.com/kata/55849d76acd73f6cc4000087
def playerRankUp(pts):
3,154
An array of size N x M represents pixels of an image. Each cell of this array contains an array of size 3 with the pixel's color information: `[R,G,B]` Convert the color image, into an *average* greyscale image. The `[R,G,B]` array contains integers between 0 and 255 for each color. To transform a color pixel into...
["from statistics import mean\n\ndef grey(rgb):\n return [int(round(mean(rgb)))]*3\n\ndef color_2_grey(colors):\n return [[grey(pixel) for pixel in row] for row in colors]", "def color_2_grey(colors):\n return [ [ [int(round(sum(rgb) / 3))] * 3 for rgb in row ] for row in colors ]", "def color_2_grey(colors):\...
{"fn_name": "color_2_grey", "inputs": [[[[[48, 36, 124], [201, 23, 247], [150, 162, 177]]]], [[[[49, 106, 224], [95, 150, 206]], [[88, 57, 134], [40, 183, 144]], [[36, 134, 174], [125, 27, 51]], [[33, 89, 186], [160, 39, 244]], [[249, 127, 245], [201, 233, 72]], [[78, 247, 124], [79, 245, 145]]]], [[[[181, 215, 243], [...
introductory
https://www.codewars.com/kata/590ee3c979ae8923bf00095b
def color_2_grey(colors):
3,155
Mr. Square is going on a holiday. He wants to bring 2 of his favorite squares with him, so he put them in his rectangle suitcase. Write a function that, given the size of the squares and the suitcase, return whether the squares can fit inside the suitcase. ```Python fit_in(a,b,m,n) a,b are the sizes of the 2 squares m...
["def fit_in(a, b, m, n):\n return max(a, b) <= min(m, n) and a + b <= max(m, n)", "def fit_in(a,b,m,n):\n return a+b<=max(m,n) and max(a,b)<=min(m,n)", "def fit_in(a,b,m,n):\n if m<a+b and n<a+b:\n return False\n if m<max([a,b]) or n<max([a,b]):\n return False\n return True", "def fit_in(a,b,m...
{"fn_name": "fit_in", "inputs": [[1, 2, 3, 2], [1, 2, 2, 1], [3, 2, 3, 2], [1, 2, 1, 2], [6, 5, 8, 7], [6, 6, 12, 6], [7, 1, 7, 8], [10, 10, 11, 11], [7, 2, 9, 7], [7, 2, 8, 7], [4, 1, 5, 3], [1, 2, 3, 4], [1, 2, 4, 3], [1, 3, 2, 4], [1, 3, 4, 2], [1, 4, 2, 3], [1, 4, 3, 2], [2, 1, 3, 4], [2, 1, 4, 3], [2, 3, 1, 4], [2...
introductory
https://www.codewars.com/kata/5c556845d7e0334c74698706
def fit_in(a,b,m,n):
3,156
The integer ```64``` is the first integer that has all of its digits even and furthermore, is a perfect square. The second one is ```400``` and the third one ```484```. Give the numbers of this sequence that are in the range ```[a,b] ```(both values inclusive) Examples: ``` python even_digit_squares(100, 1000) == [4...
["def is_even(x):\n return all(int(i) % 2 == 0 for i in str(x))\ndef even_digit_squares(a, b):\n first = int(a ** (1 / 2)) + 1\n last = int(b ** (1 / 2)) + 1\n return sorted([x * x for x in range(first, last) if is_even(x * x)])", "def even_digit_squares(a, b):\n return [i**2 for i in range(int(a**0.5), ...
{"fn_name": "even_digit_squares", "inputs": [[100, 1000], [1000, 4000], [10000, 40000]], "outputs": [[[400, 484]], [[]], [[26244, 28224, 40000]]]}
introductory
https://www.codewars.com/kata/59290e641a640c53d000002c
def even_digit_squares(a, b):
3,157
## Number of people in the bus There is a bus moving in the city, and it takes and drop some people in each bus stop. You are provided with a list (or array) of integer arrays (or tuples). Each integer array has two items which represent number of people get into bus (The first item) and number of people get off the b...
["def number(bus_stops):\n return sum([stop[0] - stop[1] for stop in bus_stops])", "def number(stops):\n return sum(i - o for i, o in stops)", "def number(bus_stops):\n return sum(on - off for on, off in bus_stops)", "def number(bus_stops):\n sum=0\n for i in bus_stops:\n sum+=i[0]-i[1]\n retur...
{"fn_name": "number", "inputs": [[[[10, 0], [3, 5], [5, 8]]], [[[3, 0], [9, 1], [4, 10], [12, 2], [6, 1], [7, 10]]], [[[3, 0], [9, 1], [4, 8], [12, 2], [6, 1], [7, 8]]], [[[0, 0]]]], "outputs": [[5], [17], [21], [0]]}
introductory
https://www.codewars.com/kata/5648b12ce68d9daa6b000099
def number(bus_stops):
3,158
A very passive-aggressive co-worker of yours was just fired. While he was gathering his things, he quickly inserted a bug into your system which renamed everything to what looks like jibberish. He left two notes on his desk, one reads: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" while the other reads: "Uif u...
["lower = \"abcdefghijklmnopqrstuvwxyz\"\n\ndef one_down(txt):\n if not isinstance(txt, str):\n return \"Input is not a string\"\n shifted = lower[-1] + lower[:-1]\n table = str.maketrans(lower + lower.upper(), shifted + shifted.upper())\n return txt.translate(table)", "def one_down(txt):\n try:\n...
{"fn_name": "one_down", "inputs": [["Ifmmp"], ["Uif usjdl up uijt lbub jt tjnqmf"], [45], ["XiBu BcPvU dSbAz UfYu"], [["Hello there", "World"]], ["BMM DBQT NBZCF"], ["qVAamFt BsF gVo"], ["CodeWars RockZ"], [""], ["J ipqf zpv bsf ibwjoh b ojdf ebz"]], "outputs": [["Hello"], ["The trick to this kata is simple"], ["Input ...
introductory
https://www.codewars.com/kata/56419475931903e9d1000087
def one_down(txt):
3,159
An array is defined to be `odd-heavy` if it contains at least one odd element and every element whose value is `odd` is greater than every even-valued element. eg. ``` Array [11,4,9,2,8] is odd-heavy because:- its odd elements [11,9] are greater than all the even elements [4,2,8] Array [11,4,9,2,3,10] is not odd-h...
["def is_odd_heavy(arr):\n maxEven, minOdd = ( f(filter(lambda n: n%2 == v, arr), default=float(\"-inf\")) for f,v in ((max, 0), (min,1)) )\n return maxEven < minOdd", "odd = lambda x: x&1\n\ndef is_odd_heavy(arr):\n it = iter(sorted(arr))\n return any(map(odd, it)) and all(map(odd, it))", "def is_odd_heavy...
{"fn_name": "is_odd_heavy", "inputs": [[[0, 2, 19, 4, 4]], [[1, -2, -1, 2]], [[-3, 2, 1, 3, -1, -2]], [[3, 4, -2, -3, -2]], [[-1, 1, -2, 2, -2, -2, -4, 4]], [[-1, -2, 21]], [[0, 0, 0, 0]], [[0, -1, 1]], [[0, 2, 3]], [[0]], [[]], [[1]], [[0, 1, 2, 3, 4, 0, -2, -1, -4, -3]], [[1, -1, 3, -1]], [[1, -1, 2, -2, 3, -3, 0]], ...
introductory
https://www.codewars.com/kata/59c7e477dcc40500f50005c7
def is_odd_heavy(arr):
3,160
Debug the functions Should be easy, begin by looking at the code. Debug the code and the functions should work. There are three functions: ```Multiplication (x)``` ```Addition (+)``` and ```Reverse (!esreveR)``` i { font-size:16px; } #heading { padding: 2em; text-align: center; background-color: #0033FF; wi...
["from functools import reduce\nfrom operator import mul\n\ndef multi(l_st):\n return reduce(mul,l_st)\ndef add(l_st):\n return sum(l_st)\ndef reverse(s):\n return s[::-1]", "import functools\n\ndef multi(l_st):\n return functools.reduce(lambda x, y: x * y, l_st)\ndef add(l_st):\n return functools.reduce...
{"fn_name": "multi", "inputs": [[[8, 2, 5]]], "outputs": [[80]]}
introductory
https://www.codewars.com/kata/5844a422cbd2279a0c000281
def multi(l_st):
3,161
_A mad sociopath scientist just came out with a brilliant invention! He extracted his own memories to forget all the people he hates! Now there's a lot of information in there, so he needs your talent as a developer to automatize that task for him._ > You are given the memories as a string containing people's surname ...
["def select(memory):\n lst = memory.split(', ')\n bad = {who.strip('!') for prev,who in zip(['']+lst,lst+['']) if who.startswith('!') or prev.startswith('!')}\n return ', '.join(who for who in map(lambda s: s.strip('!'), lst) if who not in bad)", "def select(memory):\n names = memory.split(', ')\n mark...
{"fn_name": "select", "inputs": [["Bryan Joubert"], ["Jesse Cox, !Selena Gomez"], ["!Eleena Daru, Obi-Wan Kenobi, Eleena Daru, Jar-Jar Binks"], ["Digital Daggers, !Kiny Nimaj, Rack Istley, Digital Daggers, Digital Daggers"], ["Albert Einstein, !Sarah Connor, Marilyn Monroe, Abraham Lincoln, Sarah Connor, Sean Connery, ...
introductory
https://www.codewars.com/kata/58bee820e9f98b215200007c
def select(memory):
3,162
Compare two strings by comparing the sum of their values (ASCII character code). * For comparing treat all letters as UpperCase * `null/NULL/Nil/None` should be treated as empty strings * If the string contains other characters than letters, treat the whole string as it would be empty Your method should return `true`...
["def string_cnt(s):\n try:\n if s.isalpha():\n return sum(ord(a) for a in s.upper())\n except AttributeError:\n pass\n return 0\n\n\ndef compare(s1, s2):\n return string_cnt(s1) == string_cnt(s2)", "def compare(s1,s2):\n f = lambda x: sum(map(ord,x.upper())) if x and x.isalpha()...
{"fn_name": "compare", "inputs": [["AD", "BC"], ["AD", "DD"], ["gf", "FG"], ["Ad", "DD"], ["zz1", ""], ["ZzZz", "ffPFF"], ["kl", "lz"], [null, ""], ["!!", "7476"], ["##", "1176"]], "outputs": [[true], [false], [true], [false], [true], [true], [false], [true], [true], [true]]}
introductory
https://www.codewars.com/kata/576bb3c4b1abc497ec000065
def compare(s1,s2):
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):