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,664
You will be given a string (x) featuring a cat 'C' and a mouse 'm'. The rest of the string will be made up of '.'. You need to find out if the cat can catch the mouse from it's current position. The cat can jump over three characters. So: C.....m returns 'Escaped!' <-- more than three characters between C...m retu...
["def cat_mouse(x):\n return 'Escaped!' if x.count('.') > 3 else 'Caught!'", "def cat_mouse(x):\n esc = [\"C......m\",\"C......m\",\"C.......m\",\"m.....C\",\"C........m\",\"m.........C\",\"C.........m\",\"m....C\",\"m..........C\",\"m.......C\",\"m.......C\",\"m.........C\",\"C.....m\",\"C....m\",\"C.........m\"...
{"fn_name": "cat_mouse", "inputs": [["C....m"], ["C..m"], ["C.....m"], ["C.m"], ["m...C"]], "outputs": [["Escaped!"], ["Caught!"], ["Escaped!"], ["Caught!"], ["Caught!"]]}
introductory
https://www.codewars.com/kata/57ee24e17b45eff6d6000164
def cat_mouse(x):
3,665
You are given two positive integers `a` and `b` (`a < b <= 20000`). Complete the function which returns a list of all those numbers in the interval `[a, b)` whose digits are made up of prime numbers (`2, 3, 5, 7`) but which are not primes themselves. Be careful about your timing! Good luck :)
["from math import sqrt\ndef is_prime(n):\n if n < 2: return False\n for x in range(2, int(sqrt(n)) + 1):\n if n % x == 0: return False\n return True\n\ndef all_dig_prime(n):\n for d in str(n):\n if d not in \"2357\": return False\n return True\n\ndef not_primes(a, b):\n res = []\n fo...
{"fn_name": "not_primes", "inputs": [[2, 222], [2, 77], [2700, 3000], [500, 999], [999, 2500]], "outputs": [[[22, 25, 27, 32, 33, 35, 52, 55, 57, 72, 75, 77]], [[22, 25, 27, 32, 33, 35, 52, 55, 57, 72, 75]], [[2722, 2723, 2725, 2727, 2732, 2733, 2735, 2737, 2752, 2755, 2757, 2772, 2773, 2775]], [[522, 525, 527, 532, 53...
introductory
https://www.codewars.com/kata/5a9a70cf5084d74ff90000f7
def not_primes(a, b):
3,666
Implement `String#whitespace?(str)` (Ruby), `String.prototype.whitespace(str)` (JavaScript), `String::whitespace(str)` (CoffeeScript), or `whitespace(str)` (Python), which should return `true/True` if given object consists exclusively of zero or more whitespace characters, `false/False` otherwise.
["def whitespace(string):\n return not string or string.isspace()", "def whitespace(string):\n return not string.lstrip()", "def whitespace(string):\n return string.strip() == \"\"", "def whitespace(string):\n return string.strip(\"\\n\\t\\r \") == \"\"", "whitespace = lambda x: not x.strip()", "from re imp...
{"fn_name": "whitespace", "inputs": [[""], [" "], ["\n\r\n\r"], ["a"], ["w\n"], ["\t"], [" a\n"], ["\t \n\r\n "], ["\n\r\n\r "], ["\n\r\n\r 3"]], "outputs": [[true], [true], [true], [false], [false], [true], [false], [true], [true], [false]]}
introductory
https://www.codewars.com/kata/567de8823fa5eee02100002a
def whitespace(string):
3,667
While most devs know about [big/little-endianness](https://en.wikipedia.org/wiki/Endianness), only a selected few know the secret of real hard core coolness with mid-endians. Your task is to take a number and return it in its mid-endian format, putting the most significant couple of bytes in the middle and all the oth...
["import re\ndef mid_endian(n):\n h= hex(n)[2:].upper()\n r= re.findall('..','0'*(len(h)%2)+h)\n return \"\".join(r[1::2][::-1]+r[0::2])", "def mid_endian(n):\n bs = n.to_bytes((n.bit_length() + 7) // 8 or 1, byteorder='little')\n return (bs[len(bs)%2::2] + bs[::-2]).hex().upper()", "from collections imp...
{"fn_name": "mid_endian", "inputs": [[9999999], [0], [658188], [168496141], [43135012110]], "outputs": [["96987F"], ["00"], ["0B0A0C"], ["0D0B0A0C"], ["0D0B0A0C0E"]]}
introductory
https://www.codewars.com/kata/5b3e3ca99c9a75a62400016d
def mid_endian(n):
3,668
We define the sequence ```SF``` in the following way in terms of four previous sequences: ```S1```, ```S2```, ```S3``` and ```ST``` We are interested in collecting the terms of SF that are multiple of ten. The first term multiple of ten of this sequence is ```60``` Make the function ```find_mult10_SF()``` that yo...
["def find_mult10_SF(n):\n n = 4*n - 1\n \n return (6 ** n + 3 * 2 ** n) / 4\n", "def find_mult10_SF(n):\n # ST(n) = 6 ** n + 5 ** n - 2 ** n - 1\n # SF(n) = (6 ** n + 3 * (2 ** n)) / 4\n # SF is divisible by 10 if n = 3 mod 4\n #\n # => nth 10 multiple of 10 is ST(n * 4 - 1)\n k = n * 4 - 1\...
{"fn_name": "find_mult10_SF", "inputs": [[1], [2], [3]], "outputs": [[60], [70080], [90700800]]}
introductory
https://www.codewars.com/kata/561d54055e399e2f62000045
def find_mult10_SF(n):
3,669
We define the score of permutations of combinations, of an integer number (the function to obtain this value:```sc_perm_comb```) as the total sum of all the numbers obtained from the permutations of all the possible combinations of its digits. For example we have the number 348. ```python sc_perm_comb(348) = 3 + 4 + 8 ...
["from itertools import permutations\n\ndef sc_perm_comb(num):\n sNum = str(num)\n return sum({ int(''.join(p)) for d in range(1, len(sNum)+1) for p in permutations(sNum, d) })", "import itertools\n\n#With combinations, we allow leading zeros, e.g. '03' is allowed, because when we permute, '03' becomes '30' \nde...
{"fn_name": "sc_perm_comb", "inputs": [[348], [340], [333], [6], [0]], "outputs": [[3675], [1631], [369], [6], [0]]}
introductory
https://www.codewars.com/kata/5676ffaa8da527f234000025
def sc_perm_comb(num):
3,670
You're given a string of dominos. For each slot, there are 3 options: * "|" represents a standing domino * "/" represents a knocked over domino * " " represents a space where there is no domino For example: ```python "||| ||||//| |/" ``` What you must do is find the resulting string if the first domino is ...
["def domino_reaction(s):\n ds = \"\"\n for (i,d) in enumerate(s):\n if( d==\"|\" ): \n ds += \"/\"\n else:\n return ds+s[i:]\n return ds\n", "def domino_reaction(s):\n return s.replace(\"|\", \"/\", min(len(s.split(\" \")[0]), len(s.split(\"/\")[0])))", "def domino_react...
{"fn_name": "domino_reaction", "inputs": [["||| ||||//| |/"], ["|||||"], [" ///"], [""], [" "], [" |"], ["||||| |||"], ["|||||/|||"]], "outputs": [["/// ||||//| |/"], ["/////"], [" ///"], [""], [" "], [" |"], ["///// |||"], ["//////|||"]]}
introductory
https://www.codewars.com/kata/584cfac5bd160694640000ae
def domino_reaction(s):
3,671
Make a function that returns the value multiplied by 50 and increased by 6. If the value entered is a string it should return "Error". Note: in `C#`, you'll always get the input as a string, so the above applies if the string isn't representing a double value.
["def problem(a):\n try:\n return a * 50 + 6\n except TypeError:\n return \"Error\"", "def problem(a):\n return \"Error\" if isinstance(a,str) else a*50+6", "def problem(a):\n return \"Error\" if a == str(a) else a * 50 + 6", "def problem(a):\n #Easy Points ^_^\n try:\n return flo...
{"fn_name": "problem", "inputs": [["hello"], [1], [5], [0], [1.2], [3], ["RyanIsCool"]], "outputs": [["Error"], [56], [256], [6], [66], [156], ["Error"]]}
introductory
https://www.codewars.com/kata/55a5bfaa756cfede78000026
def problem(a):
3,672
Given a string of integers, return the number of odd-numbered substrings that can be formed. For example, in the case of `"1341"`, they are `1, 1, 3, 13, 41, 341, 1341`, a total of `7` numbers. `solve("1341") = 7`. See test cases for more examples. Good luck! If you like substring Katas, please try [Longest vo...
["def solve(s):\n return sum(i+1 for i,d in enumerate(list(s)) if d in '13579')", "def solve(s):\n return sum( int(c)%2 for i in range(len(s)) for c in s[i:] )", "import itertools\n\n# Walk through s from left to right. If the current digit is odd,\n# It can create odd substrings with every previous digit.\n# The...
{"fn_name": "solve", "inputs": [["1341"], ["1357"], ["13471"], ["134721"], ["1347231"], ["13472315"]], "outputs": [[7], [10], [12], [13], [20], [28]]}
introductory
https://www.codewars.com/kata/59da47fa27ee00a8b90000b4
def solve(s):
3,673
In number theory, Euler's totient is an arithmetic function, introduced in 1763 by Euler, that counts the positive integers less than or equal to `n` that are relatively prime to `n`. Thus, if `n` is a positive integer, then `φ(n)`, notation introduced by Gauss in 1801, is the number of positive integers `k ≤ n` for wh...
["def totient(n):\n if not isinstance(n,int) or n<1: return 0\n \n phi = n >= 1 and n\n for p in range(2, int(n ** .5) + 1):\n if not n % p:\n phi -= phi // p\n while not n % p:\n n //= p\n if n > 1: phi -= phi // n\n return phi", "PRIMES = [2, 3, 5, 7, 11, ...
{"fn_name": "totient", "inputs": [[15], [18], [19], [false], ["wow doge"], [0.0435]], "outputs": [[8], [6], [18], [0], [0], [0]]}
introductory
https://www.codewars.com/kata/53c9157c689f841d16000c03
def totient(n):
3,674
Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition. The binary number returned should be a string.
["def add_binary(a,b):\n return bin(a+b)[2:]\n", "def add_binary(a,b):\n return '{0:b}'.format(a + b)", "def add_binary(a, b):\n return format(a + b, 'b')\n", "def add_binary(a,b):\n \"\"\"Adds a and b together and returns a binary string\"\"\"\n return bin(a + b)[2::]", "def find_highest_power_2(num):\n...
{"fn_name": "add_binary", "inputs": [[1, 1], [0, 1], [1, 0], [2, 2], [51, 12], [5, 9], [10, 10], [100, 100], [4096, 1], [0, 2174483647]], "outputs": [["10"], ["1"], ["1"], ["100"], ["111111"], ["1110"], ["10100"], ["11001000"], ["1000000000001"], ["10000001100110111111110010111111"]]}
introductory
https://www.codewars.com/kata/551f37452ff852b7bd000139
def add_binary(a,b):
3,675
In programming you know the use of the logical negation operator (**!**), it reverses the meaning of a condition. Your task is to complete the function 'negationValue()' that takes a string of negations with a value and returns what the value would be if those negations were applied to it. ```python negation_value("!...
["def negation_value(s, x):\n return len(s) % 2 ^ bool(x)", "def negation_value(s, val):\n return len(s)&1 ^ bool(val)", "def negation_value(s, val):\n return (bool(val) if (len(s) % 2 == 0) else not val)", "def negation_value(str, val):\n return bool(not val if len(str) % 2 else val)", "negation_value = lamb...
{"fn_name": "negation_value", "inputs": [["!", false], ["!", true], ["!!!", []]], "outputs": [[true], [false], [true]]}
introductory
https://www.codewars.com/kata/58f6f87a55d759439b000073
def negation_value(s, val):
3,676
You get an array of different numbers to sum up. But there is one problem, those numbers all have different bases. For example: ```python You get an array of numbers with their base as an input: [["101",16],["7640",8],["1",9]] ``` The output should be the sum as an integer value with a base of 10, so according to the...
["def sum_it_up(a):\n return sum(int(*x) for x in a)", "def sum_it_up(a):\n return sum(int(n, b) for n, b in a)", "sum_it_up=lambda n: sum(int(x[0],x[1]) for x in n)", "def sum_it_up(numbers_with_bases):\n return sum(int(number, base) for number, base in numbers_with_bases)", "def sum_it_up(numbers_with_bases)...
{"fn_name": "sum_it_up", "inputs": [[[["101", 2], ["10", 8]]], [[["ABC", 16], ["11", 2]]], [[["101", 16], ["7640", 8], ["1", 9]]], [[]]], "outputs": [[13], [2751], [4258], [0]]}
introductory
https://www.codewars.com/kata/5a005f4fba2a14897f000086
def sum_it_up(numbers_with_bases):
3,677
Challenge: Given a two-dimensional array, return a new array which carries over only those arrays from the original, which were not empty and whose items are all of the same type (i.e. homogenous). For simplicity, the arrays inside the array will only contain characters and integers. Example: Given [[1, 5, 4], ['a',...
["def filter_homogenous(arrays):\n return[a for a in arrays if len(set(map(type,a)))==1]", "def homogenous(a):\n return len(set(map(type, a))) == 1\n \ndef filter_homogenous(arrays):\n return list(filter(homogenous, arrays))", "def is_homogenous(array):\n return len(set(map(type, array))) == 1\n\ndef fil...
{"fn_name": "filter_homogenous", "inputs": [[[[1, 5, 4], ["a", 3, 5], ["b"], [], ["1", 2, 3]]], [[[123, 234, 432], ["", "abc"], [""], ["", 1], ["", "1"], []]], [[[1, 2, 3], ["1", "2", "3"], ["1", 2, 3]]]], "outputs": [[[[1, 5, 4], ["b"]]], [[[123, 234, 432], ["", "abc"], [""], ["", "1"]]], [[[1, 2, 3], ["1", "2", "3"]]...
introductory
https://www.codewars.com/kata/57ef016a7b45ef647a00002d
def filter_homogenous(arrays):
3,678
You've just entered a programming contest and have a chance to win a million dollars. This is the last question you have to solve, so your victory (and your vacation) depend on it. Can you guess the function just by looking at the test cases? There are two numerical inputs and one numerical output. Goodluck! hint: go ...
["TABLE = str.maketrans('0123456789','9876543210')\n\ndef code(*args):\n return sum(map(lambda n:int(str(n).translate(TABLE)), args))", "def code(x, y):\n return sum(int('9' * len(str(n))) - n for n in [x, y])\n", "code=lambda Q,S:10**len(str(Q))+10**len(str(S))-2-Q-S", "def code(x, y):\n return sum(int('9' * ...
{"fn_name": "code", "inputs": [[9, 8], [123, 456], [3, 2], [1, 1], [12, 8], [200, 100], [100, 200]], "outputs": [[1], [1419], [13], [16], [88], [1698], [1698]]}
introductory
https://www.codewars.com/kata/5b1fa8d92ae7540e700000f0
def code(x,y):
3,679
Here you have to do some mathematical operations on a "dirty string". This kata checks some basics, it's not too difficult. __So what to do?__ Input: String which consists of two positive numbers (doubles) and exactly one operator like `+, -, * or /` always between these numbers. The string is dirty, which means tha...
["import re\n\ndef calculate_string(st): \n st = re.sub(r'[^-+*/\\d.]', '', st)\n result = eval(st)\n return str(int(round(result)))", "def calculate_string(st: str) -> str:\n return f\"{eval(''.join(s for s in st if s in '0123456789.+-/*')):.0f}\"", "def calculate_string(st):\n clean = \"\"\n for i i...
{"fn_name": "calculate_string", "inputs": [[";$%\u00a7fsdfsd235??df/sdfgf5gh.000kk0000"], ["sdfsd23454sdf*2342"], ["fsdfsd235???34.4554s4234df-sdfgf2g3h4j442"], ["fsdfsd234.4554s4234df+sf234442"], ["a1a2b3c.c0c/a1a0b.cc00c"]], "outputs": [["47"], ["54929268"], ["-210908"], ["234676"], ["12"]]}
introductory
https://www.codewars.com/kata/56b5dc75d362eac53d000bc8
def calculate_string(st):
3,680
In mathematics, the factorial of integer 'n' is written as 'n!'. It is equal to the product of n and every integer preceding it. For example: **5! = 1 x 2 x 3 x 4 x 5 = 120** Your mission is simple: write a function that takes an integer 'n' and returns 'n!'. You are guaranteed an integer argument. For any values out...
["import math\n\ndef factorial(n):\n if n < 0:\n return None\n return math.factorial(n)", "def factorial(n):\n if n <= 1:\n if n < 0:\n return None\n else:\n return 1\n return n * factorial(n-1)", "# This function should return n!\nimport math\n\ndef factorial(n):\...
{"fn_name": "factorial", "inputs": [[-1]], "outputs": [[null]]}
introductory
https://www.codewars.com/kata/528e95af53dcdb40b5000171
def factorial(n):
3,681
Poor Cade has got his number conversions mixed up again! Fix his ```convert_num()``` function so it correctly converts a base-10 ```int```eger, to the selected of ```bin```ary or ```hex```adecimal. ```#The output should be a string at all times``` ```python convert_num(number, base): if 'base' = hex: re...
["def convert_num(number, base):\n try:\n if base == 'hex':\n return hex(number)\n if base == 'bin':\n return bin(number)\n except:\n return 'Invalid number input'\n return 'Invalid base input'", "def convert_num(number, base):\n if not isinstance(number, int):\n ...
{"fn_name": "convert_num", "inputs": [[122, "bin"], ["dog", "bin"], [0, "hex"], [123, "lol"]], "outputs": [["0b1111010"], ["Invalid number input"], ["0x0"], ["Invalid base input"]]}
introductory
https://www.codewars.com/kata/57cded7cf5f4ef768800003c
def convert_num(number, base):
3,682
# Task You are given two string `a` an `s`. Starting with an empty string we can do the following two operations: ``` append the given string a to the end of the current string. erase one symbol of the current string.``` Your task is to find the least number of operations needed to construct the given string s. Assume...
["def string_constructing(a, s):\n if len(s) == 0:\n return 0\n i = -1\n for j, c in enumerate(s):\n i = a.find(c, i+1)\n if i < 0 or i == len(a) - 1:\n break\n return len(a) - j + (i < 0) + string_constructing(a, s[j + (i >= 0):])", "def string_constructing(pattern,target):\...
{"fn_name": "string_constructing", "inputs": [["aba", "abbabba"], ["aba", "abaa"], ["aba", "a"], ["a", "a"], ["a", "aaa"], ["abcdefgh", "hgfedcba"]], "outputs": [[9], [4], [3], [1], [3], [64]]}
introductory
https://www.codewars.com/kata/58a3a735cebc0630830000c0
def string_constructing(a, s):
3,683
In this kata, you've to count lowercase letters in a given string and return the letter count in a hash with 'letter' as key and count as 'value'. The key must be 'symbol' instead of string in Ruby and 'char' instead of string in Crystal. Example: ```python letter_count('arithmetics') #=> {"a": 1, "c": 1, "e": 1, "h...
["from collections import Counter\ndef letter_count(s):\n return Counter(s)", "def letter_count(s):\n return {i: s.count(i) for i in s}", "from collections import Counter as letter_count", "def letter_count(s):\n letters = {}\n for i in list(s):\n if i in letters:\n letters[i] += 1\n ...
{"fn_name": "letter_count", "inputs": [["codewars"], ["activity"], ["arithmetics"], ["traveller"], ["daydreamer"]], "outputs": [[{"a": 1, "c": 1, "d": 1, "e": 1, "o": 1, "r": 1, "s": 1, "w": 1}], [{"a": 1, "c": 1, "i": 2, "t": 2, "v": 1, "y": 1}], [{"a": 1, "c": 1, "e": 1, "h": 1, "i": 2, "m": 1, "r": 1, "s": 1, "t": 2...
introductory
https://www.codewars.com/kata/5808ff71c7cfa1c6aa00006d
def letter_count(s):
3,684
Suppose I have two vectors: `(a1, a2, a3, ..., aN)` and `(b1, b2, b3, ..., bN)`. The dot product between these two vectors is defined as: ``` a1*b1 + a2*b2 + a3*b3 + ... + aN*bN ``` The vectors are classified as orthogonal if the dot product equals zero. Complete the function that accepts two sequences as inputs an...
["def is_orthogonal(u, v): \n return sum(i*j for i,j in zip(u,v)) == 0", "def is_orthogonal(u, v):\n return sum(a*b for a, b in zip(u, v)) == 0", "from numpy import dot\n\ndef is_orthogonal(u, v): \n return not dot(u,v )", "def is_orthogonal(u, v):\n dot_product = 0\n for pair in zip(u, v):\n dot_...
{"fn_name": "is_orthogonal", "inputs": [[[1, 2], [2, 1]], [[1, -2], [2, 1]], [[7, 8], [7, -6]], [[-13, -26], [-8, 4]], [[1, 2, 3], [0, -3, 2]], [[3, 4, 5], [6, 7, -8]], [[3, -4, -5], [-4, -3, 0]], [[1, -2, 3, -4], [-4, 3, 2, -1]], [[2, 4, 5, 6, 7], [-14, -12, 0, 8, 4]], [[5, 10, 1, 20, 2], [-2, -20, -1, 10, 5]]], "outp...
introductory
https://www.codewars.com/kata/53670c5867e9f2222f000225
def is_orthogonal(u, v):
3,685
An acrostic is a text in which the first letter of each line spells out a word. It is also a quick and cheap way of writing a poem for somebody, as exemplified below : Write a program that reads an acrostic to identify the "hidden" word. Specifically, your program will receive a list of words (reprensenting an acros...
["def read_out(acrostic):\n return \"\".join( word[0] for word in acrostic )", "def read_out(acrostic):\n return ''.join(next(zip(*acrostic)))", "from operator import itemgetter\n\ndef read_out(acrostic):\n return ''.join(map(itemgetter(0), acrostic))", "def read_out(acrostic):\n return ''.join(e[0] for e i...
{"fn_name": "read_out", "inputs": [[["Jolly", "Amazing", "Courteous", "Keen"]], [["Marvelous", "Excellent", "Gifted"]]], "outputs": [["JACK"], ["MEG"]]}
introductory
https://www.codewars.com/kata/59b843b58bcb7766660000f6
def read_out(acrostic):
3,686
Your task is to define a function that understands basic mathematical expressions and solves them. For example: ```python calculate("1 + 1") # => 2 calculate("18 + 4*6") # => 42 calculate("245 - 826") # => -581 calculate("09 + 000482") # => 491 calculate("8 / 4 + 6") # => 8 calculate("5 + 1 / 5") ...
["import re\ndef calculate(input):\n try:\n return eval(re.sub(r'(\\d+)', lambda m: str(int(m.group(1))), input))\n except:\n return False", "import re\ndef calculate(s):\n try:\n s = re.sub(r'(?<!\\d)0+(0|[1-9]\\d*)', lambda m: m.group(1), s)\n s = re.sub(r'\\d+(?!\\.)', lambda m: ...
{"fn_name": "calculate", "inputs": [["1 + 1"], ["9 - 4"], ["1 - 4"], ["3 * 4"], ["9 / 3"], ["26 + 73"], ["524 + 277"], ["1 / 2"], ["2 / 5"], ["1 + 2 + 3 + 4 + 5 + 6"], ["123 - 3 - 20 - 100"], ["123 * 987 * 135 * 246"], ["200 / 2 / 10 / 5"], ["1+2-3+4-5+6-7+8-9+10"], ["5*2/3*9/10*123/8"], ["1*2*3/1/2/3+1+2+3-1-2-3"], ["...
introductory
https://www.codewars.com/kata/582b3b085ad95285c4000013
def calculate(input):
3,687
# Task Your task is to find the smallest number which is evenly divided by all numbers between `m` and `n` (both inclusive). # Example For `m = 1, n = 2`, the output should be `2`. For `m = 2, n = 3`, the output should be `6`. For `m = 3, n = 2`, the output should be `6` too. For `m = 1, n = 10`, the outpu...
["from fractions import gcd\nfrom functools import reduce\n\ndef mn_lcm(m, n):\n return reduce(lambda x, y: (x * y) / gcd(x, y), list(range(min(m, n), max(m, n) + 1)))\n\n", "from fractions import gcd\nfrom functools import reduce\ndef mn_lcm(m, n):\n return reduce(lambda x, y: (x * y) / gcd(x, y), range(min(m, n...
{"fn_name": "mn_lcm", "inputs": [[1, 2], [1, 5], [5, 1], [1, 10], [2, 3], [3, 5], [10, 20], [1, 25], [24, 25]], "outputs": [[2], [60], [60], [2520], [6], [60], [232792560], [26771144400], [600]]}
introductory
https://www.codewars.com/kata/58bcdc65f6d3b11fce000045
def mn_lcm(m, n):
3,688
# Task Alireza and Ali have a `3×3 table` and playing on that. they have 4 table(2×2) A,B,C and D in this table. At beginning all of 9 numbers in 3×3 table is zero. Alireza in each move choose a 2×2 table from A, B, C and D and increase all of 4 numbers in that by one. He asks Ali, how much he increase table ...
["def table_game(table):\n (a, ab, b), (ac, abcd, bd), (c, cd, d) = table\n if (a + b == ab) and (c + d == cd) and (a + c == ac) and (b + d == bd) and (a + b + c + d == abcd):\n return [a, b, c, d]\n return [-1]", "def table_game(table):\n a, b, c, d = table[0][0], table[0][2], table[2][0], table[2][...
{"fn_name": "table_game", "inputs": [[[[1, 2, 1], [2, 4, 2], [1, 2, 1]]], [[[3, 7, 4], [5, 16, 11], [2, 9, 7]]], [[[1, 4, 2], [5, 10, 5], [4, 7, 3]]], [[[2, 4, 2], [4, 6, 4], [2, 4, 2]]], [[[1, 2, 1], [1, 2, 1], [1, 2, 1]]], [[[2, 4, 2], [4, 8, 4], [2, 4, 2]]], [[[1, 3, 2], [5, 10, 5], [4, 7, 3]]]], "outputs": [[[1, 1,...
introductory
https://www.codewars.com/kata/58aa7f18821a769a7d000190
def table_game(table):
3,689
How much bigger is a 16-inch pizza compared to an 8-inch pizza? A more pragmatic question is: How many 8-inch pizzas "fit" in a 16-incher? The answer, as it turns out, is exactly four 8-inch pizzas. For sizes that don't correspond to a round number of 8-inchers, you must round the number of slices (one 8-inch pizza = ...
["def how_many_pizzas(n):\n return 'pizzas: {}, slices: {}'.format(*divmod(n * n // 8, 8))", "def how_many_pizzas(n):\n pizzas, slices = (int(n) for n in divmod(n**2, 64))\n return f\"pizzas: {pizzas}, slices: {slices // 8}\"", "def how_many_pizzas(n):\n q, r = divmod(n**2, 8**2)\n return f\"pizzas: {q},...
{"fn_name": "how_many_pizzas", "inputs": [[16], [12], [8], [6], [0]], "outputs": [["pizzas: 4, slices: 0"], ["pizzas: 2, slices: 2"], ["pizzas: 1, slices: 0"], ["pizzas: 0, slices: 4"], ["pizzas: 0, slices: 0"]]}
introductory
https://www.codewars.com/kata/599bb194b7a047b04d000077
def how_many_pizzas(n):
3,690
In this Kata, you will be given a string with brackets and an index of an opening bracket and your task will be to return the index of the matching closing bracket. Both the input and returned index are 0-based **except in Fortran where it is 1-based**. An opening brace will always have a closing brace. Return `-1` if...
["def solve(s, idx):\n stack = []\n for i, c in enumerate(s):\n if c == '(': stack += [i]\n if c == ')':\n if not stack: break\n if stack.pop() == idx: return i\n \n return -1", "def solve(s, i):\n c = s[i] == '('\n if not c: return -1\n while c != 0 ...
{"fn_name": "solve", "inputs": [["((1)23(45))(aB)", 0], ["((1)23(45))(aB)", 1], ["((1)23(45))(aB)", 2], ["((1)23(45))(aB)", 6], ["((1)23(45))(aB)", 11], ["(g(At)IO(f)(tM(qk)YF(n)Nr(E)))", 11], ["(g(At)IO(f)(tM(qk)YF(n)Nr(E)))", 0], ["(>_(va)`?(h)C(as)(x(hD)P|(fg)))", 19]], "outputs": [[10], [3], [-1], [9], [14], [28], ...
introductory
https://www.codewars.com/kata/5a24254fe1ce0ec2eb000078
def solve(st, idx):
3,691
Given a number `n`, make a down arrow shaped pattern. For example, when `n = 5`, the output would be: 123454321 1234321 12321 121 1 and for `n = 11`, it would be: 123456789010987654321 1234567890987654321 12345678987654321 123456787654321 1234567654321 ...
["def half(i, n):\n return \"\".join(str(d%10) for d in range(1, n-i+1))\n\ndef line(i, n):\n h = half(i, n)\n return \" \" * i + h + h[-2::-1]\n\ndef get_a_down_arrow_of(n):\n return \"\\n\".join(line(i, n) for i in range(n))\n", "from itertools import cycle, islice\n\ndef get_a_down_arrow_of(n):\n \n ...
{"fn_name": "get_a_down_arrow_of", "inputs": [[5]], "outputs": [["123454321\n 1234321\n 12321\n 121\n 1"]]}
introductory
https://www.codewars.com/kata/5645b24e802c6326f7000049
def get_a_down_arrow_of(n):
3,692
Description: The mean (or average) is the most popular measure of central tendency; however it does not behave very well when the data is skewed (i.e. wages distribution). In such cases, it's better to use the median. Your task for this kata is to find the median of an array consisting of n elements. You can assume ...
["from statistics import median", "def median(arr):\n arr.sort()\n return (arr[(len(arr) - 1)//2] + arr[(len(arr))//2])/2", "from numpy import median", "import numpy as np\ndef median(arr):\n return np.median(arr) if len(arr)>0 else None\n", "from random import choice\n\ndef median(lst):\n return quickselec...
{"fn_name": "median", "inputs": [[[1, 2, 3, 4]], [[3, 4, 1, 2, 5]], [[10, 29, 23, 94, 76, 96, 5, 85, 4, 33, 47, 41, 87]], [[1]], [[1, -1]]], "outputs": [[2.5], [3], [41], [1], [0]]}
introductory
https://www.codewars.com/kata/582609930626631a9600003e
def median(arr):
3,693
In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative? **Example:** ``` c makeNegative(1); // return -1 makeNegative(-5); // return -5 makeNegative(0); // return 0 ``` ``` cfml makeNegative(1); // return -1 makeNegative(-5); // return -5 makeNegative(0)...
["def make_negative( number ):\n return -abs(number)", "def make_negative( number ):\n return -number if number>0 else number", "def make_negative( number ):\n return (-1) * abs(number)", "def make_negative(number):\n if number >= 0:\n return (0 - number)\n else:\n return number", "def make...
{"fn_name": "make_negative", "inputs": [[42], [-9], [0], [1], [-1]], "outputs": [[-42], [-9], [0], [-1], [-1]]}
introductory
https://www.codewars.com/kata/55685cd7ad70877c23000102
def make_negative( number ):
3,694
Much cooler than your run-of-the-mill Fibonacci numbers, the Triple Shiftian are so defined: `T[n] = 4 * T[n-1] - 5 * T[n-2] + 3 * T[n-3]`. You are asked to create a function which accept a base with the first 3 numbers and then returns the nth element. ```python triple_shiftian([1,1,1],25) == 1219856746 triple_shifti...
["def triple_shiftian(T,n):\n for i in range(3,n+1):\n T.append(4 * T[i-1] - 5 * T[i-2] + 3 * T[i-3])\n return T[n] ", "def triple_shiftian(base, n):\n a, b, c = base\n for _ in range(n):\n a, b, c = b, c, 4 * c - 5 * b + 3 * a\n return a", "def triple_shiftian(base,n):\n #your code her...
{"fn_name": "triple_shiftian", "inputs": [[[1, 1, 1], 25], [[1, 2, 3], 25], [[3, 2, 1], 25], [[6, 7, 2], 25], [[1, 1, 1], 35], [[1, 2, 3], 35], [[3, 2, 1], 35], [[6, 7, 2], 35], [[3, 2, 1], 0], [[6, 7, 2], 2]], "outputs": [[1219856746], [2052198929], [2827228055], [-2575238999], [10127083068293], [17037073417493], [234...
introductory
https://www.codewars.com/kata/56b7526481290c2ff1000c75
def triple_shiftian(base,n):
3,695
# Task You are given a string `s`. Let's call its substring a group, if all letters in it are adjacent and the same(such as `"aa","bbb","cccc"`..). Let's call the substiring with 2 or more adjacent group a big group(such as `"aabb","bbccc"`...). Your task is to count the number of `big groups` in the given string. ...
["from re import findall; repeat_adjacent=lambda s: len(findall(r\"((.)\\2+(?!\\2)){2,}\",s))", "import re\nrepeat_adjacent=lambda s:sum(len(set(i[0]))>1 for i in re.findall(r'((([a-z])\\3+){2,})', s))", "from functools import partial\nfrom itertools import groupby\nfrom operator import ne\n\ndef repeat_adjacent(s):\n ...
{"fn_name": "repeat_adjacent", "inputs": [["ccccoodeffffiiighhhhhhhhhhttttttts"], ["soooooldieeeeeer"], ["ccccoooooooooooooooooooooooddee"], ["wwwwaaaarrioooorrrrr"], ["gztxxxxxggggggggggggsssssssbbbbbeeeeeeehhhmmmmmmmitttttttlllllhkppppp"]], "outputs": [[3], [0], [1], [2], [2]]}
introductory
https://www.codewars.com/kata/58b8dccecf49e57a5a00000e
def repeat_adjacent(string):
3,696
Make a function **"add"** that will be able to sum elements of **list** continuously and return a new list of sums. For example: ``` add [1,2,3,4,5] == [1, 3, 6, 10, 15], because it's calculated like this : [1, 1 + 2, 1 + 2 + 3, 1 + 2 + 3 + 4, 1 + 2 + 3 + 4 + 5] ``` If you want to learn more see https://en.wikiped...
["from itertools import accumulate\ndef add(l):\n return list(accumulate(l)) if isinstance(l, list) and all(isinstance(x, int) for x in l) \\\n else 'Invalid input'", "from itertools import accumulate\n\ndef add(lst):\n return list(accumulate(lst))", "from itertools import accumulate\n\ndef add(a):\n re...
{"fn_name": "add", "inputs": [[[5, 10, 15, 20, 25, 30, 35, 40]], [[6, 12, 18, 24, 30, 36, 42]], [[7, 14, 21, 28, 35, 42, 49, 56]], [[8, 16, 24, 32, 40, 48, 56, 64]], [[9, 18, 27, 36, 45, 54]]], "outputs": [[[5, 15, 30, 50, 75, 105, 140, 180]], [[6, 18, 36, 60, 90, 126, 168]], [[7, 21, 42, 70, 105, 147, 196, 252]], [[8,...
introductory
https://www.codewars.com/kata/59b44d00bf10a439dd00006f
def add(l):
3,697
A nested list (or *array* in JavaScript) is a list that apears as a value inside another list, ```python [item, item, [item, item], item] ``` in the above list, [item, item] is a nested list. Your goal is to write a function that determines the depth of the deepest nested list within a given list. return 1 if t...
["def list_depth(l):\n depths = [1]\n for x in l:\n if isinstance(x, list):\n depths.append(list_depth(x) + 1)\n return max(depths)", "def list_depth(lst):\n result = [list_depth(a) for a in lst if isinstance(a, list)]\n return 1 + max(result) if result else 1\n", "def list_depth(l):\n ...
{"fn_name": "list_depth", "inputs": [[[1, [2, [3, [4, [5, [6], 5], 4], 3], 2], 1]], [[true]], [[]], [[2, "yes", [true, false]]], [[2.0, [2, 0], 3.7, [3, 7], 6.7, [6, 7]]], [[[[[]]], [[[]]]]], [[true, false, true, [false], true]], [[[], [], [[], []]]], [[77]], [[2, "yes", [true, [false]]]], [[77, [77]]], [[[77], 77, [[7...
introductory
https://www.codewars.com/kata/56b3b9c7a6df24cf8c00000e
def list_depth(l):
3,698
In this exercise, you will have to create a function named tiyFizzBuzz. This function will take on a string parameter and will return that string with some characters replaced, depending on the value: - If a letter is a upper case consonants, replace that character with "Iron". - If a letter is a lower case consonants...
["def tiy_fizz_buzz(s):\n return \"\".join((\"Iron \"*c.isupper() + \"Yard\"*(c.lower() in \"aeiou\")).strip() or c for c in s)", "def tiy_fizz_buzz(strin):\n strin = list(strin)\n for i, char in enumerate(strin):\n if char in \"AEIOU\" : strin[i] = \"Iron Yard\"\n elif char in ...
{"fn_name": "tiy_fizz_buzz", "inputs": [[" "], ["H"], ["b"], ["A"], ["a"], ["Hello WORLD!"], ["H6H4Na ./?U"]], "outputs": [[" "], ["Iron"], ["b"], ["Iron Yard"], ["Yard"], ["IronYardllYard IronIron YardIronIronIron!"], ["Iron6Iron4IronYard ./?Iron Yard"]]}
introductory
https://www.codewars.com/kata/5889177bf148eddd150002cc
def tiy_fizz_buzz(string):
3,699
Given an array (or list) of scores, return the array of _ranks_ for each value in the array. The largest value has rank 1, the second largest value has rank 2, and so on. Ties should be handled by assigning the same rank to all tied values. For example: ranks([9,3,6,10]) = [2,4,3,1] and ranks([3,3,3,3,3,5,1...
["def ranks(a):\n sortA = sorted(a, reverse=True)\n return [sortA.index(s) + 1 for s in a]\n", "def ranks(results):\n ranks = {}\n for k, v in enumerate(sorted(results, reverse=True), start=1):\n if not v in ranks:\n ranks[v] = k\n return [ranks[i] for i in results]", "def ranks(a):\n re...
{"fn_name": "ranks", "inputs": [[[]], [[2]], [[2, 2]], [[1, 2, 3]], [[-5, -10, 3, 1]], [[-1, 3, 3, 3, 5, 5]], [[1, 10, 4]], [[5, 2, 3, 5, 5, 4, 9, 8, 0]]], "outputs": [[[]], [[1]], [[1, 1]], [[3, 2, 1]], [[3, 4, 1, 2]], [[6, 3, 3, 3, 1, 1]], [[3, 1, 2]], [[3, 8, 7, 3, 3, 6, 1, 2, 9]]]}
introductory
https://www.codewars.com/kata/545f05676b42a0a195000d95
def ranks(a):
3,700
A family of kookaburras are in my backyard. I can't see them all, but I can hear them! # How many kookaburras are there? ## Hint The trick to counting kookaburras is to listen carefully * The males go ```HaHaHa```... * The females go ```hahaha```... * And they always alternate male/female ^ Kata Note : No...
["import re\n\ndef kooka_counter(laughing):\n return len(re.findall(r'(ha)+|(Ha)+',laughing))", "def kooka_counter(laughing):\n return 0 if laughing == '' else laughing.count('Hah') + laughing.count('haH') + 1", "def kooka_counter(laughing):\n return laughing.count(\"Haha\") + laughing.count(\"haHa\") + bool(l...
{"fn_name": "kooka_counter", "inputs": [[""], ["hahahahaha"], ["hahahahahaHaHaHa"], ["HaHaHahahaHaHa"], ["hahahahahahahaHaHa"]], "outputs": [[0], [1], [2], [3], [2]]}
introductory
https://www.codewars.com/kata/58e8cad9fd89ea0c6c000258
def kooka_counter(laughing):
3,701
Write a function that calculates the *least common multiple* of its arguments; each argument is assumed to be a non-negative integer. In the case that there are no arguments (or the provided array in compiled languages is empty), return `1`. ~~~if:objc NOTE: The first (and only named) argument of the function `n` spec...
["from functools import reduce\ndef lcm(*args):\n return reduce(lcms, args) if args else 1\n\ndef gcd(a,b):\n \"\"\"Euclidean Algorithm\"\"\"\n return b if a == 0 else gcd(b % a, a)\n \ndef lcms(a, b):\n return (a*b) // gcd(a,b)", "from math import gcd\nfrom functools import reduce\ndef lcm(*args):\n ...
{"fn_name": "lcm", "inputs": [[2, 5], [2, 3, 4], [9], [0], [0, 1], [1, 1, 1], [5, 6, 7, 9, 6, 9, 18, 4, 5, 15, 15, 10, 17, 7], [17, 20, 4, 15, 4, 18, 12, 14, 20, 19, 2, 14, 13, 7], [11, 13, 4, 5, 17, 4, 10, 13, 16, 13, 13], [20, 1, 6, 10, 3, 7, 8, 4], [3, 9, 9, 19, 18, 14, 18, 9], [3, 9, 9, 19, 18, 14, 18, 0]], "output...
introductory
https://www.codewars.com/kata/5259acb16021e9d8a60010af
def lcm(*args):
3,702
To celebrate the start of the Rio Olympics (and the return of 'the Last Leg' on C4 tonight) this is an Olympic inspired kata. Given a string of random letters, you need to examine each. Some letters naturally have 'rings' in them. 'O' is an obvious example, but 'b', 'p', 'e', 'A', etc are all just as applicable. 'B' e...
["def olympic_ring(string):\n return (['Not even a medal!'] * 2 + ['Bronze!', 'Silver!', 'Gold!'])[min(4, sum(map(\"abdegopqABBDOPQR\".count, string)) // 2)]", "def olympic_ring(string):\n rings = string.translate(str.maketrans(\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',\n '120100000000001111...
{"fn_name": "olympic_ring", "inputs": [["wHjMudLwtoPGocnJ"], ["eCEHWEPwwnvzMicyaRjk"], ["JKniLfLW"], ["EWlZlDFsEIBufsalqof"], ["IMBAWejlGRTDWetPS"]], "outputs": [["Bronze!"], ["Bronze!"], ["Not even a medal!"], ["Silver!"], ["Gold!"]]}
introductory
https://www.codewars.com/kata/57d06663eca260fe630001cc
def olympic_ring(string):
3,703
The pizza store wants to know how long each order will take. They know: - Prepping a pizza takes 3 mins - Cook a pizza takes 10 mins - Every salad takes 3 mins to make - Every appetizer takes 5 mins to make - There are 2 pizza ovens - 5 pizzas can fit in a oven - Prepping for a pizza must be done before it can be put ...
["from math import ceil\n\ndef order(pizzas, salads, appetizers):\n tp = 3 * pizzas / 2 + 10 * math.ceil(pizzas / 10)\n ts = 3 * salads + 5 * appetizers\n return max(tp, ts)\n", "def order(pizzas, salads, appetizers):\n side_total = 0\n pizza_total = 0 \n side_total += salads * 3 \n side_total += a...
{"fn_name": "order", "inputs": [[2, 0, 0], [3, 1, 2], [0, 3, 2], [13, 0, 0], [6, 2, 4], [6, 1, 3], [5, 3, 4]], "outputs": [[13], [14.5], [19], [39.5], [26], [19], [29]]}
introductory
https://www.codewars.com/kata/59e255c07997cb248500008c
def order(pizzas, salads, appetizers):
3,704
# Solve For X You will be given an equation as a string and you will need to [solve for X](https://www.mathplacementreview.com/algebra/basic-algebra.php#solve-for-a-variable) and return x's value. For example: ```python solve_for_x('x - 5 = 20') # should return 25 solve_for_x('20 = 5 * x - 5') # should return 5 solv...
["from itertools import count\n\ndef solve_for_x(equation):\n return next( x for n in count(0) for x in [n, -n] if eval(equation.replace(\"x\", str(x)).replace(\"=\", \"==\")) )", "import re\ndef solve_for_x(equation):\n left,right = equation.split(\"=\")\n answer = False\n TrialAndErrorRipMs = -1000\n w...
{"fn_name": "solve_for_x", "inputs": [["x - 5 = 20"], ["5 * x + 5 = 30"], ["20 = 5 * x - 5"], ["24 = 4 + 5 * x"], ["x = 5"], ["x * 100 = 700"], ["2 * x + 5 = 105"], ["2 * x = 198"], ["x - 100 + 2 - 50 = 52"], ["x / 3 = 33"], ["x + 80 = 20"], ["x + 20 = -60"], ["5 * x + 20 - x = 60"], ["x + x + 6 = 10"], ["5 * x = x + 8...
introductory
https://www.codewars.com/kata/59c2e2a36bddd2707e000079
def solve_for_x(equation):
3,705
Write function heron which calculates the area of a triangle with sides a, b, and c. Heron's formula: sqrt (s \* (s - a) \* (s - b) \* (s - c)), where s = (a + b + c) / 2. Output should have 2 digits precision.
["import math\ndef heron(a,b,c):\n s=(a+b+c)/2\n return round(math.sqrt(s*(s-a)*(s-b)*(s - c)),2)", "def heron(a,b,c):\n return round((1/4)*(4*b*b*c*c-(b*b+c*c-a*a)**2)**(1/2),2)", "heron=lambda*args:(lambda a,b,c,s:round((s*(s-a)*(s-b)*(s-c))**.5,2))(*args,sum(args)/2)", "def heron(*sides):\n s=sum(sides)/...
{"fn_name": "heron", "inputs": [[3, 4, 5], [6, 8, 10]], "outputs": [[6], [24]]}
introductory
https://www.codewars.com/kata/57aa218e72292d98d500240f
def heron(a,b,c):
3,706
Assume that you started to store items in progressively expanding square location, like this for the first 9 numbers: ``` 05 04 03 06 01 02 07 08 09 ``` And like this for the expanding to include up to the first 25 numbers: ``` 17 16 15 14 13 18 05 04 03 12 19 06 01 02 11 20 07 08 09 10 21 22 23 24 25 ``` You might...
["from math import ceil, sqrt\n\ndef layers(n):\n return ceil(sqrt(n)) // 2 + 1", "def layers(n):\n return (1 + (n-1)**.5) // 2 + 1", "def layers(n):\n i = 1\n r = 1\n while i*i < n: \n i += 2\n r += 1\n \n return r", "import math\ndef layers(n):\n return math.ceil( (n**0.5 + 1...
{"fn_name": "layers", "inputs": [[1], [5], [25], [30], [50]], "outputs": [[1], [2], [3], [4], [5]]}
introductory
https://www.codewars.com/kata/5a254114e1ce0ecf6a000168
def layers(n):
3,707
HELP! Jason can't find his textbook! It is two days before the test date, and Jason's textbooks are all out of order! Help him sort a list (ArrayList in java) full of textbooks by subject, so he can study before the test. The sorting should **NOT** be case sensitive
["def sorter(textbooks):\n return sorted(textbooks,key=str.lower)", "def sorter(textbooks):\n return sorted(textbooks, key=str.casefold)", "def sorter(textbooks):\n return sorted(textbooks, key = lambda arg: arg.lower())", "sorter = lambda x: sorted(x,key=lambda s:s.lower())", "sorter = lambda text: sorted(tex...
{"fn_name": "sorter", "inputs": [[["Algebra", "History", "Geometry", "English"]], [["Algebra", "history", "Geometry", "english"]], [["Alg#bra", "$istory", "Geom^try", "**english"]]], "outputs": [[["Algebra", "English", "Geometry", "History"]], [["Algebra", "english", "Geometry", "history"]], [["$istory", "**english", "...
introductory
https://www.codewars.com/kata/5a07e5b7ffe75fd049000051
def sorter(textbooks):
3,708
Complete the function which converts hex number (given as a string) to a decimal number.
["def hex_to_dec(s):\n return int(s, 16)", "from functools import partial\nhex_to_dec = partial(int, base=16)", "def hex_to_dec(s):\n key = \"0123456789abcdef\"\n n=0\n res=0\n for l in s[::-1]:\n res += key.index(l)*(16.**n)\n n+=1\n \n return int(res)", "hex_to_dec = lambda s: i...
{"fn_name": "hex_to_dec", "inputs": [["1"], ["a"], ["10"]], "outputs": [[1], [10], [16]]}
introductory
https://www.codewars.com/kata/57a4d500e298a7952100035d
def hex_to_dec(s):
3,709
This kata is about multiplying a given number by eight if it is an even number and by nine otherwise.
["def simple_multiplication(number) :\n return number * 9 if number % 2 else number * 8", "def simple_multiplication(n) :\n return n * (8 + n%2)", "def simple_multiplication(number) :\n return number * (8 if number % 2 == 0 else 9)", "simple_multiplication = lambda a : a * (8 + (a & 1))", "simple_multiplicatio...
{"fn_name": "simple_multiplication", "inputs": [[2], [1], [8], [4], [5]], "outputs": [[16], [9], [64], [32], [45]]}
introductory
https://www.codewars.com/kata/583710ccaa6717322c000105
def simple_multiplication(number) :
3,710
This is the performance edition of [this kata](https://www.codewars.com/kata/ulam-sequences). If you didn't do it yet, you should begin there. --- The Ulam sequence U is defined by `u0=u`, `u1=v`, with the general term `u_n` for `n>2` given by the least integer expressible uniquely as the sum of two distinct earlier ...
["def ulam_sequence(u, v, n):\n lst, seq, ex, q = [], 1, 1, 1 << v | 1 << u # Put u and v into queue\n for _ in range(n): # Repeat n times\n w = q & -q # Take the smallest candidate\n l = w.bit_length() - 1 # and its value\n ...
{"fn_name": "ulam_sequence", "inputs": [[1, 2, 5], [3, 4, 5], [5, 6, 8]], "outputs": [[[1, 2, 3, 4, 6]], [[3, 4, 7, 10, 11]], [[5, 6, 11, 16, 17, 21, 23, 26]]]}
introductory
https://www.codewars.com/kata/5ac94db76bde60383d000038
def ulam_sequence(u0, u1, n):
3,711
Create a function xMasTree(height) that returns a christmas tree of the correct height. The height is passed through to the function and the function should return a list containing each line of the tree. ``` xMasTree(5) should return : ['____#____', '___###___', '__#####__', '_#######_', '#########', '____#____', '__...
["def xMasTree(n):\n return [(\"#\"*(x*2+1)).center(n*2-1, \"_\") for x in list(range(n))+[0]*2]", "def xMasTree(n):\n hashtags = '#' * (n - 1)\n spaces = '_' * (n - 1)\n tree = []\n for i in range(n):\n left = spaces[i:] + hashtags[:i]\n tree.append(left + '#' + left[::-1])\n for i in ra...
{"fn_name": "xMasTree", "inputs": [[3], [7], [2], [4], [6]], "outputs": [[["__#__", "_###_", "#####", "__#__", "__#__"]], [["______#______", "_____###_____", "____#####____", "___#######___", "__#########__", "_###########_", "#############", "______#______", "______#______"]], [["_#_", "###", "_#_", "_#_"]], [["___#__...
introductory
https://www.codewars.com/kata/577c349edf78c178a1000108
def xMasTree(n):
3,712
## Task Your challenge is to write a function named `getSlope`/`get_slope`/`GetSlope` that calculates the slope of the line through two points. ## Input ```if:javascript,python Each point that the function takes in is an array 2 elements long. The first number is the x coordinate and the second number is the y coord...
["def getSlope(p1, p2):\n return None if p1[0] == p2[0] else (p2[1] - p1[1])/(p2[0] - p1[0])\n", "def getSlope(p1, p2):\n if p2[0] - p1[0]: return (p2[1]-p1[1]) / (p2[0]-p1[0])", "def getSlope(p1, p2):\n return None if p1[0] == p2[0] else (p1[1] - p2[1]) / (p1[0] - p2[0])", "def getSlope(p1, p2):\n if not (...
{"fn_name": "getSlope", "inputs": [[[1, 1], [2, 2]], [[-5, -5], [9, 9]], [[1, 8], [2, 9]], [[8, 3], [-4, 5]], [[5, 3], [8, 9]], [[1, 3], [0, 3]], [[11, 1], [1, 11]], [[1, 1], [1, 2]], [[-5, 9], [-5, 12]], [[1, 1], [1, 1]], [[-5, 9], [-5, 9]]], "outputs": [[1], [1], [1], [-0.16666666666666666], [2], [0], [-1], [null], [...
introductory
https://www.codewars.com/kata/53222010db0eea35ad000001
def getSlope(p1, p2):
3,713
An ordered sequence of numbers from 1 to N is given. One number might have deleted from it, then the remaining numbers were mixed. Find the number that was deleted. Example: - The starting array sequence is `[1,2,3,4,5,6,7,8,9]` - The mixed array with one deleted number is `[3,2,4,6,7,8,1,9]` - Your function shoul...
["def find_deleted_number(arr, mixed_arr):\n return sum(arr)-sum(mixed_arr)", "def find_deleted_number(a, b):\n return (set(a) - set(b)).pop() if len(a) != len(b) else 0", "def find_deleted_number(arr, mixed_arr):\n lost = 0\n for i in arr:\n if i not in mixed_arr:\n lost = i\n ...
{"fn_name": "find_deleted_number", "inputs": [[[1, 2, 3, 4, 5, 6, 7, 8, 9], [5, 7, 9, 4, 8, 1, 2, 3]], [[1, 2, 3, 4, 5, 6, 7], [2, 3, 6, 1, 5, 4, 7]], [[1, 2, 3, 4, 5, 6, 7, 8, 9], [5, 7, 6, 9, 4, 8, 1, 2, 3]], [[1], []], [[], []]], "outputs": [[6], [0], [0], [1], [0]]}
introductory
https://www.codewars.com/kata/595aa94353e43a8746000120
def find_deleted_number(arr, mixed_arr):
3,714
In this kata, you need to make a (simplified) LZ78 encoder and decoder. [LZ78](https://en.wikipedia.org/wiki/LZ77_and_LZ78#LZ78) is a dictionary-based compression method created in 1978. You will find a detailed explanation about how it works below. The input parameter will always be a non-empty string of upper case ...
["import re\n\ndef encoder(s):\n d, out, it = {},[], iter(s)\n for c in it:\n i,k = 0,c\n while k in d: \n i,c = d[k], next(it,'')\n if not c: break\n k += c\n d[k] = len(d)+1\n out.append(f'{i}{c}')\n return ''.join(out)\n\n\ndef decoder(s):\n d ...
{"fn_name": "encoder", "inputs": [["ABAABABAABAB"], ["ABAABABAABABAA"], ["ABBCBCABABCAABCAABBCAA"], ["AAAAAAAAAAAAAAA"], ["ABCABCABCABCABCABC"], ["ABCDDEFGABCDEDBBDEAAEDAEDCDABC"]], "outputs": [["0A0B1A2A4A4B"], ["0A0B1A2A4A4B3"], ["0A0B2C3A2A4A6B6"], ["0A1A2A3A4A"], ["0A0B0C1B3A2C4C7A6"], ["0A0B0C0D4E0F0G1B3D0E4B2D10A...
introductory
https://www.codewars.com/kata/5db42a943c3c65001dcedb1a
def encoder(data):
3,715
# Task The sequence of `Chando` is an infinite sequence of all Chando's numbers in ascending order. A number is called `Chando's` if it is an integer that can be represented as a sum of different positive integer powers of 5. The first Chando's numbers is 5 (5^1). And the following nth Chando's numbers are: ``` ...
["def nth_chandos_number(n):\n return int((bin(n)+\"0\")[2:], 5)", "from itertools import combinations, chain\nfrom math import log\ndef nth_chandos_number(n):\n l = [0] + [5 ** i for i in range(1, int(log(n, 5)) + 10)]\n m = chain(*[combinations(l, ni) for ni in range(1, len(l) + 1)])\n ls = sorted(list(se...
{"fn_name": "nth_chandos_number", "inputs": [[1], [2], [9], [123], [23]], "outputs": [[5], [25], [630], [97530], [3280]]}
introductory
https://www.codewars.com/kata/58aa8368ae929ea2e00000d9
def nth_chandos_number(n):
3,716
In another Kata I came across a weird `sort` function to implement. We had to sort characters as usual ( 'A' before 'Z' and 'Z' before 'a' ) except that the `numbers` had to be sorted **after** the `letters` ( '0' after 'z') !!! (After a couple of hours trying to solve this unusual-sorting-kata I discovered final test...
["def unusual_sort(array):\n return sorted(array, key=lambda x: (str(x).isdigit(), str(x), -isinstance(x, int)))", "def unusual_sort(array):\n return sorted(array, key=lambda item: (str(item).isdigit(), str(item), isinstance(item, str)))", "import string\n\n\ndef unusual_sort(array):\n #your code here\n upp...
{"fn_name": "unusual_sort", "inputs": [[["0", "9", "8", "1", "7", "2", "6", "3", "5", "4"]], [["3", "2", "1", "c", "b", "a"]], [["c", "b", "a", "9", "5", "0", "X", "Y", "Z"]], [[3, "3", "2", 2, "2", "1", 1, "a", "b", "c"]], [[]], [[1]], [["a"]]], "outputs": [[["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]], [["a", ...
introductory
https://www.codewars.com/kata/5443b8857fc4473cb90008e4
def unusual_sort(array):
3,717
Given a list of white pawns on a chessboard (any number of them, meaning from 0 to 64 and with the possibility to be positioned everywhere), determine how many of them have their backs covered by another. Pawns attacking upwards since we have only white ones. Please remember that a pawn attack(and defend as well) onl...
["def covered_pawns(pawns):\n pawns = set(pawns)\n return len({p for p in pawns for x,y in [map(ord, p)] if {chr(x-1)+chr(y-1), chr(x+1)+chr(y-1)} & pawns})", "def covered_pawns(pawns):\n count = 0\n for i in range(len(pawns)):\n x, y = list(pawns[i])\n if \"\".join([chr(ord(x) - 1), str(int(y...
{"fn_name": "covered_pawns", "inputs": [[["f7", "b1", "h1", "c7", "h7"]], [["e5", "b2", "b4", "g4", "a1", "a5"]], [["a2", "b1", "c2"]], [["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "d1", "d2", "d3", "d4", "d5", "d6", "d...
introductory
https://www.codewars.com/kata/597cfe0a38015079a0000006
def covered_pawns(pawns):
3,718
Count the number of divisors of a positive integer `n`. Random tests go up to `n = 500000`. ## Examples ```python divisors(4) == 3 # 1, 2, 4 divisors(5) == 2 # 1, 5 divisors(12) == 6 # 1, 2, 3, 4, 6, 12 divisors(30) == 8 # 1, 2, 3, 5, 6, 10, 15, 30 ```
["def divisors(n):\n return len([l_div for l_div in range(1, n + 1) if n % l_div == 0]);", "# For Beginners.\n\n# Time: 11724ms\n# it's slow because use isinstance\ndef divisors5(n):\n return len(list([e for e in [x if n % x == 0 else None for x in range(1, n + 1)] if isinstance(e, int)]))\n\n\n# Time: 7546ms\n#...
{"fn_name": "divisors", "inputs": [[1], [4], [5], [12], [25], [30], [4096]], "outputs": [[1], [3], [2], [6], [3], [8], [13]]}
introductory
https://www.codewars.com/kata/542c0f198e077084c0000c2e
def divisors(n):
3,719
For a pole vaulter, it is very important to begin the approach run at the best possible starting mark. This is affected by numerous factors and requires fine-tuning in practice. But there is a guideline that will help a beginning vaulter start at approximately the right location for the so-called "three-step approach,"...
["def starting_mark(height):\n return round(9.45 + (10.67 - 9.45) / (1.83 - 1.52) * (height - 1.52), 2)", "# The linear relashionship is obvious taking a couple a informations (L1,H1) and (L2,H2)\n# One gets 3.9354838709677433 = (H1-H2)/(L1-L2) and beta = H1-3.9354838709677433*H1\n\ndef starting_mark(height):\n r...
{"fn_name": "starting_mark", "inputs": [[1.52], [1.83], [1.22], [2.13], [1.75]], "outputs": [[9.45], [10.67], [8.27], [11.85], [10.36]]}
introductory
https://www.codewars.com/kata/5786f8404c4709148f0006bf
def starting_mark(height):
3,720
Complete the function that accepts a valid string and returns an integer. Wait, that would be too easy! Every character of the string should be converted to the hex value of its ascii code, then the result should be the sum of the numbers in the hex strings (ignore letters). ## Examples ``` "Yo" ==> "59 6f" ==> 5 + 9...
["def hex_hash(code):\n return sum(int(d) for c in code for d in hex(ord(c)) if d.isdigit())", "def hex_hash(s):\n return sum(sum(int(c) for c in hex(ord(c))[2:] if c in \"0123456789\") for c in s)", "def hex_hash(code):\n first = ''\n for i in code :\n first += hex(ord(i))[2:]\n second = ''\n ...
{"fn_name": "hex_hash", "inputs": [["kcxnjsklsHskjHDkl7878hHJk"], [""], ["ThisIsATest!"], ["dhsajkbfyewquilb4y83q903ybr8q9apf7\\9ph79qw0-eq230br[wq87r0=18-[#20r370B 7Q0RFP23B79037902RF79WQ0[]]]"]], "outputs": [[218], [0], [120], [802]]}
introductory
https://www.codewars.com/kata/5ab363ff6a176b29880000dd
def hex_hash(code):
3,721
Count how often sign changes in array. ### result number from `0` to ... . Empty array returns `0` ### example
["def catch_sign_change(lst):\n count = 0\n for i in range(1,len(lst)):\n if lst[i] < 0 and lst[i-1] >= 0:count += 1\n if lst[i] >= 0 and lst[i-1] < 0:count += 1\n return count", "def catch_sign_change(lst):\n return sum( (x >= 0) != (y >= 0) for x, y in zip(lst, lst[1:]) )", "def catch_sign_c...
{"fn_name": "catch_sign_change", "inputs": [[[-7, -7, 7, 0]], [[1, 5, 2, -4]], [[-8, 4, -1, 5, -3, -3, -2, -2]], [[-2, -2, -5, -4, 5, 2, 0, 6, 0]], [[2, 6, 3, 0, 5, -3]], [[-3, 3]], [[-1, 2, 2, 2, 2, -8, -1]], [[1, -2, -7, -4, 4, -2, 0, -3, 3]], [[3, 7, -6, 2, 3, 1, 1]], [[13, -7, -6, 2, -1, 1, -1]], [[]], [[0]], [[4, ...
introductory
https://www.codewars.com/kata/5bbb8887484fcd36fb0020ca
def catch_sign_change(lst):
3,722
Create a function that returns the average of an array of numbers ("scores"), rounded to the nearest whole number. You are not allowed to use any loops (including for, for/in, while, and do/while loops).
["def average(array):\n return round(sum(array) / len(array))", "from statistics import mean\n\ndef average(array):\n return round(mean(array))", "from statistics import mean\ndef average(array):\n return int(round(mean(array), 0))", "from numpy import mean\ndef average(array):\n return round(mean(array))",...
{"fn_name": "average", "inputs": [[[5, 78, 52, 900, 1]], [[5, 25, 50, 75]], [[2]], [[1, 1, 1, 1, 9999]], [[0]]], "outputs": [[207], [39], [2], [2001], [0]]}
introductory
https://www.codewars.com/kata/57b68bc7b69bfc8209000307
def average(array):
3,723
## Task You are given an array of integers. On each move you are allowed to increase exactly one of its element by one. Find the minimal number of moves required to obtain a strictly increasing sequence from the input. ## Example For `arr = [1, 1, 1]`, the output should be `3`. ## Input/Output - `[input]` integ...
["from functools import reduce\n\narray_change = lambda arr: reduce(lambda a, u: (max(a[0] + 1, u), a[1] + max(0, a[0] - u + 1)), arr, (-10001, 0))[1]", "def array_change(arr):\n if not arr: return 0\n x, y = arr[0], 0\n for i in arr[1:]:\n x = max(x + 1, i)\n y += x - i\n return y", "def array_change(arr):\n...
{"fn_name": "array_change", "inputs": [[[1, 1, 1]], [[-1000, 0, -2, 0]], [[2, 1, 10, 1]], [[2, 3, 3, 5, 5, 5, 4, 12, 12, 10, 15]]], "outputs": [[3], [5], [12], [13]]}
introductory
https://www.codewars.com/kata/5893f43b779ce54da4000124
def array_change(arr):
3,724
A hero is on his way to the castle to complete his mission. However, he's been told that the castle is surrounded with a couple of powerful dragons! each dragon takes 2 bullets to be defeated, our hero has no idea how many bullets he should carry.. Assuming he's gonna grab a specific given number of bullets and move fo...
["def hero(bullets, dragons):\n return bullets >= dragons * 2", "def hero(bullets, dragons):\n '''\n Ascertains if hero can survive\n Parameters:\n bullets: (int) - number of bullets hero has\n dragons: (int) - number of dragons\n Returns:\n True (Survive) or False (Hero gets killed)...
{"fn_name": "hero", "inputs": [[10, 5], [7, 4], [4, 5], [100, 40], [1500, 751], [0, 1]], "outputs": [[true], [false], [false], [true], [false], [false]]}
introductory
https://www.codewars.com/kata/59ca8246d751df55cc00014c
def hero(bullets, dragons):
3,725
You are given two strings. In a single move, you can choose any of them, and delete the first (i.e. leftmost) character. For Example: * By applying a move to the string `"where"`, the result is the string `"here"`. * By applying a move to the string `"a"`, the result is an empty string `""`. Implement a function tha...
["def shift_left(a, b):\n r = len(a) + len(b)\n for i in range(-1, -min(len(a), len(b)) - 1, -1):\n if a[i] != b[i]:\n break\n r -= 2\n return r", "def shift_left(a, b):\n r = 0\n while a != b:\n if len(b) > len(a):\n b = b[1::] \n r += 1\n els...
{"fn_name": "shift_left", "inputs": [["test", "west"], ["test", "yes"], ["b", "ab"], ["abacabadabacaba", "abacabadacaba"], ["aaabc", "bc"], ["dark", "d"], ["dadc", "dddc"], ["nogkvcdldfpvlbkpedsecl", "nogkvcdldfpvlbkpedsecl"]], "outputs": [[2], [7], [1], [18], [3], [5], [4], [0]]}
introductory
https://www.codewars.com/kata/5bdc191306a8a678f6000187
def shift_left(a, b):
3,726
You have an array of numbers. Your task is to sort ascending odd numbers but even numbers must be on their places. Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it. *Example* ```python sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4] ```
["def sort_array(arr):\n odds = sorted((x for x in arr if x%2 != 0), reverse=True)\n return [x if x%2==0 else odds.pop() for x in arr]", "def sort_array(source_array):\n odds = iter(sorted(v for v in source_array if v % 2))\n return [next(odds) if i % 2 else i for i in source_array]", "def sort_array(source_arr...
{"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, 2, 8, 5, 4, 11]], [[2, 22, 1, 5, 4, 11, 37, 0]], [[1, 1, 5, 11, 2, 11, ...
introductory
https://www.codewars.com/kata/578aa45ee9fd15ff4600090d
def sort_array(source_array):
3,727
# Pythagorean Triples A Pythagorean triplet is a set of three numbers a, b, and c where `a^2 + b^2 = c^2`. In this Kata, you will be tasked with finding the Pythagorean triplets whose product is equal to `n`, the given argument to the function `pythagorean_triplet`. ## Your task In this Kata, you will be tasked with...
["def pythagorean_triplet(n):\n for a in range(3, n):\n for b in range(a+1, n):\n c = (a*a + b*b)**0.5\n if a*b*c > n:\n break\n if c == int(c) and a*b*c == n:\n return [a, b, c]", "def getTriplets(n):\n divs = {y for x in range(1,int(n**.5)+1)...
{"fn_name": "pythagorean_triplet", "inputs": [[60], [780], [2040], [4200], [12180], [120120], [192720], [328860], [907200], [1440600]], "outputs": [[[3, 4, 5]], [[5, 12, 13]], [[8, 15, 17]], [[7, 24, 25]], [[20, 21, 29]], [[33, 56, 65]], [[48, 55, 73]], [[60, 63, 87]], [[42, 144, 150]], [[49, 168, 175]]]}
introductory
https://www.codewars.com/kata/59c32c609f0cbce0ea000073
def pythagorean_triplet(n):
3,728
Write function describeList which returns "empty" if the list is empty or "singleton" if it contains only one element or "longer"" if more.
["def describeList(lst):\n return [\"empty\",\"singleton\",\"longer\"][min(len(lst),2)]", "def describeList(list):\n return \"empty\" if not list else \"singleton\" if len(list) == 1 else \"longer\"", "def describeList(list):\n return ['empty', 'singleton', 'longer'][len(list[:2])]", "def describeList(list):\n...
{"fn_name": "describeList", "inputs": [[[]], [[1]], [[1, 2, 5, 4]], [["one"]], [["one", "two"]], [[[1, 2]]]], "outputs": [["empty"], ["singleton"], ["longer"], ["singleton"], ["longer"], ["singleton"]]}
introductory
https://www.codewars.com/kata/57a4a3e653ba3346bc000810
def describeList(list):
3,729
Define n!! as n!! = 1 \* 3 \* 5 \* ... \* n if n is odd, n!! = 2 \* 4 \* 6 \* ... \* n if n is even. Hence 8!! = 2 \* 4 \* 6 \* 8 = 384, there is no zero at the end. 30!! has 3 zeros at the end. For a positive integer n, please count how many zeros are there at the end of n!!. Example: count\_zeros\_n\_d...
["def count_zeros_n_double_fact(n): \n if n % 2 != 0:\n return 0\n k = 0\n while n >= 10:\n k += n // 10\n n //= 5\n return k", "def count_zeros_n_double_fact(n):\n return 0 if n%2 == 1 else (n // 6250) + (n // 1250) + (n // 250) + ( n // 50 ) + ( n // 10 ) ", "from functools import ...
{"fn_name": "count_zeros_n_double_fact", "inputs": [[8], [30], [487], [500]], "outputs": [[0], [3], [0], [62]]}
introductory
https://www.codewars.com/kata/58cbfe2516341cce1e000001
def count_zeros_n_double_fact(n):
3,730
Given a string, capitalize the letters that occupy even indexes and odd indexes separately, and return as shown below. Index `0` will be considered even. For example, `capitalize("abcdef") = ['AbCdEf', 'aBcDeF']`. See test cases for more examples. The input will be a lowercase string with no spaces. Good luck! If y...
["def capitalize(s):\n s = ''.join(c if i%2 else c.upper() for i,c in enumerate(s))\n return [s, s.swapcase()]", "def capitalize(s):\n result = ['','']\n for i,c in enumerate(s):\n result[0] += c.lower() if i % 2 else c.upper()\n result[1] += c.upper() if i % 2 else c.lower()\n return resul...
{"fn_name": "capitalize", "inputs": [["abcdef"], ["codewars"], ["abracadabra"], ["codewarriors"], ["indexinglessons"], ["codingisafunactivity"]], "outputs": [[["AbCdEf", "aBcDeF"]], [["CoDeWaRs", "cOdEwArS"]], [["AbRaCaDaBrA", "aBrAcAdAbRa"]], [["CoDeWaRrIoRs", "cOdEwArRiOrS"]], [["InDeXiNgLeSsOnS", "iNdExInGlEsSoNs"]]...
introductory
https://www.codewars.com/kata/59cfc000aeb2844d16000075
def capitalize(s):
3,731
This is simple version of harder [Square Sums](/kata/square-sums). # Square sums Write function `square_sums_row` (or `squareSumsRow`/`SquareSumsRow` depending on language rules) that, given integer number `N` (in range `2..43`), returns array of integers `1..N` arranged in a way, so sum of each 2 consecutive numbers...
["def square_sums_row(n):\n\n def dfs():\n if not inp: yield res\n for v in tuple(inp):\n if not res or not ((res[-1]+v)**.5 % 1):\n res.append(v)\n inp.discard(v)\n yield from dfs()\n inp.add(res.pop())\n\n inp, res = set(range(...
{"fn_name": "square_sums_row", "inputs": [[5], [24]], "outputs": [[false], [false]]}
introductory
https://www.codewars.com/kata/5a6b24d4e626c59d5b000066
def square_sums_row(n):
3,732
A Madhav array has the following property: ```a[0] = a[1] + a[2] = a[3] + a[4] + a[5] = a[6] + a[7] + a[8] + a[9] = ...``` Complete the function/method that returns `true` if the given array is a Madhav array, otherwise it returns `false`. *Edge cases: An array of length* `0` *or* `1` *should not be considered a Mad...
["def is_madhav_array(arr):\n nTerms = ((1+8*len(arr))**.5-1)/2\n return (len(arr) > 1 and not nTerms%1 and\n len({ sum(arr[int(i*(i+1)//2):int(i*(i+1)//2)+i+1]) for i in range(int(nTerms))}) == 1)", "def is_madhav_array(arr):\n p = 1\n c = 2\n while p < len(arr) and arr[0] == sum(arr[p:p + c]...
{"fn_name": "is_madhav_array", "inputs": [[[6, 2, 4, 2, 2, 2, 1, 5, 0, 0]], [[6, 2, 4, 2, 2, 2, 1, 5, 0, -100]], [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, -2, -1]], [[-6, -3, -3, 8, -5, -4]], [[-6, -3, -3, 8, -10, -4]], [[3, 1, 2, 3, 0]], [[3, 3]], [[]], [[1]], [[5, 2, 4, 1, 0, 3]], [[6, 2, 4, 2, 2, 2, 1, 5, 0, 0, -12, ...
introductory
https://www.codewars.com/kata/59b0492f7d3c9d7d4a0000bd
def is_madhav_array(arr):
3,733
In your class, you have started lessons about [arithmetic progression](https://en.wikipedia.org/wiki/Arithmetic_progression). Since you are also a programmer, you have decided to write a function that will return the first `n` elements of the sequence with the given common difference `d` and first element `a`. Note tha...
["def arithmetic_sequence_elements(a, r, n):\n return ', '.join(str(a + b * r) for b in range(n))\n", "def arithmetic_sequence_elements(a, r, n):\n return \", \".join((str(a+r*i) for i in range(n)))", "from itertools import count, islice\n\ndef arithmetic_sequence_elements(a, r, n):\n return ', '.join([str(x) ...
{"fn_name": "arithmetic_sequence_elements", "inputs": [[1, 2, 5], [1, 0, 5], [1, -3, 10], [100, -10, 10]], "outputs": [["1, 3, 5, 7, 9"], ["1, 1, 1, 1, 1"], ["1, -2, -5, -8, -11, -14, -17, -20, -23, -26"], ["100, 90, 80, 70, 60, 50, 40, 30, 20, 10"]]}
introductory
https://www.codewars.com/kata/55caf1fd8063ddfa8e000018
def arithmetic_sequence_elements(a, r, n):
3,734
# The die is cast! Your task in this kata is to write a "dice roller" that interprets a subset of [dice notation](http://en.wikipedia.org/wiki/Dice_notation). # Description In most role-playing games, die rolls required by the system are given in the form `AdX`. `A` and `X` are variables, separated by the letter **d...
["import re, random\n\ndef roll(desc, verbose=False):\n if not isinstance(desc,str): return False\n \n ans = re.findall(r'^(\\d*)d(\\d+)(([+\\-]\\d+)*)$', desc.replace(' ',''))\n \n if len(ans) == 0: return False\n \n dct = {i: eval(v) for i,v in enumerate(ans[0]) if v}\n dices = {'dice': [ ...
{"fn_name": "roll", "inputs": [[""], [{}], ["abc"], ["2d6+3 abc"], ["abc 2d6+3"], ["2d6++4"]], "outputs": [[false], [false], [false], [false], [false], [false]]}
introductory
https://www.codewars.com/kata/549cb9c0c36a02ce2e000156
def roll(desc, verbose=False):
3,735
You will get an array of numbers. Every preceding number is smaller than the one following it. Some numbers will be missing, for instance: ``` [-3,-2,1,5] //missing numbers are: -1,0,2,3,4 ``` Your task is to return an array of those missing numbers: ``` [-1,0,2,3,4] ```
["def find_missing_numbers(arr):\n if not arr:\n return []\n return sorted(set(range(arr[0] + 1, arr[-1])).difference(arr))\n", "def find_missing_numbers(arr):\n return [x for x in range(arr[0], arr[-1]+1) if x not in arr] if arr else []", "def find_missing_numbers(arr):\n return [n for n in range(ar...
{"fn_name": "find_missing_numbers", "inputs": [[[-3, -2, 1, 4]], [[-1, 0, 1, 2, 3, 4]], [[]], [[0]], [[-4, 4]]], "outputs": [[[-1, 0, 2, 3]], [[]], [[]], [[]], [[-3, -2, -1, 0, 1, 2, 3]]]}
introductory
https://www.codewars.com/kata/56d02e6cc6c8b49c510005bb
def find_missing_numbers(arr):
3,736
Your task is to make two functions, ```max``` and ```min``` (`maximum` and `minimum` in PHP and Python) that take a(n) array/vector of integers ```list``` as input and outputs, respectively, the largest and lowest number in that array/vector. #Examples ```python maximun([4,6,2,1,9,63,-134,566]) returns 566 minimun([-5...
["minimum = min\nmaximum = max", "minimum,maximum = min,max", "def minimum(arr):\n return min(arr)\n\ndef maximum(arr):\n return max(arr)", "\ndef minimum(arr):\n min = None\n for i in arr:\n if min == None:\n min = i\n elif i < min:\n min = i\n return min\n \nd...
{"fn_name": "minimum", "inputs": [[[-52, 56, 30, 29, -54, 0, -110]], [[42, 54, 65, 87, 0]], [[1, 2, 3, 4, 5, 10]], [[-1, -2, -3, -4, -5, -10]], [[9]]], "outputs": [[-110], [0], [1], [-10], [9]]}
introductory
https://www.codewars.com/kata/577a98a6ae28071780000989
def minimum(arr):
3,737
**Steps** 1. Square the numbers that are greater than zero. 2. Multiply by 3 every third number. 3. Multiply by -1 every fifth number. 4. Return the sum of the sequence. **Example** `{ -2, -1, 0, 1, 2 }` returns `-6` ``` 1. { -2, -1, 0, 1 * 1, 2 * 2 } 2. { -2, -1, 0 * 3, 1, 4 } 3. { -2, -1, 0, 1, -1 * 4 } 4. -6 ```...
["def calc(a):\n return sum( x**(1 + (x>=0)) * (1 + 2*(not i%3)) * (-1)**(not i%5) for i,x in enumerate(a,1))", "def calc(a):\n for i, n in enumerate(a):\n if a[i] > 0: a[i] *= a[i]\n if i % 3 == 2: a[i] = a[i] * 3\n if i % 5 == 4: a[i] = a[i] * -1\n return sum(a)", "def calc(a):\n prin...
{"fn_name": "calc", "inputs": [[[0, 2, 1, -6, -3, 3]], [[0]], [[1, 1, 1, 1, 1]], [[1, 1, -9, 9, 16, -15, -45, -73, 26]], [[1, -1, 10, -9, 16, 15, 45, -73, -26]], [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], [[-5, -5, -5, -5, -5, -5, -5]]], "outputs": [[31], [0], [5], [1665], [2584], [0], [-45]]}
introductory
https://www.codewars.com/kata/596ddaccdd42c1cf0e00005c
def calc(a):
3,738
# Task In the city, a bus named Fibonacci runs on the road every day. There are `n` stations on the route. The Bus runs from station1 to stationn. At the departure station(station1), `k` passengers get on the bus. At the second station(station2), a certain number of passengers get on and the same number get off. T...
["def sim(k,n,p):\n r = [(k,k,0),(k,p,p)]\n for i in range(n-2):\n u,d = r[0][1]+r[1][1],r[1][1]\n r = [r[1],(r[1][0]+u-d,u,d)]\n return r[1][0]\n\ndef calc(k,n,m,x):\n z,o = sim(k,n-1,0), sim(k,n-1,1)\n return sim(k,x,(m-z)//(o-z))", "def fibLikeGen():\n a,b = (1,0), (0,1) ...
{"fn_name": "calc", "inputs": [[5, 7, 32, 4], [12, 23, 212532, 8]], "outputs": [[13], [252]]}
introductory
https://www.codewars.com/kata/5c2c0c5e2f172f0fae21729f
def calc(k,n,m,x):
3,739
Similar setting of the [previous](https://www.codewars.com/kata/progressive-spiral-number-position/), this time you are called to identify in which "branch" of the spiral a given number will end up. Considering a square of numbers disposed as the 25 items in [the previous kata](https://www.codewars.com/kata/progressiv...
["from math import ceil\n\ndef branch(n):\n if n == 1:\n return 0\n l = int(ceil(n ** 0.5)) // 2\n n -= (2 * l - 1) ** 2 + 1\n return n // (2*l or 1)", "branch=lambda n:(lambda r:r and(n-2)//r+2-r)(0-(1-n**.5)//2*2)", "branch=lambda n: 0 if n==1 else (lambda s: (n-s*s-1)//(s+1))(((n-1)**0.5-1)//2*2+1...
{"fn_name": "branch", "inputs": [[1], [5], [25], [30], [50]], "outputs": [[0], [1], [3], [0], [0]]}
introductory
https://www.codewars.com/kata/5a26ca51e1ce0e987b0000ee
def branch(n):
3,740
###Instructions A time period starting from ```'hh:mm'``` lasting until ```'hh:mm'``` is stored in an array: ``` ['08:14', '11:34'] ``` A set of different time periods is then stored in a 2D Array like so, each in its own sub-array: ``` [['08:14','11:34'], ['08:16','08:18'], ['22:18','01:14'], ['09:30','10:32'], ['04:...
["def sort_time(arr):\n arr, s = sorted(arr, key=lambda t: t[0]), []\n while arr:\n nextTP = next((i for i,t in enumerate(arr) if not s or t[0] >= s[-1][1]), 0)\n s.append(arr.pop(nextTP))\n return s", "def sort_time(arr):\n arr = sorted(arr, key = lambda x: x[0])\n out = [[\"\", \"00:00\"]...
{"fn_name": "sort_time", "inputs": [[[["08:14", "11:34"], ["08:16", "08:18"], ["13:48", "01:14"], ["09:30", "10:32"], ["04:23", "05:11"], ["11:48", "13:48"], ["01:12", "01:14"], ["01:13", "08:15"]]], [[["00:00", "00:05"], ["16:37", "18:19"], ["12:07", "12:12"], ["00:30", "02:49"], ["12:12", "12:14"], ["12:14", "15:00"]...
introductory
https://www.codewars.com/kata/57024825005264fe9200057d
def sort_time(arr):
3,741
Calculate the number of items in a vector that appear at the same index in each vector, with the same value. ```python vector_affinity([1, 2, 3, 4, 5], [1, 2, 2, 4, 3]) # => 0.6 vector_affinity([1, 2, 3], [1, 2, 3]) # => 1.0 ``` Affinity value should be realized on a scale of 0.0 to 1.0, with 1.0 being absolut...
["def vector_affinity(a, b):\n longer = len(a) if len(a) > len(b) else len(b)\n return len([i for i, j in zip(a, b) if i == j]) / float(longer) if longer > 0 else 1.0", "def vector_affinity(a, b):\n return sum([1.0 for x, y in zip(a, b) if x == y]) / max(len(a), len(b)) if max(len(a), len(b)) else 1", "from iterto...
{"fn_name": "vector_affinity", "inputs": [[[1, 2, 3], [1, 2, 3, 4, 5]], [[1, 2, 3, 4], [1, 2, 3, 5]], [[1, 2, 3, 4, 5], []], [[1, 2, 3], [1, 2, 3]], [[6, 6, 6, 6, 6, 6], [6, null, null, 6, 6, null]], [[6], [6, 6, 6, 6, 6, 6]], [[], []], [[null], [null]]], "outputs": [[0.6], [0.75], [0.0], [1.0], [0.5], [0.1666666666666...
introductory
https://www.codewars.com/kata/5498505a43e0fd83620010a9
def vector_affinity(a, b):
3,742
You probably know that the "mode" of a set of data is the data point that appears most frequently. Looking at the characters that make up the string `"sarsaparilla"` we can see that the letter `"a"` appears four times, more than any other letter, so the mode of `"sarsaparilla"` is `"a"`. But do you know what happens w...
["from collections import Counter\n\ndef modes(data):\n cnts = Counter(data)\n mx, mn = max(cnts.values()), min(cnts.values())\n return sorted([k for k in cnts if cnts[k] == mx and cnts[k] != mn])", "def modes(data):\n frequency = {}\n mode_list = []\n \n # adds or creates a counter for each charac...
{"fn_name": "modes", "inputs": [["tomato"], [[1, 3, 3, 7]], [["redder"]]], "outputs": [[["o", "t"]], [[3]], [[]]]}
introductory
https://www.codewars.com/kata/586f5808aa04285bc800009d
def modes(data):
3,743
A grid is a perfect starting point for many games (Chess, battleships, Candy Crush!). Making a digital chessboard I think is an interesting way of visualising how loops can work together. Your task is to write a function that takes two integers `rows` and `columns` and returns a chessboard pattern as a two dimensiona...
["def chess_board(rows, columns):\n return [[\"OX\"[(row+col)%2] for col in range(columns)] for row in range(rows)]", "def chess_board(rows, columns):\n ans=[]\n for i in range(1,rows+1,1):\n l=[]\n for j in range(i,columns+i,1):\n if j%2!=0:\n l.append('O')\n ...
{"fn_name": "chess_board", "inputs": [[1, 1], [1, 2], [2, 1], [2, 2], [6, 6]], "outputs": [[[["O"]]], [[["O", "X"]]], [[["O"], ["X"]]], [[["O", "X"], ["X", "O"]]], [[["O", "X", "O", "X", "O", "X"], ["X", "O", "X", "O", "X", "O"], ["O", "X", "O", "X", "O", "X"], ["X", "O", "X", "O", "X", "O"], ["O", "X", "O", "X", "O", ...
introductory
https://www.codewars.com/kata/56242b89689c35449b000059
def chess_board(rows, columns):
3,744
Integral numbers can be even or odd. Even numbers satisfy `n = 2m` ( with `m` also integral ) and we will ( completely arbitrarily ) think of odd numbers as `n = 2m + 1`. Now, some odd numbers can be more odd than others: when for some `n`, `m` is more odd than for another's. Recursively. :] Even numbers are just ...
["def oddest(numbers):\n most_odd = 0 # The current most odd number in the list\n max_oddity = -1 # The current greatest oddity rate, starts at -1 so that even an even number can be the unique most odd\n is_unique = True # If the current most odd number is really the most, so if there is no uniqu...
{"fn_name": "oddest", "inputs": [[[1, 2]], [[1, 3]], [[1, 5]], [[]], [[0]], [[0, 1]], [[1, 3, 5, 7]], [[2, 4]], [[-1]], [[-1, -1]], [[-1, 0, 1]], [[-3, 3]], [[-5, 3]]], "outputs": [[1], [3], [null], [null], [0], [1], [7], [null], [-1], [null], [-1], [3], [null]]}
introductory
https://www.codewars.com/kata/5d6ee508aa004c0019723c1c
def oddest(a):
3,745
# Introduction The Condi (Consecutive Digraphs) cipher was introduced by G4EGG (Wilfred Higginson) in 2011. The cipher preserves word divisions, and is simple to describe and encode, but it's surprisingly difficult to crack. # Encoding Algorithm The encoding steps are: - Start with an `initial key`, e.g. `cryptogra...
["#from string import ascii_lowercase as LOWER\nLOWER = \"abcdefghijklmnopqrstuvwxyz\"\n\ndef encode(message, key, shift, encode=True):\n key = sorted(LOWER, key=f\"{key}{LOWER}\".index)\n result = []\n for char in message:\n if char in key:\n i = key.index(char)\n char = key[(i + ...
{"fn_name": "encode", "inputs": [["on", "cryptogram", 10]], "outputs": [["jx"]]}
introductory
https://www.codewars.com/kata/59bf6b73bf10a4c8e5000047
def encode(message, key, shift, encode=True):
3,746
There were and still are many problem in CW about palindrome numbers and palindrome strings. We suposse that you know which kind of numbers they are. If not, you may search about them using your favourite search engine. In this kata you will be given a positive integer, ```val``` and you have to create the function ``...
["def palindrome(n):\n s = str(n)\n return s[::-1] == s\n\ndef next_pal(val):\n val += 1\n while not palindrome(val):\n val += 1\n return val", "def next_pal(val):\n int_to_digits = lambda n: [int(d) for d in str(n)]\n digits_to_int = lambda a: int(\"\".join(map(str, a)))\n \n digits =...
{"fn_name": "next_pal", "inputs": [[11], [188], [191], [2541]], "outputs": [[22], [191], [202], [2552]]}
introductory
https://www.codewars.com/kata/56a6ce697c05fb4667000029
def next_pal(val):
3,747
Implement `String#ipv4_address?`, which should return true if given object is an IPv4 address - four numbers (0-255) separated by dots. It should only accept addresses in canonical representation, so no leading `0`s, spaces etc.
["from re import compile, match\n\nREGEX = compile(r'((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.){4}$')\n\n\ndef ipv4_address(address):\n # refactored thanks to @leonoverweel on CodeWars\n return bool(match(REGEX, address + '.'))\n", "import socket\ndef ipv4_address(address):\n try: # No need to do work that'...
{"fn_name": "ipv4_address", "inputs": [[""], ["127.0.0.1"], ["0.0.0.0"], ["255.255.255.255"], ["10.20.30.40"], ["10.256.30.40"], ["10.20.030.40"], ["127.0.1"], ["127.0.0.0.1"], ["..255.255"], ["127.0.0.1\n"], ["\n127.0.0.1"], [" 127.0.0.1"], ["127.0.0.1 "], [" 127.0.0.1 "], ["127.0.0.1."], [".127.0.0.1"], ["127..0.1"]]...
introductory
https://www.codewars.com/kata/567fe8b50c201947bc000056
def ipv4_address(address):
3,748
# Task A common way for prisoners to communicate secret messages with each other is to encrypt them. One such encryption algorithm goes as follows. You take the message and place it inside an `nx6` matrix (adjust the number of rows depending on the message length) going from top left to bottom right (one row at a ti...
["def six_column_encryption(msg):\n msg=msg.replace(' ','.')+'.'*((6-len(msg)%6)%6)\n return ' '.join(msg[n::6] for n in range(6))", "from itertools import zip_longest\n\ndef six_column_encryption(msg, size=6):\n msg = msg.replace(' ','.')\n L = [msg[i:i+size] for i in range(0, len(msg), size)]\n return ...
{"fn_name": "six_column_encryption", "inputs": [["Attack at noon or we are done for"], ["Let's kill them all"], ["Meet me behind the kitchen tomorrow at seven in the evening"]], "outputs": [["A.ow.f tanedo tt..or a.oan. cnrre. ko.e.."], ["Lkhl eie. tlm. 'l.. s.a. .tl."], ["Men.eoaete e.dknrtnhn eb.i.r..ei tetttosi.n .h...
introductory
https://www.codewars.com/kata/58a65945fd7051d5e1000041
def six_column_encryption(msg):
3,749
# Write Number in Expanded Form You will be given a number and you will need to return it as a string in [Expanded Form](https://www.mathplacementreview.com/arithmetic/whole-numbers.php#expanded-form). For example: ```python expanded_form(12) # Should return '10 + 2' expanded_form(42) # Should return '40 + 2' expande...
["def expanded_form(num):\n num = list(str(num))\n return ' + '.join(x + '0' * (len(num) - y - 1) for y,x in enumerate(num) if x != '0')", "def expanded_form(n):\n result = []\n for a in range(len(str(n)) - 1, -1, -1):\n current = 10 ** a\n quo, n = divmod(n, current)\n if quo:\n ...
{"fn_name": "expanded_form", "inputs": [[2], [12], [42], [70304], [4982342]], "outputs": [["2"], ["10 + 2"], ["40 + 2"], ["70000 + 300 + 4"], ["4000000 + 900000 + 80000 + 2000 + 300 + 40 + 2"]]}
introductory
https://www.codewars.com/kata/5842df8ccbd22792a4000245
def expanded_form(num):
3,750
Bob is a lazy man. He needs you to create a method that can determine how many ```letters``` and ```digits``` are in a given string. Example: "hel2!lo" --> 6 "wicked .. !" --> 6 "!?..A" --> 1
["def count_letters_and_digits(s):\n return isinstance(s, str) and sum(map(str.isalnum, s))", "def count_letters_and_digits(s):\n return sum(map(str.isalnum, s))", "import re\ndef count_letters_and_digits(s):\n if s == None or s == []:\n return 0\n return len(re.findall(\"[A-Za-z0-9]\",s))", "def cou...
{"fn_name": "count_letters_and_digits", "inputs": [["n!!ice!!123"], ["de?=?=tttes!!t"], [""], ["!@#$%^&`~."], ["u_n_d_e_r__S_C_O_R_E"]], "outputs": [[7], [8], [0], [0], [10]]}
introductory
https://www.codewars.com/kata/5738f5ea9545204cec000155
def count_letters_and_digits(s):
3,751
Complete the method that takes a boolean value and return a `"Yes"` string for `true`, or a `"No"` string for `false`.
["def bool_to_word(bool):\n return \"Yes\" if bool else \"No\"", "def bool_to_word(bool):\n if bool:\n return \"Yes\"\n return \"No\"", "def bool_to_word(bool):\n if bool:\n return 'Yes'\n else:\n return 'No'", "def bool_to_word(boolean):\n return \"Yes\" if boolean else \"No\"...
{"fn_name": "bool_to_word", "inputs": [[true], [false]], "outputs": [["Yes"], ["No"]]}
introductory
https://www.codewars.com/kata/53369039d7ab3ac506000467
def bool_to_word(boolean):
3,752
The Binomial Form of a polynomial has many uses, just as the standard form does. For comparison, if p(x) is in Binomial Form and q(x) is in standard form, we might write p(x) := a0 \* xC0 + a1 \* xC1 + a2 \* xC2 + ... + aN \* xCN q(x) := b0 + b1 \* x + b2 \* x^(2) + ... + bN \* x^(N) Both forms have tricks for eval...
["from functools import reduce\nfrom math import factorial\n\n\ndef value_at(poly, x):\n return round(sum(n * aCb(x, i) for i, n in enumerate(poly[::-1])), 2)\n\ndef aCb(a, b):\n return reduce(lambda x, y: x * y, (a - i for i in range(b)), 1) / factorial(b)\n", "def aCb(a, b):\n result = 1.0\n for i in rang...
{"fn_name": "value_at", "inputs": [[[1, 2, 7], 3], [[1, 2, 7, 0, 5], 2], [[1, 1, 1, 1, 7, 0, 5], 2], [[1, 2, 7, 0, 5], 0.6], [[1, 2, 7, 0, 5], 0]], "outputs": [[16], [12], [12], [4.24], [5.0]]}
introductory
https://www.codewars.com/kata/56782b25c05cad45f700000f
def value_at(poly_spec, x):
3,753
```if-not:swift Write simple .camelCase method (`camel_case` function in PHP, `CamelCase` in C# or `camelCase` in Java) for strings. All words must have their first letter capitalized without spaces. ``` ```if:swift Write a simple `camelCase` function for strings. All words must have their first letter capitalized and ...
["def camel_case(string):\n return string.title().replace(\" \", \"\")", "def camel_case(s):\n return s.title().replace(' ','')", "def camel_case(string):\n return ''.join([i.capitalize() for i in string.split()])", "def camel_case(string):\n if len(string) == 0: return \"\"\n str_list = list(string)\n ...
{"fn_name": "camel_case", "inputs": [["test case"], ["camel case method"], ["say hello "], [" camel case word"], [""]], "outputs": [["TestCase"], ["CamelCaseMethod"], ["SayHello"], ["CamelCaseWord"], [""]]}
introductory
https://www.codewars.com/kata/587731fda577b3d1b0001196
def camel_case(string):
3,754
# Task We know that some numbers can be split into two primes. ie. `5 = 2 + 3, 10 = 3 + 7`. But some numbers are not. ie. `17, 27, 35`, etc.. Given a positive integer `n`. Determine whether it can be split into two primes. If yes, return the maximum product of two primes. If not, return `0` instead. # Input/Output ...
["def isPrime(n):\n return n==2 or n>2 and n&1 and all(n%p for p in range(3,int(n**.5+1),2))\n\ndef prime_product(n):\n return next( (x*(n-x) for x in range(n>>1,1,-1) if isPrime(x) and isPrime(n-x)), 0)", "def prime_product(n):\n def is_prime(n): return n == 2 or n > 2 and n % 2 and all(n % d for d in range(3...
{"fn_name": "prime_product", "inputs": [[1], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [20], [100]], "outputs": [[0], [0], [4], [6], [9], [10], [15], [14], [25], [0], [35], [91], [2491]]}
introductory
https://www.codewars.com/kata/592538b3071ba54511000219
def prime_product(n):
3,755
Sort the given strings in alphabetical order, case **insensitive**. For example: ``` ["Hello", "there", "I'm", "fine"] --> ["fine", "Hello", "I'm", "there"] ["C", "d", "a", "B"]) --> ["a", "B", "C", "d"] ```
["def sortme(words):\n return sorted(words, key=str.lower)", "def sortme(words):\n return sorted(words,key=lambda x: x.lower())", "def sortme(a):\n return sorted(a, key=str.lower)", "def sortme(words):\n # your code here\n return sorted(words,key=str.casefold)", "def lower(e):\n return e.lower()\n\ndef ...
{"fn_name": "sortme", "inputs": [[["Hello", "there", "I'm", "fine"]], [["C", "d", "a", "B"]], [["CodeWars"]], [[]]], "outputs": [[["fine", "Hello", "I'm", "there"]], [["a", "B", "C", "d"]], [["CodeWars"]], [[]]]}
introductory
https://www.codewars.com/kata/51f41fe7e8f176e70d0002b9
def sortme(words):
3,756
German mathematician Christian Goldbach (1690-1764) [conjectured](https://en.wikipedia.org/wiki/Goldbach%27s_conjecture) that every even number greater than 2 can be represented by the sum of two prime numbers. For example, `10` can be represented as `3+7` or `5+5`. Your job is to make the function return a list conta...
["import math\ndef goldbach_partitions(n):\n def is_prime(x):\n for i in range(2, int(math.sqrt(x))+1):\n if x % i == 0:\n return False\n return True\n\n if n % 2: return []\n\n ret = []\n for first in range(2, n//2 + 1):\n if is_prime(first):\n seco...
{"fn_name": "goldbach_partitions", "inputs": [[15], [393], [31133], [4], [100], [594], [1500]], "outputs": [[[]], [[]], [[]], [["2+2"]], [["3+97", "11+89", "17+83", "29+71", "41+59", "47+53"]], [["7+587", "17+577", "23+571", "31+563", "37+557", "47+547", "53+541", "71+523", "73+521", "103+491", "107+487", "127+467", "1...
introductory
https://www.codewars.com/kata/578dec07deaed9b17d0001b8
def goldbach_partitions(n):
3,757
Given an array of numbers, return an array, with each member of input array rounded to a nearest number, divisible by 5. For example: ``` roundToFive([34.5, 56.2, 11, 13]); ``` should return ``` [35, 55, 10, 15] ``` ```if:python Roundings have to be done like "in real life": `22.5 -> 25` ```
["from decimal import Decimal, ROUND_HALF_UP\n\ndef round_to_five(numbers):\n return [(n/5).quantize(1, ROUND_HALF_UP) * 5 for n in map(Decimal, numbers)]", "def round_to_five(numbers):\n \n return [5*int(x/5 + 0.5) for x in numbers]", "def round_to_five(numbers):\n return [int((n + 2.5) / 5) * 5 for n in n...
{"fn_name": "round_to_five", "inputs": [[[1, 5, 87, 45, 8, 8]], [[3, 56.2, 11, 13]], [[22.5, 544.9, 77.5]]], "outputs": [[[0, 5, 85, 45, 10, 10]], [[5, 55, 10, 15]], [[25, 545, 80]]]}
introductory
https://www.codewars.com/kata/582f52208278c6be55000067
def round_to_five(numbers):
3,758
You will be given an array of strings. The words in the array should mesh together where one or more letters at the end of one word will have the same letters (in the same order) as the next word in the array. But, there are times when all the words won't mesh. Examples of meshed words: "apply" and "plywood" ...
["import re\n\ndef word_mesh(arr):\n common = re.findall(r'(.+) (?=\\1)',' '.join(arr))\n return ''.join(common) if len(common) + 1 == len(arr) else 'failed to mesh'", "def word_mesh(arr):\n result = \"\"\n \n for a, b in zip(arr, arr[1:]):\n while not a.endswith(b):\n b = b[:-1]\n ...
{"fn_name": "word_mesh", "inputs": [[["beacon", "condominium", "umbilical", "california"]], [["allow", "lowering", "ringmaster", "terror"]], [["abandon", "donation", "onion", "ongoing"]], [["jamestown", "ownership", "hippocampus", "pushcart", "cartographer", "pheromone"]], [["marker", "kerchief", "effortless", "lesson"...
introductory
https://www.codewars.com/kata/5c1ae703ba76f438530000a2
def word_mesh(arr):
3,759
# Introduction and Warm-up (Highly recommended) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) ___ # Task **_Given_** an *array/list [] of integers* , **_Construct_** a *product array **_Of same size_** Such That prod[i] is equal to The Product of all the e...
["from operator import mul\nfrom functools import reduce\n\ndef product_array(numbers):\n tot = reduce(mul,numbers)\n return [tot//n for n in numbers]", "from numpy import prod\n\ndef product_array(numbers):\n p = prod(numbers)\n return [p // i for i in numbers]", "def product_array(numbers):\n prod = ev...
{"fn_name": "product_array", "inputs": [[[12, 20]], [[3, 27, 4, 2]], [[13, 10, 5, 2, 9]], [[16, 17, 4, 3, 5, 2]]], "outputs": [[[20, 12]], [[216, 24, 162, 324]], [[900, 1170, 2340, 5850, 1300]], [[2040, 1920, 8160, 10880, 6528, 16320]]]}
introductory
https://www.codewars.com/kata/5a905c2157c562994900009d
def product_array(numbers):
3,760
Scheduling is how the processor decides which jobs (processes) get to use the processor and for how long. This can cause a lot of problems. Like a really long process taking the entire CPU and freezing all the other processes. One solution is Round-Robin, which today you will be implementing. Round-Robin works by queu...
["def roundRobin(jobs, slice, index):\n total_cc = 0\n while True:\n for idx in range(len(jobs)):\n cc = min(jobs[idx], slice)\n jobs[idx] -= cc\n total_cc += cc\n if idx == index and jobs[idx] == 0:\n return total_cc", "def roundRobin(jobs, slice,...
{"fn_name": "roundRobin", "inputs": [[[10], 4, 0], [[10, 20], 5, 0], [[10, 20, 1, 2, 3], 5, 2], [[10, 20, 1, 2, 3], 5, 0], [[10, 20, 1, 2, 3], 4, 2], [[10, 20, 1, 2, 3], 4, 3]], "outputs": [[10], [15], [11], [21], [9], [11]]}
introductory
https://www.codewars.com/kata/550cb646b9e7b565d600048a
def roundRobin(jobs, slice, index):
3,761
# Task Mirko has been moving up in the world of basketball. He started as a mere spectator, but has already reached the coveted position of the national team coach! Mirco is now facing a difficult task: selecting five primary players for the upcoming match against Tajikistan. Since Mirko is incredibly lazy, he doesn...
["from collections import Counter\n\ndef strange_coach(players):\n return ''.join(\n sorted(i for i,j in\n Counter(map(lambda x: x[0], players)).most_common()\n if j >= 5)) or 'forfeit'", "def strange_coach(players):\n d = {l:0 for l in map(chr,...
{"fn_name": "strange_coach", "inputs": [[["michael", "jordan", "lebron", "james", "kobe", "bryant"]], [["babic", "keksic", "boric", "bukic", "sarmic", "balic", "kruzic", "hrenovkic", "beslic", "boksic", "krafnic", "pecivic", "klavirkovic", "kukumaric", "sunkic", "kolacic", "kovacic", "prijestolonasljednikovic"]], [["jg...
introductory
https://www.codewars.com/kata/58fd91af13b0012e8e000010
def strange_coach(players):
3,762
### Task: You have to write a function `pattern` which creates the following pattern (See Examples) upto desired number of rows. If the Argument is `0` or a Negative Integer then it should return `""` i.e. empty string. ### Examples: `pattern(9)`: 123456789 234567891 345678912 456789123 5678912...
["def pattern(n):\n return '\\n'.join(''.join(str((x+y)%n+1) for y in range(n)) for x in range(n))", "def pattern(n):\n nums = list(range(1,n+1))\n result = ''\n result += ''.join(str(n) for n in nums)\n \n for i in range(1, n):\n result += '\\n'\n nums.append(nums.pop(0))\n resul...
{"fn_name": "pattern", "inputs": [[7], [1], [4], [0], [-25]], "outputs": [["1234567\n2345671\n3456712\n4567123\n5671234\n6712345\n7123456"], ["1"], ["1234\n2341\n3412\n4123"], [""], [""]]}
introductory
https://www.codewars.com/kata/557592fcdfc2220bed000042
def pattern(n):
3,763
You are required to create a simple calculator that returns the result of addition, subtraction, multiplication or division of two numbers. Your function will accept three arguments: The first and second argument should be numbers. The third argument should represent a sign indicating the operation to perform on these...
["def calculator(x, y, op):\n return eval(f'{x}{op}{y}') if type(x) == type(y) == int and str(op) in '+-*/' else 'unknown value'", "def calculator(x,y,op):\n try:\n assert op in \"+-*/\"\n return eval('%d%s%d' % (x, op, y))\n except:\n return \"unknown value\"", "def calculator(x, y, op):\n ...
{"fn_name": "calculator", "inputs": [[6, 2, "+"], [4, 3, "-"], [5, 5, "*"], [5, 4, "/"], [6, "$", "+"], [6, 2, "&"], [4, 3, "\\"], ["a", 3, "+"], [6, 2, "="], [6, 2, "\t"], [":", ",", "+"]], "outputs": [[8], [1], [25], [1.25], ["unknown value"], ["unknown value"], ["unknown value"], ["unknown value"], ["unknown value"]...
introductory
https://www.codewars.com/kata/5810085c533d69f4980001cf
def calculator(x,y,op):