problem_id
stringlengths
32
32
name
stringclasses
1 value
problem
stringlengths
200
14k
solutions
stringlengths
12
1.12M
test_cases
stringlengths
37
74M
difficulty
stringclasses
3 values
language
stringclasses
1 value
source
stringclasses
7 values
num_solutions
int64
12
1.12M
starter_code
stringlengths
0
956
e6e0dfc3c07cc4895a751f7475c3c7d0
UNKNOWN
# 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
PYTHON3
CODEWARS
2,195
def six_column_encryption(msg):
332779f6b391bc1fe955342afb75b7d4
UNKNOWN
# 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
PYTHON3
CODEWARS
1,925
def expanded_form(num):
9872ec706274cfc3cb3f18a4727d9e42
UNKNOWN
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
PYTHON3
CODEWARS
2,905
def value_at(poly_spec, x):
eee239f090e8d630d4cbc7b0af1604d8
UNKNOWN
```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
PYTHON3
CODEWARS
1,343
def camel_case(string):
532eac8469a987ec5efb756b91be8866
UNKNOWN
# 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
PYTHON3
CODEWARS
4,602
def prime_product(n):
cdad003ad88ed28119a9dd853ece50bf
UNKNOWN
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
PYTHON3
CODEWARS
1,202
def sortme(words):
f3501a6f13c18f6b07c48c4dca34749d
UNKNOWN
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
PYTHON3
CODEWARS
3,536
def goldbach_partitions(n):
fe6f0b2bc5bfbe7a32711c7e742e97c7
UNKNOWN
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
PYTHON3
CODEWARS
1,613
def round_to_five(numbers):
00f7646cd23dc3222f44fdc41f895e44
UNKNOWN
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
PYTHON3
CODEWARS
2,520
def word_mesh(arr):
75fb5563b755ea1755f4bafe61870d74
UNKNOWN
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
PYTHON3
CODEWARS
2,399
def roundRobin(jobs, slice, index):
9c41effccc621598c3da5de70b385ef3
UNKNOWN
# 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
PYTHON3
CODEWARS
2,156
def strange_coach(players):
64e0364930828704bf5c4aecb9a09827
UNKNOWN
### 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
PYTHON3
CODEWARS
1,593
def pattern(n):
22693008ea23a62730df9787f0402374
UNKNOWN
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
PYTHON3
CODEWARS
31,148
def calculator(x,y,op):
7da173808e754b70c7a4ac35bbaca698
UNKNOWN
When multiple master devices are connected to a single bus (https://en.wikipedia.org/wiki/System_bus), there needs to be an arbitration in order to choose which of them can have access to the bus (and 'talk' with a slave). We implement here a very simple model of bus mastering. Given `n`, a number representing the num...
["def arbitrate(s, n):\n i = s.find('1') + 1\n return s[:i] + '0' * (n - i)", "def arbitrate(s, n):\n i = s.find('1') + 1\n return s[:i] + '0' * (len(s) - i)", "def arbitrate(bus_str, n):\n return ''.join(['0' if i != bus_str.find('1') else '1' for i, x in enumerate(bus_str)]) ", "def arbitrate(input, n)...
{"fn_name": "arbitrate", "inputs": [["001000101", 9], ["000000101", 9], ["0000", 4]], "outputs": [["001000000"], ["000000100"], ["0000"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,035
def arbitrate(s, n):
9d36dacceafd33727bb17f1372908648
UNKNOWN
Algorithmic predicament - Bug Fixing #9 Oh no! Timmy's algorithim has gone wrong! help Timmy fix his algorithim! Task Your task is to fix timmy's algorithim so it returns the group name with the highest total age. You will receive two groups of `people` objects, with two properties `name` and `age`. The name prope...
["from collections import Counter\nfrom itertools import chain\n\n\ndef highest_age(persons1, persons2):\n c = Counter()\n\n for p in chain(persons1, persons2):\n c[p['name']] += p['age']\n\n return min(iter(c.items()), key=lambda n_a: (-n_a[1], n_a[0]))[0] if c else None\n", "from functools import redu...
{"fn_name": "highest_age", "inputs": [[[{"name": "kay", "age": 1}, {"name": "john", "age": 13}, {"name": "kay", "age": 76}], [{"name": "john", "age": 1}, {"name": "alice", "age": 77}]], [[{"name": "kay", "age": 1}, {"name": "john", "age": 13}, {"name": "kay", "age": 76}], [{"name": "john", "age": 1}, {"name": "alice", ...
INTRODUCTORY
PYTHON3
CODEWARS
2,039
def highest_age(group1,group2):
e2ac82974f076400059f7a30bb692eef
UNKNOWN
~~~if-not:java You have to code a function **getAllPrimeFactors** wich take an integer as parameter and return an array containing its prime decomposition by ascending factors, if a factors appears multiple time in the decomposition it should appear as many time in the array. exemple: `getAllPrimeFactors(100)` return...
["def getAllPrimeFactors(n):\n if n == 0: return []\n elif n == 1: return [1]\n elif type(n) != int: return errora\n elif n < 0: return errora\n allfacts = []\n current = 2\n n_copy = n\n while current <= n:\n if n_copy % current == 0:\n allfacts.append(current)\n n_...
{"fn_name": "getAllPrimeFactors", "inputs": [[10], [100], [1000], [1000001], [0], [1], [2], ["a"], [1.1], [-1]], "outputs": [[[2, 5]], [[2, 2, 5, 5]], [[2, 2, 2, 5, 5, 5]], [[101, 9901]], [[]], [[1]], [[2]], [[]], [[]], [[]]]}
INTRODUCTORY
PYTHON3
CODEWARS
8,787
def getAllPrimeFactors(n):
4ce13a914b841ca459909308a928abae
UNKNOWN
Naming multiple files can be a pain sometimes. #### Task: Your job here is to create a function that will take three parameters, `fmt`, `nbr` and `start`, and create an array of `nbr` elements formatted according to `frm` with the starting index `start`. `fmt` will have `` inserted at various locations; this is where...
["def name_file(fmt, nbr, start):\n try:\n return [fmt.replace('<index_no>', '{0}').format(i)\n for i in range(start, start + nbr)]\n except TypeError:\n return []", "def name_file(fmt, n, start):\n return [fmt.replace('<index_no>', str(i)) for i in range(start, start+n)] if n > 0 and is...
{"fn_name": "name_file", "inputs": [["IMG <index_no>", 4, 1], ["image #<index_no>.jpg", 3, 7], ["#<index_no> #<index_no>", 3, -2], ["<file> number <index_no>", 5, 0], ["<file_no> number <index_no>", 2, -1], ["file", 2, 3], ["<file_no> number <index_no>", -1, 0], ["file <index_no>", 2, 0.1], ["file <index_no>", 0.2, 0],...
INTRODUCTORY
PYTHON3
CODEWARS
1,694
def name_file(fmt, nbr, start):
3b37ad74c1832f4f4c614222f843e6db
UNKNOWN
# RoboScript #2 - Implement the RS1 Specification ## Disclaimer The story presented in this Kata Series is purely fictional; any resemblance to actual programming languages, products, organisations or people should be treated as purely coincidental. ## About this Kata Series This Kata Series is based on a fictional...
["from collections import deque\nimport re\n\nTOKENIZER = re.compile(r'(R+|F+|L+)(\\d*)')\n\ndef execute(code):\n \n pos, dirs = (0,0), deque([(0,1), (1,0), (0,-1), (-1,0)])\n seens = {pos}\n \n for act,n in TOKENIZER.findall(code):\n s,r = act[0], int(n or '1') + len(act)-1\n \n if ...
{"fn_name": "execute", "inputs": [[""], ["FFFFF"], ["FFFFFLFFFFFLFFFFFLFFFFFL"], ["LFFFFFRFFFRFFFRFFFFFFF"], ["LF5RF3RF3RF7"], ["FFFLLFFFFFFRRFFFLFFFRRFFFFFFFF"], ["F3L2F6R2F3LF3R2F8"], ["F2FLLF3F3R2FFFLF2FRRF3F2F2F"], ["FFLFFFLFFFFLFFFFFLFFFFFFLFFFFFFFLFFFFFFFFLFFFFFFFFFLFFFFFFFFFF"], ["F2LF3LF4LF5LF6LF7LF8LF9LF10"], ...
INTRODUCTORY
PYTHON3
CODEWARS
16,123
def execute(code):
af0216ba486115b9078075968e4e5480
UNKNOWN
Hello! Your are given x and y and 2D array size tuple (width, height) and you have to: Calculate the according index in 1D space (zero-based). Do reverse operation. Implement: to_1D(x, y, size): --returns index in 1D space to_2D(n, size) --returns x and y in 2D space 1D array: [0, 1, 2, 3, 4, 5, 6, 7, 8] 2D arra...
["def to_1D(x, y, size):\n return y * size[0] + x \n \ndef to_2D(n, size):\n return (n % size[0], n // size[0])", "def to_1D(x, y, size):\n w, h = size\n return x + y * w\n \ndef to_2D(n, size):\n w, h = size\n return (n % w, n // w)", "def to_1D(x, y, size):\n return size[0] * y + x\n ...
{"fn_name": "to_1D", "inputs": [[0, 0, [3, 3]], [1, 1, [3, 3]], [2, 2, [3, 3]], [0, 0, [1, 1]], [1, 5, [4, 6]], [2, 3, [4, 6]]], "outputs": [[0], [4], [8], [0], [21], [14]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,503
def to_1D(x, y, size):
9a0d82509e228a14319608a9235c8e43
UNKNOWN
Congratulations! That Special Someone has given you their phone number. But WAIT, is it a valid number? Your task is to write a function that verifies whether a given string contains a valid British mobile (cell) phone number or not. If valid, return 'In with a chance'. If invalid, or if you're given an empty str...
["import re\nyes = \"In with a chance\"\nno = \"Plenty more fish in the sea\"\ndef validate_number(string):\n return yes if re.match(r'^(\\+44|0)7[\\d]{9}$',re.sub('-','',string)) else no", "import re\ndef validate_number(string):\n if re.match(r\"^(0|\\+44)7[0-9]{9}$\", string.replace(\"-\", \"\")):\n retur...
{"fn_name": "validate_number", "inputs": [["07454876120"], ["0754876120"], ["0745--487-61-20"], ["+447535514555"], ["-07599-51-4555"], ["075335440555"], ["+337535512555"], ["00535514555"], ["+447+4435512555"], ["+44"]], "outputs": [["In with a chance"], ["Plenty more fish in the sea"], ["In with a chance"], ["In with a...
INTRODUCTORY
PYTHON3
CODEWARS
1,958
def validate_number(s):
40f42aa90d9bcfc370536c1361cd6efb
UNKNOWN
Now we will confect a reagent. There are eight materials to choose from, numbered 1,2,..., 8 respectively. We know the rules of confect: ``` material1 and material2 cannot be selected at the same time material3 and material4 cannot be selected at the same time material5 and material6 must be selected at the same time ...
["def isValid(formula):\n return not ( \\\n ( 1 in formula and 2 in formula) or \\\n ( 3 in formula and 4 in formula) or \\\n ( 5 in formula and not 6 in formula) or \\\n (not 5 in formula and 6 in formula) or \\\n (not 7 in formula and not 8 in formula))", "def isValid(formula):\n ...
{"fn_name": "isValid", "inputs": [[[1, 3, 7]], [[7, 1, 2, 3]], [[1, 3, 5, 7]], [[1, 5, 6, 7, 3]], [[5, 6, 7]], [[5, 6, 7, 8]], [[6, 7, 8]], [[7, 8]]], "outputs": [[true], [false], [false], [true], [true], [true], [false], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
40,757
def isValid(formula):
9682b4b6cbe6fc33ab93d844a391c6fc
UNKNOWN
Define a function that takes one integer argument and returns logical value `true` or `false` depending on if the integer is a prime. Per Wikipedia, a prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself. ## Requirements * You can assume you will be given...
["# This is the Miller-Rabin test for primes, which works for super large n\n\nimport random\n\ndef even_odd(n):\n s, d = 0, n\n while d % 2 == 0:\n s += 1\n d >>= 1\n return s, d\n\ndef Miller_Rabin(a, p):\n s, d = even_odd(p-1)\n a = pow(a, d, p)\n if a == 1: return True\n for i...
{"fn_name": "is_prime", "inputs": [[0], [1], [2], [73], [75], [-1]], "outputs": [[false], [false], [true], [true], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,958
def is_prime(num):
91e1ebcfb50bd1699b944af4cabb10a7
UNKNOWN
Determine the total number of digits in the integer (`n>=0`) given as input to the function. For example, 9 is a single digit, 66 has 2 digits and 128685 has 6 digits. Be careful to avoid overflows/underflows. All inputs will be valid.
["def digits(n):\n return len(str(n))", "from math import log10,ceil\n\ndef digits(n):\n return ceil(log10(n+1))", "from math import log10\n\ndef digits(n):\n return int(log10(n)+1)", "def digits(n):\n return len('%s'%n)", "from typing import Union\nfrom re import findall\n\ndef digits(number: Union[int, st...
{"fn_name": "digits", "inputs": [[5], [12345], [9876543210]], "outputs": [[1], [5], [10]]}
INTRODUCTORY
PYTHON3
CODEWARS
9,517
def digits(n):
5b1b4b59fbb56e3fb4477e51137e623f
UNKNOWN
# Task Given some points(array `A`) on the same line, determine the minimum number of line segments with length `L` needed to cover all of the given points. A point is covered if it is located inside some segment or on its bounds. # Example For `A = [1, 3, 4, 5, 8]` and `L = 3`, the output should be `2`. Check ou...
["def segment_cover(A, L):\n n=1\n s=min(A)\n for i in sorted(A):\n if s+L<i:\n s=i\n n+=1\n return n", "def segment_cover(a, l):\n a, n = set(a), 0\n while a:\n a -= set(range(min(a), min(a) + l + 1))\n n += 1\n return n\n", "def segment_cover(A, L):\n A = sorted(A)...
{"fn_name": "segment_cover", "inputs": [[[1, 3, 4, 5, 8], 3], [[-7, -2, 0, -1, -6, 7, 3, 4], 4], [[1, 5, 2, 4, 3], 1], [[1, 10, 100, 1000], 1]], "outputs": [[2], [3], [3], [4]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,789
def segment_cover(A, L):
527b3a00789852094c15bbaaa8f41a7e
UNKNOWN
A checksum is an algorithm that scans a packet of data and returns a single number. The idea is that if the packet is changed, the checksum will also change, so checksums are often used for detecting transmission errors, validating document contents, and in many other situations where it is necessary to detect undesira...
["from string import ascii_uppercase\n\nvalues = {x: i for i, x in enumerate(ascii_uppercase, 1)}\n\ndef quicksum(packet):\n return sum(values.get(c, 0) * i for i, c in enumerate(packet, 1)) * all(c.isspace() or c.isupper() for c in packet)", "def quicksum(packet):\n result = 0\n \n for idx, char in enumera...
{"fn_name": "quicksum", "inputs": [["ACM"], ["MID CENTRAL"], ["BBC"], ["???"], ["axg "], ["234 234 WEF ASDF AAA 554211 ???? "], ["A C M"], ["ABCDEFGHIJKLMNOPQRSTUVWXYZ"], ["A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"], ["ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ...
INTRODUCTORY
PYTHON3
CODEWARS
2,568
def quicksum(packet):
c4706577bc4f7acf5adfc3490981d1e6
UNKNOWN
Given an array of integers your solution should find the smallest integer. For example: - Given `[34, 15, 88, 2]` your solution will return `2` - Given `[34, -345, -1, 100]` your solution will return `-345` You can assume, for the purpose of this kata, that the supplied array will not be empty.
["def find_smallest_int(arr):\n return min(arr);", "def find_smallest_int(arr):\n return sorted(arr)[0]", "find_smallest_int = min ", "def find_smallest_int(arr):\n # Code here\n smallest=min(arr)\n for i in arr:\n if i<min(arr):\n smallest=i\n return smallest", "def find_smalles...
{"fn_name": "find_smallest_int", "inputs": [[[78, 56, 232, 12, 11, 43]], [[78, 56, -2, 12, 8, -33]], [[0, -18446744073709551615, 18446744073709551616]], [[-133, -5666, -89, -12341, -321423, 18446744073709551616]], [[0, 18446744073709551616, -18446744073709551617, 18446744073709551616, 18446744073709551616]], [[1, 2, 3,...
INTRODUCTORY
PYTHON3
CODEWARS
11,506
def find_smallest_int(arr):
cced0d9bddb2ed50425a16419ecec1de
UNKNOWN
Clock shows 'h' hours, 'm' minutes and 's' seconds after midnight. Your task is to make 'Past' function which returns time converted to milliseconds. ## Example: ```python past(0, 1, 1) == 61000 ``` Input constraints: `0 <= h <= 23`, `0 <= m <= 59`, `0 <= s <= 59`
["def past(h, m, s):\n return (3600*h + 60*m + s) * 1000", "def past(h, m, s):\n return (s + (m + h * 60) * 60) * 1000", "def past(h, m, s):\n # Good Luck!\n return 3600000 * h + 60000 * m + 1000 * s", "def past(h, m, s):\n return ((h * 60 + m) * 60 + s) * 1000", "def past(h, m, s):\n return h * (60 *...
{"fn_name": "past", "inputs": [[0, 1, 1], [1, 1, 1], [0, 0, 0], [1, 0, 1], [1, 0, 0]], "outputs": [[61000], [3661000], [0], [3601000], [3600000]]}
INTRODUCTORY
PYTHON3
CODEWARS
12,885
def past(h, m, s):
f8269c2be7e52a61da3bb83857a1ca6d
UNKNOWN
Given an Array and an Example-Array to sort to, write a function that sorts the Array following the Example-Array. Assume Example Array catalogs all elements possibly seen in the input Array. However, the input Array does not necessarily have to have all elements seen in the Example. Example: Arr: [1,3,4,4,4,4,5] E...
["def example_sort(arr, example_arr):\n return sorted(arr, key=example_arr.index)", "def example_sort(arr, example_arr):\n keys = {k: i for i, k in enumerate(example_arr)}\n return sorted(arr, key=lambda a: keys[a])", "def example_sort(a, b):\n return sorted(a, key=b.index)", "from collections import Counte...
{"fn_name": "example_sort", "inputs": [[[1, 2, 3, 4, 5], [2, 3, 4, 1, 5]], [[1, 2, 3, 3, 3, 4, 5], [2, 3, 4, 1, 5]], [[1, 2, 3, 3, 3, 5], [2, 3, 4, 1, 5]], [[1, 2, 3, 3, 3, 5], [3, 4, 5, 6, 9, 11, 12, 13, 1, 7, 8, 2, 10]], [["a", "a", "b", "f", "d", "a"], ["c", "a", "d", "b", "e", "f"]]], "outputs": [[[2, 3, 4, 1, 5]],...
INTRODUCTORY
PYTHON3
CODEWARS
1,473
def example_sort(arr, example_arr):
316b639db9ec0111faef392016664617
UNKNOWN
You should have done Product Partitions I to do this second part. If you solved it, you should have notice that we try to obtain the multiplicative partitions with ```n ≤ 100 ```. In this kata we will have more challenging values, our ```n ≤ 10000```. So, we need a more optimized a faster code. We need the function ...
["def prod_int_partII(n, s, min_=2):\n total, fac = 0, []\n for d in range(min_, int(n ** .5) + 1):\n if not n % d:\n count, l, sub = prod_int_partII(n // d, s-1, d)\n if l == 1: sub = [sub]\n total += count + 1\n fac.extend([d] + x for x in sub)\n if s == 1: ...
{"fn_name": "prod_int_partII", "inputs": [[36, 3], [48, 5], [37, 2], [96, 5], [96, 6]], "outputs": [[[8, 3, [[2, 2, 9], [2, 3, 6], [3, 3, 4]]]], [[11, 1, [2, 2, 2, 2, 3]]], [[0, 0, []]], [[18, 2, [[2, 2, 2, 2, 6], [2, 2, 2, 3, 4]]]], [[18, 1, [2, 2, 2, 2, 2, 3]]]]}
INTRODUCTORY
PYTHON3
CODEWARS
5,104
def prod_int_partII(n, s):
ba571aba95d4654b08f039af0902ff93
UNKNOWN
Given an array with exactly 5 strings `"a"`, `"b"` or `"c"` (`char`s in Java, `character`s in Fortran), check if the array contains three and two of the same values. ## Examples ``` ["a", "a", "a", "b", "b"] ==> true // 3x "a" and 2x "b" ["a", "b", "c", "b", "c"] ==> false // 1x "a", 2x "b" and 2x "c" ["a", "a", "a"...
["def check_three_and_two(array):\n return { array.count(x) for x in set(array) } == {2, 3}", "def check_three_and_two(array):\n return True if ((len(set(array)) == 2) and [each for each in set(array) if array.count(each) in [2,3]])else False", "from collections import Counter\ndef check_three_and_two(array):\n ...
{"fn_name": "check_three_and_two", "inputs": [[["a", "a", "a", "b", "b"]], [["a", "c", "a", "c", "b"]], [["a", "a", "a", "a", "a"]]], "outputs": [[true], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,233
def check_three_and_two(array):
aeaa13212f44a2ce711c69ca3fd6ce8d
UNKNOWN
``` ************************* * Create a frame! * * __ __ * * / \~~~/ \ * * ,----( .. ) * * / \__ __/ * * /| (\ |( * * ^ \ /___\ /\ | * * |__| |__|-.. * ************************* ``` Given an array of strings and a character to be use...
["def frame(text, char):\n text_lens = [len(x) for x in text]\n longest_len = max(text_lens)\n frame_list = [char*(longest_len + 4)]\n for str in text:\n frame_list.append(\"{} {}{} {}\".format(char, str, \" \" * (longest_len - len(str)), char)) \n frame_list.append(char*(longest_len + 4))\n r...
{"fn_name": "frame", "inputs": [[["Small", "frame"], "~"], [["Create", "this", "kata"], "+"], [["This is a very long single frame"], "-"]], "outputs": [["~~~~~~~~~\n~ Small ~\n~ frame ~\n~~~~~~~~~"], ["++++++++++\n+ Create +\n+ this +\n+ kata +\n++++++++++"], ["------------------------------------\n- This is a very...
INTRODUCTORY
PYTHON3
CODEWARS
2,503
def frame(text, char):
5af2e306de8024118d48f881dc57976d
UNKNOWN
Given an array of numbers, return a string made up of four parts: a) a four character 'word', made up of the characters derived from the first two and last two numbers in the array. order should be as read left to right (first, second, second last, last), b) the same as above, post sorting the array into ascending or...
["def extract(arr): return ''.join(arr[:2]+arr[-2:])\n\ndef sort_transform(arr):\n arr = list(map(chr,arr))\n w1 = extract(arr)\n arr.sort()\n w2 = extract(arr)\n return f'{w1}-{w2}-{w2[::-1]}-{w2}'", "def as_str(xs):\n return ''.join(map(chr, xs[:2] + xs[-2:]))\n\ndef sort_transform(arr):\n retu...
{"fn_name": "sort_transform", "inputs": [[[111, 112, 113, 114, 115, 113, 114, 110]], [[51, 62, 73, 84, 95, 100, 99, 126]], [[66, 101, 55, 111, 113]], [[78, 117, 110, 99, 104, 117, 107, 115, 120, 121, 125]], [[101, 48, 75, 105, 99, 107, 121, 122, 124]], [[80, 117, 115, 104, 65, 85, 112, 115, 66, 76, 62]], [[91, 100, 111...
INTRODUCTORY
PYTHON3
CODEWARS
2,487
def sort_transform(arr):
63db5709257d7f698f78a18d61c1b53b
UNKNOWN
Create a function that returns an array containing the first `l` digits from the `n`th diagonal of [Pascal's triangle](https://en.wikipedia.org/wiki/Pascal's_triangle). `n = 0` should generate the first diagonal of the triangle (the 'ones'). The first number in each diagonal should be 1. If `l = 0`, return an empty a...
["def generate_diagonal(d, l):\n result = [1] if l else []\n for k in range(1, l):\n result.append(result[-1] * (d+k) // k)\n return result", "def generate_diagonal(n, l):\n d = []\n for k in range(l):\n d.append(d[-1] * (n + k) // k if d else 1)\n return d", "from scipy.special import c...
{"fn_name": "generate_diagonal", "inputs": [[0, 10], [1, 10], [2, 10], [3, 10], [4, 10], [10, 0], [100, 6]], "outputs": [[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], [[1, 3, 6, 10, 15, 21, 28, 36, 45, 55]], [[1, 4, 10, 20, 35, 56, 84, 120, 165, 220]], [[1, 5, 15, 35, 70, 126, 210, 330, 495, 715]...
INTRODUCTORY
PYTHON3
CODEWARS
3,261
def generate_diagonal(n, l):
57c32f40b0ecc99ec524c83cf16fe82d
UNKNOWN
# Do you ever wish you could talk like Siegfried of KAOS ? ## YES, of course you do! https://en.wikipedia.org/wiki/Get_Smart # Task Write the function ```siegfried``` to replace the letters of a given sentence. Apply the rules using the course notes below. Each week you will learn some more rules. Und by ze fif...
["import re\n\nPATTERNS = [re.compile(r'(?i)ci|ce|c(?!h)'),\n re.compile(r'(?i)ph'),\n re.compile(r'(?i)(?<!\\b[a-z]{1})(?<!\\b[a-z]{2})e\\b|([a-z])\\1'),\n re.compile(r'(?i)th|w[rh]?'),\n re.compile(r'(?i)ou|an|ing\\b|\\bsm')]\n \nCHANGES = {\"ci\": \"si\", \"ce\...
{"fn_name": "siegfried", "inputs": [[1, "City civilians"], [1, "Centre receiver"], [1, "Chatanooga choo choo crashed"], [1, "Capital city cats chew cheese"], [2, "Photo of 5 pheasants with graphs"], [3, "Meet me at the same place at noon"], [3, "The time is now"], [3, "Be quite quiet"], [3, "Aardvarks are nice most of ...
INTRODUCTORY
PYTHON3
CODEWARS
16,451
def siegfried(week, txt):
2a05a9b3e87e8030e9281a5bd8939f0a
UNKNOWN
Many people choose to obfuscate their email address when displaying it on the Web. One common way of doing this is by substituting the `@` and `.` characters for their literal equivalents in brackets. Example 1: ``` user_name@example.com => user_name [at] example [dot] com ``` Example 2: ``` af5134@borchmore.edu => a...
["def obfuscate(email):\n return email.replace(\"@\", \" [at] \").replace(\".\", \" [dot] \")\n", "def obfuscate(email):\n return email.replace('.', ' [dot] ').replace('@', ' [at] ')", "def obfuscate(email):\n '''\nSalvador Dali - The Persistence of Memory\n ;!>,!!!>\n <! ;!!!`\n !! `!!!.\n ...
{"fn_name": "obfuscate", "inputs": [["user_name@example.com"], ["af5134@borchmore.edu"], ["jim.kuback@ennerman-hatano.com"], ["sir_k3v1n_wulf@blingblong.net"], ["Hmm, this would be better with input validation...!"]], "outputs": [["user_name [at] example [dot] com"], ["af5134 [at] borchmore [dot] edu"], ["jim [dot] kub...
INTRODUCTORY
PYTHON3
CODEWARS
7,686
def obfuscate(email):
0d00c90008f4db8872ab95b7d4c152c9
UNKNOWN
## Task You have to write three functions namely - `PNum, GPNum and SPNum` (JS, Coffee), `p_num, g_p_num and s_p_num` (Python and Ruby), `pNum, gpNum and spNum` (Java, C#), `p-num, gp-num and sp-num` (Clojure) - to check whether a given argument `n` is a Pentagonal, Generalized Pentagonal, or Square Pentagonal Number,...
["def p_num(n):\n r = (1 + (24*n+1)**.5) / 6\n return r.is_integer() and (3*(r**2) - r) / 2 == n \n \ndef g_p_num(n):\n r = ((1 + 24 * n) ** .5) % 6\n return r != 0 and r.is_integer()\n\ns_p_num=lambda n:(n**.5).is_integer() and p_num(n) and g_p_num(n)", "def get_p(n):\n mean = round((n * 2 / 3)**0.5)...
{"fn_name": "p_num", "inputs": [[0], [1], [2], [3], [4], [5], [100]], "outputs": [[false], [true], [false], [false], [false], [true], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,072
def p_num(n):
8161f0ac0295f8bbe1660c3bb9fb28a5
UNKNOWN
You've just recently been hired to calculate scores for a Dart Board game! Scoring specifications: * 0 points - radius above 10 * 5 points - radius between 5 and 10 inclusive * 10 points - radius less than 5 **If all radii are less than 5, award 100 BONUS POINTS!** Write a function that accepts an array of radii (...
["def score_throws(radiuses):\n score = 0\n for r in radiuses:\n if r < 5:\n score += 10\n elif 5 <= r <= 10:\n score += 5\n if radiuses and max(radiuses) < 5:\n score += 100\n return score", "def score_throws(radiuses):\n scores = [5 * ((v<5) + (v<=10)) for v i...
{"fn_name": "score_throws", "inputs": [[[1, 5, 11]], [[15, 20, 30, 31, 32, 44, 100]], [[1, 2, 3, 4]], [[]], [[1, 2, 3, 4, 5, 6, 7, 8, 9]], [[0, 5, 10, 10.5, 4.5]], [[1]], [[21, 10, 10]], [[5, 5, 5, 5]], [[4.9, 5.1]]], "outputs": [[15], [0], [140], [0], [65], [30], [110], [10], [20], [15]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,999
def score_throws(radii):
03b5c2be5310576035eb4209f40be0cb
UNKNOWN
In this Kata, you will be given an array of arrays and your task will be to return the number of unique arrays that can be formed by picking exactly one element from each subarray. For example: `solve([[1,2],[4],[5,6]]) = 4`, because it results in only `4` possiblites. They are `[1,4,5],[1,4,6],[2,4,5],[2,4,6]`. ``...
["from operator import mul\nfrom functools import reduce\n\ndef solve(arr):\n return reduce(mul, map(len, map(set, arr)), 1)", "def solve(arr):\n x = 1\n for a in arr:\n x *= len(set(a))\n return x", "from functools import reduce\nfrom operator import mul\ndef solve(arr):\n return reduce(mul, map(...
{"fn_name": "solve", "inputs": [[[[1, 2], [4], [5, 6]]], [[[1, 2], [4, 4], [5, 6, 6]]], [[[1, 2], [3, 4], [5, 6]]], [[[1, 2, 3], [3, 4, 6, 6, 7], [8, 9, 10, 12, 5, 6]]]], "outputs": [[4], [4], [8], [72]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,031
def solve(arr):
cd02d1a123f1a70efcbebc88ff39b209
UNKNOWN
# Task You are given a `moment` in time and space. What you must do is break it down into time and space, to determine if that moment is from the past, present or future. `Time` is the sum of characters that increase time (i.e. numbers in range ['1'..'9']. `Space` in the number of characters which do not increase...
["def moment_of_time_in_space(moment):\n d = sum(int(c) if c in '123456789' else -1 for c in moment)\n return [d < 0, d == 0, d > 0]", "def moment_of_time_in_space(moment):\n time = sum(int(c) for c in moment if c in \"123456789\")\n space = sum(c not in \"123456789\" for c in moment)\n return [time < sp...
{"fn_name": "moment_of_time_in_space", "inputs": [["12:30 am"], ["12:02 pm"], ["01:00 pm"], ["11:12 am"], ["05:20 pm"], ["04:20 am"]], "outputs": [[[false, false, true]], [[false, true, false]], [[true, false, false]], [[false, false, true]], [[false, false, true]], [[false, true, false]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,256
def moment_of_time_in_space(moment):
b92ad2eab5506863e8583ec7c647a987
UNKNOWN
# Task You know the slogan `p`, which the agitators have been chanting for quite a while now. Roka has heard this slogan a few times, but he missed almost all of them and grasped only their endings. You know the string `r` that Roka has heard. You need to determine what is the `minimal number` of times agitators r...
["import re\ndef slogans(p,r):\n reg=re.compile(\"|\".join([p[i:] for i in range(len(p))]))\n return len(re.findall(reg,r))", "from re import findall\n\ndef slogans(p, r):\n return len(findall('|'.join(p[i:] for i in range(len(p))), r))", "def slogans(slogan,heard):\n li = []\n while heard:\n temp = l...
{"fn_name": "slogans", "inputs": [["glorytoukraine", "ukraineaineaine"], ["glorytoukraine", "ukraineaineainee"], ["glorytoukraine", "einene"], ["programming", "ingmingmming"], ["mcoecqwmjdudc", "dcoecqwmjdudcdcudc"], ["erjernhxvbqfjsj", "ernhxvbqfjsjjrnhxvbqfjsjjernhxvbqfjsj"], ["dhgusdlifons", "lifonsssdlifonsgusdlifo...
INTRODUCTORY
PYTHON3
CODEWARS
2,349
def slogans(p,r):
b66e5b16d2c2ba274861338b858c959b
UNKNOWN
Given a list of integers, return the nth smallest integer in the list. **Only distinct elements should be considered** when calculating the answer. `n` will always be positive (`n > 0`) If the nth small integer doesn't exist, return `-1` (C++) / `None` (Python) / `nil` (Ruby) / `null` (JavaScript). Notes: * "indexing...
["def nth_smallest(arr, n):\n s = set(arr)\n return sorted(s)[n-1] if n<=len(s) else None", "def nth_smallest(arr, n):\n try:\n return sorted(set(arr))[n-1]\n except:\n pass", "import random\n\ndef partition(vector, left, right, pivotIndex):\n pivotValue = vector[pivotIndex]\n vector[piv...
{"fn_name": "nth_smallest", "inputs": [[[14, 12, 46, 34, 334], 3], [[4000], 1], [[14, 12, 46, 0, 334], 1]], "outputs": [[34], [4000], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,863
def nth_smallest(arr, n):
2fe386967b5080d85153898153eb7a87
UNKNOWN
It started as a discussion with a friend, who didn't fully grasp some way of setting defaults, but I thought the idea was cool enough for a beginner kata: binary `OR` each matching element of two given arrays (or lists, if you do it in Python; vectors in c++) of integers and give the resulting ORed array [starts to sou...
["from itertools import zip_longest\n\ndef or_arrays(a1, a2, d=0):\n return [x|y for x,y in zip_longest(a1, a2, fillvalue=d)]", "def or_arrays(a, b, d=0):\n return [(a[i] if i<len(a) else d)|(b[i] if i<len(b) else d) for i in range(max(len(a), len(b)))]", "from itertools import zip_longest\n\ndef or_arrays(arr1, ...
{"fn_name": "or_arrays", "inputs": [[[1, 2, 3], [1, 2, 3]], [[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [1, 2]], [[1, 0], [1, 2, 3]], [[1, 0, 3], [1, 2, 3], 3]], "outputs": [[[1, 2, 3]], [[5, 7, 7]], [[1, 2, 3]], [[1, 2, 3]], [[1, 2, 3]]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,635
def or_arrays(a, b, filler=0):
5babda6e691f38b5eeb11843d72f4c34
UNKNOWN
"The Shell Game" involves cups upturned on a playing surface, with a ball placed underneath one of them. The index of the cups are swapped around multiple times. After that the players will try to find which cup contains the ball. Your task is as follows. Given the cup that the ball starts under, and list of swaps, ...
["def find_the_ball(start, swaps):\n pos = start\n for (a, b) in swaps:\n if a == pos:\n pos = b\n elif b == pos:\n pos = a\n return pos\n", "def find_the_ball(start, swaps):\n for sw in swaps:\n if start in sw:\n start = sw[1-sw.index(start)]\n retur...
{"fn_name": "find_the_ball", "inputs": [[5, []], [0, []], [9, []], [0, [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9], [9, 10], [10, 11], [11, 12], [12, 13], [13, 14], [14, 15], [15, 16], [16, 17], [17, 18], [18, 19], [19, 20], [20, 21], [21, 22], [22, 23], [23, 24], [24, 25], [25, 26], [26, 27...
INTRODUCTORY
PYTHON3
CODEWARS
1,488
def find_the_ball(start, swaps):
f7f75c9522946dc7adebf05c8657b1c1
UNKNOWN
# Task Pero has been into robotics recently, so he decided to make a robot that checks whether a deck of poker cards is complete. He’s already done a fair share of work - he wrote a programme that recognizes the suits of the cards. For simplicity’s sake, we can assume that all cards have a suit and a number. The s...
["from collections import defaultdict\n\ndef cards_and_pero(s):\n deck = defaultdict(set)\n for n in range(0,len(s),3):\n card = s[n:n+3]\n if card[1:] in deck[card[0]]: return [-1,-1,-1,-1]\n deck[card[0]] |= {card[1:]}\n return [ 13 - len(deck[suit]) for suit in \"PKHT\"]", "from collect...
{"fn_name": "cards_and_pero", "inputs": [["P01K02H03H04"], ["H02H10P11H02"], ["P10K10H10T01"], ["P05P01P02P03P13P09P11P07K01P12K03K02K13K12K10K08H03H02H13H12H10H08T01T03T02T13T12T10T08P04K07H02T07H06T11K11T05K05H05H11"], ["P01K02P03P11K09K10P13P10"]], "outputs": [[[12, 12, 11, 13]], [[-1, -1, -1, -1]], [[12, 12, 12, 12...
INTRODUCTORY
PYTHON3
CODEWARS
3,499
def cards_and_pero(s):
0c701ac65aa46f45ce807e499475462f
UNKNOWN
You've came to visit your grandma and she straight away found you a job - her Christmas tree needs decorating! She first shows you a tree with an identified number of branches, and then hands you a some baubles (or loads of them!). You know your grandma is a very particular person and she would like the baubles to be...
["def baubles_on_tree(baubles, branches):\n if not branches: return \"Grandma, we will have to buy a Christmas tree first!\"\n d,r=divmod(baubles,branches)\n return [d+1]*r+[d]*(branches-r)", "def baubles_on_tree(baubles, branches):\n if not branches:\n return 'Grandma, we will have to buy a Christma...
{"fn_name": "baubles_on_tree", "inputs": [[5, 5], [5, 0], [6, 5], [50, 9], [0, 10]], "outputs": [[[1, 1, 1, 1, 1]], ["Grandma, we will have to buy a Christmas tree first!"], [[2, 1, 1, 1, 1]], [[6, 6, 6, 6, 6, 5, 5, 5, 5]], [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,413
def baubles_on_tree(baubles, branches):
de3a913c89aeb54c91323157f76258b7
UNKNOWN
# Task John is new to spreadsheets. He is well aware of rows and columns, but he is not comfortable with spreadsheets numbering system. ``` Spreadsheet Row Column A1 R1C1 D5 R5C4 AA48 R48C27 BK12 R12C63``` Since John has a lot ...
["import re\n\ndef spreadsheet(s):\n nums = re.findall(r'(\\d+)', s)\n if len(nums) == 2:\n n, cStr = int(nums[1]), ''\n while n:\n n, r = divmod(n-1, 26)\n cStr += chr(r + 65)\n return \"{}{}\".format(cStr[::-1], nums[0])\n else:\n return \"R{}C{}\".format(num...
{"fn_name": "spreadsheet", "inputs": [["A1"], ["R1C1"], ["R5C4"], ["AA48"], ["BK12"], ["R12C63"], ["R85C26"], ["R31C78"], ["BZ31"]], "outputs": [["R1C1"], ["A1"], ["D5"], ["R48C27"], ["R12C63"], ["BK12"], ["Z85"], ["BZ31"], ["R31C78"]]}
INTRODUCTORY
PYTHON3
CODEWARS
6,390
def spreadsheet(s):
ec41258e5b1967e844106c4d898c0767
UNKNOWN
If `a = 1, b = 2, c = 3 ... z = 26` Then `l + o + v + e = 54` and `f + r + i + e + n + d + s + h + i + p = 108` So `friendship` is twice stronger than `love` :-) The input will always be in lowercase and never be empty.
["def words_to_marks(s):\n return sum(ord(c)-96 for c in s)", "def words_to_marks(s):\n return sum('_abcdefghijklmnopqrstuvwxyz'.index(e) for e in s)", "def words_to_marks(s):\n return sum( ord(i)-(ord('a')-1) for i in s )", "def words_to_marks(s):\n return sum(map(ord,s))-len(s)*96", "def words_to_marks(s):\...
{"fn_name": "words_to_marks", "inputs": [["attitude"], ["friends"], ["family"], ["selfness"], ["knowledge"]], "outputs": [[100], [75], [66], [99], [96]]}
INTRODUCTORY
PYTHON3
CODEWARS
19,129
def words_to_marks(s):
9a433f985cb21857ba0bcf4477202db5
UNKNOWN
Alex just got a new hula hoop, he loves it but feels discouraged because his little brother is better than him Write a program where Alex can input (n) how many times the hoop goes round and it will return him an encouraging message :) -If Alex gets 10 or more hoops, return the string "Great, now move on to tricks"....
["def hoop_count(n):\n return \"Keep at it until you get it\" if n <10 else \"Great, now move on to tricks\"", "def hoop_count(n):\n if n < 10:\n return(\"Keep at it until you get it\")\n else:\n return(\"Great, now move on to tricks\")\n", "def hoop_count(n):\n return \"Great, now move on to ...
{"fn_name": "hoop_count", "inputs": [[6], [10], [22]], "outputs": [["Keep at it until you get it"], ["Great, now move on to tricks"], ["Great, now move on to tricks"]]}
INTRODUCTORY
PYTHON3
CODEWARS
13,856
def hoop_count(n):
81dd887abb3596825354e9a050ee5e91
UNKNOWN
You will be given an array which lists the current inventory of stock in your store and another array which lists the new inventory being delivered to your store today. Your task is to write a function that returns the updated list of your current inventory **in alphabetical order**. ## Example ```python cur_stock =...
["from collections import defaultdict\ndef update_inventory(cur_stock, new_stock):\n answer = defaultdict(int)\n for stock, item in cur_stock + new_stock:\n answer[item] += stock\n return [(answer[item], item) for item in sorted(answer)]", "from collections import defaultdict\n\ndef update_inventory(cur...
{"fn_name": "update_inventory", "inputs": [[[], []]], "outputs": [[[]]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,790
def update_inventory(cur_stock, new_stock):
2ba4639eb77ae4e674036e5ecc9ec3ac
UNKNOWN
# Task: We define the "self reversed power sequence" as one shown below: Implement a function that takes 2 arguments (`ord max` and `num dig`), and finds the smallest term of the sequence whose index is less than or equal to `ord max`, and has exactly `num dig` number of digits. If there is a number with correct a...
["# precalculate results\nresults = {}\nn, digits = 1, 0\nwhile digits <= 1000:\n digits = len(str(sum( x**(n-x+1) for x in range(1, n) )))\n if digits not in results:\n results[digits] = n\n n += 1\n\n\ndef min_length_num(digits, max_num): \n n = results.get(digits, 0)\n return [True, n+1] if n a...
{"fn_name": "min_length_num", "inputs": [[5, 10], [7, 11], [7, 14], [8, 16], [10, 20]], "outputs": [[[true, 10]], [[false, -1]], [[true, 13]], [[true, 15]], [[true, 17]]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,903
def min_length_num(num_dig, ord_max):
6b4383647c60af55c9ef72ffa9111ebe
UNKNOWN
You will be given an array of non-negative integers and positive integer bin width. Your task is to create the Histogram method that will return histogram data corresponding to the input array. The histogram data is an array that stores under index i the count of numbers that belong to bin i. The first bin always sta...
["def histogram(lst, w):\n lst = [n // w for n in lst]\n m = max(lst, default=-1) + 1\n return [lst.count(n) for n in range(m)]", "def histogram(v, w):\n return [sum(j in range(i, w+i) for j in v) for i in range(0, max(v)+1, w)] if v else []", "def histogram(values, bin_width):\n return [sum([values.coun...
{"fn_name": "histogram", "inputs": [[[1, 1, 0, 1, 3, 2, 6], 1], [[1, 1, 0, 1, 3, 2, 6], 2], [[], 1], [[8], 1]], "outputs": [[[1, 3, 1, 1, 0, 0, 1]], [[4, 2, 0, 1]], [[]], [[0, 0, 0, 0, 0, 0, 0, 0, 1]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,051
def histogram(values, bin_width):
0b1c52492d216c6cb3ea6c18c50b4d78
UNKNOWN
Write ```python smaller(arr) ``` that given an array ```arr```, you have to return the amount of numbers that are smaller than ```arr[i]``` to the right. For example: ```python smaller([5, 4, 3, 2, 1]) == [4, 3, 2, 1, 0] smaller([1, 2, 0]) == [1, 1, 0] ``` ``` haskell smaller [5,4,3,2,1] `shouldBe` [4,3,2,1,0] smalle...
["def smaller(arr):\n # Good Luck!\n return [len([a for a in arr[i:] if a < arr[i]]) for i in range(0, len(arr))]\n", "def smaller(arr):\n return [sum(b < a for b in arr[i + 1:]) for i, a in enumerate(arr)]\n", "def smaller(arr):\n return [sum(x > y for y in arr[i+1:]) for i, x in enumerate(arr)]", "def sma...
{"fn_name": "smaller", "inputs": [[[5, 4, 3, 2, 1]], [[1, 2, 3]], [[1, 2, 0]], [[1, 2, 1]], [[1, 1, -1, 0, 0]], [[5, 4, 7, 9, 2, 4, 4, 5, 6]]], "outputs": [[[4, 3, 2, 1, 0]], [[0, 0, 0]], [[1, 1, 0]], [[0, 1, 0]], [[3, 3, 0, 0, 0]], [[4, 1, 5, 5, 0, 0, 0, 0, 0]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,817
def smaller(arr):
29300a713ee75e61082029d4f0a275b9
UNKNOWN
Remember the movie with David Bowie: 'The Labyrinth'? You can remember your childhood here: https://www.youtube.com/watch?v=2dgmgub8mHw In this scene the girl is faced with two 'Knights" and two doors. One door leads the castle where the Goblin King and her kid brother is, the other leads to certain death. She can as...
["def knight_or_knave(said):\n return \"Knight!\" if eval(str(said)) else \"Knave! Do not trust.\"", "def knight_or_knave(said):\n try:\n return 'Knight!' if eval(said) else 'Knave! Do not trust.'\n except:\n return 'Knight!' if said else 'Knave! Do not trust.'", "knight_or_knave = lambda said: '...
{"fn_name": "knight_or_knave", "inputs": [[true], [false], ["4+2==5"], ["2+2==4"], ["not True and False or False or False"], ["3 is 3"], ["True"], ["not True"], ["2+2==5"], ["4+1==5"], ["4 is 3"], ["9+2==3"], ["105+30076==30181"], ["3 is 3 is 3 is 9"], ["False"], ["\"orange\" is not \"red\""], ["4 is \"blue\""], ["True...
INTRODUCTORY
PYTHON3
CODEWARS
1,466
def knight_or_knave(said):
ee8b8257d4e4e431838a56b9e6c79e28
UNKNOWN
Cara is applying for several different jobs. The online application forms ask her to respond within a specific character count. Cara needs to check that her answers fit into the character limit. Annoyingly, some application forms count spaces as a character, and some don't. Your challenge: Write Cara a function `ch...
["def charCheck(text, mx, spaces):\n text = text if spaces else text.replace(' ', '')\n return [len(text) <= mx, text[:mx]]", "def charCheck(text, mx, spaces):\n if not spaces:\n text = text.replace(' ', '')\n return [len(text) <= mx, text[:mx]]", "def charCheck(s, mx, spaces):\n res = ''.join((s....
{"fn_name": "charCheck", "inputs": [["I am applying for the role of Base Manager on Titan.", 60, true], ["I am looking to relocate to the vicinity of Saturn for family reasons.", 70, true], ["As Deputy Base Manager on Phobos for five Martian years, I have significant relevant experience.", 90, false], ["A challenging c...
INTRODUCTORY
PYTHON3
CODEWARS
1,637
def charCheck(text, mx, spaces):
fe2db94914df1df9c7af88e13fa8ef20
UNKNOWN
Complete the `greatestProduct` method so that it'll find the greatest product of five consecutive digits in the given string of digits. For example: The input string always has more than five digits. Adapted from Project Euler.
["from itertools import islice\nfrom functools import reduce\n\ndef greatest_product(n):\n numbers=[int(value) for value in n]\n result=[reduce(lambda x,y: x*y, islice(numbers, i, i+5), 1) for i in range(len(numbers)-4)]\n return max(result) \n", "def product(list):\n p = 1\n for i in list:\n p *=...
{"fn_name": "greatest_product", "inputs": [["123834539327238239583"], ["395831238345393272382"], ["92494737828244222221111111532909999"], ["02494037820244202221011110532909999"]], "outputs": [[3240], [3240], [5292], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,215
def greatest_product(n):
9de14aa65321b2be1530cf9bc31b2805
UNKNOWN
This kata is part of the collection [Mary's Puzzle Books](https://www.codewars.com/collections/marys-puzzle-books). # Zero Terminated Sum Mary has another puzzle book, and it's up to you to help her out! This book is filled with zero-terminated substrings, and you have to find the substring with the largest sum of it...
["def largest_sum(s):\n return max(sum(map(int,x)) for x in s.split('0'))", "def largest_sum(s):\n return max(sum(map(int, e)) for e in s.split('0'))", "def largest_sum(s):\n return max(sum(int(i) for i in j) for j in s.split('0'))", "def largest_sum(s):\n return max(sum(int(x) for x in n) for n in s.split(...
{"fn_name": "largest_sum", "inputs": [["72102450111111090"], ["123004560"], ["0"], ["4755843230"], ["3388049750"], ["3902864190"], ["4098611970"], ["5628206860"], ["5891002970"], ["0702175070"]], "outputs": [[11], [15], [0], [41], [25], [30], [41], [23], [23], [15]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,123
def largest_sum(s):
c5854a786e62d03836d6d5073d602fb8
UNKNOWN
Make your strings more nerdy: Replace all 'a'/'A' with 4, 'e'/'E' with 3 and 'l' with 1 e.g. "Fundamentals" --> "Fund4m3nt41s" ```if:csharp Documentation: Kata.Nerdify Method (String) Nerdifies a string. Returns a copy of the original string with 'a'/'A' characters replaced with '4', 'e'/'E' characters replaced with...
["def nerdify(txt):\n return txt.translate(str.maketrans(\"aAeEl\", \"44331\"))", "def nerdify(txt):\n return txt.translate(str.maketrans(\"aelAE\",\"43143\"))\n", "def nerdify(txt):\n intab = 'aelAE'\n outab = '43143'\n trantab = str.maketrans(intab,outab)\n return txt.translate(trantab)", "def nerdi...
{"fn_name": "nerdify", "inputs": [["Fund4m3nt41s"], ["Seven"], ["Los Angeles"], ["Seoijselawuue"]], "outputs": [["Fund4m3nt41s"], ["S3v3n"], ["Los 4ng313s"], ["S3oijs314wuu3"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,971
def nerdify(txt):
13a6b82b4745c48dbec90889af8b28f1
UNKNOWN
Given a time in AM/PM format as a string, convert it to military (24-hour) time as a string. Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock Sample Input: 07:05:45PM Sample Output: 19:05:45 Try not to use built in Dat...
["def get_military_time(time):\n if time[-2:] == 'AM':\n hour = '00' if time[0:2] == '12' else time[0:2]\n else:\n hour = '12' if time[0:2] == '12' else str(int(time[0:2])+12)\n return hour + time[2:-2]", "def get_military_time(time_str):\n hour = int(time_str[:2])\n pm = time_str[-2] == \"...
{"fn_name": "get_military_time", "inputs": [["12:00:01AM"], ["01:02:03AM"], ["02:04:05AM"], ["03:06:07AM"], ["04:08:09AM"], ["05:10:11AM"], ["06:12:13AM"], ["07:14:15AM"], ["08:16:17AM"], ["09:18:19AM"], ["10:20:21AM"], ["11:22:23AM"], ["12:24:25PM"], ["01:26:27PM"], ["02:28:29PM"], ["03:30:31PM"], ["04:32:33PM"], ["05...
INTRODUCTORY
PYTHON3
CODEWARS
1,674
def get_military_time(time):
b4529b733f9f23381aabdf4807a356fa
UNKNOWN
Two integers are coprimes if the their only greatest common divisor is 1. ## Task In this kata you'll be given a number ```n >= 2``` and output a list with all positive integers less than ```gcd(n, k) == 1```, with ```k``` being any of the output numbers. The list cannot include duplicated entries and has to be sorte...
["from fractions import gcd\n\ndef coprimes(n):\n return [i for i in range(1,n+1) if gcd(n,i)==1]", "from fractions import gcd\ndef coprimes(n):\n return [i for i in range(n) if gcd(i,n)==1]", "from fractions import gcd\n\ncoprimes = lambda n: [i for i in range(1, n) if gcd(n, i) == 1]", "from fractions import gcd ...
{"fn_name": "coprimes", "inputs": [[2], [3], [6], [10], [20], [25], [30]], "outputs": [[[1]], [[1, 2]], [[1, 5]], [[1, 3, 7, 9]], [[1, 3, 7, 9, 11, 13, 17, 19]], [[1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19, 21, 22, 23, 24]], [[1, 7, 11, 13, 17, 19, 23, 29]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,467
def coprimes(n):
fc0ae897021ed3c5f143bb912c2369ba
UNKNOWN
Most languages have a `split` function that lets you turn a string like `“hello world”` into an array like`[“hello”, “world”]`. But what if we don't want to lose the separator? Something like `[“hello”, “ world”]`. #### Task: Your job is to implement a function, (`split_without_loss` in Ruby/Crystal, and `splitWithou...
["def split_without_loss(s, split_p):\n return [i for i in s.replace(split_p.replace('|', ''), split_p).split('|') if i]", "import re\n\ndef split_without_loss(s, m):\n r,iM = m.replace('|',''), m.index('|')\n out,i,j = [],0,0\n while 1:\n j = s.find(r,j)\n if j==-1:\n if i<len(s):...
{"fn_name": "split_without_loss", "inputs": [["hello world!", " |"], ["hello world!", "o|rl"], ["hello world!", "ello| "], ["hello world!", "hello wo|rld!"], ["hello world!", "h|ello world!"], ["hello world! hello world!", " |"], ["hello world! hello world!", "o|rl"], ["hello world! hello world!", "ello| "], ["hello wo...
INTRODUCTORY
PYTHON3
CODEWARS
2,072
def split_without_loss(s, split_p):
305d113e49be525539629e9e6b362efb
UNKNOWN
# Convert Improper Fraction to Mixed Number You will need to convert an [improper fraction](https://www.mathplacementreview.com/arithmetic/fractions.php#improper-fractions) to a [mixed number](https://www.mathplacementreview.com/arithmetic/fractions.php#mixed-number). For example: ```python get_mixed_num('18/11') # S...
["def get_mixed_num(fraction):\n n, d = [int(i) for i in fraction.split('/')]\n return '{} {}/{}'.format(n // d, n % d, d)", "def get_mixed_num(f):\n [a, b] = map(int, f.split('/'))\n return \"{} {}/{}\".format(a//b, a%b, b)", "def get_mixed_num(f):n,d=map(int,f.split('/'));return'%d %d/%d'%(n/d,n%d,d)", "d...
{"fn_name": "get_mixed_num", "inputs": [["18/11"], ["13/5"], ["75/10"]], "outputs": [["1 7/11"], ["2 3/5"], ["7 5/10"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,343
def get_mixed_num(fraction):
1978fc8538770cd624082b6a8aeaea24
UNKNOWN
# Sentence Smash Write a function that takes an array of words and smashes them together into a sentence and returns the sentence. You can ignore any need to sanitize words or add punctuation, but you should add spaces between each word. **Be careful, there shouldn't be a space at the beginning or the end of the sente...
["def smash(words):\n return \" \".join(words)", "smash = ' '.join", "# http://www.codewars.com/kata/53dc23c68a0c93699800041d/\n\n\ndef smash(words):\n return \" \".join(words)\n", "smash=lambda x:' '.join(x)", "def smash(words):\n smash = \" \".join(words)\n return smash\n", "def smash(words):\n \n s...
{"fn_name": "smash", "inputs": [[[]], [["hello"]], [["hello", "world"]], [["hello", "amazing", "world"]], [["this", "is", "a", "really", "long", "sentence"]]], "outputs": [[""], ["hello"], ["hello world"], ["hello amazing world"], ["this is a really long sentence"]]}
INTRODUCTORY
PYTHON3
CODEWARS
12,806
def smash(words):
196822b026adc60872804297d34f2463
UNKNOWN
Write a function which takes one parameter representing the dimensions of a checkered board. The board will always be square, so 5 means you will need a 5x5 board. The dark squares will be represented by a unicode white square, while the light squares will be represented by a unicode black square (the opposite colours...
["def checkered_board(n):\n return isinstance(n,int) and n>1 and \\\n '\\n'.join(' '.join( \"\u25a0\" if (x+y)%2 ^ n%2 else \"\u25a1\" for y in range(n) ) for x in range(n))\n", "def checkered_board(n):\n l = ['\u25a1', '\u25a0']\n return False if type(n) != int or n < 2 else '\\n'.join(' '.join(l[(...
{"fn_name": "checkered_board", "inputs": [[1], [0], [-1], ["test"], [null], [[]], [2], [100], [3], [7]], "outputs": [[false], [false], [false], [false], [false], [false], ["\u25a1 \u25a0\n\u25a0 \u25a1"], ["\u25a1 \u25a0 \u25a1 \u25a0 \u25a1 \u25a0 \u25a1 \u25a0 \u25a1 \u25a0 \u25a1 \u25a0 \u25a1 \u25a0 \u25a1 \u25a0 \...
INTRODUCTORY
PYTHON3
CODEWARS
2,411
def checkered_board(n):
b1da6a84c9b9fe223b419260d65d9ee5
UNKNOWN
The [Chinese zodiac](https://en.wikipedia.org/wiki/Chinese_zodiac) is a repeating cycle of 12 years, with each year being represented by an animal and its reputed attributes. The lunar calendar is divided into cycles of 60 years each, and each year has a combination of an animal and an element. There are 12 animals and...
["animals = ['Rat', 'Ox', 'Tiger', 'Rabbit', 'Dragon', 'Snake', 'Horse', 'Goat', 'Monkey', 'Rooster', 'Dog', 'Pig']\nelements = ['Wood', 'Fire', 'Earth', 'Metal', 'Water']\ndef chinese_zodiac(year):\n year -= 1984\n return elements[year//2 % 5] + \" \" + animals[year % 12]", "def chinese_zodiac(year):\n s = ''...
{"fn_name": "chinese_zodiac", "inputs": [[1965], [1938], [1998], [2016], [1924], [1968], [2162], [6479], [3050], [6673], [6594], [9911], [2323], [3448], [1972]], "outputs": [["Wood Snake"], ["Earth Tiger"], ["Earth Tiger"], ["Fire Monkey"], ["Wood Rat"], ["Earth Monkey"], ["Water Dog"], ["Earth Goat"], ["Metal Dog"], [...
INTRODUCTORY
PYTHON3
CODEWARS
1,339
def chinese_zodiac(year):
338ab9a46b4163ce255c7db61278d43c
UNKNOWN
For a given array whose element values are randomly picked from single-digit integers `0` to `9`, return an array with the same digit order but all `0`'s paired. Paring two `0`'s generates one `0` at the location of the first. Ex: ```python pair_zeros([0, 1, 0, 2]) # paired: ^-----^ cull second zero == [0, 1, 2...
["from itertools import count\ndef pair_zeros(arr, *args):\n c = count(1)\n return [elem for elem in arr if elem != 0 or next(c) % 2]", "def pair_zeros(nums, *_):\n result = []\n skip_zero = False\n for a in nums:\n if a == 0:\n if not skip_zero:\n result.append(a)\n ...
{"fn_name": "pair_zeros", "inputs": [[[]], [[1]], [[1, 2, 3]], [[0]], [[0, 0]], [[1, 0, 1, 0, 2, 0, 0]], [[0, 0, 0]], [[1, 0, 1, 0, 2, 0, 0, 3, 0]], [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]], "outputs": [[[]], [[1]], [[1, 2, 3]], [[0]], [[0]], [[1, 0, 1, 2, 0]], [[0, 0]], [[1, 0...
INTRODUCTORY
PYTHON3
CODEWARS
1,526
def pair_zeros(arr):
be38af59f9ef485e85eed4725e324473
UNKNOWN
```if:javascript `Array.prototype.length` will give you the number of top-level elements in an array. ``` ```if:ruby `Array#length` will give you the number of top-level elements in an array. ``` ```if:csharp The `Length` property of an array will give you the number of top-level elements in an array. ``` ```if:php `co...
["def deep_count(a):\n result = 0\n for i in range(len(a)):\n if type(a[i]) is list:\n result += deep_count(a[i])\n result += 1\n return result\n", "def deep_count(a):\n return sum(1 + (deep_count(x) if isinstance(x, list) else 0) for x in a)", "def deep_count(a):\n return len(a)...
{"fn_name": "deep_count", "inputs": [[[]], [[1, 2, 3]], [["x", "y", ["z"]]], [[1, 2, [3, 4, [5]]]], [[[[[[[[[[]]]]]]]]]], [["a"]], [[["a"]]], [[["a"], []]], [["[a]"]], [[[[[[[[[["Everybody!"]]]]]]]]]], [["cat", [["dog"]], ["[bird]"]]]], "outputs": [[0], [3], [4], [7], [8], [1], [2], [3], [1], [9], [6]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,433
def deep_count(a):
04d7cef5e9eacfcfd7618598ad1f79df
UNKNOWN
Given a certain integer ```n, n > 0```and a number of partitions, ```k, k > 0```; we want to know the partition which has the maximum or minimum product of its terms. The function ```find_spec_partition() ```, will receive three arguments, ```n```, ```k```, and a command: ```'max' or 'min'``` The function should...
["def find_spec_partition(n, k, com):\n x,r = divmod(n,k)\n return {'max': [x+1]*r + [x]*(k-r),\n 'min': [n+1-k] + [1]*(k-1)}[com]", "def find_spec_partition(n, k, com):\n return [n-k+1] + [1] * (k-1) if com == \"min\" else [n//k + 1] * (n%k) + [n//k] * (k - n%k)", "def find_spec_partition(n, k, com...
{"fn_name": "find_spec_partition", "inputs": [[10, 4, "max"], [10, 4, "min"]], "outputs": [[[3, 3, 2, 2]], [[7, 1, 1, 1]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,607
def find_spec_partition(n, k, com):
6e0b54b9ebf7f42f604b9b9d676e4d5a
UNKNOWN
Let be `n` an integer prime with `10` e.g. `7`. `1/7 = 0.142857 142857 142857 ...`. We see that the decimal part has a cycle: `142857`. The length of this cycle is `6`. In the same way: `1/11 = 0.09 09 09 ...`. Cycle length is `2`. # Task Given an integer n (n > 1), the function cycle(n) returns the length of the...
["import math\n\ndef cycle(n) :\n if n % 2 == 0 or n % 5 ==0:\n return -1\n k = 1\n while pow(10,k,n) != 1:\n k += 1\n return k\n \n \n \n", "def cycle(n):\n if not n % 2 or not n % 5:\n return -1\n x, mods = 1, set()\n while x not in mods:\n mods.add...
{"fn_name": "cycle", "inputs": [[3], [33], [18118], [69], [197], [65], [97], [19], [111], [53], [59], [93], [51], [159], [183], [167], [94], [133], [218713], [38127], [431541], [221193], [1234567]], "outputs": [[1], [2], [-1], [22], [98], [-1], [96], [18], [3], [13], [58], [15], [16], [13], [60], [166], [-1], [18], [97...
INTRODUCTORY
PYTHON3
CODEWARS
1,830
def cycle(n) :
7e2154b92eb5fc82fa7b7cc67fa3cd52
UNKNOWN
Below is a right-angled triangle: ``` |\ | \ | \ | \ o | \ h | \ | θ \ |_______\ a ``` Your challange is to write a function (```missingAngle``` in C/C#, ```missing_angle``` in Ruby), that calculates the angle θ in degrees to the nearest integer. You will be given three arguments re...
["import math\n\ndef missing_angle(h, a, o):\n if h == 0:\n radians = math.atan(o/a)\n elif a == 0:\n radians = math.asin(o/h)\n else:\n radians = math.acos(a/h)\n return round(math.degrees(radians))", "from math import asin, acos, atan, degrees as d\nmissing_angle=lambda h,a,o:round(d(...
{"fn_name": "missing_angle", "inputs": [[0, 400, 300], [5, 4, 0], [8, 0, 5], [16.7, 0, 12.3], [7, 5, 0]], "outputs": [[37], [37], [39], [47], [44]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,973
def missing_angle(h, a, o):
c9c8d9a9c845be2809a6e9ab6f9e4509
UNKNOWN
## Task To charge your mobile phone battery, do you know how much time it takes from 0% to 100%? It depends on your cell phone battery capacity and the power of the charger. A rough calculation method is: ``` 0% --> 85% (fast charge) (battery capacity(mAh) * 85%) / power of the charger(mA) 85% --> 95% (decreasing ch...
["calculate_time=lambda b,c: round(b/float(c)*1.3+0.0001,2)\n \n", "CHARGE_CONFIG = ((.85, 1), (.1, .5), (.05, .2)) \n\ndef calculate_time(battery, charger):\n return round(1e-4 + sum(battery * pb / (charger * pc) for pb,pc in CHARGE_CONFIG), 2)", "def calculate_time(battery, charger):\n return round(battery /...
{"fn_name": "calculate_time", "inputs": [[1000, 500], [1500, 500], [2000, 1000], [5000, 1000], [1000, 5000], [3050, 2600]], "outputs": [[2.6], [3.9], [2.6], [6.5], [0.26], [1.53]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,493
def calculate_time(battery,charger):
9f4dcb81a735087cfc5d1b94fccba4ef
UNKNOWN
# The Invitation Most of us played with toy blocks growing up. It was fun and you learned stuff. So what else can you do but rise to the challenge when a 3-year old exclaims, "Look, I made a square!", then pointing to a pile of blocks, "Can _you_ do it?" # These Blocks Just to play along, of course we'll be viewing ...
["def build_square(blocks):\n for x in range(4):\n if 4 in blocks:\n blocks.remove(4)\n elif 3 in blocks and 1 in blocks:\n blocks.remove(3)\n blocks.remove(1)\n elif blocks.count(2) >= 2:\n blocks.remove(2)\n blocks.remove(2)\n elif ...
{"fn_name": "build_square", "inputs": [[[1, 1, 1, 1, 1, 1, 1, 2, 3, 4]], [[1, 3, 2, 2, 4, 1, 1, 3, 1, 4, 2]], [[1, 3, 2, 4, 3, 3, 2]], [[2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4]], [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], [[3, 1, 3, 1, 3, 1, 3, 2]], [[1, 3, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1]], [[4, 2, 2, 1, 1, 1, 1, 3, 3,...
INTRODUCTORY
PYTHON3
CODEWARS
3,246
def build_square(blocks):
e65bd638005a9791bcc40a6c0c66dbf7
UNKNOWN
Every natural number, ```n```, may have a prime factorization like: We define the arithmetic derivative of ```n```, ```n'``` the value of the expression: Let's do the calculation for ```n = 231525```. ``` 231525 = 3³5²7³ n' = (3*3²)*5²7³ + 3³*(2*5)*7³ + 3³*5²*(3*7²) = 231525 + 92610 + 99225 = 423360 ``` We may m...
["def chain_arith_deriv(n, k):\n if len(prime_factors(n)) < 2:\n return \"{} is a prime number\".format(n)\n chain = [n]\n while k > 1:\n k, n = k-1, arith_deriv(n)\n chain.append(n)\n return chain\n\n\ndef arith_deriv(n):\n factors = prime_factors(n)\n return sum(n * factors.coun...
{"fn_name": "chain_arith_deriv", "inputs": [[231525, 5], [997, 5]], "outputs": [[[231525, 423360, 1899072, 7879680, 51895296]], ["997 is a prime number"]]}
INTRODUCTORY
PYTHON3
CODEWARS
6,574
def chain_arith_deriv(n, k):
dcb11addeed9cbc400fdcb0f58cac234
UNKNOWN
We have an array of unique elements. A special kind of permutation is the one that has all of its elements in a different position than the original. Let's see how many of these permutations may be generated from an array of four elements. We put the original array with square brackets and the wanted permutations with...
["def all_permuted(n):\n a,b = 0, 1\n for i in range(1,n): a,b = b, (i+1)*(a+b)\n return a", "from itertools import islice\n\n\ndef A000166():\n # https://oeis.org/A000166\n a, b, n = 1, 0, 1\n while True:\n yield a\n a, b = b, n * (a + b)\n n += 1\n\n\nall_permuted = dict(enumera...
{"fn_name": "all_permuted", "inputs": [[1], [4], [30]], "outputs": [[0], [9], [97581073836835777732377428235481]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,587
def all_permuted(n):
ab3c6973f71d9603285266072d7b74c6
UNKNOWN
Take 2 strings `s1` and `s2` including only letters from `a`to `z`. Return a new **sorted** string, the longest possible, containing distinct letters, - each taken only once - coming from s1 or s2. # Examples: ``` a = "xyaabbbccccdefww" b = "xxxxyyyyabklmopq" longest(a, b) -> "abcdefklmopqwxy" a = "abcdefghijklmnopqr...
["def longest(a1, a2):\n return \"\".join(sorted(set(a1 + a2)))", "def longest(s1, s2):\n return ''.join(sorted((set(s1+s2))))", "def longest(s1, s2):\n # your code\n \n # Defining the Alphabet\n alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n \n # Concatenating the Two Given Strings\n s = s1 + s...
{"fn_name": "longest", "inputs": [["aretheyhere", "yestheyarehere"], ["loopingisfunbutdangerous", "lessdangerousthancoding"], ["inmanylanguages", "theresapairoffunctions"], ["lordsofthefallen", "gamekult"], ["codewars", "codewars"], ["agenerationmustconfrontthelooming", "codewarrs"]], "outputs": [["aehrsty"], ["abcdefg...
INTRODUCTORY
PYTHON3
CODEWARS
3,927
def longest(s1, s2):
3e23689785a333f0cd31bfe5fdc2043b
UNKNOWN
Four-digit palindromes start with `[1001,1111,1221,1331,1441,1551,1551,...]` and the number at position `2` is `1111`. You will be given two numbers `a` and `b`. Your task is to return the `a-digit` palindrome at position `b` if the palindromes were arranged in increasing order. Therefore, `palin(4,2) = 1111`, bec...
["def palin(length, pos):\n left = str(10**((length-1) // 2) + (pos - 1))\n right = left[::-1][length%2:]\n return int(left + right)", "def palin(a,b):\n s = str(10**((a-1)//2) + b-1)\n return int(s+s[::-1][a%2:])", "def palin(a, b):\n half = str(10**((a + 1) // 2 - 1) + b - 1)\n return int(half + ...
{"fn_name": "palin", "inputs": [[2, 2], [3, 10], [4, 5], [5, 19], [6, 3], [6, 20], [7, 3]], "outputs": [[22], [191], [1441], [11811], [102201], [119911], [1002001]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,123
def palin(a,b):
6d18e0e3a4972dc9d94e0b1e3f57924d
UNKNOWN
Your friend Cody has to sell a lot of jam, so he applied a good 25% discount to all his merchandise. Trouble is that he mixed all the prices (initial and discounted), so now he needs your cool coding skills to filter out only the discounted prices. For example, consider this inputs: ``` "15 20 60 75 80 100" "9 9 12 1...
["from bisect import bisect_left\nfrom collections import deque\n\n\ndef find_discounted(prices: str) -> str:\n all_prices = deque(list(map(int, prices.split())))\n discounts = []\n\n while all_prices:\n d = all_prices.popleft()\n discounts.append(d)\n del all_prices[bisect_left(all_prices...
{"fn_name": "find_discounted", "inputs": [["15 20 60 75 80 100"], ["9 9 12 12 12 15 16 20"], ["4131 5508 7344 7803 8397 8667 9792 10404 11196 11556 13872 14553 14742 14928 15408 17631 18496 19404 19656 19904 20544 20925 21816 23508 23598 23949 25872 26208 27900 29088 31344 31464 31932 34496 34944 37200 38784 41792 4195...
INTRODUCTORY
PYTHON3
CODEWARS
2,344
def find_discounted(prices):
f479c2c8947b87b01ca75d9001822331
UNKNOWN
Create a function that takes a number and finds the factors of it, listing them in **descending** order in an **array**. If the parameter is not an integer or less than 1, return `-1`. In C# return an empty array. For Example: `factors(54)` should return `[54, 27, 18, 9, 6, 3, 2, 1]`
["def factors(x):\n if not isinstance(x, int) or x < 1:\n return -1\n return [i for i in range(x, 0, -1) if x % i == 0]\n", "def factors(x):\n if not isinstance(x, int) or x < 1:\n return -1\n return sorted({j for i in range(1, int(x**0.5)+1) if x % i == 0 for j in [i, x//i]}, reverse=True)\n"...
{"fn_name": "factors", "inputs": [[-4], [0], [-12], ["a"], [4.5], ["hello world"], [54], [49], [1]], "outputs": [[-1], [-1], [-1], [-1], [-1], [-1], [[54, 27, 18, 9, 6, 3, 2, 1]], [[49, 7, 1]], [[1]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,314
def factors(x):
c821c80d6052741999c9d77340d2dbec
UNKNOWN
If this challenge is too easy for you, check out: https://www.codewars.com/kata/5cc89c182777b00001b3e6a2 ___ Upside-Down Pyramid Addition is the process of taking a list of numbers and consecutively adding them together until you reach one number. When given the numbers `2, 1, 1` the following process occurs: ``` ...
["def reverse(lst):\n ret = []\n while lst:\n ret.append(lst[-1])\n lst = [a-b for a,b in zip(lst, lst[1:])]\n return ret[::-1]", "from functools import reduce\ndef reverse(r):\n return reduce(lambda a,n: reduce(lambda b,s: b.append(s-b[-1]) or b,reversed(a),[n])[::-1],r,[])", "f=reverse=lambd...
{"fn_name": "reverse", "inputs": [[[5, 2, 1]], [[84, 42, 21, 10, 2]], [[83, 47, 28, 16, 7]], [[101, 57, 29, 13, 6]], [[66, 39, 25, 15, 7]], [[45, 25, 14, 8, 6]], [[60, 32, 16, 7, 4]], [[84, 44, 21, 8, 2]], [[51, 26, 13, 6, 2]], [[78, 42, 22, 11, 6]]], "outputs": [[[2, 1, 1]], [[4, 7, 3, 8, 2]], [[6, 4, 3, 9, 7]], [[1, ...
INTRODUCTORY
PYTHON3
CODEWARS
2,137
def reverse(right):
ad60f5a234b3d3bbab353ea1c53b128a
UNKNOWN
There is a house with 4 levels. In that house there is an elevator. You can program this elevator to go up or down, depending on what button the user touches inside the elevator. Valid levels must be only these numbers: `0,1,2,3` Valid buttons must be only these strings: `'0','1','2','3'` Possible return values are...
["levels = [0, 1, 2, 3]\nbuttons = ['0', '1', '2', '3']\ndef goto(level,button):\n if level not in levels or button not in buttons:\n return 0\n else:\n return int(button) - level", "def goto(l,b):\n if b in ('0','1','2','3') and l in (0,1,2,3):\n return int(b)-l\n return 0", "def goto(...
{"fn_name": "goto", "inputs": [[0, "0"], [0, "1"], [0, "2"], [0, "3"], [1, "0"], [1, "1"], [1, "2"], [1, "3"], [2, "0"], [2, "1"], [2, "2"], [2, "3"], [3, "0"], [3, "1"], [3, "2"], [3, "3"], [0, "4"], [0, null], [1, "4"], [1, null], [2, "4"], [2, null], [3, "4"], [3, null], [4, "2"], [null, "2"], [[], "2"], [3, {}], ["...
INTRODUCTORY
PYTHON3
CODEWARS
1,437
def goto(level,button):
7d6475e7f773f74e629bbf48f1f65782
UNKNOWN
A new school year is approaching, which also means students will be taking tests. The tests in this kata are to be graded in different ways. A certain number of points will be given for each correct answer and a certain number of points will be deducted for each incorrect answer. For ommitted answers, points will eit...
["def score_test(tests, right, omit, wrong):\n points = (right, omit, -wrong)\n return sum(points[test] for test in tests)\n", "#returns test score\ndef score_test(tests, right, omit, wrong):\n final = 0\n for scores in tests:\n if scores == 0:\n final = final + right\n elif scores ...
{"fn_name": "score_test", "inputs": [[[0, 0, 0, 0, 2, 1, 0], 2, 0, 1], [[0, 1, 0, 0, 2, 1, 0, 2, 2, 1], 3, -1, 2], [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 5, -1, 2], [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 2, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2, 0], 6, 0, 1.5], [[0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 0, 2, 1, 2, 0, 2, 1], 10, -...
INTRODUCTORY
PYTHON3
CODEWARS
1,742
def score_test(tests, right, omit, wrong):
000539c308ff9e62182a78d1d4709f46
UNKNOWN
## **Task** You are given a positive integer (`n`), and your task is to find the largest number **less than** `n`, which can be written in the form `a**b`, where `a` can be any non-negative integer and `b` is an integer greater than or equal to `2`. Try not to make the code time out :) The input range is from `1` to ...
["def largest_power(n):\n print(n)\n if n <= 4:\n if n == 1:\n return (0, -1)\n return (1, -1)\n \n #num_of_occurances\n freq = 0\n x = []\n largest = 0\n j = 0\n while 2**largest < n:\n largest += 1\n largest -= 1\n for i in range(2, largest + 1):\n ...
{"fn_name": "largest_power", "inputs": [[90], [6], [65], [2], [1], [81], [29], [4]], "outputs": [[[81, 2]], [[4, 1]], [[64, 3]], [[1, -1]], [[0, -1]], [[64, 3]], [[27, 1]], [[1, -1]]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,625
def largest_power(n):
abc3ea82d3bdc70d37f20802cd6de66e
UNKNOWN
Given a hash of letters and the number of times they occur, recreate all of the possible anagram combinations that could be created using all of the letters, sorted alphabetically. The inputs will never include numbers, spaces or any special characters, only lowercase letters a-z. E.g. get_words({2=>["a"], 1=>["b", "...
["from itertools import permutations\n\ndef get_words(letters):\n word = \"\".join(qty * char for qty in letters for chars in letters[qty] for char in chars)\n return sorted({\"\".join(permutation) for permutation in permutations(word)})", "from itertools import permutations\n\n\ndef get_words(hash_of_letters):\n...
{"fn_name": "get_words", "inputs": [[{"1": ["a", "b"]}], [{"1": ["a", "b", "c", "n", "o"]}], [{"1": ["a", "b", "c"]}], [{"2": ["a"], "1": ["b", "c"]}], [{"2": ["i", "a"], "1": ["z", "x"]}]], "outputs": [[["ab", "ba"]], [["abcno", "abcon", "abnco", "abnoc", "abocn", "abonc", "acbno", "acbon", "acnbo", "acnob", "acobn", ...
INTRODUCTORY
PYTHON3
CODEWARS
2,049
def get_words(hash_of_letters):
ac102acb8deebffebbf331b30014b726
UNKNOWN
Your job is to write a function that takes a string and a maximum number of characters per line and then inserts line breaks as necessary so that no line in the resulting string is longer than the specified limit. If possible, line breaks should not split words. However, if a single word is longer than the limit, it o...
["def word_wrap(s, limit):\n s, i, li = s.split(), 0, []\n while i < len(s):\n t = s[i]\n if len(t) <= limit:\n while i + 1 < len(s) and len(t) + len(s[i + 1]) + 1 <= limit:\n t += ' ' + s[i + 1] ; i += 1\n if len(t) < limit:\n if i + 1 < len(s) an...
{"fn_name": "word_wrap", "inputs": [["test", 7], ["hello world", 7], ["a lot of words for a single line", 10], ["this is a test", 4], ["a longword", 6], ["areallylongword", 6], ["aa", 3], ["aaa", 3], ["aaaa", 3], ["a a", 3], ["a aa", 3], ["a aaa", 3], ["a aaaa", 3], ["a aaaaa", 3], ["a a a", 3], ["a aa a", 3], ["a aaa ...
INTRODUCTORY
PYTHON3
CODEWARS
8,375
def word_wrap(text, limit):
5301339166e160a38e5e8aa995eca5ee
UNKNOWN
For encrypting strings this region of chars is given (in this order!): * all letters (ascending, first all UpperCase, then all LowerCase) * all digits (ascending) * the following chars: `.,:;-?! '()$%&"` These are 77 chars! (This region is zero-based.) Write two methods: ```python def encrypt(text) def decrypt(enc...
["region = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;-?! '()$%&\" + '\"'\n\ndef decrypt(encrypted_text):\n if not encrypted_text: return encrypted_text\n \n letters = list(encrypted_text)\n letters[0] = region[-(region.index(letters[0]) + 1)]\n for i in range(1, len(letters)):\n...
{"fn_name": "decrypt", "inputs": [["$-Wy,dM79H'i'o$n0C&I.ZTcMJw5vPlZc Hn!krhlaa:khV mkL;gvtP-S7Rt1Vp2RV:wV9VuhO Iz3dqb.U0w"], ["5MyQa9p0riYplZc"], ["5MyQa79H'ijQaw!Ns6jVtpmnlZ.V6p"], [""], [null]], "outputs": [["Do the kata \"Kobayashi-Maru-Test!\" Endless fun and excitement when finding a solution!"], ["This is a test...
INTRODUCTORY
PYTHON3
CODEWARS
11,632
def decrypt(encrypted_text):
2b659f3d44d532f8b0abc88d186421cf
UNKNOWN
Calculate the product of all elements in an array. ```if:csharp If the array is *null*, you should throw `ArgumentNullException` and if the array is empty, you should throw `InvalidOperationException`. As a challenge, try writing your method in just one line of code. It's possible to have only 36 characters within you...
["from functools import reduce\nfrom operator import mul\n\n\ndef product(numbers):\n return reduce(mul, numbers) if numbers else None", "def product(numbers):\n if not numbers:\n return None\n prod = 1\n\n for i in numbers:\n prod *= i\n\n return prod", "def product(numbers):\n if numbe...
{"fn_name": "product", "inputs": [[[5, 4, 1, 3, 9]], [[-2, 6, 7, 8]], [[10]], [[0, 2, 9, 7]], [null], [[]]], "outputs": [[540], [-672], [10], [0], [null], [null]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,421
def product(numbers):
66cfa1123bbad81034c742b4fc9c0818
UNKNOWN
_This kata is based on [Project Euler Problem 546](https://projecteuler.net/problem=546)_ # Objective Given the recursive sequence fk(n) = ∑ i = 0 n fk(floor(i / k)) where fk(0) = 1 Define a function `f` that takes arguments `k` and `n` and returns the nth term in the sequence fk ## Examples `f(2, 3)` = ...
["def f(k,n):\n a = []\n for i in range(0,n+1):\n if i < k:\n a += [i+1]\n else:\n a += [a[-1] + a[i//k]]\n return a[-1]\n \n", "def f(k, n):\n memo = [1]\n for i in range(1,n+1): memo.append(memo[-1]+memo[i//k])\n return memo[-1]", "def f(k, n):\n if n ==...
{"fn_name": "f", "inputs": [[2, 3], [2, 200], [2, 1000], [7, 500], [100, 0], [3, 50000], [97, 100000], [100, 500000]], "outputs": [[6], [7389572], [264830889564], [74845], [1], [80887845303700596855], [209497156], [21469002551]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,978
def f(k, n):
68db212322f79a4b1821772515237958
UNKNOWN
You were given a string of integer temperature values. Create a function `close_to_zero(t)` and return the closest value to 0 or `0` if the string is empty. If two numbers are equally close to zero, return the positive integer.
["def close_to_zero(t):\n if len(t)==0:\n return (0)\n x=t.split(\" \")\n l=[]\n poz=[]\n neg=[]\n for i in x:\n l.append(int(i))\n for i in l:\n if i == 0:\n return (0)\n if i>0:\n poz.append(i)\n if i<0:\n neg.append(i)\n ...
{"fn_name": "close_to_zero", "inputs": [[""], ["-1 50 -4 20 22 -7 0 10 -8"], ["28 35 -21 17 38 -17"]], "outputs": [[0], [0], [17]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,266
def close_to_zero(t):
ab56ce9d9fe4ba81b01ecaed8b857fde
UNKNOWN
Simple interest on a loan is calculated by simply taking the initial amount (the principal, p) and multiplying it by a rate of interest (r) and the number of time periods (n). Compound interest is calculated by adding the interest after each time period to the amount owed, then calculating the next interest payment b...
["def interest(principal, interest, periods):\n return [round(principal * (1 + interest * periods)),\n round(principal * (1 + interest) ** periods)]", "def interest(p, r, n):\n return [round(p * i) for i in ((1 + (r * n)), (1 + r)**n)]", "def interest(money, rate, periods):\n simple = money * (1 + r...
{"fn_name": "interest", "inputs": [[100, 0.1, 1], [100, 0.1, 2], [100, 0.1, 10], [100, 0, 10], [0, 0.1, 10], [100, 0.1, 0]], "outputs": [[[110, 110]], [[120, 121]], [[200, 259]], [[100, 100]], [[0, 0]], [[100, 100]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,128
def interest(p,r,n):
c719ec68a56e6e9a4a2dd0443a7bb81a
UNKNOWN
```if-not:sql Implement a function that receives two IPv4 addresses, and returns the number of addresses between them (including the first one, excluding the last one). ``` ```if:sql Given a database of first and last IPv4 addresses, calculate the number of addresses between them (including the first one, excluding th...
["from ipaddress import ip_address\n\ndef ips_between(start, end):\n return int(ip_address(end)) - int(ip_address(start))", "def ips_between(start, end):\n a = sum([int(e)*256**(3-i) for i, e in enumerate(start.split('.'))])\n b = sum([int(e)*256**(3-i) for i, e in enumerate(end.split('.'))])\n return abs(a...
{"fn_name": "ips_between", "inputs": [["150.0.0.0", "150.0.0.1"], ["10.0.0.0", "10.0.0.50"], ["20.0.0.10", "20.0.1.0"], ["10.11.12.13", "10.11.13.0"], ["160.0.0.0", "160.0.1.0"], ["170.0.0.0", "170.1.0.0"], ["50.0.0.0", "50.1.1.1"], ["180.0.0.0", "181.0.0.0"], ["1.2.3.4", "5.6.7.8"]], "outputs": [[1], [50], [246], [243...
INTRODUCTORY
PYTHON3
CODEWARS
1,620
def ips_between(start, end):
4f3c7da1593789fc18864ea47e2c7866
UNKNOWN
Your goal is to create a function to format a number given a template; if the number is not present, use the digits `1234567890` to fill in the spaces. A few rules: * the template might consist of other numbers, special characters or the like: you need to replace only alphabetical characters (both lower- and uppercas...
["from itertools import cycle\n\ndef numeric_formatter(template, data='1234567890'):\n data = cycle(data)\n return ''.join(next(data) if c.isalpha() else c for c in template)", "from itertools import cycle\nimport re\n\ndef numeric_formatter(template, source=\"1234567890\"):\n gen = cycle(source)\n return r...
{"fn_name": "numeric_formatter", "inputs": [["xxx xxxxx xx", "5465253289"], ["xxx xxxxx xx"], ["+555 aaaa bbbb", "18031978"], ["+555 aaaa bbbb"], ["xxxx yyyy zzzz"]], "outputs": [["546 52532 89"], ["123 45678 90"], ["+555 1803 1978"], ["+555 1234 5678"], ["1234 5678 9012"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,461
def numeric_formatter(template, data='1234567890'):
bef413ba6e7e4d2ee78e7022732d64ab
UNKNOWN
## Story Your company migrated the last 20 years of it's *very important data* to a new platform, in multiple phases. However, something went wrong: some of the essential time-stamps were messed up! It looks like that some servers were set to use the `dd/mm/yyyy` date format, while others were using the `mm/dd/yyyy` f...
["def candidates(ymd):\n y, m, d = ymd.split('-')\n return {ymd, f'{y}-{d}-{m}'}\n\ndef check_dates(records):\n result = [0, 0, 0]\n for start, end in records:\n xs = [(dt1, dt2) for dt1 in candidates(start) for dt2 in candidates(end)\n if dt1 <= dt2 and dt1[5:7] <= '12' >= dt2[5:7]]\n ...
{"fn_name": "check_dates", "inputs": [[[]]], "outputs": [[[0, 0, 0]]]}
INTRODUCTORY
PYTHON3
CODEWARS
11,101
def check_dates(records):
906f91378405810598d8ddca2d2f9455
UNKNOWN
You're on your way to the market when you hear beautiful music coming from a nearby street performer. The notes come together like you wouln't believe as the musician puts together patterns of tunes. As you wonder what kind of algorithm you could use to shift octaves by 8 pitches or something silly like that, it dawns ...
["def is_lock_ness_monster(s):\n return any(i in s for i in ('tree fiddy', 'three fifty', '3.50'))", "import re\n\ndef is_lock_ness_monster(s):\n return bool(re.search(r\"3\\.50|tree fiddy|three fifty\", s))", "def is_lock_ness_monster(s):\n return any(phrase in s for phrase in [\"tree fiddy\", \"three fifty\"...
{"fn_name": "is_lock_ness_monster", "inputs": [["Your girlscout cookies are ready to ship. Your total comes to tree fiddy"], ["Howdy Pardner. Name's Pete Lexington. I reckon you're the kinda stiff who carries about tree fiddy?"], ["I'm from Scottland. I moved here to be with my family sir. Please, $3.50 would go a long...
INTRODUCTORY
PYTHON3
CODEWARS
1,307
def is_lock_ness_monster(string):
921233eaa245460869f13a46bb81ed0e
UNKNOWN
The prime number sequence starts with: `2,3,5,7,11,13,17,19...`. Notice that `2` is in position `one`. `3` occupies position `two`, which is a prime-numbered position. Similarly, `5`, `11` and `17` also occupy prime-numbered positions. We shall call primes such as `3,5,11,17` dominant primes because they occupy prime...
["n = 500000\nsieve, PRIMES = [0]*(n//2+1), [0,2]\nfor i in range(3, n+1, 2):\n if not sieve[i//2]:\n PRIMES.append(i)\n for j in range(i**2, n+1, i*2): sieve[j//2] = 1\n\nDOMINANTS = []\nfor p in PRIMES:\n if p >= len(PRIMES): break\n DOMINANTS.append(PRIMES[p])\n\ndef solve(a,b):\n return su...
{"fn_name": "solve", "inputs": [[0, 10], [2, 200], [200, 2000], [500, 10000], [1000, 100000], [2000, 200000], [3000, 400000], [4000, 500000]], "outputs": [[8], [1080], [48132], [847039], [52114889], [183035206], [650120994], [972664400]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,567
def solve(a,b):
c028e82040aadd96d90070d4f822a5e5
UNKNOWN
###BACKGROUND: Jacob recently decided to get healthy and lose some weight. He did a lot of reading and research and after focusing on steady exercise and a healthy diet for several months, was able to shed over 50 pounds! Now he wants to share his success, and has decided to tell his friends and family how much weight ...
["def lose_weight(gender, weight, duration):\n if not gender in ['M', 'F']: return 'Invalid gender'\n if weight <= 0: return 'Invalid weight'\n if duration <= 0: return 'Invalid duration'\n \n nl = 0.985 if gender == 'M' else 0.988\n \n for i in range(duration): weight *= nl\n return round(weigh...
{"fn_name": "lose_weight", "inputs": [["K", 200, 10], ["M", 0, 10], ["M", -5, 10], ["F", 160, 0], ["F", 160, -10], [",", 0, 1100], ["??", -10, -10], ["llama", 1, -10], ["F", -461.9, 0.0], ["M", 250, 5], ["F", 190, 8], ["M", 405, 12], ["F", 130, 7]], "outputs": [["Invalid gender"], ["Invalid weight"], ["Invalid weight"]...
INTRODUCTORY
PYTHON3
CODEWARS
3,533
def lose_weight(gender, weight, duration):
17a97f80cf6bf7ac33ebb95a92d99ea4
UNKNOWN
Unscramble the eggs. The string given to your function has had an "egg" inserted directly after each consonant. You need to return the string before it became eggcoded. ## Example Kata is supposed to be for beginners to practice regular expressions, so commenting would be appreciated.
["def unscramble_eggs(word):\n return word.replace('egg','')", "from re import sub\ndef unscramble_eggs(word):\n # Geggoodegg Legguceggkegg!\n return sub(r'([^aieou])egg',r'\\1', word)", "unscramble_eggs = lambda x:''.join(x.split('egg'))\n", "import re\ndef unscramble_eggs(word):\n return re.sub('([^aeiouA...
{"fn_name": "unscramble_eggs", "inputs": [["ceggodegge heggeregge"], ["FeggUNegg KeggATeggA"], ["egegggegg"], ["Heggeleggleggo weggoreggleggdegg"], ["seggceggreggameggbeggleggedegg egegggeggsegg"], ["egegggeggyegg beggreggeadegg"], ["veggegeggyeggmeggitegge onegg teggoaseggtegg"]], "outputs": [["code here"], ["FUN KATA...
INTRODUCTORY
PYTHON3
CODEWARS
979
def unscramble_eggs(word):
92a45160dadffc9274e293e4fec01892
UNKNOWN
```if-not:swift Create a method that takes an array/list as an input, and outputs the index at which the sole odd number is located. This method should work with arrays with negative numbers. If there are no odd numbers in the array, then the method should output `-1`. ``` ```if:swift reate a function `oddOne` that ta...
["def odd_one(arr):\n for i in range(len(arr)):\n if arr[i] % 2 != 0:\n return i\n return -1\n", "def odd_one(arr):\n return next((i for i,v in enumerate(arr) if v&1), -1)", "def odd_one(arr):\n for i in arr:\n if i%2: return arr.index(i)\n return -1", "def odd_one(arr):\n ad = ...
{"fn_name": "odd_one", "inputs": [[[2, 4, 6, 7, 10]], [[2, 16, 98, 10, 13, 78]], [[4, -8, 98, -12, -7, 90, 100]], [[2, 4, 6, 8]]], "outputs": [[3], [4], [4], [-1]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,251
def odd_one(arr):
6a6fc2b6b8831b243a53f75a4b96a27c
UNKNOWN
# Task There are `n` bears in the orchard and they picked a lot of apples. They distribute apples like this: ``` The first bear divided the apple into n piles, each with the same number. leaving an apple at last, and the apple was thrown away. Then he took 1 pile and left the n-1 pile. The second bear divided the ...
["how_many_apples=lambda n:n**n-(n-1)+[0,4][n==2]", "def how_many_apples(n):\n return n ** n - n + 1 if n > 2 else 7", "def how_many_apples(n):\n if n == 2:\n return 7\n else:\n return n**n-(n-1)", "def how_many_apples(n):\n if n==2:\n return 7\n return (n**(n-1))*n-n+1", "def how_ma...
{"fn_name": "how_many_apples", "inputs": [[2], [5]], "outputs": [[7], [3121]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,057
def how_many_apples(n):
bd747d33b971aa7dfbbf15127df1cca8
UNKNOWN
# The President's phone is broken He is not very happy. The only letters still working are uppercase ```E```, ```F```, ```I```, ```R```, ```U```, ```Y```. An angry tweet is sent to the department responsible for presidential phone maintenance. # Kata Task Decipher the tweet by looking for words with known meaning...
["import re\nfrom itertools import groupby\n\nCONFIG = {'FURY': \" really\",\n 'FIRE': \" and you\",\n 'FAKE': \"Fake tweet.\",\n 'FURY_f': \"I am{} furious.\",\n 'FIRE_f': \"You{} are fired!\"}\n\ndef fire_and_fury(tweet):\n if re.findall(r'[^FURYIE]', tweet): return CONFIG...
{"fn_name": "fire_and_fury", "inputs": [["FURYYYFIREYYFIRE"], ["FIREYYFURYYFURYYFURRYFIRE"], ["FYRYFIRUFIRUFURE"], [""], ["FURYFURYFURY"], ["FURYFURYFURYFURY"], ["FURYFURYFURYFURYFURY"], ["FIRE"], ["FIREFIRE"], ["FIREFIREFIRE"], ["FIREFIREFIREFIRE"], ["FIREFIREFIREFIREFIRE"]], "outputs": [["I am furious. You and you ar...
INTRODUCTORY
PYTHON3
CODEWARS
5,397
def fire_and_fury(tweet):
f36feb6d4d70981276bc071b5f802433
UNKNOWN
Your back at your newly acquired decrypting job for the secret organization when a new assignment comes in. Apparently the enemy has been communicating using a device they call "The Mirror". It is a rudimentary device with encrypts the message by switching its letter with its mirror opposite (A => Z), (B => Y), (C ...
["def mirror(code, chars=\"abcdefghijklmnopqrstuvwxyz\"):\n return code.lower().translate(str.maketrans(chars, chars[::-1]))", "from string import ascii_lowercase\n\ndef mirror(code, letters=ascii_lowercase):\n return code.lower().translate(str.maketrans(letters, letters[::-1]))", "from string import ascii_lowerc...
{"fn_name": "mirror", "inputs": [["Welcome home"], ["hello"], ["goodbye"], ["ngmlsoor"], ["gsrh rh z hvxivg"], ["Welcome home", "w"], ["hello", "abcdefgh"], ["goodbye", ""], ["CodeWars", "+-*/="], ["this is a secret", " *"]], "outputs": [["dvoxlnv slnv"], ["svool"], ["tllwybv"], ["mtnohlli"], ["this is a secret"], ["we...
INTRODUCTORY
PYTHON3
CODEWARS
1,684
def mirror(code, chars="abcdefghijklmnopqrstuvwxyz"):
393e8fa5f9b52e69028335f546a4d6a5
UNKNOWN
# Task John is playing a RPG game. The initial attack value of the player is `x`. The player will face a crowd of monsters. Each monster has different defense value. If the monster's defense value is less than or equal to the player's attack value, the player can easily defeat the monster, and the player's attack val...
["from functools import reduce\nfrom fractions import gcd\n\ndef final_attack_value(x, monster_list):\n return reduce(lambda a, b: a + (b if b <= a else gcd(a, b)), monster_list, x)", "from fractions import gcd\ndef final_attack_value(x,monster_list):\n for i in monster_list:\n x += gcd(i,x) if i > x else ...
{"fn_name": "final_attack_value", "inputs": [[50, [50, 105, 200]], [20, [30, 20, 15, 40, 100]]], "outputs": [[110], [205]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,886
def final_attack_value(x,monster_list):