problem_id
int64
0
5k
question
stringlengths
50
14k
solutions
stringlengths
12
1.21M
input_output
stringlengths
0
23.6M
difficulty
stringclasses
3 values
url
stringlengths
36
108
starter_code
stringlengths
0
1.4k
4,700
In this Kata, you will be given a multi-dimensional array containing `2 or more` sub-arrays of integers. Your task is to find the maximum product that can be formed by taking any one element from each sub-array. ``` Examples: solve( [[1, 2],[3, 4]] ) = 8. The max product is given by 2 * 4 solve( [[10,-15],[-1,-3]] ) =...
["def solve(arr):\n \n p, q = 1, 1\n \n for k in arr:\n \n x, y = max(k), min(k)\n \n a = p * x\n b = q * x\n c = p * y\n d = q * y\n \n p = max(a, b, c, d)\n q = min(a, b, c, d)\n \n return max(p, q)", "def solve(arr):\n ...
{"fn_name": "solve", "inputs": [[[[1, 2], [3, 4]]], [[[10, -15], [-1, -3]]], [[[-1, 2, -3, 4], [1, -2, 3, -4]]], [[[-11, -6], [-20, -20], [18, -4], [-20, 1]]], [[[14, 2], [0, -16], [-12, -16]]], [[[-3, -4], [1, 2, -3]]], [[[-2, -15, -12, -8, -16], [-4, -15, -7], [-10, -5]]]], "outputs": [[8], [45], [12], [17600], [3584...
introductory
https://www.codewars.com/kata/5d0365accfd09600130a00c9
def solve(arr):
4,701
Mr Leicester's cheese factory is the pride of the East Midlands, but he's feeling a little blue. It's the time of the year when **the taxman is coming round to take a slice of his cheddar** - and the final thing he has to work out is how much money he's spending on his staff. Poor Mr Leicester can barely sleep he's so ...
["from math import ceil\ndef pay_cheese(arr):\n return f'L{ceil(sum(arr) / 100) * 35}'", "from math import ceil\n\ndef pay_cheese(lst):\n return f\"L{35 * ceil(sum(lst) / 100)}\"", "from math import ceil\ndef pay_cheese(a): \n return f\"L{round(ceil(((sum(a)*6.)/10.)/60.)*35)}\"", "pay_cheese=lambda l:f\"L{...
{"fn_name": "pay_cheese", "inputs": [[[750, 750, 750, 750, 600]], [[700, 750, 700, 750, 600]], [[574, 574, 574, 574, 574]], [[1, 1, 1, 1, 1]], [[0, 0, 0, 0, 0]]], "outputs": [["L1260"], ["L1225"], ["L1015"], ["L35"], ["L0"]]}
introductory
https://www.codewars.com/kata/5ab7ee556a176b1043000047
def pay_cheese(arr):
4,702
# Task Given an integer `product`, find the smallest positive integer the product of whose digits is equal to product. If there is no such integer, return -1 instead. # Example For `product = 1`, the output should be `11`; `1 x 1 = 1` (1 is not a valid result, because it has only 1 digit) For `product = 12`, ...
["def digits_product(product):\n if product < 10:\n return 10 + product\n n = ''\n for d in range(9, 1, -1):\n while not product % d:\n n += str(d)\n product //= d\n return int(n[::-1]) if product == 1 else -1", "from functools import reduce\nfrom operator import mul\n\nd...
{"fn_name": "digits_product", "inputs": [[12], [19], [450], [0], [13], [1], [5], [10]], "outputs": [[26], [-1], [2559], [10], [-1], [11], [15], [25]]}
introductory
https://www.codewars.com/kata/589436311a8808bf560000f9
def digits_product(product):
4,703
The medians of a triangle are the segments that unit the vertices with the midpoint of their opposite sides. The three medians of a triangle intersect at the same point, called the barycenter or the centroid. Given a triangle, defined by the cartesian coordinates of its vertices we need to localize its barycenter or ce...
["def bar_triang(a, b, c):\n return [round(sum(x)/3.0, 4) for x in zip(a, b, c)]", "def bar_triang(pointA, pointB, pointC): \n a = (pointA[0] + pointB[0] + pointC[0]) / 3.0\n b = (pointA[1] + pointB[1] + pointC[1]) / 3.0\n return [round(a, 4), round(b, 4)]", "def bar_triang(pointA, pointB, pointC): # points...
{"fn_name": "bar_triang", "inputs": [[[4, 6], [12, 4], [10, 10]], [[4, 2], [12, 2], [6, 10]], [[4, 8], [8, 2], [16, 6]]], "outputs": [[[8.6667, 6.6667]], [[7.3333, 4.6667]], [[9.3333, 5.3333]]]}
introductory
https://www.codewars.com/kata/5601c5f6ba804403c7000004
def bar_triang(pointA, pointB, pointC):
4,704
In this kata you must take an input string, reverse the order of the words, and reverse the order of the letters within the words. But, as a bonus, every test input will end with a punctuation mark (! ? .) and the output should be returned with the mark at the end. A few examples should help clarify: ```python esrev...
["def esrever(s):\n return s[:-1][::-1] + s[-1] if s else ''", "def esrever(string):\n return string and string[-2::-1] + string[-1]", "def esrever(string):\n return string[:-1][::-1] + string[-1:]", "def esrever(string):\n return string[-2::-1] + string[-1:]", "esrever = lambda s: s[-2::-1] + s[:-2:-1]", "...
{"fn_name": "esrever", "inputs": [["an Easy one?"], ["a small lOan OF 1,000,000 $!"], ["<?> &!.\"."], ["b3tTer p4ss thIS 0ne."], [""]], "outputs": [["eno ysaE na?"], ["$ 000,000,1 FO naOl llams a!"], ["\".!& >?<."], ["en0 SIht ss4p reTt3b."], [""]]}
introductory
https://www.codewars.com/kata/57e0206335e198f82b00001d
def esrever(string):
4,705
This is the simple version of Fastest Code series. If you need some challenges, please try the [Performance version](http://www.codewars.com/kata/5714594d2817ff681c000783) ## Task: Give you a number array ```numbers``` and a number ```c```. Find out a pair of numbers(we called them number a and number b) from t...
["def find_a_b(numbers,c):\n for i, a in enumerate(numbers, 1):\n for b in numbers[i:]:\n if a * b == c: return [a, b]", "from itertools import combinations\n\ndef find_a_b(numbers,c):\n return next(([a,b] for a,b in combinations(numbers,2) if a*b==c),None)", "def find_a_b(numbers, c):\n for ...
{"fn_name": "find_a_b", "inputs": [[[1, 2, 3], 3], [[1, 2, 3], 6], [[1, 2, 3], 7], [[1, 2, 3, 6], 6], [[1, 2, 3, 4, 5, 6], 15], [[0, 0, 2], 4], [[0, 0, 2, 2], 4], [[-3, -2, -2, -1, 0, 1, 2, 3, 4], 4], [[-3, -2, -2, -1, 0, 1, 2, 3, 4], 0], [[-3, -2, -1, 0, 1, 2, 3, 4], 4]], "outputs": [[[1, 3]], [[2, 3]], [null], [[1, 6...
introductory
https://www.codewars.com/kata/5714803d2817ffce17000a35
def find_a_b(numbers,c):
4,706
# Task You are given a decimal number `n` as a **string**. Transform it into an array of numbers (given as **strings** again), such that each number has only one nonzero digit and their sum equals n. Each number in the output array should be written without any leading and trailing zeros. # Input/Output - `[inpu...
["def split_exp(n):\n dot = n.find('.')\n if dot == -1: dot = len(n)\n return [d+\"0\"*(dot-i-1) if i<dot else \".{}{}\".format(\"0\"*(i-dot-1), d)\n for i,d in enumerate(n) if i != dot and d != '0']", "def split_exp(n):\n j = n.find('.') + 1 or len(n) + 1\n return [f\"{c}{'0'*(j-i-2)}\" if i ...
{"fn_name": "split_exp", "inputs": [["7970521.5544"], ["7496314"], ["0"], ["6"], ["1.0000000000"], ["0000000000.1"], ["1010101"], ["1234567890.1234567890"]], "outputs": [[["7000000", "900000", "70000", "500", "20", "1", ".5", ".05", ".004", ".0004"]], [["7000000", "400000", "90000", "6000", "300", "10", "4"]], [[]], [[...
introductory
https://www.codewars.com/kata/58fd9f6213b00172ce0000c9
def split_exp(n):
4,707
In this kata, your task is to write a function `to_bytes(n)` (or `toBytes(n)` depending on language) that produces a list of bytes that represent a given non-negative integer `n`. Each byte in the list is represented by a string of `'0'` and `'1'` of length 8. The most significant byte is first in the list. The example...
["def to_bytes(n):\n if not n:\n return ['00000000']\n \n res = []\n while n:\n res.append('{:08b}'.format(n % 256))\n n //= 256\n \n return res[::-1]", "import re\nfrom math import ceil\ndef to_bytes(n):\n return re.findall('.{8}', '{:0{}b}'.format(n, int(8 * ceil(n.bit_length...
{"fn_name": "to_bytes", "inputs": [[0], [1]], "outputs": [[["00000000"]], [["00000001"]]]}
introductory
https://www.codewars.com/kata/5705601c5eef1fad69000674
def to_bytes(n):
4,708
# Kata Task I have a cat and a dog. I got them at the same time as kitten/puppy. That was `humanYears` years ago. Return their respective ages now as [`humanYears`,`catYears`,`dogYears`] NOTES: * humanYears >= 1 * humanYears are whole numbers only ## Cat Years * `15` cat years for first year * `+9` cat years for ...
["def human_years_cat_years_dog_years(x):\n return [x, 24+(x-2)*4 if (x != 1) else 15, 24+(x-2)*5 if (x != 1) else 15]", "def human_years_cat_years_dog_years(human_years):\n catYears = 0\n dogYears = 0\n if human_years == 1:\n catYears += 15\n dogYears += 15\n return [human_years, catYe...
{"fn_name": "human_years_cat_years_dog_years", "inputs": [[1], [2], [10]], "outputs": [[[1, 15, 15]], [[2, 24, 24]], [[10, 56, 64]]]}
introductory
https://www.codewars.com/kata/5a6663e9fd56cb5ab800008b
def human_years_cat_years_dog_years(human_years):
4,709
Consider a sequence, which is formed by the following rule: next term is taken as the smallest possible non-negative integer, which is not yet in the sequence, so that `no 3` terms of sequence form an arithmetic progression. ## Example `f(0) = 0` -- smallest non-negative `f(1) = 1` -- smallest non-negative, which i...
["sequence=lambda n:int(format(n,'b'),3)", "def sequence(n):\n return int(format(n, 'b'), 3)", "sequence=lambda n:int(bin(n)[2:],3)", "# A005836\ndef sequence(n):\n return n and 3*sequence(n>>1) + (n&1)", "from math import log2\n\ndef sequence(i):\n if i == 0:\n return 0\n e = int(log2(i))\n retur...
{"fn_name": "sequence", "inputs": [[0], [1], [2], [3], [4], [5], [334], [123], [546], [1634], [14514]], "outputs": [[0], [1], [3], [4], [9], [10], [7329], [1084], [19929], [79707], [2305425]]}
introductory
https://www.codewars.com/kata/5e0607115654a900140b3ce3
def sequence(n):
4,710
In some countries of former Soviet Union there was a belief about lucky tickets. A transport ticket of any sort was believed to posess luck if sum of digits on the left half of its number was equal to the sum of digits on the right half. Here are examples of such numbers: ``` 003111 # 3 = 1 + 1 + 1 81337...
["def luck_check(string):\n e0, b1 = len(string) // 2, (len(string) + 1) // 2\n return sum(map(int, string[:e0])) == sum(map(int, string[b1:]))", "def luck_check(s):\n if not s or not all(c in '0123456789' for c in s):\n raise ValueError('Invalid ticket number')\n e0, b1 = len(s) // 2, (len(s) + 1) /...
{"fn_name": "luck_check", "inputs": [["5555"], ["003111"], ["543970707"], ["439924"], ["943294329932"], ["000000"], ["454319"], ["1233499943"], ["935336"]], "outputs": [[true], [true], [false], [false], [false], [true], [true], [false], [false]]}
introductory
https://www.codewars.com/kata/5314b3c6bb244a48ab00076c
def luck_check(string):
4,711
Write a program that will calculate the number of trailing zeros in a factorial of a given number. `N! = 1 * 2 * 3 * ... * N` Be careful `1000!` has 2568 digits... For more info, see: http://mathworld.wolfram.com/Factorial.html ## Examples ```python zeros(6) = 1 # 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing ...
["def zeros(n):\n \"\"\"\n No factorial is going to have fewer zeros than the factorial of a smaller\n number.\n\n Each multiple of 5 adds a 0, so first we count how many multiples of 5 are\n smaller than `n` (`n // 5`).\n\n Each multiple of 25 adds two 0's, so next we add another 0 for each multiple\...
{"fn_name": "zeros", "inputs": [[0], [6], [30], [100], [1000], [100000], [1000000000]], "outputs": [[0], [1], [7], [24], [249], [24999], [249999998]]}
introductory
https://www.codewars.com/kata/52f787eb172a8b4ae1000a34
def zeros(n):
4,712
Lucas numbers are numbers in a sequence defined like this: ``` L(0) = 2 L(1) = 1 L(n) = L(n-1) + L(n-2) ``` Your mission is to complete the function that returns the `n`th term of this sequence. **Note:** It should work for negative numbers as well; how you do this is you flip the equation around, so for negative num...
["def lucasnum(n):\n a = 2\n b = 1\n\n flip = n < 0 and n % 2 != 0\n\n for _ in range(abs(n)):\n a, b = b, a + b\n \n return -a if flip else a", "SEQUENCE = [2, 1]\n\ndef lucasnum(n):\n try:\n return SEQUENCE[abs(n)] * (1, -1)[n < 0 and n % 2]\n except IndexError:\n while l...
{"fn_name": "lucasnum", "inputs": [[-10], [-1]], "outputs": [[123], [-1]]}
introductory
https://www.codewars.com/kata/55a7de09273f6652b200002e
def lucasnum(n):
4,713
`late_clock` function receive an array with 4 digits and should return the latest time that can be built with those digits. The time should be in `HH:MM` format. Examples: ``` [1, 9, 8, 3] => 19:38 [9, 1, 2, 5] => 21:59 ``` You can suppose the input is correct and you can build from it a correct 24-hour time.
["from itertools import permutations\n\ndef late_clock(digits):\n for p in permutations(sorted(digits, reverse=True)):\n if p[0] > 2 or (p[0] == 2 and p[1] > 3) or p[2] > 5: continue\n return '{}{}:{}{}'.format(*p)", "def late_clock(digits):\n res, digits = [], digits[:]\n def rec(i):\n if i == 3:\n...
{"fn_name": "late_clock", "inputs": [[[9, 1, 2, 5]], [[1, 9, 8, 3]], [[0, 2, 2, 2]], [[3, 5, 0, 2]], [[9, 0, 1, 1]], [[2, 3, 2, 4]], [[1, 2, 8, 9]]], "outputs": [["21:59"], ["19:38"], ["22:20"], ["23:50"], ["19:10"], ["23:42"], ["19:28"]]}
introductory
https://www.codewars.com/kata/58925dcb71f43f30cd00005f
def late_clock(digits):
4,714
## Task Write a method `remainder` which takes two integer arguments, `dividend` and `divisor`, and returns the remainder when dividend is divided by divisor. Do NOT use the modulus operator (%) to calculate the remainder! #### Assumption Dividend will always be `greater than or equal to` divisor. #### Notes Make ...
["def remainder(dividend,divisor):\n while divisor <= dividend:\n dividend = dividend - divisor\n return dividend", "# Take your pick\nfrom operator import mod as remainder\nremainder = int.__mod__", "def remainder(d1,d2):\n return d1%d2", "def remainder(dividend,divisor):\n return dividend - (dividend...
{"fn_name": "remainder", "inputs": [[3, 2], [19, 2], [10, 2], [34, 7], [27, 5]], "outputs": [[1], [1], [0], [6], [2]]}
introductory
https://www.codewars.com/kata/564f458b4d75e24fc9000041
def remainder(dividend, divisor):
4,715
## Task Given a string, add the fewest number of characters possible from the front or back to make it a palindrome. ## Example For the input `cdcab`, the output should be `bacdcab` ## Input/Output Input is a string consisting of lowercase latin letters with length 3 <= str.length <= 10 The output is a palindrome...
["def build_palindrome(s):\n for n in range(len(s), -1, -1):\n if s[:n] == s[:n][::-1]:\n return s[n:][::-1] + s\n if s[-n:] == s[-n:][::-1]:\n return s + s[:-n][::-1]", "def build_palindrome(s):\n a = s[1:][::-1] + s\n temp = s\n for i in range(len(s)+1):\n temp =...
{"fn_name": "build_palindrome", "inputs": [["abcdc"], ["ababa"]], "outputs": [["abcdcba"], ["ababa"]]}
introductory
https://www.codewars.com/kata/58efb6ef0849132bf000008f
def build_palindrome(s):
4,716
# Task In the field, two beggars A and B found some gold at the same time. They all wanted the gold, and they decided to use simple rules to distribute gold: ``` They divided gold into n piles and be in line. The amount of each pile and the order of piles all are randomly. They took turns to take away a pile of gold...
["def distribution_of(golds):\n g = golds[:]\n turn, total = 0, [0, 0]\n while g:\n total[turn % 2] += g.pop(-(g[0] < g[-1]))\n turn += 1\n return total\n", "from collections import deque\ndef distribution_of(golds):\n g = deque(golds)\n s = [0, 0]\n t = 0\n while g:\n s[t] ...
{"fn_name": "distribution_of", "inputs": [[[4, 7, 2, 9, 5, 2]], [[10, 1000, 2, 1]]], "outputs": [[[11, 18]], [[12, 1001]]]}
introductory
https://www.codewars.com/kata/59547688d8e005759e000092
def distribution_of(golds):
4,717
## Task: You have to write a function **pattern** which returns the following Pattern(See Examples) upto (2n-1) rows, where n is parameter. ### Rules/Note: * If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string. * All the lines in the pattern have same length i.e equal to the number o...
["def pattern(n):\n lines = []\n for i in range(1, n + 1):\n line = ' ' * (n - i)\n line += ''.join(str(j % 10) for j in range(1, i + 1))\n line += line[::-1][1:]\n lines.append(line)\n return '\\n'.join(lines + lines[::-1][1:])\n", "def pattern(n):\n lines = []\n for c in ran...
{"fn_name": "pattern", "inputs": [[1], [3], [7], [0], [-25]], "outputs": [["1"], [" 1 \n 121 \n12321\n 121 \n 1 "], [" 1 \n 121 \n 12321 \n 1234321 \n 123454321 \n 12345654321 \n1234567654321\n 12345654321 \n 123454321 \n 1234321 \n 12321 \n 121 \n 1 "], [...
introductory
https://www.codewars.com/kata/5579e6a5256bac65e4000060
def pattern(n):
4,718
Write a function ```x(n)``` that takes in a number ```n``` and returns an ```nxn``` array with an ```X``` in the middle. The ```X``` will be represented by ```1's``` and the rest will be ```0's```. E.g. ```python x(5) == [[1, 0, 0, 0, 1], [0, 1, 0, 1, 0], [0, 0, 1, 0, 0], [0, 1, 0, 1, 0]...
["def x(n): \n d = [[0] * n for i in range (n)]\n for i in range(n):\n d[i][i] = 1\n d[i][-i-1] = 1\n return d", "def fill(i, j, n):\n if i == j or i + j == n - 1:\n return 1\n else:\n return 0\n\ndef x(n):\n return [[fill(i, j, n) for j in range(n)] for i in range(n)]", "...
{"fn_name": "x", "inputs": [[1], [2], [3], [4], [5], [6]], "outputs": [[[[1]]], [[[1, 1], [1, 1]]], [[[1, 0, 1], [0, 1, 0], [1, 0, 1]]], [[[1, 0, 0, 1], [0, 1, 1, 0], [0, 1, 1, 0], [1, 0, 0, 1]]], [[[1, 0, 0, 0, 1], [0, 1, 0, 1, 0], [0, 0, 1, 0, 0], [0, 1, 0, 1, 0], [1, 0, 0, 0, 1]]], [[[1, 0, 0, 0, 0, 1], [0, 1, 0, 0,...
introductory
https://www.codewars.com/kata/55cc20eb943f1d8b11000045
def x(n):
4,719
You are given an array of integers. Your task is to sort odd numbers within the array in ascending order, and even numbers in descending order. Note that zero is an even number. If you have an empty array, you need to return it. For example: ``` [5, 3, 2, 8, 1, 4] --> [1, 3, 8, 4, 5, 2] odd numbers ascending: [...
["def sort_array(xs):\n es = sorted(x for x in xs if x % 2 == 0)\n os = sorted((x for x in xs if x % 2 != 0), reverse=True)\n return [(es if x % 2 == 0 else os).pop() for x in xs]", "def sort_array(a):\n odds = []; evens = []; newArray = []\n for i in a:\n if i % 2 == 0:\n evens.append(...
{"fn_name": "sort_array", "inputs": [[[5, 3, 2, 8, 1, 4, 11]], [[2, 22, 37, 11, 4, 1, 5, 0]], [[1, 111, 11, 11, 2, 1, 5, 0]], [[]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]], [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]], [[0, 1, 2, 3, 4, 9, 8, 7, 6, 5]]], "outputs": [[[1, 3, 8, 4, 5, 2, 11]], [[22, 4, 1, 5, 2, 11, 37, 0]], [[1, 1, 5, 11, 2...
introductory
https://www.codewars.com/kata/5a1cb5406975987dd9000028
def sort_array(a):
4,720
In this kata, we will check is an array is (hyper)rectangular. A rectangular array is an N-dimensional array with fixed sized within one dimension. Its sizes can be repsented like A1xA2xA3...xAN. That means a N-dimensional array has N sizes. The 'As' are the hyperrectangular properties of an array. You should implem...
["from itertools import chain\n\ndef hyperrectangularity_properties(arr):\n hr, arr = [], [arr]\n while 1:\n check = sum(isinstance(v, int) for v in arr) # Check homogeneity\n if check or not arr: # some int are present or empty array (edge case)\n if...
{"fn_name": "hyperrectangularity_properties", "inputs": [[[]]], "outputs": [[[0]]]}
introductory
https://www.codewars.com/kata/5b33e9c291c746b102000290
def hyperrectangularity_properties(arr):
4,721
Write a function ```convert_temp(temp, from_scale, to_scale)``` converting temperature from one scale to another. Return converted temp value. Round converted temp value to an integer(!). Reading: http://en.wikipedia.org/wiki/Conversion_of_units_of_temperature ``` possible scale inputs: "C" for Celsius "F...
["TO_KELVIN = {\n 'C': (1, 273.15),\n 'F': (5.0 / 9, 459.67 * 5.0 / 9),\n 'R': (5.0 / 9, 0),\n 'De': (-2.0 / 3, 373.15),\n 'N': (100.0 / 33, 273.15),\n 'Re': (5.0 / 4, 273.15),\n 'Ro': (40.0 / 21, -7.5 * 40 / 21 + 273.15),\n}\n\ndef convert_temp(temp, from_scale, to_scale):\n if from_scale == to...
{"fn_name": "convert_temp", "inputs": [[100, "C", "F"], [-30, "De", "K"], [40, "Re", "C"], [60, "De", "F"], [373.15, "K", "N"], [666, "K", "K"], [60, "C", "F"], [60, "De", "C"], [128.25, "Ro", "C"], [-273.15, "C", "R"], [0, "K", "R"]], "outputs": [[212], [393], [50], [140], [33], [666], [140], [60], [230], [0], [0]]}
introductory
https://www.codewars.com/kata/54ce9497975ca65e1a0008c6
def convert_temp(temp, from_scale, to_scale):
4,722
# Challenge : Write a function that takes a single argument `n` that is a string representation of a simple mathematical expression and evaluates it as a floating point value. # Commands : - positive or negative decimal numbers - `+, -, *, /, ( / ).` --- Expressions use [infix notation](https://en.wikipedia.org/...
["def e(s):return f([*s,'+'])\ndef f(s,r=0,o=0,x='',c=0):\n while s and')'!=c:\n c=s.pop(0);i='+-*/)('.find(c)\n if c=='-'>x or i<0:x+=c\n elif c=='(':x=str(f(s))\n elif i>-1:a=float(x);r=[r+a,r-a,r*a,r/a][o];o=i;x=''\n return r", "def e(s,t=[],x=0,o='+',m=')*+-/'):\n if s:t+=list(s.replace(' ','')+')')\n while o!=...
{"fn_name": "e", "inputs": [["2*3*4*5+99"]], "outputs": [[219]]}
introductory
https://www.codewars.com/kata/5b05a8dd91cc5739df0000aa
def e(s):
4,723
Write a method that takes one argument as name and then greets that name, capitalized and ends with an exclamation point. Example: ``` "riley" --> "Hello Riley!" "JACK" --> "Hello Jack!" ```
["def greet(name): \n return f'Hello {name.title()}!'", "def greet(name): \n return f\"Hello {name.capitalize()}!\"", "def greet(name):\n name = name.lower()\n return \"Hello \" + name[0].upper() + name[1:] + \"!\"\n \n \nprint((greet(\"BILLY\")))\n", "def greet(name): \n name = name.lower() # Conv...
{"fn_name": "greet", "inputs": [["riley"], ["molly"], ["BILLY"]], "outputs": [["Hello Riley!"], ["Hello Molly!"], ["Hello Billy!"]]}
introductory
https://www.codewars.com/kata/535474308bb336c9980006f2
def greet(name):
4,724
DropCaps means that the first letter of the starting word of the paragraph should be in caps and the remaining lowercase, just like you see in the newspaper. But for a change, let's do that for each and every word of the given String. Your task is to capitalize every word that has length greater than 2, leaving small...
["def drop_cap(str_):\n return ' '.join( w.capitalize() if len(w) > 2 else w for w in str_.split(' ') )\n", "import re\n\ndef drop_cap(s):\n return re.sub(r'\\w{3,}', lambda m: m[0].title(), s)", "def drop_cap(str_):\n return \" \".join([i[0].upper() + i[1::].lower() if len(i) > 2 else i for i in str_.split(\"...
{"fn_name": "drop_cap", "inputs": [["Apple Banana"], ["Apple"], [""], ["of"], ["Revelation of the contents outraged American public opinion, and helped generate"], ["more than one space between words"], [" leading spaces"], ["trailing spaces "], ["ALL CAPS CRAZINESS"], ["rAnDoM CaPs CrAzInEsS"]], "outputs": [["A...
introductory
https://www.codewars.com/kata/559e5b717dd758a3eb00005a
def drop_cap(str_):
4,725
Impliment the reverse function, which takes in input n and reverses it. For instance, `reverse(123)` should return `321`. You should do this without converting the inputted number into a string.
["def reverse(n):\n m = 0\n while n > 0:\n n, m = n // 10, m * 10 + n % 10\n return m", "def reverse(n):\n return int(str(n)[::-1])", "def reverse(n):\n r = 0\n while n:\n r = r*10 + n%10\n n //= 10\n return r", "def reverse(n):\n \"\"\"Returns n with all digits reversed. As...
{"fn_name": "reverse", "inputs": [[1234], [4321], [1001], [1010], [12005000]], "outputs": [[4321], [1234], [1001], [101], [50021]]}
introductory
https://www.codewars.com/kata/58069e4cf3c13ef3a6000168
def reverse(n):
4,726
Given a string `s` of uppercase letters, your task is to determine how many strings `t` (also uppercase) with length equal to that of `s` satisfy the followng conditions: * `t` is lexicographical larger than `s`, and * when you write both `s` and `t` in reverse order, `t` is still lexicographical larger than `s`. ``...
["def solve(s):\n r, l = 0, 0\n for c in s:\n m = ord('Z') - ord(c)\n r, l = r + m + l * m, m + l * 26\n return r % 1000000007", "def solve(s, z=ord('Z')):\n a = r = 0\n for i in (z - ord(c) for c in s):\n r += (a + 1) * i\n a = a * 26 + i\n r %= 1000000007\n a %...
{"fn_name": "solve", "inputs": [["XYZ"], ["ABC"], ["ABCD"], ["ZAZ"], ["XYZA"]], "outputs": [[5], [16174], [402230], [25], [34480]]}
introductory
https://www.codewars.com/kata/5cfd36ea4c60c3001884ed42
def solve(s):
4,727
**This Kata is intended as a small challenge for my students** Create a function, called ``removeVowels`` (or ``remove_vowels``), that takes a string argument and returns that same string with all vowels removed (vowels are "a", "e", "i", "o", "u").
["REMOVE_VOWS = str.maketrans('','','aeiou')\n\ndef remove_vowels(s):\n return s.translate(REMOVE_VOWS)", "def remove_vowels(strng):\n return ''.join([i for i in strng if i not in 'aeiou'])", "def remove_vowels(stg):\n return \"\".join(c for c in stg if c not in \"aeiou\")", "def remove_vowels(s):\n return ...
{"fn_name": "remove_vowels", "inputs": [["drake"], ["scholarstem"], ["codewars"], ["high fives!"], [""], ["i"], ["b"]], "outputs": [["drk"], ["schlrstm"], ["cdwrs"], ["hgh fvs!"], [""], [""], ["b"]]}
introductory
https://www.codewars.com/kata/58640340b3a675d9a70000b9
def remove_vowels(s):
4,728
Complete the function so that it takes an array of keys and a default value and returns a hash (Ruby) / dictionary (Python) with all keys set to the default value. ## Example ```python ["draft", "completed"], 0 # should return {"draft": 0, "completed: 0} ```
["def populate_dict(keys, default):\n return {key: default for key in keys}", "populate_dict = dict.fromkeys", "def populate_dict(keys, default):\n return dict.fromkeys(keys, default)", "def populate_dict(keys, default):\n return {k:default for k in keys}", "from itertools import repeat\ndef populate_dict(keys...
{"fn_name": "populate_dict", "inputs": [[["draft", "completed"], 0], [["a", "b", "c"], null], [[1, 2, 3, 4], "OK"]], "outputs": [[{"completed": 0, "draft": 0}], [{"c": null, "b": null, "a": null}], [{"1": "OK", "2": "OK", "3": "OK", "4": "OK"}]]}
introductory
https://www.codewars.com/kata/51c38e14ea1c97ffaf000003
def populate_dict(keys, default):
4,729
If we write out the digits of "60" as English words we get "sixzero"; the number of letters in "sixzero" is seven. The number of letters in "seven" is five. The number of letters in "five" is four. The number of letters in "four" is four: we have reached a stable equilibrium. Note: for integers larger than 9, write ou...
["digits = 'zero one two three four five six seven eight nine'.split()\n\ndef f(n):\n return ''.join(map(digits.__getitem__, map(int, str(n))))\n\ndef numbers_of_letters(n):\n result = [f(n)]\n print(n, result)\n while result[-1] != 'four':\n result.append(f(len(result[-1])))\n return result", "wo...
{"fn_name": "numbers_of_letters", "inputs": [[1], [2], [3], [4], [12], [37], [311], [999]], "outputs": [[["one", "three", "five", "four"]], [["two", "three", "five", "four"]], [["three", "five", "four"]], [["four"]], [["onetwo", "six", "three", "five", "four"]], [["threeseven", "onezero", "seven", "five", "four"]], [["...
introductory
https://www.codewars.com/kata/599febdc3f64cd21d8000117
def numbers_of_letters(n):
4,730
We need a function ```prime_bef_aft()``` that gives the largest prime below a certain given value ```n```, ```befPrime or bef_prime``` (depending on the language), and the smallest prime larger than this value, ```aftPrime/aft_prime``` (depending on the language). The result should be output in a list like the f...
["def prime(a):\n if a < 2: return False\n if a == 2 or a == 3: return True \n if a % 2 == 0 or a % 3 == 0: return False\n maxDivisor = a**0.5\n d, i = 5, 2\n while d <= maxDivisor:\n if a % d == 0: return False\n d += i \n i = 6 - i\n \n return True\n\ndef prime_bef_aft(num)...
{"fn_name": "prime_bef_aft", "inputs": [[3], [4], [100], [97], [101], [120], [130]], "outputs": [[[2, 5]], [[3, 5]], [[97, 101]], [[89, 101]], [[97, 103]], [[113, 127]], [[127, 131]]]}
introductory
https://www.codewars.com/kata/560b8d7106ede725dd0000e2
def prime_bef_aft(num):
4,731
It is 2050 and romance has long gone, relationships exist solely for practicality. MatchMyHusband is a website that matches busy working women with perfect house husbands. You have been employed by MatchMyHusband to write a function that determines who matches!! The rules are... a match occurs providing the husband's...
["def match(usefulness, months):\n return \"Match!\" if sum(usefulness) >= 0.85**months * 100 else \"No match!\"", "def match(usefulness, months):\n return 'Match!' if sum(usefulness) >= 100*0.85**months else 'No match!'", "def current(usefulness):\n return sum(usefulness)\n\ndef needed(months):\n if months...
{"fn_name": "match", "inputs": [[[15, 24, 12], 4], [[26, 23, 19], 3], [[11, 25, 36], 1], [[22, 9, 24], 5], [[8, 11, 4], 10], [[17, 31, 21], 2], [[34, 25, 36], 1], [[35, 35, 29], 0], [[35, 35, 30], 0], [[35, 35, 31], 0]], "outputs": [["No match!"], ["Match!"], ["No match!"], ["Match!"], ["Match!"], ["No match!"], ["Matc...
introductory
https://www.codewars.com/kata/5750699bcac40b3ed80001ca
def match(usefulness, months):
4,732
Your job is to figure out the index of which vowel is missing from a given string: * `A` has an index of 0, * `E` has an index of 1, * `I` has an index of 2, * `O` has an index of 3, * `U` has an index of 4. **Notes:** There is no need for string validation and every sentence given will contain all vowles but one. ...
["def absent_vowel(x): \n return ['aeiou'.index(i) for i in 'aeiou' if i not in x][0]", "def absent_vowel(x): \n return 'aeiou'.index((set('aeiou') - set(x.lower())).pop())", "def absent_vowel(stg): \n return next(i for i, v in enumerate(\"aeiou\") if v not in stg)", "def absent_vowel(x): \n strings = ['a',...
{"fn_name": "absent_vowel", "inputs": [["John Doe hs seven red pples under his bsket"], ["Bb Smith sent us six neatly arranged range bicycles"]], "outputs": [[0], [3]]}
introductory
https://www.codewars.com/kata/56414fdc6488ee99db00002c
def absent_vowel(x):
4,733
Quantum mechanics tells us that a molecule is only allowed to have specific, discrete amounts of internal energy. The 'rigid rotor model', a model for describing rotations, tells us that the amount of rotational energy a molecule can have is given by: `E = B * J * (J + 1)`, where J is the state the molecule is in...
["def rot_energies(B, Jmin, Jmax):\n return [B * J * (J + 1) for J in range(Jmin, Jmax + 1)] if B > 0 else []", "def rot_energies(rot, energy_min, energy_max):\n # We're programmers, not scientists or mathematicians, we can use legible variable names.\n if rot <= 0:\n return []\n else:\n retur...
{"fn_name": "rot_energies", "inputs": [[1, 1, 2], [2, 0, 3], [423, 100, 150], [1, 2, 0], [1, 2, 2], [-1.0, 2, 2]], "outputs": [[[2, 6]], [[0, 4, 12, 24]], [[4272300, 4357746, 4444038, 4531176, 4619160, 4707990, 4797666, 4888188, 4979556, 5071770, 5164830, 5258736, 5353488, 5449086, 5545530, 5642820, 5740956, 5839938, 5...
introductory
https://www.codewars.com/kata/587b6a5e8726476f9b0000e7
def rot_energies(B, Jmin, Jmax):
4,734
It's bonus time in the big city! The fatcats are rubbing their paws in anticipation... but who is going to make the most money? Build a function that takes in two arguments (salary, bonus). Salary will be an integer, and bonus a boolean. If bonus is true, the salary should be multiplied by 10. If bonus is false, the...
["def bonus_time(salary, bonus):\n return \"${}\".format(salary * (10 if bonus else 1))", "def bonus_time(salary, bonus):\n #your code here\n if bonus :\n return \"$\" + str(salary * 10)\n else:\n return \"$\" + str(salary)", "def bonus_time(salary, bonus):\n return '$' + str(salary * [1,10...
{"fn_name": "bonus_time", "inputs": [[10000, true], [25000, true], [10000, false], [60000, false], [2, true], [78, false], [67890, true]], "outputs": [["$100000"], ["$250000"], ["$10000"], ["$60000"], ["$20"], ["$78"], ["$678900"]]}
introductory
https://www.codewars.com/kata/56f6ad906b88de513f000d96
def bonus_time(salary, bonus):
4,735
#### Task: Your job here is to write a function (`keepOrder` in JS/CoffeeScript, `keep_order` in Ruby/Crystal/Python, `keeporder` in Julia), which takes a sorted array `ary` and a value `val`, and returns the lowest index where you could insert `val` to maintain the sorted-ness of the array. The input array will alway...
["from bisect import bisect_left as keep_order", "from bisect import bisect_left\n\ndef keep_order(arr, val):\n return bisect_left(arr, val)", "def keep_order(ary, val):\n for i, x in enumerate(ary):\n if x >= val:\n return i\n return len(ary)", "def keep_order(arr, val):\n for i in range(...
{"fn_name": "keep_order", "inputs": [[[1, 2, 3, 4, 7], 5], [[1, 2, 3, 4, 7], 0], [[1, 1, 2, 2, 2], 2], [[1, 2, 3, 4], 5], [[1, 2, 3, 4], -1], [[1, 2, 3, 4], 2], [[1, 2, 3, 4], 0], [[1, 2, 3, 4], 1], [[1, 2, 3, 4], 3], [[], 1], [[], 0], [[1, 1, 1, 1], 2], [[1, 1, 1, 1], 1], [[1, 1, 1, 1], 0], [[1, 3, 5, 6], 0], [[1, 3, ...
introductory
https://www.codewars.com/kata/582aafca2d44a4a4560000e7
def keep_order(ary, val):
4,736
How many bees are in the beehive? * bees can be facing UP, DOWN, LEFT, or RIGHT * bees can share parts of other bees Examples Ex1 ``` bee.bee .e..e.. .b..eeb ``` *Answer: 5* Ex2 ``` bee.bee e.e.e.e eeb.eeb ``` *Answer: 8* # Notes * The hive may be empty or null/None/nil/... * Python: the hive is passe...
["from itertools import chain\ndef how_many_bees(hive):\n return bool(hive) and sum(s.count('bee') + s.count('eeb') for s in map(''.join, chain(hive, zip(*hive))))", "def count(it):\n return sum(''.join(x).count('bee') + ''.join(x).count('eeb') for x in it)\n\ndef how_many_bees(hive):\n return count(hive) ...
{"fn_name": "how_many_bees", "inputs": [[null]], "outputs": [[0]]}
introductory
https://www.codewars.com/kata/57d6b40fbfcdc5e9280002ee
def how_many_bees(hive):
4,737
```if:python,php In this kata you will have to write a function that takes `litres` and `price_per_litre` as arguments. Purchases of 2 or more litres get a discount of 5 cents per litre, purchases of 4 or more litres get a discount of 10 cents per litre, and so on every two litres, up to a maximum discount of 25 cents ...
["def fuel_price(litres, price_per_liter):\n discount = int(min(litres, 10)/2) * 5 / 100\n return round((price_per_liter - discount) * litres, 2)", "fuel_price = lambda l,p: round(l*(p-min(0.05*(l//2), 0.25)), 2)", "from bisect import bisect\n\n\ndef fuel_price(litres, price_per_liter):\n discount = (0, 5, 10,...
{"fn_name": "fuel_price", "inputs": [[10, 21.5], [40, 10], [15, 5.83]], "outputs": [[212.5], [390], [83.7]]}
introductory
https://www.codewars.com/kata/57b58827d2a31c57720012e8
def fuel_price(litres, price_per_liter):
4,738
## The Riddle The King of a small country invites 1000 senators to his annual party. As a tradition, each senator brings the King a bottle of wine. Soon after, the Queen discovers that one of the senators is trying to assassinate the King by giving him a bottle of poisoned wine. Unfortunately, they do not know which s...
["def find(r):\n return sum(2**i for i in r)", "def find(rats):\n \"\"\"\n The rule the king should use is the following:\n 1) Label all bottle from 1 to 1000\n 2) Label all rats from 0 to 9\n 3) For each rat r, make it drink the bottle b if the binary representation of b has it's rth bit\...
{"fn_name": "find", "inputs": [[[0]], [[1]], [[2]], [[3]], [[4]], [[5]], [[6]], [[7]], [[8]], [[9]], [[3, 5, 6, 7, 8, 9]], [[0, 3, 5, 4, 9, 8]], [[0, 1, 9, 3, 5]], [[0, 1, 2, 3, 4, 6]], [[0, 1, 3, 4]]], "outputs": [[1], [2], [4], [8], [16], [32], [64], [128], [256], [512], [1000], [825], [555], [95], [27]]}
introductory
https://www.codewars.com/kata/58c47a95e4eb57a5b9000094
def find(r):
4,739
We have the numbers with different colours with the sequence: ['red', 'yellow', 'blue']. That sequence colours the numbers in the following way: 1 2 3 4 5 6 7 8 9 10 11 12 13 ..... We have got the following recursive function: ``` f(1) = 1 f(n) = f(n - 1) + n ``` Some terms of this seque...
["D, R = {}, [[], [], []]\nfor i in range(10000):\n D[i] = D.get(i - 1, 0) + i\n R[D[i]%3].append(D[i])\n \ndef same_col_seq(val, k, col):\n r = ['blue', 'red', 'yellow'].index(col)\n return [e for e in R[r] if e > val][:k] ", "def same_col_seq(val, k, col):\n colDct = {'red': 1, 'blue': 0}\n\n ...
{"fn_name": "same_col_seq", "inputs": [[3, 3, "blue"], [100, 4, "red"], [250, 6, "yellow"], [1000, 7, "red"]], "outputs": [[[6, 15, 21]], [[136, 190, 253, 325]], [[]], [[1081, 1225, 1378, 1540, 1711, 1891, 2080]]]}
introductory
https://www.codewars.com/kata/57f891255cae44b2e10000c5
def same_col_seq(val, k, col):
4,740
Given the triangle of consecutive odd numbers: ``` 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 ... ``` Calculate the row sums of this triangle from the row index (starting at index 1) e.g.: ```python row_sum_odd_numbers(1); # 1 row_sum_odd_numbers(2); # 3 ...
["def row_sum_odd_numbers(n):\n #your code here\n return n ** 3", "def row_sum_odd_numbers(n):\n if type(n)==int and n>0:\n return n**3\n else:\n return \"Input a positive integer\"", "def row_sum_odd_numbers(n):\n return n*n*n", "def row_sum_odd_numbers(n):\n return pow(n, 3)", "def row...
{"fn_name": "row_sum_odd_numbers", "inputs": [[1], [2], [13], [19], [41], [42], [74], [86], [93], [101]], "outputs": [[1], [8], [2197], [6859], [68921], [74088], [405224], [636056], [804357], [1030301]]}
introductory
https://www.codewars.com/kata/55fd2d567d94ac3bc9000064
def row_sum_odd_numbers(n):
4,741
Given a standard english sentence passed in as a string, write a method that will return a sentence made up of the same words, but sorted by their first letter. However, the method of sorting has a twist to it: * All words that begin with a lower case letter should be at the beginning of the sorted sentence, and sorted...
["from string import punctuation\n\nt = str.maketrans(\"\", \"\", punctuation)\n\ndef pseudo_sort(s):\n a = s.translate(t).split()\n b = sorted(x for x in a if x[0].islower())\n c = sorted((x for x in a if x[0].isupper()), reverse=True)\n return \" \".join(b + c)", "from string import punctuation\ndef pseud...
{"fn_name": "pseudo_sort", "inputs": [["I, habitan of the Alleghanies, treating of him as he is in himself in his own rights"], ["take up the task eternal, and the burden and the lesson"], ["Land of the eastern Chesapeake"], ["And I send these words to Paris with my love"], ["O Liberty! O mate for me!"], ["With Egypt, ...
introductory
https://www.codewars.com/kata/52dffa05467ee54b93000712
def pseudo_sort(st):
4,742
You are given array of integers, your task will be to count all pairs in that array and return their count. **Notes:** * Array can be empty or contain only one value; in this case return `0` * If there are more pairs of a certain number, count each pair only once. E.g.: for `[0, 0, 0, 0]` the return value is `2` ...
["def duplicates(arr):\n return sum(arr.count(i)//2 for i in set(arr))", "from collections import Counter\n\ndef duplicates(arr):\n return sum(v//2 for v in list(Counter(arr).values()))\n", "def duplicates(arr):\n return sum((arr.count(n) // 2 for n in set(arr))) ", "from collections import Counter\n\ndef d...
{"fn_name": "duplicates", "inputs": [[[1, 2, 2, 20, 6, 20, 2, 6, 2]], [[1000, 1000]], [[]], [[54]]], "outputs": [[4], [1], [0], [0]]}
introductory
https://www.codewars.com/kata/5c55ad8c9d76d41a62b4ede3
def duplicates(arr):
4,743
## Task In your favorite game, you must shoot a target with a water-gun to gain points. Each target can be worth a different amount of points. You are guaranteed to hit every target that you try to hit. You cannot hit consecutive targets though because targets are only visible for one second (one at a time) and it...
["def target_game(values):\n a = b = 0\n for n in values:\n a, b = b, max(a + n, b)\n return max(a, b)", "def target_game(values):\n max_can_shoot, max_can_not_shoot = 0, 0\n for val in values:\n new = max_can_shoot + val\n max_can_shoot = max(max_can_not_shoot, new)\n max_can...
{"fn_name": "target_game", "inputs": [[[1, 2, 3, 4]], [[1, 3, 1]], [[5, 5, 5, 5, 5]], [[36, 42, 93, 29, 0, 33, 15, 84, 14, 24, 81, 11]], [[73, 80, 40, 86, 14, 96, 10, 56, 61, 84, 82, 36, 85]], [[11, 82, 47, 48, 80, 35, 73, 99, 86, 32, 32]], [[26, 54, 36, 35, 63, 58, 31, 80, 59, 61, 34, 54, 62, 73, 89, 7, 98, 91, 78]], ...
introductory
https://www.codewars.com/kata/58acf858154165363c00004e
def target_game(values):
4,744
My friend wants a new band name for her band. She like bands that use the formula: "The" + a noun with the first letter capitalized, for example: `"dolphin" -> "The Dolphin"` However, when a noun STARTS and ENDS with the same letter, she likes to repeat the noun twice and connect them together with the first and last...
["def band_name_generator(name):\n return name.capitalize()+name[1:] if name[0]==name[-1] else 'The '+ name.capitalize()", "def band_name_generator(name):\n if name[0] == name[-1]:\n return name.title()+name[1:]\n return (\"the \"+name).title()", "def band_name_generator(name):\n if name[0] != name[-...
{"fn_name": "band_name_generator", "inputs": [["knife"], ["tart"], ["sandles"], ["bed"], ["qq"]], "outputs": [["The Knife"], ["Tartart"], ["Sandlesandles"], ["The Bed"], ["Qqq"]]}
introductory
https://www.codewars.com/kata/59727ff285281a44e3000011
def band_name_generator(name):
4,745
Ever since you started work at the grocer, you have been faithfully logging down each item and its category that passes through. One day, your boss walks in and asks, "Why are we just randomly placing the items everywhere? It's too difficult to find anything in this place!" Now's your chance to improve the system, impr...
["def group_groceries(groceries):\n categories = {\"fruit\": [], \"meat\": [], \"other\": [], \"vegetable\": []}\n for entry in groceries.split(\",\"):\n category, item = entry.split(\"_\")\n categories[category if category in categories else \"other\"].append(item)\n return \"\\n\".join([f\"{cat...
{"fn_name": "group_groceries", "inputs": [["fruit_banana,vegetable_carrot,meat_chicken,drink_juice"], ["fruit_banana,vegetable_carrot,fruit_apple,canned_sardines,drink_juice,fruit_orange"], ["vegetable_celery,meat_chicken,meat_beef,fruit_banana,vegetable_carrot,canned_sardines,drink_juice,frozen_fries,fruit_lemon"], ["...
introductory
https://www.codewars.com/kata/593c0ebf8b90525a62000221
def group_groceries(groceries):
4,746
# How much is the fish! (- Scooter ) The ocean is full of colorful fishes. We as programmers want to know the hexadecimal value of these fishes. ## Task Take all hexadecimal valid characters (a,b,c,d,e,f) of the given name and XOR them. Return the result as an integer. ## Input The input is always a string, which can...
["from functools import reduce\nVALID = frozenset('abcdefABCDEF')\n\n\ndef fisHex(s):\n return reduce(lambda b, c: b ^ c, (int(a, 16) for a in s if a in VALID), 0)\n", "def fisHex(name):\n # fish is 15\n hexdict={'A':10,'B':11,'C':12,'D':13,'E':14,'F':15}\n res=0\n for c in name.upper():\n if c in...
{"fn_name": "fisHex", "inputs": [["pufferfish"], ["puffers"], ["balloonfish"], ["blowfish"], ["bubblefish"], ["globefish"], ["swellfish"], ["toadfish"], ["toadies"], ["honey toads"], ["sugar toads"], ["sea squab"], [""], ["Aeneus corydoras"], ["African glass catfish"], ["African lungfish"], ["Aholehole"], ["Airbreathin...
introductory
https://www.codewars.com/kata/5714eb80e1bf814e53000c06
def fisHex(name):
4,747
```if-not:racket Write a function called `repeat_str` which repeats the given string `src` exactly `count` times. ``` ```if:racket Write a function called `repeat-string` which repeats the given string `str` exactly `count` times. ```
["def repeat_str(repeat, string):\n return repeat * string", "def repeat_str(a,b):\n '''crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a cr...
{"fn_name": "repeat_str", "inputs": [[4, "a"], [3, "hello "], [2, "abc"]], "outputs": [["aaaa"], ["hello hello hello "], ["abcabc"]]}
introductory
https://www.codewars.com/kata/57a0e5c372292dd76d000d7e
def repeat_str(repeat, string):
4,748
This is a follow up from my kata Insert Dashes. Write a function ```insertDashII(num)``` that will insert dashes ('-') between each two odd numbers and asterisk ('\*') between each even numbers in ```num``` For example: ```insertDashII(454793)``` --> 4547-9-3 ```insertDashII(1012356895)``` --> 10123-56*89-5 Zero...
["def insert_dash2(num):\n \n prev = 0\n out = ''\n\n for dig in str(num):\n if int(dig) % 2 == int(prev) % 2 and int(prev) and int(dig):\n out += '*-'[int(prev) % 2]\n out += dig\n prev = dig\n return out", "import re\n\ndef insert_dash2(num):\n s = str(num)\n s = r...
{"fn_name": "insert_dash2", "inputs": [[454793], [123456], [40546793], [1012356895], [0]], "outputs": [["4547-9-3"], ["123456"], ["4054*67-9-3"], ["10123-56*89-5"], ["0"]]}
introductory
https://www.codewars.com/kata/55c3026406402936bc000026
def insert_dash2(num):
4,749
Uh oh, Someone at the office has dropped all these sequences on the floor and forgotten to label them with their correct bases. We have to fix this before the boss gets back or we're all going to be fired! This is what your years of coding have been leading up to, now is your time to shine! ## Task You will have t...
["def base_finder(seq):\n return len(set(''.join(seq)))", "def base_finder(a):\n return int(max(x[-1] for x in a)) + 1", "def base_finder(seq):\n base = 0\n for i in range(10): #as the sequence will always be 10 numbers long\n number = seq[i] # converting each list element to a string\n for i ...
{"fn_name": "base_finder", "inputs": [[["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]], [["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]], [["1", "2", "3", "4", "5", "6", "10", "11", "12", "13"]], [["301", "302", "303", "304", "305", "310", "311", "312", "313", "314"]], [["50", "51", "61", "53", "54", "60", "52...
introductory
https://www.codewars.com/kata/5f47e79e18330d001a195b55
def base_finder(seq):
4,750
Write a function that flattens an `Array` of `Array` objects into a flat `Array`. Your function must only do one level of flattening. ```python flatten [1,2,3] # => [1,2,3] flatten [[1,2,3],["a","b","c"],[1,2,3]] # => [1,2,3,"a","b","c",1,2,3] flatten [[[1,2,3]]] # => [[1,2,3]] ```
["def flatten(lst):\n r = []\n for x in lst:\n if type(x) is list:\n r.extend(x)\n else:\n r.append(x)\n return r ", "def flatten(lst):\n return sum(([i] if not isinstance(i, list) else i for i in lst), [])", "from itertools import chain\ndef flatten(lst):\n try:\n re...
{"fn_name": "flatten", "inputs": [[[[[3], [4], [5]], [9], [9, 9], [8], [[1, 2, 3]]]], [[[[3], [4], [5]], [9], [9, 9], [8], [[1, 2, 3], [77777]]]], [[[[3], [4], [5]], [9], [9, 9], [8], [[1, 2, 3], [77777]], "a"]], [[[[3], [4], [5]], [9], [9, 9], [8], [[1, 2, 3], [77777]], [["a"]]]]], "outputs": [[[[3], [4], [5], 9, 9, 9...
introductory
https://www.codewars.com/kata/5250a89b1625e5decd000413
def flatten(lst):
4,751
For a given two numbers your mission is to derive a function that evaluates whether two given numbers are **abundant**, **deficient** or **perfect** and whether together they are **amicable**. ### Abundant Numbers An abundant number or excessive number is a number for which the sum of its proper divisors is greater ...
["def deficiently_abundant_amicable_numbers(a,b):\n c,d = list(map(sumOfDivs,(a,b)))\n return f'{ kind(a,c)} { kind(b,d) } { \"not \"*(a!=d or b!=c or a==b) }amicable'\n\ndef kind(n,sD): return 'abundant' if sD>n else 'perfect' if sD==n else 'deficient'\ndef sumOfDivs(n): return sum(d for d in range(1,int(n/2+1...
{"fn_name": "deficiently_abundant_amicable_numbers", "inputs": [[220, 284], [220, 280], [1184, 1210], [220221, 282224], [10744, 10856], [299920, 9284], [999220, 2849], [139815, 122265], [496, 28], [8128, 8128]], "outputs": [["abundant deficient amicable"], ["abundant abundant not amicable"], ["abundant deficient amicab...
introductory
https://www.codewars.com/kata/56bc7687e8936faed5000c09
def deficiently_abundant_amicable_numbers(n1, n2):
4,752
Similar to the [previous kata](https://www.codewars.com/kata/string-subpattern-recognition-ii/), but this time you need to operate with shuffled strings to identify if they are composed repeating a subpattern Since there is no deterministic way to tell which pattern was really the original one among all the possible p...
["from collections import Counter\nfrom functools import reduce\nfrom fractions import gcd\n\ndef has_subpattern(s):\n c = Counter(s)\n m = reduce(gcd, c.values())\n return ''.join(sorted(k*(v//m) for k,v in c.items()))", "from collections import Counter\nfrom functools import reduce\nfrom math import gcd\n\n\...
{"fn_name": "has_subpattern", "inputs": [["a"], ["aaaa"], ["abcd"], ["babababababababa"], ["bbabbaaabbaaaabb"], ["123a123a123a"], ["123A123a123a"], ["12aa13a21233"], ["12aa13a21233A"], ["abcdabcaccd"]], "outputs": [["a"], ["a"], ["abcd"], ["ab"], ["ab"], ["123a"], ["111222333Aaa"], ["123a"], ["111222333Aaaa"], ["aaabbc...
introductory
https://www.codewars.com/kata/5a4a2973d8e14586c700000a
def has_subpattern(string):
4,753
Write a function, `gooseFilter` / `goose-filter` / `goose_filter` /` GooseFilter`, that takes an array of strings as an argument and returns a filtered array containing the same elements but with the 'geese' removed. The geese are any strings in the following array, which is pre-populated in your solution: ```python ...
["geese = {\"African\", \"Roman Tufted\", \"Toulouse\", \"Pilgrim\", \"Steinbacher\"}\n\ndef goose_filter(birds):\n return [bird for bird in birds if bird not in geese]", "geese = [\"African\", \"Roman Tufted\", \"Toulouse\", \"Pilgrim\", \"Steinbacher\"]\ndef goose_filter(birds):\n return list(filter(lambda x: x...
{"fn_name": "goose_filter", "inputs": [[["Mallard", "Hook Bill", "African", "Crested", "Pilgrim", "Toulouse", "Blue Swedish"]], [["Mallard", "Barbary", "Hook Bill", "Blue Swedish", "Crested"]], [["African", "Roman Tufted", "Toulouse", "Pilgrim", "Steinbacher"]]], "outputs": [[["Mallard", "Hook Bill", "Crested", "Blue S...
introductory
https://www.codewars.com/kata/57ee4a67108d3fd9eb0000e7
def goose_filter(birds):
4,754
Hi! Welcome to my first kata. In this kata the task is to take a list of integers (positive and negative) and split them according to a simple rule; those ints greater than or equal to the key, and those ints less than the key (the itself key will always be positive). However, in this kata the goal is to sort the num...
["from itertools import groupby\n\n\ndef group_ints(lst, key=0):\n return [list(g) for _, g in groupby(lst, lambda a: a < key)]\n\n\n# PEP8: function name should use snake_case\ngroupInts = group_ints", "from itertools import groupby\n\ndef group_ints(lst, key=0):\n return [list(g) for _, g in groupby(lst, key.__...
{"fn_name": "group_ints", "inputs": [[[], 0], [[1], 1], [[1, 2, 3], 0], [[1, 2, 3], 3], [[1, 1, 1, 0, 0, 6, 10, 5, 10], 6]], "outputs": [[[]], [[[1]]], [[[1, 2, 3]]], [[[1, 2], [3]]], [[[1, 1, 1, 0, 0], [6, 10], [5], [10]]]]}
introductory
https://www.codewars.com/kata/583fe48ca20cfc3a230009a1
def group_ints(lst, key=0):
4,755
Every non-negative integer N has a binary representation.  For example, 5 can be represented as "101" in binary, 11 as "1011" in binary, and so on.  Note that except for N = 0, there are no leading zeroes in any binary representation. The complement of a binary representation is the number in binary you get when changi...
["class Solution:\n def bitwiseComplement(self, N: int) -> int:\n return (1 << len(bin(N))-2) - N - 1", "class Solution:\n def bitwiseComplement(self, N: int) -> int:\n \n if N==0:\n return 1\n \n dummy_num=N\n \n n=0\n while(dummy_num):\n ...
{"fn_name": "bitwiseComplement", "inputs": [[5]], "outputs": [2]}
introductory
https://leetcode.com/problems/complement-of-base-10-integer/
class Solution: def bitwiseComplement(self, N: int) -> int:
4,756
=====Function Descriptions===== re.findall() The expression re.findall() returns all the non-overlapping matches of patterns in a string as a list of strings. Code >>> import re >>> re.findall(r'\w','http://www.hackerrank.com/') ['h', 't', 't', 'p', 'w', 'w', 'w', 'h', 'a', 'c', 'k', 'e', 'r', 'r', 'a', 'n', 'k', 'c'...
["import re\ns = input()\nresult = re.findall(r'(?<=[QWRTYPSDFGHJKLZXCVBNMqwrtypsdfghjklzxcvbnm])([AEIOUaeiou]{2,})(?=[QWRTYPSDFGHJKLZXCVBNMqwrtypsdfghjklzxcvbnm])',s)\nif result:\n for i in result:\n print(i)\nelse:\n print((-1))\n", "#!/usr/bin/env python3\n\nimport re\n\ncons = 'QWRTYPSDFGHJKLZXCVBNMqwr...
{"inputs": ["rabcdeefgyYhFjkIoomnpOeorteeeeet"], "outputs": ["ee\nIoo\nOeo\neeeee"]}
introductory
https://www.hackerrank.com/challenges/re-findall-re-finditer/problem
# Enter your code here. Read input from STDIN. Print output to STDOUT
4,757
You are given four positive integers $n$, $m$, $a$, $b$ ($1 \le b \le n \le 50$; $1 \le a \le m \le 50$). Find any such rectangular matrix of size $n \times m$ that satisfies all of the following conditions: each row of the matrix contains exactly $a$ ones; each column of the matrix contains exactly $b$ ones; all ...
["for _ in range(int(input())):\n n, m, a, b = list(map(int, input().split()))\n if a * n != b * m:\n print('NO')\n else:\n ar = []\n for i in range(n):\n ar.append([0] * m)\n x, y = 0, a\n for i in range(n):\n if x < y:\n for j in range(x...
{ "inputs": [ "5\n3 6 2 1\n2 2 2 1\n2 2 2 2\n4 4 2 2\n2 1 1 2\n" ], "outputs": [ "YES\n110000\n001100\n000011\nNO\nYES\n11\n11\nYES\n1100\n0110\n0011\n1001\nYES\n1\n1\n" ] }
introductory
https://codeforces.com/problemset/problem/1360/G
4,758
Let's just place tokens on a connect four board. ** INPUT ** Provided as input the list of columns where a token is placed, from 0 to 6 included. The first player starting is the yellow one (marked with `Y`), then the red (marked with `R`); the other cells might be empty and marked with `-`. ** OUTPUT ** The outp...
["def connect_four_place(columns):\n player, board, placed = 1, [['-']*7 for _ in range(6)], [-1]*7\n for c in columns:\n player ^= 1\n board[placed[c]][c] = \"YR\"[player]\n placed[c] -= 1\n return board\n", "from itertools import cycle, zip_longest\n\nEMPTY_CELL, HIGH, WIDTH = '-', 6, 7\...
{"fn_name": "connect_four_place", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5864f90473bd9c4b47000057
def connect_four_place(columns):
4,759
Write function toAcronym which takes a string and make an acronym of it. Rule of making acronym in this kata: 1. split string to words by space char 2. take every first letter from word in given string 3. uppercase it 4. join them toghether Eg: Code wars -> C, w -> C W -> CW
["def to_acronym(input):\n # only call upper() once\n return ''.join(word[0] for word in input.split()).upper()", "def to_acronym(input):\n return ''.join(w[0].upper() for w in input.split())", "def to_acronym(input):\n return \"\".join(i[0].upper() for i in input.split())", "def to_acronym(input):\n fstring =...
{"fn_name": "to_acronym", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/57a60bad72292d3e93000a5a
def to_acronym(input):
4,760
A [binary search tree](https://en.wikipedia.org/wiki/Binary_search_tree) is a binary tree that is ordered. This means that if you were to convert the tree to an array using an in-order traversal, the array would be in sorted order. The benefit gained by this ordering is that when the tree is balanced, searching is a lo...
["class T:\n def __init__(self,value,left=None,right=None):\n self.value=value\n self.left=left\n self.right=right\n\n\ndef is_bst(node):\n\n def extract(node):\n if node is not None:\n yield from extract(node.left)\n yield node.value\n yield from extra...
{"fn_name": "__init__", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/588534713472944a9e000029
def __init__(self,value,left=None,right=None):
4,761
This kata is about singly linked list. A linked list is an ordered set of data elements, each containing a link to its successor (and sometimes its predecessor, known as a double linked list). You are you to implement an algorithm to find the kth to last element. For example given a linked list of: a -> b -> c -> d...
["def search_k_from_end(linked_list, k):\n a = b = linked_list.head\n \n for __ in xrange(k - 1):\n b = b.next\n if not b:\n return None\n \n while b.next:\n a, b = a.next, b.next\n \n return a.data", "# pass in the linked list\n# to access the head of the li...
{"fn_name": "search_k_from_end", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5567e7d0adb11174c50000a7
def search_k_from_end(linked_list, k):
4,762
The business has been suffering for years under the watch of Homie the Clown. Every time there is a push to production it requires 500 hands-on deck, a massive manual process, and the fire department is on stand-by along with Fire Marshall Bill the king of manual configuration management. He is called a Fire Marshall b...
["def nkotb_vs_homie(requirements):\n return [\"{}! Homie dont play that!\".format(a[8:-5].title())\n for b in requirements for a in b] + \\\n [\"{} monitoring objections, {} automation, {} deployment pipeline, {} cloud, and {} microservices.\".\n format(*(len(x) for x in requirements...
{"fn_name": "nkotb_vs_homie", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/58b497914c5d0af407000049
def nkotb_vs_homie(requirements):
4,763
Each test case will generate a variable whose value is 777. Find the name of the variable.
["def find_variable():\n return next(k for k,v in globals().items() if v == 777)", "def find_variable():\n d = globals()\n for x in d[\"VVV\"]:\n if d[x] == 777:\n return x", "def find_variable():\n for k, v in globals().items(): # k = name of variable, v = value of variable\n if v ...
{"fn_name": "find_variable", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5a47d5ddd8e145ff6200004e
def find_variable():
4,764
Given a matrix represented as a list of string, such as ``` ###..... ..###... ....###. .....### .....### ....###. ..###... ###..... ``` write a function ```if:javascript `rotateClockwise(matrix)` ``` ```if:ruby,python `rotate_clockwise(matrix)` ``` that return its 90° clockwise rotation, for our example: ``` #......# ...
["def rotate_clockwise(m):\n return [''.join(l[::-1]) for l in zip(*m)]", "def rotate_clockwise(matrix):\n matrix=[[c for c in line] for line in matrix]\n return [''.join(line) for line in zip(*matrix[::-1])]", "rotate_clockwise=lambda m:list(map(''.join,zip(*m[::-1])))", "def rotate_clockwise(matrix):\n re...
{"fn_name": "rotate_clockwise", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/593e978a3bb47a8308000b8f
def rotate_clockwise(matrix):
4,765
```if:csharp ## Terminal Game - Create Hero Class In this first kata in the series, you need to define a Hero class to be used in a terminal game. The hero should have the following attributes: attribute | type | value ---|---|--- Name | string | user argument or "Hero" Position | string | "00" Health | float | 100 D...
["class Hero(object):\n def __init__(self, name='Hero'):\n self.name = name\n self.position = '00'\n self.health = 100\n self.damage = 5\n self.experience = 0", "class Hero(object):\n def __init__(self, name=\"Hero\", position=\"00\",\n health=100, damage=5, experience=0)...
{"fn_name": "__init__", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/55e8aba23d399a59500000ce
def __init__(self, name='Hero'):
4,766
This the second part part of the kata: https://www.codewars.com/kata/the-sum-and-the-rest-of-certain-pairs-of-numbers-have-to-be-perfect-squares In this part we will have to create a faster algorithm because the tests will be more challenging. The function ```n_closestPairs_tonum()```, (Javascript: ```nClosestPairsT...
["def n_closestPairs_tonum(upper_lim, k):\n square_lim = int((2 * upper_lim) ** .5) + 1\n squares = [n*n for n in range(1, square_lim)]\n p, s = [], set(squares)\n for m in range(upper_lim - 1, 1, -1):\n for b in squares:\n if b >= m: break\n if 2*m - b in s:\n p....
{"fn_name": "n_closestPairs_tonum", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/57aaaada72292d3b8f0001b4
def n_closestPairs_tonum(num, k):
4,767
Given a certain array of positive and negative numbers, give the longest increasing or decreasing combination of elements of the array. If our array is ```a = [a[0], a[1], ....a[n-1]]```: i) For the increasing case: there is a combination: ```a[i] < a[j] < a[k]..< a[p]```, such that ```0 ≤ i < j < k < ...< p ≤ n - 1`...
["from itertools import starmap, combinations\nfrom operator import lt, gt\n\ndef longest_comb(arr, command):\n check = lt if command.startswith('<') else gt\n for i in range(len(arr), 2, -1):\n # if all(map(check, x, x[1:])) In Python 3\n result = [list(x) for x in combinations(arr, i) if all(starm...
{"fn_name": "longest_comb", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5715508de1bf8174c1001832
def longest_comb(arr, command):
4,768
A company is opening a bank, but the coder who is designing the user class made some errors. They need you to help them. You must include the following: - A withdraw method - Subtracts money from balance - One parameter, money to withdraw - Raise ValueError if there isn't enough money to withdraw - Return ...
["class User(object):\n def __init__(self, name, balance, checking_account):\n self.name = name\n self.balance = balance\n self.checking_account = checking_account\n \n def withdraw(self, v):\n if v > self.balance: raise ValueError()\n self.balance -= v\n return \"{} h...
{"fn_name": "__init__", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5a03af9606d5b65ff7000009
def __init__(self, name, balance, checking_account):
4,769
Find the area of a rectangle when provided with one diagonal and one side of the rectangle. If the input diagonal is less than or equal to the length of the side, return "Not a rectangle". If the resultant area has decimals round it to two places. `This kata is meant for beginners. Rank and upvote to bring it out of b...
["def area(d, l): \n return \"Not a rectangle\" if d<=l else round( l*(d*d-l*l)**.5, 2)", "import math\n\ndef area ( diagonal, side ):\n if diagonal <= side: return 'Not a rectangle'\n \n return round(math.sqrt(diagonal ** 2 - side ** 2) * side, 2)", "def area(d, l): \n if d<=l:\n return \"Not a r...
{"fn_name": "area", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/580a0347430590220e000091
def area(d, l):
4,770
# Kata Task A bird flying high above a mountain range is able to estimate the height of the highest peak. Can you? # Example ## The birds-eye view ^^^^^^ ^^^^^^^^ ^^^^^^^ ^^^^^ ^^^^^^^^^^^ ^^^^^^ ^^^^ ## The bird-brain calculations 111111 1^^^^111 1^^^^11 1^^^1 1^^^^111111 1^^^11 1111 ...
["def peak_height(mountain):\n M = {(r, c) for r, l in enumerate(mountain) for c in range(len(l)) if l[c] == '^'}\n h = 0\n while M:\n M -= {(r, c) for r, c in M if {(r, c+1), (r, c-1), (r+1, c), (r-1, c)} - M}\n h += 1\n return h", "from scipy.ndimage.morphology import binary_erosion as erode...
{"fn_name": "peak_height", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5c09ccc9b48e912946000157
def peak_height(mountain):
4,771
Caesar Ciphers are one of the most basic forms of encryption. It consists of a message and a key, and it shifts the letters of the message for the value of the key. Read more about it here: https://en.wikipedia.org/wiki/Caesar_cipher ## Your task Your task is to create a function encryptor that takes 2 arguments -...
["from string import maketrans as mt, ascii_lowercase as lc, ascii_uppercase as uc\ndef encryptor(key, message):\n key %= 26\n return message.translate(mt(lc+uc, lc[key:]+lc[:key]+uc[key:]+uc[:key]))", "def encryptor(key, message):\n upper_alpha = list(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\")\n lower_alpha = list(\"...
{"fn_name": "encryptor", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/546937989c0b6ab3c5000183
def encryptor(key, message):
4,772
The 26 letters of the English alphabets are randomly divided into 5 groups of 5 letters with the remaining letter being ignored. Each of the group is assigned a score of more than 0. The ignored letter always has a score of 0. With this kata, write a function ```nameScore(name)``` to work out the score of a name tha...
["def name_score(name):\n scores = {k: v for keys, v in alpha.iteritems() for k in keys}\n return {name: sum(scores.get(a, 0) for a in name.upper())}", "def name_score(name):\n return {name: sum(alpha[key] for c in name for key in alpha if c.upper() in key)}", "def name_score(name):\n up = name.upper()\n ...
{"fn_name": "name_score", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/576a29ab726f4bba4b000bb1
def name_score(name):
4,773
Given a list of prime factors, ```primesL```, and an integer, ```limit```, try to generate in order, all the numbers less than the value of ```limit```, that have **all and only** the prime factors of ```primesL``` ## Example ```python primesL = [2, 5, 7] limit = 500 List of Numbers Under 500 Prime Factorizat...
["def count_find_num(primes, limit):\n base = eval( '*'.join( map(str, primes) ) )\n \n if base > limit:\n return []\n \n results = [base]\n \n for p in primes:\n for num in results:\n num *= p\n while num not in results and num <= limit:\n results...
{"fn_name": "count_find_num", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/58f9f9f58b33d1b9cf00019d
def count_find_num(primesL, limit):
4,774
We'll create a function that takes in two parameters: * a sequence (length and types of items are irrelevant) * a function (value, index) that will be called on members of the sequence and their index. The function will return either true or false. Your function will iterate through the members of the sequence in ord...
["def find_in_array(seq, predicate): \n for index, value in enumerate(seq):\n if predicate(value, index):\n return index\n return -1", "def find_in_array(seq, fn): \n return next((i for i, j in enumerate(seq) if fn(j, i)), -1)", "def find_in_array(seq, predicate): \n return next((i for i,v...
{"fn_name": "find_in_array", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/51f082ba7297b8f07f000001
def find_in_array(seq, predicate):
4,775
The fusc function is defined recursively as follows: 1. fusc(0) = 0 2. fusc(1) = 1 3. fusc(2 * n) = fusc(n) 4. fusc(2 * n + 1) = fusc(n) + fusc(n + 1) The 4 rules above are sufficient to determine the value of `fusc` for any non-negative input `n`. For example, let's say you want to compute `fusc...
["def fusc(n):\n assert type(n) == int and n >= 0\n \n if n < 2:\n return n\n \n if n % 2 == 0:\n return fusc(n//2)\n else:\n return fusc(n//2) + fusc(n//2 + 1)", "\ndef fusc(n):\n f = [0, 1]\n for i in range(1, n + 1):\n f.append(f[i])\n f.append(f[i] + f[i+1]) \n return f[n]",...
{"fn_name": "fusc", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/570409d3d80ec699af001bf9
def fusc(n):
4,776
Be u(n) a sequence beginning with: ``` u[1] = 1, u[2] = 1, u[3] = 2, u[4] = 3, u[5] = 3, u[6] = 4, u[7] = 5, u[8] = 5, u[9] = 6, u[10] = 6, u[11] = 6, u[12] = 8, u[13] = 8, u[14] = 8, u[15] = 10, u[16] = 9, u[17] = 10, u[18] = 11, u[19] = 11, u[20] = 12, u[21] = 12, u[22] = 12, u[23] = 12 etc......
["from itertools import islice, count\n\ndef u1():\n a = {1:1, 2:1}\n yield a[1]\n yield a[2]\n for n in count(3):\n a[n] = a[n-a[n-1]] + a[n-a[n-2]]\n yield a[n]\n \ndef length_sup_u_k(n, k):\n return len(list(filter(lambda x: x >= k, islice(u1(), 1, n))))\n \ndef comp(n):\n retur...
{"fn_name": "length_sup_u_k", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5772382d509c65de7e000982
def length_sup_u_k(n, k):
4,777
In this kata, your task is to write a function that returns the smallest and largest integers in an unsorted string. In this kata, a range is considered a finite sequence of consecutive integers. Input Your function will receive two arguments: A string comprised of integers in an unknown range; think of this string as...
["from collections import Counter\n\ndef mystery_range(s, n):\n i, target = -1, Counter(s)\n sum_ = sum(map(Counter, map(str, range(n))), Counter())\n while True:\n i += 1\n sum_ = sum_ - Counter(str(i)) + Counter(str(i + n))\n if sum_ == target:\n if len(str(i + 1)) < len(str(i...
{"fn_name": "mystery_range", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5b6b67a5ecd0979e5b00000e
def mystery_range(s,n):
4,778
You're going on a trip with some students and it's up to you to keep track of how much money each Student has. A student is defined like this: ```python class Student: def __init__(self, name, fives, tens, twenties): self.name = name self.fives = fives self.tens = tens self.twenties...
["def most_money(students):\n total = []\n for student in students:\n total.append((student.fives * 5) + (student.tens * 10) + (student.twenties * 20))\n \n if min(total) == max(total) and len(students) > 1:\n return \"all\"\n else:\n return students[total.index(max(total))].name", "...
{"fn_name": "most_money", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/528d36d7cc451cd7e4000339
def most_money(students):
4,779
[comment]: # (Hello Contributors, the following guidelines in order of importance should help you write new translations and squash any pesky unintended bugs.) [//]: # (The epsilon of all floating point test case comparisons is 0.01.) [//]: # (Each test case shall pass if the statement "a^2 + b^2 = c^2" is true of the ...
["def how_to_find_them(rt):\n return {d: rt[d] if d in rt\n else (rt[\"a\"]**2 + rt[\"b\"]**2)**.5 if d==\"c\"\n else (rt[\"c\"]**2 - rt[(set(\"ab\")-{d}).pop()]**2)**.5 for d in\"abc\"}", "def how_to_find_them(right_triangle):\n result = dict(**right_triangle)\n if \"a\" not in res...
{"fn_name": "how_to_find_them", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/592dcbfedc403be22f00018f
def how_to_find_them(right_triangle):
4,780
Everybody loves **pi**, but what if **pi** were a square? Given a number of digits ```digits```, find the smallest integer whose square is greater or equal to the sum of the squares of the first ```digits``` digits of pi, including the ```3``` before the decimal point. **Note:** Test cases will not extend beyond 100 d...
["from math import ceil\n\nPI_DIGITS_SQUARED = [int(d)**2 for d in \"31415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679\"]\n\ndef square_pi(n):\n return ceil(sum(PI_DIGITS_SQUARED[:n])**0.5)", "square_pi = (0, 3, 4, 6, 6, 8, 12, 12, 14, 15, 15, 16, 18, 20, 21, 23, 2...
{"fn_name": "square_pi", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5cd12646cf44af0020c727dd
def square_pi(digits):
4,781
# Background A spider web is defined by * "rings" numbered out from the centre as `0`, `1`, `2`, `3`, `4` * "radials" labelled clock-wise from the top as `A`, `B`, `C`, `D`, `E`, `F`, `G`, `H` Here is a picture to help explain: # Web Coordinates As you can see, each point where the rings and the radials inte...
["import math\n\ndef spider_to_fly(spider, fly):\n web = {'A': 0, 'B': 45, 'C': 90, 'D': 135, 'E': 180, 'F': 225, 'G': 270, 'H': 315}\n angle = min(abs(web[spider[0]] - web[fly[0]]), 360 - abs(web[spider[0]] - web[fly[0]]))\n sideA, sideB = int(spider[1]), int(fly[1])\n return math.sqrt(sideA ** 2 + sideB *...
{"fn_name": "spider_to_fly", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5a30e7e9c5e28454790000c1
def spider_to_fly(spider, fly):
4,782
In Scala, an underscore may be used to create a partially applied version of an infix operator using placeholder syntax. For example, `(_ * 3)` is a function that multiplies its input by 3. With a bit of manipulation, this idea can be extended to work on any arbitrary expression. Create an value/object named `x` that ...
["# -*- coding: utf-8 -*-\nimport operator\n\n\nclass Placeholder:\n def __init__(self, op=None, left=None, right=None):\n self.op = op\n self.left = left\n self.right = right\n\n def calc(self, args):\n if self.op:\n x, args = self.left.calc(args) if isinstance(self.left, P...
{"fn_name": "__init__", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5e7bc286a758770033b56a5a
def __init__(self, op=None, left=None, right=None):
4,783
## Debug celsius converter Your friend is traveling abroad to the United States so he wrote a program to convert fahrenheit to celsius. Unfortunately his code has some bugs. Find the errors in the code to get the celsius converter working properly. To convert fahrenheit to celsius: ``` celsius = (fahrenheit - 32) * ...
["def weather_info (temp):\n c = convertToCelsius(temp)\n if (c <= 0):\n return (str(c) + \" is freezing temperature\")\n else:\n return (str(c) + \" is above freezing temperature\")\n \ndef convertToCelsius (temperature):\n celsius = (temperature - 32) * (5.0/9.0)\n return celsius", "#I nee...
{"fn_name": "weather_info ", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/55cb854deb36f11f130000e1
def weather_info (temp):
4,784
Convert the 8-bit grayscale input image (2D-list) into an ASCII-representation. ``` _____/\\\\\\\\\________/\\\\\\\\\\\__________/\\\\\\\\\__/\\\\\\\\\\\__/\\\\\\\\\\\_ ___/\\\\\\\\\\\\\____/\\\/////////\\\_____/\\\////////__\/////\\\///__\/////\\\///__ __/\\\/////////\\\__\//\\\______\///____/\\\/__...
["def image2ascii(image):\n return '\\n'.join(''.join( glyphs[(v*8)//255] for v in r) for r in image)", "GLYPHS = \" .,:;xyYX\"\n\ndef image2ascii(image):\n return '\\n'.join(\n ''.join(GLYPHS[x * 8 // 255] for x in row)\n for row in image\n )", "GLYPHS = \" .,:;xyYX\"\n\ndef quantize(value, max_...
{"fn_name": "image2ascii", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5c22954a58251f1fdc000008
def image2ascii(image):
4,785
#Task: Write a function `get_member_since` which accepts a username from someone at Codewars and returns an string containing the month and year separated by a space that they joined CodeWars. ###If you want/don't want your username to be in the tests, ask me in the discourse area. There can't be too many though becau...
["from urllib.request import urlopen\nfrom bs4 import BeautifulSoup as bs\ndef get_member_since(username):\n html = urlopen(f'https://www.codewars.com/users/{username}')\n soup = bs(html.read(), \"html.parser\")\n tags = soup.find_all(\"div\", {\"class\": \"stat\"})\n member_tag = [x.text for x in tags if '...
{"fn_name": "get_member_since", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/58ab2ed1acbab2eacc00010e
def get_member_since(username):
4,786
*** Nova polynomial derivative*** This kata is from a series on polynomial handling. ( [#1](http://www.codewars.com/kata/nova-polynomial-1-add-1) [#2](http://www.codewars.com/kata/570eb07e127ad107270005fe) [#3](http://www.codewars.com/kata/5714041e8807940ff3001140 ) [#4](http://www.codewars.com/kata/571a2e2df24b...
["def poly_derivative(p):\n return [i * x for i, x in enumerate(p)][1:]\n", "def poly_derivative(p):\n return [i * n for i, n in enumerate(p[1:], 1)]", "def poly_derivative(p):\n return [ n*d for d,n in enumerate(p[1:], 1)]", "def poly_derivative(p):\n return [i * p[i] for i in range(1, len(p))]", "def poly...
{"fn_name": "poly_derivative", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/571a2e2df24bdfd4e20001f5
def poly_derivative(p):
4,787
# Description: Move all exclamation marks to the end of the sentence # Examples ``` remove("Hi!") === "Hi!" remove("Hi! Hi!") === "Hi Hi!!" remove("Hi! Hi! Hi!") === "Hi Hi Hi!!!" remove("Hi! !Hi Hi!") === "Hi Hi Hi!!!" remove("Hi! Hi!! Hi!") === "Hi Hi Hi!!!!" ```
["def remove(s):\n return s.replace('!','') + s.count('!') * '!'", "def remove(s):\n return ''.join(sorted(s, key=lambda a: a == '!'))\n", "def remove(s: str) -> str:\n r = s.replace('!', '')\n return r + '!' * (len(s) - len(r))\n", "def remove(s):\n i = 0\n count = 0\n while i < len(s):\n i...
{"fn_name": "remove", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/57fafd0ed80daac48800019f
def remove(s):
4,788
My 5th kata, and 1st in a planned series of rock climbing themed katas. In rock climbing ([bouldering](https://en.wikipedia.org/wiki/Bouldering) specifically), the V/Vermin (USA) climbing grades start at `'VB'` (the easiest grade), and then go `'V0'`, `'V0+'`, `'V1'`, `'V2'`, `'V3'`, `'V4'`, `'V5'` etc. up to `'V17'` ...
["def sort_grades(gs):\n return sorted(gs, key=grade)\n\ndef grade(v):\n if v == 'VB': return -2\n if v == 'V0': return -1\n if v == 'V0+': return 0\n return int(v[1:])", "# G is just a dict mapping string after `V` to int.\nG = {str(k):k for k in range(1, 18)}; G['B'] = -2; G['0'] = -1; G['0+'] = 0\ndef sort_g...
{"fn_name": "sort_grades", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/58a08e622e7fb654a300000e
def sort_grades(lst):
4,789
# An introduction to propositional logic Logic and proof theory are fields that study the formalization of logical statements and the structure of valid proofs. One of the most common ways to represent logical reasonings is with **propositional logic**. A propositional formula is no more than what you normally use in...
["from itertools import compress, product, chain\nfrom functools import partial\n\ndef check(f, s):\n if f.is_literal(): return f in s\n elif f.is_and(): return all(check(e, s) for e in f.args)\n elif f.is_or(): return any(check(e, s) for e in f.args)\n elif f.is_not(): return not check(f.args[0], s)\n\ndef...
{"fn_name": "sat", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5e5fbcc5fa2602003316f7b5
def sat(f:
4,790
The mean and standard deviation of a sample of data can be thrown off if the sample contains one or many outlier(s) : (image source) For this reason, it is usually a good idea to check for and remove outliers before computing the mean or the standard deviation of a sample. To this aim, your function will receive a l...
["def clean_mean(sample, cutoff):\n mean = sum(sample)/len(sample)\n dev = ((1/len(sample))*sum((num-mean)**2 for num in sample))**(1/2)\n cleaned = [num for num in sample if abs(num-mean) <= cutoff*dev]\n if sample==cleaned:\n return round(mean,2)\n else:\n return clean_mean(cleaned,cutoff...
{"fn_name": "clean_mean", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5962d557be3f8bb0ca000010
def clean_mean(sample, cutoff):
4,791
Write a function that takes a string and returns an array containing binary numbers equivalent to the ASCII codes of the characters of the string. The binary strings should be eight digits long. Example: `'man'` should return `[ '01101101', '01100001', '01101110' ]`
["def word_to_bin(word):\n return ['{:08b}'.format(ord(c)) for c in word]", "def word_to_bin(word):\n return [format(ord(c), '08b') for c in word]", "def word_to_bin(word):\n return [\"{:0>8b}\".format(ord(c)) for c in word]", "def word_to_bin(word):\n return [ f\"{ord(c):08b}\" for c in word ]", "def word_...
{"fn_name": "word_to_bin", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/59859f435f5d18ede7000050
def word_to_bin(word):
4,792
```if-not:javascript,python Write function `parseFloat` which takes an input and returns a number or `Nothing` if conversion is not possible. ``` ```if:python Write function `parse_float` which takes a string/list and returns a number or 'none' if conversion is not possible. ``` ```if:javascript Write function `parse...
["def parse_float(string):\n try:\n return float(string)\n except:\n return None", "def parse_float(string):\n try:\n return float(string)\n except (ValueError, TypeError):\n return None", "def parse_float(string):\n try:\n return float(string)\n except:\n pas...
{"fn_name": "parse_float", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/57a386117cb1f31890000039
def parse_float(string):
4,793
Write a function that takes an integer in input and outputs a string with currency format. Integer in currency format is expressed by a string of number where every three characters are separated by comma. For example: ``` 123456 --> "123,456" ``` Input will always be an positive integer, so don't worry about type...
["def to_currency(price):\n return '{:,}'.format(price)", "def to_currency(price):\n return format(price, ',d')", "to_currency = '{:,}'.format", "def to_currency(price):\n return ''.join((',' + x[1]) if (x[0] % 3 == 0 and x[0]) else (x[1]) for x in enumerate(str(price)[::-1]))[::-1]\n", "def to_currency(price):\...
{"fn_name": "to_currency", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/54e9554c92ad5650fe00022b
def to_currency(price):
4,794
# Task Let's say that number a feels comfortable with number b if a ≠ b and b lies in the segment` [a - s(a), a + s(a)]`, where `s(x)` is the sum of x's digits. How many pairs (a, b) are there, such that a < b, both a and b lie on the segment `[L, R]`, and each number feels comfortable with the other? # Example F...
["def comfortable_numbers(l, r):\n s = [sum(map(int, str(n))) for n in range(l, r + 1)]\n return sum(s[i] >= i-j <= s[j] for i in range(1, len(s)) for j in range(i))", "from collections import defaultdict\n\ndef comfortable_numbers(l, r):\n D, res = defaultdict(set), 0\n for i in range(l, r+1):\n s =...
{"fn_name": "comfortable_numbers", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5886dbc685d5788715000071
def comfortable_numbers(l, r):
4,795
We will use the Flesch–Kincaid Grade Level to evaluate the readability of a piece of text. This grade level is an approximation for what schoolchildren are able to understand a piece of text. For example, a piece of text with a grade level of 7 can be read by seventh-graders and beyond. The way to calculate the grade ...
["from re import compile as reCompile\n\nSENTENCE = reCompile(r'[.!?]')\nSYLLABLE = reCompile(r'(?i)[aeiou]+')\n\ndef count(string, pattern):\n return len(pattern.findall(string))\n\ndef flesch_kincaid(text):\n nWords = text.count(' ') + 1\n return round(0.39 * nWords / count(text, SENTENCE) + 11.8 * count(tex...
{"fn_name": "flesch_kincaid", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/52b2cf1386b31630870005d4
def flesch_kincaid(text):
4,796
Linked Lists - Get Nth Implement a GetNth() function that takes a linked list and an integer index and returns the node stored at the Nth index position. GetNth() uses the C numbering convention that the first node is index 0, the second is index 1, ... and so on. So for the list 42 -> 13 -> 666, GetNth() with index 1...
["class Node(object):\n def __init__(self, data):\n self.data = data\n self.next = None\n \ndef get_nth(node, index):\n v = -1\n n = node\n while n:\n v += 1\n if v == index:\n return n\n n = n.next\n \n raise ValueError", "class Node(object):\n def __...
{"fn_name": "__init__", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/55befc42bfe4d13ab1000007
def __init__(self, data):
4,797
Given 2 strings, `a` and `b`, return a string of the form: `shorter+reverse(longer)+shorter.` In other words, the shortest string has to be put as prefix and as suffix of the reverse of the longest. Strings `a` and `b` may be empty, but not null (In C# strings may also be null. Treat them as if they are empty.). I...
["def shorter_reverse_longer(a,b):\n if len(a) < len(b): a, b = b, a\n return b+a[::-1]+b", "def shorter_reverse_longer(a,b):\n return b + a[::-1] + b if len(a) >= len(b) else a + b[::-1] + a", "def shorter_reverse_longer(a,b):\n if len(a) >= len(b):\n return b + a[::-1] + b\n else:\n return a +...
{"fn_name": "shorter_reverse_longer", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/54557d61126a00423b000a45
def shorter_reverse_longer(a,b):
4,798
Given a certain square matrix ```A```, of dimension ```n x n```, that has negative and positive values (many of them may be 0). We need the following values rounded to the closest integer: - the average of all the positive numbers (more or equal to 0) that are in the principal diagonal and in the columns with odd ind...
["def avg_diags(m):\n a1,a2,l,l1,l2=0,0,len(m),0,0\n for i in range (0,l):\n if i&1: \n if m[i][i]>=0: a1+=m[i][i]; l1+=1\n else:\n if m[l-i-1][i]<0: a2+=m[len(m)-i-1][i]; l2+=1\n return [round(a1/l1) if l1>0 else -1,round(abs(a2)/l2) if l2>0 else -1]", "def avg_diags(m):\n n, avg = len(m), [[0,...
{"fn_name": "avg_diags", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/58fef91f184b6dcc07000179
def avg_diags(m):
4,799
Let us define a function `f`such as: - (1) for k positive odd integer > 2 : - (2) for k positive even integer >= 2 : - (3) for k positive integer > 1 : where `|x|` is `abs(x)` and Bk the kth Bernoulli number. `f` is not defined for `0, 1, -1`. These values will not be tested. # Guidelines for Bernoulli ...
["from math import factorial,pi\nfrom fractions import Fraction\n\ndef comb(n,k):\n return factorial(n)//(factorial(n-k)*factorial(k))\n\ndef bernoulli(m):\n b=[1]\n for i in range(1,m+1):\n n=0\n for k in range(0,i):\n n+=comb(i+1,k)*b[k]\n b.append(Fraction(-n,i+1))\n retur...
{"fn_name": "comb", "inputs": [], "outputs": []}
introductory
https://www.codewars.com/kata/5a02cf76c9fc0ee71d0000d5
def comb(n,k):