problem_id
int64
80
5k
question
stringlengths
170
10.1k
solutions
stringlengths
0
675k
input_output
stringlengths
0
33.5k
difficulty
stringclasses
3 values
url
stringlengths
38
68
starter_code
stringlengths
0
315
3,633
OK, my warriors! Now that you beat the big BOSS, you can unlock three new skills. (Does it sound like we're playing an RPG? ;-) ## The Arrow Function (JS only) The first skill is the arrow function. Let's look at some examples to see how it works: ```python #ignore this part, it is just for JS ``` As you can see, it...
["def shuffle_it(A,*T):\n for x,y in T:\n A[x],A[y]=A[y],A[x]\n return A\n", "def shuffle_it(arr, *ind):\n for a, b in ind:\n [arr[b],arr[a]] = [arr[a],arr[b]]\n return arr", "def shuffle_it(a, *args):\n for x, y in args:\n a[x], a[y] = a[y], a[x]\n return a", "def shuffle_it(a,*b...
{"fn_name": "shuffle_it", "inputs": [[[1, 2, 3, 4, 5], [1, 2]], [[1, 2, 3, 4, 5], [1, 2], [3, 4]], [[1, 2, 3, 4, 5], [1, 2], [3, 4], [2, 3]], [[1, 2, 3, 4, 5], [4, 4]], [[1, 2, 3, 4, 5]]], "outputs": [[[1, 3, 2, 4, 5]], [[1, 3, 2, 5, 4]], [[1, 3, 5, 2, 4]], [[1, 2, 3, 4, 5]], [[1, 2, 3, 4, 5]]]}
introductory
https://www.codewars.com/kata/572ab0cfa3af384df7000ff8
def shuffle_it(A,*T):
3,636
Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468. Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420. We shall call a positive integer that is neither increasing nor decreasi...
["from operator import lt, gt\n\nmemo = {}\nis_bouncy = lambda s: memo[s] if s in memo else memo.setdefault(s, any(map(lt, s[:-1], s[1:])) and any(map(gt, s[:-1], s[1:])))\n\ndef bouncy_ratio(percent):\n if not 0 < percent < 1: raise Exception(\"Wrong percentage: {}\".format(percent))\n x, y = 100, 0\n while y...
{"fn_name": "bouncy_ratio", "inputs": [[0.1], [0.15], [0.5], [0.75], [0.9]], "outputs": [[132], [160], [538], [3088], [21780]]}
introductory
https://www.codewars.com/kata/562b099becfe844f3800000a
def bouncy_ratio(percent):
3,637
# Definition (Primorial Of a Number) *Is similar to factorial of a number*, **_In primorial_**, not all the natural numbers get multiplied, **_only prime numbers are multiplied to calculate the primorial of a number_**. It's denoted with **_P_****_#_** and it is the product of the first n prime numbers. ___ # Task ...
["def num_primorial(n):\n primorial, x, n = 2, 3, n-1\n while n:\n if all(x % d for d in range(3, int(x ** .5) + 1, 2)):\n primorial *= x\n n -= 1\n x += 2\n return primorial", "def num_primorial(n):\n primNums = [\n 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ...
{"fn_name": "num_primorial", "inputs": [[3], [4], [5], [8], [9]], "outputs": [[30], [210], [2310], [9699690], [223092870]]}
introductory
https://www.codewars.com/kata/5a99a03e4a6b34bb3c000124
def num_primorial(n):
3,640
Imagine a funnel filled with letters. The bottom letter drops out of the funnel and onto a conveyor belt: ``` \b,c/ --> \b,c/ \a/ --> \ / a ------- ------- ``` If there are two letters above a gap, the smaller letter falls into the gap. ``` \b,c/ --> \ c/ \ / --> \b/ ...
["def funnel_out(funnel):\n r=\"\"\n h=len(funnel)\n while funnel[h-1][0]!=\"~\":\n r+=funnel[h-1][0]\n funnel[h-1][0]=\"~\"\n i=h-1\n j=0\n while i>0:\n if funnel[i-1][j] < funnel[i-1][j+1]:\n funnel[i][j]=funnel[i-1][j]\n funnel[i-1][j]=\"~\"\n else:\n...
{"fn_name": "funnel_out", "inputs": [[[["q"]]], [[["b", "c"], ["a"]]], [[["d", "a", "c"], ["b", "e"], ["f"]]], [[["a", "e", "c", "f"], ["d", "i", "h"], ["j", "g"], ["b"]]]], "outputs": [["q"], ["abc"], ["fbadec"], ["bghcfiejda"]]}
introductory
https://www.codewars.com/kata/5a4b612ee626c5d116000084
def funnel_out(funnel):
3,641
In genetic the reverse complement of a sequence is formed by **reversing** the sequence and then taking the complement of each symbol. The four nucleotides in DNA is Adenine (A), Cytosine (C), Guanine (G) and Thymine (Thymine). - A is the complement of T - C is the complement of G. This is a bi-directional relatio...
["get = dict(zip(\"ATCG\", \"TAGC\")).__getitem__\n\ndef reverse_complement(dna):\n try:\n return ''.join(map(get, reversed(dna)))\n except KeyError:\n return \"Invalid sequence\"", "def reverse_complement(dna):\n table = str.maketrans(\"ACGT\", \"TGCA\")\n return \"Invalid sequence\" if set(d...
{"fn_name": "reverse_complement", "inputs": [["TTCCGGAA"], ["GACTGACTGTA"], [""], ["XYZ"]], "outputs": [["TTCCGGAA"], ["TACAGTCAGTC"], [""], ["Invalid sequence"]]}
introductory
https://www.codewars.com/kata/574a7d0dca4a8a0fbe000100
def reverse_complement(dna):
3,653
# Task Write a function that accepts `msg` string and returns local tops of string from the highest to the lowest. The string's tops are from displaying the string in the below way: ``` 7891012 TUWvXY 6 3 ABCDE S ...
["def tops(msg):\n n = len(msg)\n res,i,j,k = \"\",2,2,7\n while i < n:\n res = msg[i:i+j] + res\n i,j,k=i+k,j+1,k+4\n return res", "def transform(i): return (3*i-4+2*(i-1)*(i-2), i)\n\ndef tops(msg):\n iMax = int((3+(9+8*len(msg))**.5) / 4)\n return ''.join( msg[i:i+c] for i,c in map(tr...
{"fn_name": "tops", "inputs": [[""], ["abcde"], ["123456789abcdefghijklmnopqrstuwyxvzABCDEFGHIJKLMNOPQRSTU"], ["123456789abcdefghijklmnopqrstuwyxvzABCDEFGHIJKLMNOPQRSTUWvXYZ123456789012345678910123"]], "outputs": [[""], ["cd"], ["TUABCDElmnoabc34"], ["7891012TUWvXYABCDElmnoabc34"]]}
introductory
https://www.codewars.com/kata/5aa3e2b0373c2e4b420009af
def tops(msg):
3,655
## Task Given `n` representing the number of floors build a beautiful multi-million dollar mansions like the ones in the example below: ``` /\ / \ / \ /______\ number of floors 3 | | | | |______| /\ / \ /____\ | | 2 floors |____| /\ /__\ 1 floor...
["def my_crib(n):\n roof = \"\\n\".join(\"%s/%s\\\\%s\"%(\" \"*(n-i),\" \"*i*2,\" \"*(n-i)) for i in range(n))\n ceiling = \"\\n/%s\\\\\\n\"%(\"_\"*(n*2))\n walls = (\"|%s|\\n\"%(\" \"*(n*2)))*(n-1)\n floor = \"|%s|\"%(\"_\"*(n*2))\n \n return roof + ceiling + walls + floor", "def my_crib(n):\n roo...
{"fn_name": "my_crib", "inputs": [[1], [2], [3]], "outputs": [[" /\\ \n/__\\\n|__|"], [" /\\ \n / \\ \n/____\\\n| |\n|____|"], [" /\\ \n / \\ \n / \\ \n/______\\\n| |\n| |\n|______|"]]}
introductory
https://www.codewars.com/kata/5834a44e44ff289b5a000075
def my_crib(n):
3,656
Given a rational number n ``` n >= 0, with denominator strictly positive``` - as a string (example: "2/3" in Ruby, Python, Clojure, JS, CS, Go) - or as two strings (example: "2" "3" in Haskell, Java, CSharp, C++, Swift) - or as a rational or decimal number (example: 3/4, 0.67 in R) - or two integers (Fortran) d...
["from math import ceil\nfrom fractions import Fraction as F\ndef decompose(n):\n f = F(n)\n ff = int(f)\n result = [str(ff)] if ff else []\n f -= ff\n while f>0:\n x = F(1,int(ceil(f**-1)))\n f -= x\n result.append(str(x))\n return result", "from fractions import Fraction\nfrom m...
{"fn_name": "decompose", "inputs": [["0"], ["3/4"], ["12/4"], ["4/5"], ["0.66"], ["22/23"], ["1001/3456"], ["16/17"], ["30/45"], ["1.25"], ["75/3"], ["2/8"], ["0.9"]], "outputs": [[[]], [["1/2", "1/4"]], [["3"]], [["1/2", "1/4", "1/20"]], [["1/2", "1/7", "1/59", "1/5163", "1/53307975"]], [["1/2", "1/3", "1/9", "1/83", ...
introductory
https://www.codewars.com/kata/54f8693ea58bce689100065f
def decompose(n):
3,667
While most devs know about [big/little-endianness](https://en.wikipedia.org/wiki/Endianness), only a selected few know the secret of real hard core coolness with mid-endians. Your task is to take a number and return it in its mid-endian format, putting the most significant couple of bytes in the middle and all the oth...
["import re\ndef mid_endian(n):\n h= hex(n)[2:].upper()\n r= re.findall('..','0'*(len(h)%2)+h)\n return \"\".join(r[1::2][::-1]+r[0::2])", "def mid_endian(n):\n bs = n.to_bytes((n.bit_length() + 7) // 8 or 1, byteorder='little')\n return (bs[len(bs)%2::2] + bs[::-2]).hex().upper()", "from collections imp...
{"fn_name": "mid_endian", "inputs": [[9999999], [0], [658188], [168496141], [43135012110]], "outputs": [["96987F"], ["00"], ["0B0A0C"], ["0D0B0A0C"], ["0D0B0A0C0E"]]}
introductory
https://www.codewars.com/kata/5b3e3ca99c9a75a62400016d
def mid_endian(n):
3,672
Given a string of integers, return the number of odd-numbered substrings that can be formed. For example, in the case of `"1341"`, they are `1, 1, 3, 13, 41, 341, 1341`, a total of `7` numbers. `solve("1341") = 7`. See test cases for more examples. Good luck! If you like substring Katas, please try [Longest vo...
["def solve(s):\n return sum(i+1 for i,d in enumerate(list(s)) if d in '13579')", "def solve(s):\n return sum( int(c)%2 for i in range(len(s)) for c in s[i:] )", "import itertools\n\n# Walk through s from left to right. If the current digit is odd,\n# It can create odd substrings with every previous digit.\n# The...
{"fn_name": "solve", "inputs": [["1341"], ["1357"], ["13471"], ["134721"], ["1347231"], ["13472315"]], "outputs": [[7], [10], [12], [13], [20], [28]]}
introductory
https://www.codewars.com/kata/59da47fa27ee00a8b90000b4
def solve(s):
3,680
In mathematics, the factorial of integer 'n' is written as 'n!'. It is equal to the product of n and every integer preceding it. For example: **5! = 1 x 2 x 3 x 4 x 5 = 120** Your mission is simple: write a function that takes an integer 'n' and returns 'n!'. You are guaranteed an integer argument. For any values out...
["import math\n\ndef factorial(n):\n if n < 0:\n return None\n return math.factorial(n)", "def factorial(n):\n if n <= 1:\n if n < 0:\n return None\n else:\n return 1\n return n * factorial(n-1)", "# This function should return n!\nimport math\n\ndef factorial(n):\...
{"fn_name": "factorial", "inputs": [[-1]], "outputs": [[null]]}
introductory
https://www.codewars.com/kata/528e95af53dcdb40b5000171
def factorial(n):
3,694
Much cooler than your run-of-the-mill Fibonacci numbers, the Triple Shiftian are so defined: `T[n] = 4 * T[n-1] - 5 * T[n-2] + 3 * T[n-3]`. You are asked to create a function which accept a base with the first 3 numbers and then returns the nth element. ```python triple_shiftian([1,1,1],25) == 1219856746 triple_shifti...
["def triple_shiftian(T,n):\n for i in range(3,n+1):\n T.append(4 * T[i-1] - 5 * T[i-2] + 3 * T[i-3])\n return T[n] ", "def triple_shiftian(base, n):\n a, b, c = base\n for _ in range(n):\n a, b, c = b, c, 4 * c - 5 * b + 3 * a\n return a", "def triple_shiftian(base,n):\n #your code her...
{"fn_name": "triple_shiftian", "inputs": [[[1, 1, 1], 25], [[1, 2, 3], 25], [[3, 2, 1], 25], [[6, 7, 2], 25], [[1, 1, 1], 35], [[1, 2, 3], 35], [[3, 2, 1], 35], [[6, 7, 2], 35], [[3, 2, 1], 0], [[6, 7, 2], 2]], "outputs": [[1219856746], [2052198929], [2827228055], [-2575238999], [10127083068293], [17037073417493], [234...
introductory
https://www.codewars.com/kata/56b7526481290c2ff1000c75
def triple_shiftian(base,n):
3,696
Make a function **"add"** that will be able to sum elements of **list** continuously and return a new list of sums. For example: ``` add [1,2,3,4,5] == [1, 3, 6, 10, 15], because it's calculated like this : [1, 1 + 2, 1 + 2 + 3, 1 + 2 + 3 + 4, 1 + 2 + 3 + 4 + 5] ``` If you want to learn more see https://en.wikiped...
["from itertools import accumulate\ndef add(l):\n return list(accumulate(l)) if isinstance(l, list) and all(isinstance(x, int) for x in l) \\\n else 'Invalid input'", "from itertools import accumulate\n\ndef add(lst):\n return list(accumulate(lst))", "from itertools import accumulate\n\ndef add(a):\n re...
{"fn_name": "add", "inputs": [[[5, 10, 15, 20, 25, 30, 35, 40]], [[6, 12, 18, 24, 30, 36, 42]], [[7, 14, 21, 28, 35, 42, 49, 56]], [[8, 16, 24, 32, 40, 48, 56, 64]], [[9, 18, 27, 36, 45, 54]]], "outputs": [[[5, 15, 30, 50, 75, 105, 140, 180]], [[6, 18, 36, 60, 90, 126, 168]], [[7, 21, 42, 70, 105, 147, 196, 252]], [[8,...
introductory
https://www.codewars.com/kata/59b44d00bf10a439dd00006f
def add(l):
3,704
# Solve For X You will be given an equation as a string and you will need to [solve for X](https://www.mathplacementreview.com/algebra/basic-algebra.php#solve-for-a-variable) and return x's value. For example: ```python solve_for_x('x - 5 = 20') # should return 25 solve_for_x('20 = 5 * x - 5') # should return 5 solv...
["from itertools import count\n\ndef solve_for_x(equation):\n return next( x for n in count(0) for x in [n, -n] if eval(equation.replace(\"x\", str(x)).replace(\"=\", \"==\")) )", "import re\ndef solve_for_x(equation):\n left,right = equation.split(\"=\")\n answer = False\n TrialAndErrorRipMs = -1000\n w...
{"fn_name": "solve_for_x", "inputs": [["x - 5 = 20"], ["5 * x + 5 = 30"], ["20 = 5 * x - 5"], ["24 = 4 + 5 * x"], ["x = 5"], ["x * 100 = 700"], ["2 * x + 5 = 105"], ["2 * x = 198"], ["x - 100 + 2 - 50 = 52"], ["x / 3 = 33"], ["x + 80 = 20"], ["x + 20 = -60"], ["5 * x + 20 - x = 60"], ["x + x + 6 = 10"], ["5 * x = x + 8...
introductory
https://www.codewars.com/kata/59c2e2a36bddd2707e000079
def solve_for_x(equation):
3,706
Assume that you started to store items in progressively expanding square location, like this for the first 9 numbers: ``` 05 04 03 06 01 02 07 08 09 ``` And like this for the expanding to include up to the first 25 numbers: ``` 17 16 15 14 13 18 05 04 03 12 19 06 01 02 11 20 07 08 09 10 21 22 23 24 25 ``` You might...
["from math import ceil, sqrt\n\ndef layers(n):\n return ceil(sqrt(n)) // 2 + 1", "def layers(n):\n return (1 + (n-1)**.5) // 2 + 1", "def layers(n):\n i = 1\n r = 1\n while i*i < n: \n i += 2\n r += 1\n \n return r", "import math\ndef layers(n):\n return math.ceil( (n**0.5 + 1...
{"fn_name": "layers", "inputs": [[1], [5], [25], [30], [50]], "outputs": [[1], [2], [3], [4], [5]]}
introductory
https://www.codewars.com/kata/5a254114e1ce0ecf6a000168
def layers(n):
3,710
This is the performance edition of [this kata](https://www.codewars.com/kata/ulam-sequences). If you didn't do it yet, you should begin there. --- The Ulam sequence U is defined by `u0=u`, `u1=v`, with the general term `u_n` for `n>2` given by the least integer expressible uniquely as the sum of two distinct earlier ...
["def ulam_sequence(u, v, n):\n lst, seq, ex, q = [], 1, 1, 1 << v | 1 << u # Put u and v into queue\n for _ in range(n): # Repeat n times\n w = q & -q # Take the smallest candidate\n l = w.bit_length() - 1 # and its value\n ...
{"fn_name": "ulam_sequence", "inputs": [[1, 2, 5], [3, 4, 5], [5, 6, 8]], "outputs": [[[1, 2, 3, 4, 6]], [[3, 4, 7, 10, 11]], [[5, 6, 11, 16, 17, 21, 23, 26]]]}
introductory
https://www.codewars.com/kata/5ac94db76bde60383d000038
def ulam_sequence(u0, u1, n):
3,714
In this kata, you need to make a (simplified) LZ78 encoder and decoder. [LZ78](https://en.wikipedia.org/wiki/LZ77_and_LZ78#LZ78) is a dictionary-based compression method created in 1978. You will find a detailed explanation about how it works below. The input parameter will always be a non-empty string of upper case ...
["import re\n\ndef encoder(s):\n d, out, it = {},[], iter(s)\n for c in it:\n i,k = 0,c\n while k in d: \n i,c = d[k], next(it,'')\n if not c: break\n k += c\n d[k] = len(d)+1\n out.append(f'{i}{c}')\n return ''.join(out)\n\n\ndef decoder(s):\n d ...
{"fn_name": "encoder", "inputs": [["ABAABABAABAB"], ["ABAABABAABABAA"], ["ABBCBCABABCAABCAABBCAA"], ["AAAAAAAAAAAAAAA"], ["ABCABCABCABCABCABC"], ["ABCDDEFGABCDEDBBDEAAEDAEDCDABC"]], "outputs": [["0A0B1A2A4A4B"], ["0A0B1A2A4A4B3"], ["0A0B2C3A2A4A6B6"], ["0A1A2A3A4A"], ["0A0B0C1B3A2C4C7A6"], ["0A0B0C0D4E0F0G1B3D0E4B2D10A...
introductory
https://www.codewars.com/kata/5db42a943c3c65001dcedb1a
def encoder(data):
3,717
Given a list of white pawns on a chessboard (any number of them, meaning from 0 to 64 and with the possibility to be positioned everywhere), determine how many of them have their backs covered by another. Pawns attacking upwards since we have only white ones. Please remember that a pawn attack(and defend as well) onl...
["def covered_pawns(pawns):\n pawns = set(pawns)\n return len({p for p in pawns for x,y in [map(ord, p)] if {chr(x-1)+chr(y-1), chr(x+1)+chr(y-1)} & pawns})", "def covered_pawns(pawns):\n count = 0\n for i in range(len(pawns)):\n x, y = list(pawns[i])\n if \"\".join([chr(ord(x) - 1), str(int(y...
{"fn_name": "covered_pawns", "inputs": [[["f7", "b1", "h1", "c7", "h7"]], [["e5", "b2", "b4", "g4", "a1", "a5"]], [["a2", "b1", "c2"]], [["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "d1", "d2", "d3", "d4", "d5", "d6", "d...
introductory
https://www.codewars.com/kata/597cfe0a38015079a0000006
def covered_pawns(pawns):
3,730
Given a string, capitalize the letters that occupy even indexes and odd indexes separately, and return as shown below. Index `0` will be considered even. For example, `capitalize("abcdef") = ['AbCdEf', 'aBcDeF']`. See test cases for more examples. The input will be a lowercase string with no spaces. Good luck! If y...
["def capitalize(s):\n s = ''.join(c if i%2 else c.upper() for i,c in enumerate(s))\n return [s, s.swapcase()]", "def capitalize(s):\n result = ['','']\n for i,c in enumerate(s):\n result[0] += c.lower() if i % 2 else c.upper()\n result[1] += c.upper() if i % 2 else c.lower()\n return resul...
{"fn_name": "capitalize", "inputs": [["abcdef"], ["codewars"], ["abracadabra"], ["codewarriors"], ["indexinglessons"], ["codingisafunactivity"]], "outputs": [[["AbCdEf", "aBcDeF"]], [["CoDeWaRs", "cOdEwArS"]], [["AbRaCaDaBrA", "aBrAcAdAbRa"]], [["CoDeWaRrIoRs", "cOdEwArRiOrS"]], [["InDeXiNgLeSsOnS", "iNdExInGlEsSoNs"]]...
introductory
https://www.codewars.com/kata/59cfc000aeb2844d16000075
def capitalize(s):
3,733
In your class, you have started lessons about [arithmetic progression](https://en.wikipedia.org/wiki/Arithmetic_progression). Since you are also a programmer, you have decided to write a function that will return the first `n` elements of the sequence with the given common difference `d` and first element `a`. Note tha...
["def arithmetic_sequence_elements(a, r, n):\n return ', '.join(str(a + b * r) for b in range(n))\n", "def arithmetic_sequence_elements(a, r, n):\n return \", \".join((str(a+r*i) for i in range(n)))", "from itertools import count, islice\n\ndef arithmetic_sequence_elements(a, r, n):\n return ', '.join([str(x) ...
{"fn_name": "arithmetic_sequence_elements", "inputs": [[1, 2, 5], [1, 0, 5], [1, -3, 10], [100, -10, 10]], "outputs": [["1, 3, 5, 7, 9"], ["1, 1, 1, 1, 1"], ["1, -2, -5, -8, -11, -14, -17, -20, -23, -26"], ["100, 90, 80, 70, 60, 50, 40, 30, 20, 10"]]}
introductory
https://www.codewars.com/kata/55caf1fd8063ddfa8e000018
def arithmetic_sequence_elements(a, r, n):
3,734
# The die is cast! Your task in this kata is to write a "dice roller" that interprets a subset of [dice notation](http://en.wikipedia.org/wiki/Dice_notation). # Description In most role-playing games, die rolls required by the system are given in the form `AdX`. `A` and `X` are variables, separated by the letter **d...
["import re, random\n\ndef roll(desc, verbose=False):\n if not isinstance(desc,str): return False\n \n ans = re.findall(r'^(\\d*)d(\\d+)(([+\\-]\\d+)*)$', desc.replace(' ',''))\n \n if len(ans) == 0: return False\n \n dct = {i: eval(v) for i,v in enumerate(ans[0]) if v}\n dices = {'dice': [ ...
{"fn_name": "roll", "inputs": [[""], [{}], ["abc"], ["2d6+3 abc"], ["abc 2d6+3"], ["2d6++4"]], "outputs": [[false], [false], [false], [false], [false], [false]]}
introductory
https://www.codewars.com/kata/549cb9c0c36a02ce2e000156
def roll(desc, verbose=False):
3,739
Similar setting of the [previous](https://www.codewars.com/kata/progressive-spiral-number-position/), this time you are called to identify in which "branch" of the spiral a given number will end up. Considering a square of numbers disposed as the 25 items in [the previous kata](https://www.codewars.com/kata/progressiv...
["from math import ceil\n\ndef branch(n):\n if n == 1:\n return 0\n l = int(ceil(n ** 0.5)) // 2\n n -= (2 * l - 1) ** 2 + 1\n return n // (2*l or 1)", "branch=lambda n:(lambda r:r and(n-2)//r+2-r)(0-(1-n**.5)//2*2)", "branch=lambda n: 0 if n==1 else (lambda s: (n-s*s-1)//(s+1))(((n-1)**0.5-1)//2*2+1...
{"fn_name": "branch", "inputs": [[1], [5], [25], [30], [50]], "outputs": [[0], [1], [3], [0], [0]]}
introductory
https://www.codewars.com/kata/5a26ca51e1ce0e987b0000ee
def branch(n):
3,749
# Write Number in Expanded Form You will be given a number and you will need to return it as a string in [Expanded Form](https://www.mathplacementreview.com/arithmetic/whole-numbers.php#expanded-form). For example: ```python expanded_form(12) # Should return '10 + 2' expanded_form(42) # Should return '40 + 2' expande...
["def expanded_form(num):\n num = list(str(num))\n return ' + '.join(x + '0' * (len(num) - y - 1) for y,x in enumerate(num) if x != '0')", "def expanded_form(n):\n result = []\n for a in range(len(str(n)) - 1, -1, -1):\n current = 10 ** a\n quo, n = divmod(n, current)\n if quo:\n ...
{"fn_name": "expanded_form", "inputs": [[2], [12], [42], [70304], [4982342]], "outputs": [["2"], ["10 + 2"], ["40 + 2"], ["70000 + 300 + 4"], ["4000000 + 900000 + 80000 + 2000 + 300 + 40 + 2"]]}
introductory
https://www.codewars.com/kata/5842df8ccbd22792a4000245
def expanded_form(num):
3,752
The Binomial Form of a polynomial has many uses, just as the standard form does. For comparison, if p(x) is in Binomial Form and q(x) is in standard form, we might write p(x) := a0 \* xC0 + a1 \* xC1 + a2 \* xC2 + ... + aN \* xCN q(x) := b0 + b1 \* x + b2 \* x^(2) + ... + bN \* x^(N) Both forms have tricks for eval...
["from functools import reduce\nfrom math import factorial\n\n\ndef value_at(poly, x):\n return round(sum(n * aCb(x, i) for i, n in enumerate(poly[::-1])), 2)\n\ndef aCb(a, b):\n return reduce(lambda x, y: x * y, (a - i for i in range(b)), 1) / factorial(b)\n", "def aCb(a, b):\n result = 1.0\n for i in rang...
{"fn_name": "value_at", "inputs": [[[1, 2, 7], 3], [[1, 2, 7, 0, 5], 2], [[1, 1, 1, 1, 7, 0, 5], 2], [[1, 2, 7, 0, 5], 0.6], [[1, 2, 7, 0, 5], 0]], "outputs": [[16], [12], [12], [4.24], [5.0]]}
introductory
https://www.codewars.com/kata/56782b25c05cad45f700000f
def value_at(poly_spec, x):
3,756
German mathematician Christian Goldbach (1690-1764) [conjectured](https://en.wikipedia.org/wiki/Goldbach%27s_conjecture) that every even number greater than 2 can be represented by the sum of two prime numbers. For example, `10` can be represented as `3+7` or `5+5`. Your job is to make the function return a list conta...
["import math\ndef goldbach_partitions(n):\n def is_prime(x):\n for i in range(2, int(math.sqrt(x))+1):\n if x % i == 0:\n return False\n return True\n\n if n % 2: return []\n\n ret = []\n for first in range(2, n//2 + 1):\n if is_prime(first):\n seco...
{"fn_name": "goldbach_partitions", "inputs": [[15], [393], [31133], [4], [100], [594], [1500]], "outputs": [[[]], [[]], [[]], [["2+2"]], [["3+97", "11+89", "17+83", "29+71", "41+59", "47+53"]], [["7+587", "17+577", "23+571", "31+563", "37+557", "47+547", "53+541", "71+523", "73+521", "103+491", "107+487", "127+467", "1...
introductory
https://www.codewars.com/kata/578dec07deaed9b17d0001b8
def goldbach_partitions(n):
3,759
# Introduction and Warm-up (Highly recommended) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) ___ # Task **_Given_** an *array/list [] of integers* , **_Construct_** a *product array **_Of same size_** Such That prod[i] is equal to The Product of all the e...
["from operator import mul\nfrom functools import reduce\n\ndef product_array(numbers):\n tot = reduce(mul,numbers)\n return [tot//n for n in numbers]", "from numpy import prod\n\ndef product_array(numbers):\n p = prod(numbers)\n return [p // i for i in numbers]", "def product_array(numbers):\n prod = ev...
{"fn_name": "product_array", "inputs": [[[12, 20]], [[3, 27, 4, 2]], [[13, 10, 5, 2, 9]], [[16, 17, 4, 3, 5, 2]]], "outputs": [[[20, 12]], [[216, 24, 162, 324]], [[900, 1170, 2340, 5850, 1300]], [[2040, 1920, 8160, 10880, 6528, 16320]]]}
introductory
https://www.codewars.com/kata/5a905c2157c562994900009d
def product_array(numbers):
3,764
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
https://www.codewars.com/kata/5a0366f12b651dbfa300000c
def arbitrate(s, n):
3,767
Coding decimal numbers with factorials is a way of writing out numbers in a base system that depends on factorials, rather than powers of numbers. In this system, the last digit is always `0` and is in base 0!. The digit before that is either `0 or 1` and is in base 1!. The digit before that is either `0, 1, or 2` a...
["from math import factorial\nfrom string import digits, ascii_uppercase\n\nDIGITS = digits + ascii_uppercase\nFACTORIALS = [1, 1]\n\nf = 1\nfor i in range(2, 36):\n f *= i\n FACTORIALS.append(f)\n\ndef dec2FactString(nb):\n ret = []\n for f in reversed(FACTORIALS):\n (d, nb) = divmod(nb, f)\n ...
{"fn_name": "dec2FactString", "inputs": [[463], [2982], [36288000]], "outputs": [["341010"], ["4041000"], ["A0000000000"]]}
introductory
https://www.codewars.com/kata/54e320dcebe1e583250008fd
def dec2FactString(nb):
3,768
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
https://www.codewars.com/kata/5829994cd04efd4373000468
def name_file(fmt, nbr, start):
3,769
# 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
https://www.codewars.com/kata/5870fa11aa0428da750000da
def execute(code):
3,772
In genetics a reading frame is a way to divide a sequence of nucleotides (DNA bases) into a set of consecutive non-overlapping triplets (also called codon). Each of this triplets is translated into an amino-acid during a translation process to create proteins. In a single strand of DNA you find 3 Reading frames, for e...
["import re\n\n\ndef translate_with_frame(dna, frames=[1, 2, 3, -1, -2, -3]):\n AAs = 'FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG'\n Base1 = 'TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG'\n Base2 = 'TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG'\n ...
{"fn_name": "translate_with_frame", "inputs": [["AAA", [1]], ["AAA", [2]], ["AAA", [-1]], ["AAAA", [2]], ["AGGTGACACCGCAAGCCTTATATTAGC"], ["AGGTGACACCGCAAGCCTTATATTAGC", [1, 2]], ["AGGTGACACCGCAAGCCTTATATTAGC", [2, 1]], ["AGGTGACACCGCAAGCCTTATATTAGC", []], [""], ["", []]], "outputs": [[["K"]], [[""]], [["F"]], [["K"]],...
introductory
https://www.codewars.com/kata/5708ef48fe2d018413000776
def translate_with_frame(dna, frames=[1,2,3,-1,-2,-3]):
3,776
# 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
https://www.codewars.com/kata/589ac16a0cccbff11d000115
def segment_cover(A, L):
3,785
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
https://www.codewars.com/kata/576b072359b1161a7b000a17
def generate_diagonal(n, l):
3,786
# 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
https://www.codewars.com/kata/57fd6c4fa5372ead1f0004aa
def siegfried(week, txt):
3,790
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
https://www.codewars.com/kata/59e66e48fc3c499ec5000103
def solve(arr):
3,793
In this kata, you should calculate type of triangle with three given sides ``a``, ``b`` and ``c`` (given in any order). If all angles are less than ``90°``, this triangle is ``acute`` and function should return ``1``. If one angle is strictly ``90°``, this triangle is ``right`` and function should return ``2``. If o...
["def triangle_type(a, b, c):\n x,y,z = sorted([a,b,c])\n if z >= x + y: return 0\n if z*z == x*x + y*y: return 2\n return 1 if z*z < x*x + y*y else 3", "def triangle_type(a, b, c):\n a,b,c = sorted((a,b,c))\n if a+b <= c: return 0\n t = a**2+b**2 - c**2\n if t > 0: return 1\n if t == 0: return 2\n else: retu...
{"fn_name": "triangle_type", "inputs": [[1, 2, 3], [5.5, 4.5, 10], [7, 3, 2], [5, 10, 5], [3, 3, 0], [3, 3, 1], [5, 5, 5], [122.14, 222.11, 250], [8, 5, 7], [100000, 100005, 111111], [3, 4, 5], [21, 220, 221], [8.625, 33.625, 32.5], [65, 56, 33], [68000, 285000, 293000], [2, 4, 5], [105, 100, 6], [102, 200, 250], [65, ...
introductory
https://www.codewars.com/kata/53907ac3cd51b69f790006c5
def triangle_type(a, b, c):
3,806
# Task In a black and white image we can use `1` instead of black pixels and `0` instead of white pixels. For compression image file we can reserve pixels by consecutive pixels who have the same color. Your task is to determine how much of black and white pixels is in each row sorted by place of those. # Exa...
["def black_and_white(height, width, compressed):\n res, left, i, color = [], 0, 0, 0\n for h in range(height):\n tot, tmp = 0, []\n if color == 1: tmp.append(0)\n while tot < width and i < len(compressed):\n if left:\n if left <= width:\n tmp.appe...
{"fn_name": "black_and_white", "inputs": [[2, 100, [40, 120, 40, 0]], [2, 100, [0, 180, 20, 0]]], "outputs": [[[[40, 60], [0, 60, 40, 0]]], [[[0, 100], [0, 80, 20, 0]]]]}
introductory
https://www.codewars.com/kata/58a6a56942fd72afdd000161
def black_and_white(height, width, compressed):
3,808
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
https://www.codewars.com/kata/574881a216ac9be096001ade
def knight_or_knave(said):
3,811
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
https://www.codewars.com/kata/5a2d70a6f28b821ab4000004
def largest_sum(s):
3,813
# Task Fred Mapper is considering purchasing some land in Louisiana to build his house on. In the process of investigating the land, he learned that the state of Louisiana is actually shrinking by 50 square miles each year, due to erosion caused by the Mississippi River. Since Fred is hoping to live in this house the ...
["from math import ceil, pi\n\ndef does_fred_need_houseboat(x, y):\n return ceil(pi * (x**2 + y**2) / 100)", "from math import pi, hypot, ceil\n\ndef does_fred_need_houseboat(x,y):\n return ceil(hypot(x, y)**2 * pi / 50 / 2)", "from math import pi, sqrt, hypot\nfrom itertools import count\n\ndef radius(year):\n ...
{"fn_name": "does_fred_need_houseboat", "inputs": [[1, 1], [25, 0]], "outputs": [[1], [20]]}
introductory
https://www.codewars.com/kata/58bf72b02d1c7c18d9000127
def does_fred_need_houseboat(x,y):
3,814
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
https://www.codewars.com/kata/57729a09914da60e17000329
def get_military_time(time):
3,817
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
https://www.codewars.com/kata/581951b3704cccfdf30000d2
def split_without_loss(s, split_p):
3,818
# 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
https://www.codewars.com/kata/584acbee7d22f84dc80000e2
def get_mixed_num(fraction):
3,821
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
https://www.codewars.com/kata/57a73e697cb1f31dd70000d2
def chinese_zodiac(year):
3,829
# 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
https://www.codewars.com/kata/5cab471da732b30018968071
def build_square(blocks):
3,834
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
https://www.codewars.com/kata/59f0ee47a5e12962cb0000bf
def palin(a,b):
3,835
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
https://www.codewars.com/kata/56f3ed90de254a2ca7000e20
def find_discounted(prices):
3,837
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
https://www.codewars.com/kata/5cc1e284ece231001ccf7014
def reverse(right):
3,840
## **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
https://www.codewars.com/kata/5e860c16c7826f002dc60ebb
def largest_power(n):
3,844
*** Nova polynomial from roots*** This kata is from a series on polynomial handling. ( [#1](http://www.codewars.com/kata/nova-polynomial-1-add-1) [#2](http://www.codewars.com/kata/570eb07e127ad107270005fe) [#3](http://www.codewars.com/kata/5714041e8807940ff3001140 ) [#4](http://www.codewars.com/kata/571a2e2df24b...
["import numpy\n\ndef poly_from_roots(r): return list(reversed(numpy.poly(tuple(r)))) if len(r)>0 else [1]", "from collections import Counter\nfrom itertools import product\nfrom functools import reduce\nfrom operator import mul\n\nclass P(Counter):\n def __mul__(self, other):\n m = P()\n for (ao, av),...
{"fn_name": "poly_from_roots", "inputs": [[[4]], [[0, 0, 0, 0]], [[1, 1, 1, 1]], [[-1, 1, 2, -2]], [[]]], "outputs": [[[-4, 1]], [[0, 0, 0, 0, 1]], [[1, -4, 6, -4, 1]], [[4, 0, -5, 0, 1]], [[1]]]}
introductory
https://www.codewars.com/kata/571df7c31f95429529000092
def poly_from_roots(r):
3,846
_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
https://www.codewars.com/kata/56b85fc4f18876abf0000877
def f(k, n):
3,847
In computer science, cycle detection is the algorithmic problem of finding a cycle in a sequence of iterated function values. For any function ƒ, and any initial value x0 in S, the sequence of iterated function values x0,x1=f(x0), x2=f(x1), ...,xi=f(x{i-1}),... may eventually use the same value twice under some ...
["def cycle(sequence):\n for j, x in enumerate(sequence):\n i = sequence.index(x)\n if 0 <= i < j:\n return [i, j - i]\n return []\n", "def cycle(sequence):\n found = {}\n for i, item in enumerate(sequence):\n if item in found:\n return [found[item], i - found[item...
{"fn_name": "cycle", "inputs": [[[2, 3, 4, 2, 3, 4]], [[1, 2, 3, 4, 2, 3, 4]], [[1, 1, 1, 1, 1, 1, 1, 1]], [[]], [[7]], [[1, 2, 3, 4]]], "outputs": [[[0, 3]], [[1, 3]], [[0, 1]], [[]], [[]], [[]]]}
introductory
https://www.codewars.com/kata/5416f1834c24604c46000696
def cycle(sequence):
3,848
You are given three integers in the range [0-99]. You must determine if any ordering of the numbers forms a date from the 20th century. - If no ordering forms a date, return the string `"invalid"`. - If multiple distinct orderings form dates, return the string `"ambiguous"`. - If only one ordering forms a date, retu...
["from datetime import datetime\nfrom itertools import permutations\n\ndef unique_date(*args):\n dates = set()\n for p in permutations(args):\n try:\n date = '{:02}/{:02}/{:02}'.format(*p)\n datetime.strptime(date, '%y/%m/%d')\n dates.add(date)\n except ValueError: p...
{"fn_name": "unique_date", "inputs": [["[[2, 3, 4, 2, 3, 4]]", "[[1, 2, 3, 4, 2, 3, 4]]", "[[1, 1, 1, 1, 1, 1, 1, 1]]", "[[]]", "[[7]]", "[[1, 2, 3, 4]]"]], "outputs": [["invalid"]]}
introductory
https://www.codewars.com/kata/582406166cf35b7f93000057
def unique_date(*args):
3,851
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
https://www.codewars.com/kata/59cd0535328801336e000649
def interest(p,r,n):
3,854
## 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
https://www.codewars.com/kata/5bc5cfc9d38567e29600019d
def check_dates(records):
3,856
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
https://www.codewars.com/kata/59ce11ea9f0cbc8a390000ed
def solve(a,b):
3,869
# Task Below we will define what and n-interesting polygon is and your task is to find its area for a given n. A 1-interesting polygon is just a square with a side of length 1. An n-interesting polygon is obtained by taking the n - 1-interesting polygon and appending 1-interesting polygons to its rim side by side. Y...
["def shape_area(n):\n return n**2 + (n - 1) ** 2", "def shape_area(n):\n return 2 * n * (n - 1) + 1", "def shape_area(n):\n if n==1:\n return 1\n return n*n*2-n-(n-1)", "def shape_area(n):\n p = 0\n area = 1\n for i in range (1, n):\n p = n*4-4\n n -= 1\n area += p\n return area\n...
{"fn_name": "shape_area", "inputs": [[2], [3], [1], [5]], "outputs": [[5], [13], [1], [41]]}
introductory
https://www.codewars.com/kata/5893e0c41a88085c330000a0
def shape_area(n):
3,870
In this Kata, we are going to reverse a string while maintaining the spaces (if any) in their original place. For example: ``` solve("our code") = "edo cruo" -- Normal reversal without spaces is "edocruo". -- However, there is a space at index 3, so the string becomes "edo cruo" solve("your code rocks") = "skco redo...
["def solve(s):\n it = reversed(s.replace(' ',''))\n return ''.join(c if c == ' ' else next(it) for c in s)", "def solve(s):\n space_index=[i for i in range(len(s)) if s[i]==\" \"] #find index of saces \n s = ''.join(s.split()) #remove spaces\n s=s[::-1] ...
{"fn_name": "solve", "inputs": [["codewars"], ["your code"], ["your code rocks"], ["i love codewars"]], "outputs": [["srawedoc"], ["edoc ruoy"], ["skco redo cruoy"], ["s rawe docevoli"]]}
introductory
https://www.codewars.com/kata/5a71939d373c2e634200008e
def solve(s):
3,878
Adapted from here, with less terrible instructions and a couple tweaks. Two kangaroos are jumping on a line. They start out at different points on the line, and jump in the same direction at different speeds. Your task is to determine whether or not they'll ever land in the same spot at the same time (you'll just have...
["def kangaroo(k1, r1, k2, r2):\n if r1==r2: return k1==k2\n cross, r = divmod(k1-k2, r2-r1)\n return cross >= 0 and not r", "def kangaroo(x1, v1, x2, v2):\n if x1 > x2 and v1 > v2:\n return False\n if (v1 > v2 and (x2-x1)%(v1-v2)==0):\n return True\n else:\n return False", "def k...
{"fn_name": "kangaroo", "inputs": [[0, 3, 4, 2], [0, 9, 16, 4], [-1, 3, 0, 2], [-1571, 4240, 9023, 4234], [-7855, 4240, 9023, 4234], [43, 5, 49, 3], [9023, 4240, 1571, 4234], [129, 15, 147, 9], [129, 15, 147, 90], [0, 2, 100000, 1], [72893, 11125, 24432, 4202], [13613, 299, 65130, 73]], "outputs": [[true], [false], [tr...
introductory
https://www.codewars.com/kata/5ae7e1522c5061beb7000051
def kangaroo(kanga1, rate1, kanga2, rate2):
3,880
The concept of "[smooth number](https://en.wikipedia.org/wiki/Smooth_number)" is applied to all those numbers whose prime factors are lesser than or equal to `7`: `60` is a smooth number (`2 * 2 * 3 * 5`), `111` is not (`3 * 37`). More specifically, smooth numbers are classified by their highest prime factor and your ...
["def is_smooth(n):\n for x in [2,3,5,7]:\n while n%x==0:n//=x\n if n==1:return (\"power of 2\",'3-smooth','Hamming number','humble number')[(2<x)+(3<x)+(5<x)] \n return \"non-smooth\"", "from collections import defaultdict\n\n\nnames = defaultdict(lambda: 'non-smooth', {\n 2: 'power of 2',\n ...
{"fn_name": "is_smooth", "inputs": [[16], [36], [60], [98], [111], [4096], [729], [3125], [7], [17]], "outputs": [["power of 2"], ["3-smooth"], ["Hamming number"], ["humble number"], ["non-smooth"], ["power of 2"], ["3-smooth"], ["Hamming number"], ["humble number"], ["non-smooth"]]}
introductory
https://www.codewars.com/kata/5b2f6ad842b27ea689000082
def is_smooth(n):
3,883
If we alternate the vowels and consonants in the string `"have"`, we get the following list, arranged alphabetically: `['ahev', 'aveh', 'ehav', 'evah', 'vahe', 'veha']`. These are the only possibilities in which vowels and consonants are alternated. The first element, `ahev`, is alphabetically lowest. Given a string:...
["def solve(s):\n vowels = sorted(c for c in s if c in \"aeiou\")\n consonants = sorted(c for c in s if c not in \"aeiou\")\n part1, part2 = sorted((vowels, consonants), key=len, reverse=True)\n part2.append('')\n if len(part1) > len(part2):\n return \"failed\"\n return \"\".join(a + b for a, b...
{"fn_name": "solve", "inputs": [["java"], ["oruder"], ["zodiac"], ["apple"], ["acidity"], ["codewars"], ["orudere"]], "outputs": [["ajav"], ["edorur"], ["acidoz"], ["lapep"], ["caditiy"], ["failed"], ["ederoru"]]}
introductory
https://www.codewars.com/kata/59cf8bed1a68b75ffb000026
def solve(s):
3,884
# RegExp Fun #1 - When I miss few days of gym ## Disclaimer The background story of this Kata is 100% fiction. Any resemblance to real people or real events is **nothing more than a coincidence** and should be regarded as such. ## Background Story You are a person who loves to go to the gym everyday with the squad...
["import re\n\ndef gym_slang(phrase):\n phrase = re.sub(r'([pP])robably', r'\\1rolly', phrase)\n phrase = re.sub(r'([iI]) am', r\"\\1'm\", phrase)\n phrase = re.sub(r'([iI])nstagram', r'\\1nsta', phrase)\n phrase = re.sub(r'([dD])o not', r\"\\1on't\", phrase)\n phrase = re.sub(r'([gG])oing to', r'\\1onna...
{"fn_name": "gym_slang", "inputs": [["When I miss few days of gym"], ["Squad probably think I am fake"], ["Whole squad probably bigger than me now"], ["No selfie to post on Instagram either"], ["Gym crush probably found someone else"], ["What if I die fat"], ["What if I do not fit in my clothes now"], ["Going to feel l...
introductory
https://www.codewars.com/kata/5720a81309e1f9b232001c5b
def gym_slang(phrase):
3,885
The palindromic number `595` is interesting because it can be written as the sum of consecutive squares: `6^2 + 7^2 + 8^2 + 9^2 + 10^2 + 11^2 + 12^2 = 595`. There are exactly eleven palindromes below one-thousand that can be written as consecutive square sums. Note that `1 = 0^2 + 1^2` has not been included as this pr...
["l, m, p = [1], 10 ** 7, []\nfor n in range(2, int(m ** .5) + 1):\n l = [n*n + j for j in [0]+l]\n p += [int(k) for k in map(str, l[1:]) if k == k[::-1]]\np = sorted(set(p))\n\nfrom bisect import bisect_left\ndef values(n): return bisect_left(p, n)", "def values(n):\n pal = set()\n for i in range(1, int(n*...
{"fn_name": "values", "inputs": [[100], [200], [300], [400], [1000], [100000], [1000000], [5000000], [9000000], [10000000]], "outputs": [[3], [4], [4], [5], [11], [30], [59], [78], [98], [110]]}
introductory
https://www.codewars.com/kata/599b1a4a3c5292b4cc0000d5
def values(n):
3,886
In this Kata, you will be given an integer array and your task is to return the sum of elements occupying prime-numbered indices. ~~~if-not:fortran The first element of the array is at index `0`. ~~~ ~~~if:fortran The first element of an array is at index `1`. ~~~ Good luck! If you like this Kata, try: [Dominan...
["def is_prime(n):\n return n >= 2 and all(n%i for i in range(2, 1+int(n**.5)))\n \ndef total(arr):\n return sum(n for i, n in enumerate(arr) if is_prime(i))", "def sieve(n):\n sieve, primes = [0]*(n+1), set()\n for i in range(2, n+1):\n if not sieve[i]:\n primes.add(i)\n for...
{"fn_name": "total", "inputs": [[[]], [[1, 2, 3, 4]], [[1, 2, 3, 4, 5, 6]], [[1, 2, 3, 4, 5, 6, 7, 8]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]]], "outputs": [[0], [7], [13], [21], [21], [33], [47]]}
introductory
https://www.codewars.com/kata/59f38b033640ce9fc700015b
def total(arr):
3,894
In this Kata, you will be given a string that may have mixed uppercase and lowercase letters and your task is to convert that string to either lowercase only or uppercase only based on: * make as few changes as possible. * if the string contains equal number of uppercase and lowercase letters, convert the string to ...
["def solve(s):\n return s.upper() if sum(map(str.isupper, s)) * 2 > len(s) else s.lower()", "def solve(s):\n upper = 0\n lower = 0\n \n for char in s:\n if char.islower():\n lower += 1\n else:\n upper += 1\n \n if upper == lower or lower > upper:\n ...
{"fn_name": "solve", "inputs": [["code"], ["CODe"], ["COde"], ["Code"]], "outputs": [["code"], ["CODE"], ["code"], ["code"]]}
introductory
https://www.codewars.com/kata/5b180e9fedaa564a7000009a
def solve(s):
3,898
Convert DD (decimal degrees) position to DMS (degrees, minutes, seconds). ##### Inputs: `dd_lat` and `dd_lon` 2 strings representing the latitude and the longitude in degree -i.e. 2 floats included in [-90, 90] and [-180, 180]. Note that latitude 0 is north, longitude 0 is east. ##### Outputs: A tuple of DMS latitude...
["from math import floor\n\ndef convert(dd, direction):\n degrees = floor(dd)\n seconds = round((dd % 1) * 3600000)\n return \"%03d*%02d\\'%06.3f\\\"%s\" % (degrees, \n seconds // 60000,\n seconds % 60000 / 1000,\n ...
{"fn_name": "convert_to_dms", "inputs": [["35.03299485527936", "33.233755230903625"], ["-37.111415669561595", "-12.284317023586482"], ["19.61499312350978", "-155.48217818140984"]], "outputs": [["035*01'58.781\"N", "033*14'01.519\"E"], ["037*06'41.096\"S", "012*17'03.541\"W"], ["019*36'53.975\"N", "155*28'55.841\"W"]]}
introductory
https://www.codewars.com/kata/5a72fd224a6b3463b00000a0
def convert_to_dms(dd_lat, dd_lon):
3,900
A **Seven Segment Display** is an electronic display device, used to display decimal or hexadecimal numerals. It involves seven led segments that are lit in specific combinations to represent a specific numeral. An example of each combination is shown below: ![seven segment display](https://upload.wikimedia.org/wikipe...
["BASE = [r.split('|') for r in '''\\\n ### | | ### | ### | | ### | ### | ### | ### | ### | \n # # | # | # | # | # # | # | # | # | # # | # # | \n # # | # | # | # | # # | # | # | # | # # | # # | \n # # | #...
{"fn_name": "segment_display", "inputs": [[123456], [987654], [0]], "outputs": [["| | ### | ### | | ### | ### |\n| # | # | # | # # | # | # |\n| # | # | # | # # | # | # |\n| # | # | # | # # | # | # |\n| | ### | ### | ### | ...
introductory
https://www.codewars.com/kata/5d7091aa7bf8d0001200c133
def segment_display(num):
3,903
In Russia, there is an army-purposed station named UVB-76 or "Buzzer" (see also https://en.wikipedia.org/wiki/UVB-76). Most of time specific "buzz" noise is being broadcasted, but on very rare occasions, the buzzer signal is interrupted and a voice transmission in Russian takes place. Transmitted messages have always t...
["import re\nvalidate = lambda msg: bool(re.match('^MDZHB \\d\\d \\d\\d\\d [A-Z]+ \\d\\d \\d\\d \\d\\d \\d\\d$', msg))", "import re\ndef validate(message):\n return bool(re.match(r\"^MDZHB \\d{2} \\d{3} [A-Z]+ \\d{2} \\d{2} \\d{2} \\d{2}$\", message))", "import re\ndef validate(message):\n return re.match(r'^MDZHB(...
{"fn_name": "validate", "inputs": [["Is this a right message?"], ["MDZHB 85 596 KLASA 81 00 02 91"], ["MDZHB 12 733 EDINENIE 67 79 66 32"], ["MDZHV 60 130 VATRUKH 58 89 54 54"], ["MDZHB 85 596 BRAMIRKA 81 00 02 91"], ["MDZHB 12 733 INITIAL 67 79 66 32"], ["MDZHB 60 130 KROLI5T 58 89 54 54"], ["MDZHB 85 596 KAMASIT 81 0...
introductory
https://www.codewars.com/kata/56445cc2e5747d513c000033
def validate(message):
3,904
Same as [the original](https://www.codewars.com/kata/simple-fun-number-258-is-divisible-by-6) (same rules, really, go there for example and I strongly recommend completing it first), but with more than one asterisk (but always at least one). For example, `"*2"` should return `["12", "42", "72"]`. Similarly, `"*2*"` s...
["from itertools import product\n\ndef is_divisible_by_6(s):\n if s[-1] in '13579': return []\n ss = s.replace('*','{}')\n return [ v for v in (ss.format(*p) for p in product(*(['0123456789']*s.count('*')))) if not int(v)%6]", "def create_permutations(string):\n if '*' not in string:\n return [int(st...
{"fn_name": "is_divisible_by_6", "inputs": [["*2"], ["*21"], ["**1"], ["*2*"], ["***"]], "outputs": [[["12", "42", "72"]], [[]], [[]], [["024", "120", "126", "222", "228", "324", "420", "426", "522", "528", "624", "720", "726", "822", "828", "924"]], [["000", "006", "012", "018", "024", "030", "036", "042", "048", "054...
introductory
https://www.codewars.com/kata/5a1a8b7ec374cbea92000086
def is_divisible_by_6(s):
3,908
In this Kata, you will sort elements in an array by decreasing frequency of elements. If two elements have the same frequency, sort them by increasing value. More examples in test cases. Good luck! Please also try [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2)
["from collections import Counter\n\ndef solve(a):\n c = Counter(a)\n return sorted(a, key=lambda k: (-c[k], k))", "def solve(arr):\n return sorted(arr, key= lambda x: (-arr.count(x), x))", "def solve(arr):\n return sorted(sorted(arr), key=lambda n: arr.count(n), reverse=True)", "def solve(arr):\n freq =...
{"fn_name": "solve", "inputs": [[[2, 3, 5, 3, 7, 9, 5, 3, 7]], [[1, 2, 3, 0, 5, 0, 1, 6, 8, 8, 6, 9, 1]], [[5, 9, 6, 9, 6, 5, 9, 9, 4, 4]], [[4, 4, 2, 5, 1, 1, 3, 3, 2, 8]], [[4, 9, 5, 0, 7, 3, 8, 4, 9, 0]]], "outputs": [[[3, 3, 3, 5, 5, 7, 7, 2, 9]], [[1, 1, 1, 0, 0, 6, 6, 8, 8, 2, 3, 5, 9]], [[9, 9, 9, 9, 4, 4, 5, 5,...
introductory
https://www.codewars.com/kata/5a8d2bf60025e9163c0000bc
def solve(arr):
3,909
In recreational mathematics, a [Keith number](https://en.wikipedia.org/wiki/Keith_number) or repfigit number (short for repetitive Fibonacci-like digit) is a number in the following integer sequence: `14, 19, 28, 47, 61, 75, 197, 742, 1104, 1537, 2208, 2580, 3684, 4788, 7385, 7647, 7909, ...` (sequence A007629 in the ...
["def is_keith_number(n):\n numList = [int(i) for i in str(n)] # int array\n if len(numList) > 1: # min 2 digits\n itr = 0\n while numList[0] <= n:\n # replace array entries by its sum:\n numList[itr % len(numList)] = sum(numList)\n itr += 1\n if n in nu...
{"fn_name": "is_keith_number", "inputs": [[14], [10], [4], [28], [23], [0], [19], [47], [34], [61], [58], [75], [197], [742], [1104], [1537], [2208], [2697], [7385], [31331], [120284], [1084051], [44121607], [251133297], [96189170155], [11812665388886672], [855191324330802397989], [18354972585225358067718266], [4179620...
introductory
https://www.codewars.com/kata/590e4940defcf1751c000009
def is_keith_number(n):
3,910
An expression is formed by taking the digits 1 to 9 in numerical order and then inserting into each gap between the numbers either a plus sign or a minus sign or neither. Your task is to write a method which takes one parameter and returns the **smallest possible number** of plus and minus signs necessary to form such...
["from itertools import product\n\ndef operator_insertor(n):\n result = []\n \n for ops in product([\"+\", \"-\", \"\"], repeat=8):\n expression = \"\".join(a+b for a, b in zip(\"123456789\", list(ops) + [\"\"]))\n res = eval(expression)\n if res == n:\n result.append(len(expres...
{"fn_name": "operator_insertor", "inputs": [[11], [100], [766], [160], [70], [389]], "outputs": [[5], [3], [4], [null], [6], [2]]}
introductory
https://www.codewars.com/kata/596b7f284f232df61e00001b
def operator_insertor(n):
3,916
Your goal is to implement the method **meanVsMedian** which accepts an *odd-length* array of integers and returns one of the following: * 'mean' - in case **mean** value is **larger than** median value * 'median' - in case **median** value is **larger than** mean value * 'same' - in case both mean and median share the...
["from numpy import mean, median\n\ndef mean_vs_median(numbers):\n if mean(numbers) > median(numbers):\n return 'mean'\n elif mean(numbers) < median(numbers):\n return 'median'\n else:\n return 'same'", "def mean_vs_median(numbers):\n mean = sum(numbers)/len(numbers)\n med = sorted(n...
{"fn_name": "mean_vs_median", "inputs": [[[1, 1, 1]], [[1, 2, 37]], [[7, 14, -70]], [[-10, 20, 5]]], "outputs": [["same"], ["mean"], ["median"], ["same"]]}
introductory
https://www.codewars.com/kata/5806445c3f1f9c2f72000031
def mean_vs_median(numbers):
3,922
# Task You are a lonely frog. You live on an integer array. The meaning of your life is to jump and jump.. Now, here comes your new task. You are given an integer array `arr` and a positive integer `n`. You will jump following the rules below: - Your initial position at `arr[0]`. arr[0] will always be `0`. - ...
["def jumping(arr, n):\n i = 0\n while i < len(arr):\n x = arr[i]\n arr[i] += 1 if x < n else -1\n i += x\n return arr.count(n)", "def jumping(arr, n):\n i, arr = 0, arr[:]\n arr[0] += 1\n while i<len(arr):\n delta = arr[i]\n arr[i] += (arr[i]<n) - (arr[i]>=n)\n ...
{"fn_name": "jumping", "inputs": [[[0, 3, 0, 1, -3], 3], [[0, -1, -2, -3, -4], 4], [[0, -1, -2, -3, -4], 3], [[0, -1, -2, -3, -4], 2], [[0, -1, -2, -3, -4], 1]], "outputs": [[2], [2], [0], [3], [0]]}
introductory
https://www.codewars.com/kata/5a274c9fc5e284a9f7000072
def jumping(arr, n):
3,931
# Letterss of Natac In a game I just made up that doesn’t have anything to do with any other game that you may or may not have played, you collect resources on each turn and then use those resources to build settlements, roads, and cities or buy a development. Other kata about this game can be found [here](https://www....
["from collections import Counter\n\nREQUIRE = {x: Counter(s) for x,s in [('road', 'bw'), ('settlement', 'bwsg'), ('city', 'ooogg'), ('development', 'osg')] }\n\ndef build_or_buy(hand):\n h = Counter(hand)\n return [item for item,c in REQUIRE.items() if not c-h]", "def build_or_buy(hand):\n d = {'bw': 'road', ...
{"fn_name": "build_or_buy", "inputs": [["bwoo"], [""], ["ogogoogogo"], ["bwbwwwbb"]], "outputs": [[["road"]], [[]], [["city"]], [["road"]]]}
introductory
https://www.codewars.com/kata/59e6aec2b2c32c9d8b000184
def build_or_buy(hand):
3,934
## Task: You have to write a function `pattern` which returns the following Pattern (See Pattern & Examples) upto `n` number of rows. * Note: `Returning` the pattern is not the same as `Printing` the pattern. ### Rules/Note: * If `n < 1` then it should return "" i.e. empty string. * There are `no whitespaces` in the...
["def pattern(n):\n return \"\\n\".join([\"\".join([str(y) for y in range(n, x, -1)]) for x in range(n)]);", "def pattern(n):\n return '\\n'.join([''.join(map(str, list(range(n, x, -1)))) for x in range(n)])\n", "def pattern(n):\n return('\\n'.join(''.join(str(i) for i in range(n,j,-1)) for j in range(n)))", "def ...
{"fn_name": "pattern", "inputs": [[1], [2], [5], [0], [-25]], "outputs": [["1"], ["21\n2"], ["54321\n5432\n543\n54\n5"], [""], [""]]}
introductory
https://www.codewars.com/kata/55733d3ef7c43f8b0700007c
def pattern(n):
3,936
# History This kata is a sequel of my [Mixbonacci](https://www.codewars.com/kata/mixbonacci/python) kata. Zozonacci is a special integer sequence named after [**ZozoFouchtra**](https://www.codewars.com/users/ZozoFouchtra), who came up with this kata idea in the [Mixbonacci discussion](https://www.codewars.com/kata/mix...
["from itertools import cycle\n\nROOT = {'fib': [0, 0, 0, 1],\n 'jac': [0, 0, 0, 1],\n 'pad': [0, 1, 0, 0],\n 'pel': [0, 0, 0, 1],\n 'tet': [0, 0, 0, 1],\n 'tri': [0, 0, 0, 1]}\nGEN = {'fib': lambda a: a[-1] + a[-2],\n 'jac': lambda a: a[-1] + 2 * a[-2],\n 'pad': lambda...
{"fn_name": "zozonacci", "inputs": [[["fib"], 0], [[], 10], [["fib"], 10], [["tri"], 10], [["tet"], 10], [["pad"], 10], [["pel"], 10], [["jac"], 10], [["fib", "tri"], 10], [["tri", "fib"], 10], [["pad", "fib"], 10], [["tri", "tet"], 10], [["fib", "pel", "tri"], 10], [["tet", "jac"], 10]], "outputs": [[[]], [[]], [[0, 0...
introductory
https://www.codewars.com/kata/5b7c80094a6aca207000004d
def zozonacci(pattern, length):
3,939
# Rock Paper Scissors Let's play! You have to return which player won! In case of a draw return `Draw!`. Examples: ![rockpaperscissors](http://i.imgur.com/aimOQVX.png)
["def rps(p1, p2):\n beats = {'rock': 'scissors', 'scissors': 'paper', 'paper': 'rock'}\n if beats[p1] == p2:\n return \"Player 1 won!\"\n if beats[p2] == p1:\n return \"Player 2 won!\"\n return \"Draw!\"", "def rps(p1, p2):\n hand = {'rock':0, 'paper':1, 'scissors':2}\n results = ['Draw...
{"fn_name": "rps", "inputs": [["rock", "scissors"], ["scissors", "paper"], ["paper", "rock"], ["scissors", "rock"], ["paper", "scissors"], ["rock", "paper"], ["rock", "rock"], ["scissors", "scissors"], ["paper", "paper"]], "outputs": [["Player 1 won!"], ["Player 1 won!"], ["Player 1 won!"], ["Player 2 won!"], ["Player ...
introductory
https://www.codewars.com/kata/5672a98bdbdd995fad00000f
def rps(p1, p2):
3,952
The [half-life](https://en.wikipedia.org/wiki/Half-life) of a radioactive substance is the time it takes (on average) for one-half of its atoms to undergo radioactive decay. # Task Overview Given the initial quantity of a radioactive substance, the quantity remaining after a given period of time, and the period of tim...
["from math import log\n\ndef half_life(N0, N, t):\n return t / log(N0/N, 2)", "from math import log2\n\ndef half_life(ini, rem, t):\n return t / log2(ini / rem)", "from math import log\n\n\ndef half_life(initial, remaining, time):\n return time*log(2.0)/log(initial/remaining)", "from math import log2\n\ndef h...
{"fn_name": "half_life", "inputs": [[10, 5, 1], [8, 4, 2], [12, 3, 2]], "outputs": [[1], [2], [1]]}
introductory
https://www.codewars.com/kata/59f33b86a01431d5ae000032
def half_life(initial, remaining, time):
3,953
#Detail [Countdown](https://en.wikipedia.org/wiki/Countdown_(game_show) is a British game show with number and word puzzles. The letters round consists of the contestant picking 9 shuffled letters - either picking from the vowel pile or the consonant pile. The contestants are given 30 seconds to try to come up with th...
["def longest_word(letters):\n try:\n word_list = [w for w in words if all(w.count(c) <= letters.count(c) for c in w)]\n largest = sorted([w for w in word_list if len(w) == len(max(word_list, key=len))])\n return largest if largest else None\n except:\n return None"]
{"fn_name": "longest_word", "inputs": [[""], ["MKMKMKMKM"], ["IIIWUGEZI"]], "outputs": [[null], [null], [null]]}
introductory
https://www.codewars.com/kata/57a4c85de298a795210002da
def longest_word(letters):
3,958
Leonardo Fibonacci in a rare portrait of his younger days I assume you are all familiar with the famous Fibonacci sequence, having to get each number as the sum of the previous two (and typically starting with either `[0,1]` or `[1,1]` as the first numbers). While there are plenty of variation on it ([including](http...
["from collections import deque\n\ndef custom_fib(signature, indexes, n):\n fib = deque(signature)\n for _ in range(n):\n fib.append(sum(map(fib.__getitem__, indexes)))\n fib.popleft()\n return fib[0]", "def custom_fib(signature,indexes,n):\n for _ in range(n):\n signature = signature[1...
{"fn_name": "custom_fib", "inputs": [[[1, 1], [0, 1], 2], [[1, 1], [0, 1], 3], [[1, 1], [0, 1], 4], [[3, 5, 2], [0, 1, 2], 4], [[7, 3, 4, 1], [1, 1], 6]], "outputs": [[2], [3], [5], [17], [2]]}
introductory
https://www.codewars.com/kata/596144f0ada6db581200004f
def custom_fib(signature, indexes, n):
3,959
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said # Description: ```if:javascript Given an array `arr` that contains some integers(positive, negative or 0), and a `range` list such as `[[start1,end1],[start2,end2],...]`,...
["def max_sum(arr, ranges):\n return max( sum(arr[start:stop+1]) for start, stop in ranges )", "from itertools import accumulate\n\ndef max_sum(arr, ranges): \n xs = list(accumulate(arr)) + [0]\n return max(xs[j] - xs[i-1] for i, j in ranges)", "def max_sum(arr,ranges): \n return max(sum(arr[start:end+1]) f...
{"fn_name": "max_sum", "inputs": [[[1, -2, 3, 4, -5, -4, 3, 2, 1], [[1, 3], [0, 4], [6, 8]]], [[1, -2, 3, 4, -5, -4, 3, 2, 1], [[1, 3]]], [[1, -2, 3, 4, -5, -4, 3, 2, 1], [[1, 4], [2, 5]]], [[11, -22, 31, 34, -45, -46, 35, 32, 21], [[1, 4], [0, 3], [6, 8], [0, 8]]]], "outputs": [[6], [5], [0], [88]]}
introductory
https://www.codewars.com/kata/583d10c03f02f41462000137
def max_sum(arr,ranges):
3,960
Your task in this Kata is to emulate text justify right in monospace font. You will be given a single-lined text and the expected justification width. The longest word will never be greater than this width. Here are the rules: - Use spaces to fill in the gaps on the left side of the words. - Each line should contain ...
["import textwrap\n\ndef align_right(text,width):\n return \"\\n\".join([l.rjust(width, ' ') for l in textwrap.wrap(text, width)])", "def align_right(text, width):\n res = []\n line = []\n \n for word in text.split():\n if len(' '.join(line + [word])) <= width:\n line.append(word)\n ...
{"fn_name": "align_right", "inputs": [["abc def", 10], ["I take up the whole line", 24], ["Two lines, I am", 10]], "outputs": [[" abc def"], ["I take up the whole line"], ["Two lines,\n I am"]]}
introductory
https://www.codewars.com/kata/583601518d3b9b8d3b0000c9
def align_right(text, width):
3,962
You want to build a standard house of cards, but you don't know how many cards you will need. Write a program which will count the minimal number of cards according to the number of floors you want to have. For example, if you want a one floor house, you will need 7 of them (two pairs of two cards on the base floor, on...
["def house_of_cards(n):\n if n>=1:\n return(n+1)*n/2 + (n+2)*(n+1)\n raise ValueError", "def house_of_cards(n):\n assert n > 0\n return (n + 1) * (3 * n + 4) // 2", "def house_of_cards(floors):\n assert isinstance(floors, int) and floors > 0\n return (floors + 1) * (3 * floors + 4) // 2", "def...
{"fn_name": "house_of_cards", "inputs": [[1], [2], [3]], "outputs": [[7], [15], [26]]}
introductory
https://www.codewars.com/kata/543abbc35f0461d28f000c11
def house_of_cards(floors):
3,963
Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to the other number. (A proper divisor of a number is a positive factor of that number other than the number itself. For example, the proper divisors of 6 are 1, 2, and 3.) For example, the smallest pair of amic...
["def getDivs(n):\n return {1} | {y for x in range(2,int(n**.5)+1) for y in [n//x, x] if not n%x}\n\ndef amicable_numbers(n1,n2):\n return sum(getDivs(n1)) == n2 and sum(getDivs(n2)) == n1", "def amicable_numbers(n1, n2):\n return spd(n1) == n2 and spd(n2) == n1\n\ndef spd(n):\n return sum(i for i in range(...
{"fn_name": "amicable_numbers", "inputs": [[220, 284], [220, 280], [1184, 1210], [220221, 282224], [10744, 10856], [299920, 9284], [999220, 2849], [122265, 139815]], "outputs": [[true], [false], [true], [false], [true], [false], [false], [true]]}
introductory
https://www.codewars.com/kata/56b5ebaa26fd54188b000018
def amicable_numbers(n1,n2):
3,970
Given a triangle of consecutive odd numbers: ``` 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 ... ``` find the triangle's row knowing its index (the rows are 1-indexed), e.g.: ``` odd_row(1) == [1] odd_row(2) == [3, 5] odd_row(3) == [7, 9, 11] ``` **...
["odd_row = lambda n:list(range(n*(n-1)+1,n*(n+1),2))\n", "def odd_row(n):\n m = (n - 1) * n + 1\n return [*range(m, m + n * 2, 2)]", "def odd_row(n):\n return [x for x in range(n**2-n+1, (n+1)**2-n,2)]", "def odd_row(n):\n return [x for x in range(n*n-n, n*n+n) if (x)%2!=0]", "def odd_row(n):\n return l...
{"fn_name": "odd_row", "inputs": [[1], [2], [13], [19], [41], [93]], "outputs": [[[1]], [[3, 5]], [[157, 159, 161, 163, 165, 167, 169, 171, 173, 175, 177, 179, 181]], [[343, 345, 347, 349, 351, 353, 355, 357, 359, 361, 363, 365, 367, 369, 371, 373, 375, 377, 379]], [[1641, 1643, 1645, 1647, 1649, 1651, 1653, 1655, 1657...
introductory
https://www.codewars.com/kata/5d5a7525207a674b71aa25b5
def odd_row(n):
3,971
# Definition A **_Tidy number_** *is a number whose* **_digits are in non-decreasing order_**. ___ # Task **_Given_** a number, **_Find if it is Tidy or not_** . ____ # Warm-up (Highly recommended) # [Playing With Numbers Series](https://www.codewars.com/collections/playing-with-numbers) ___ # Notes * **_Num...
["def tidyNumber(n):\n s = list(str(n))\n return s == sorted(s)", "def tidyNumber(n):\n s = str(n)\n return all(a<=b for a,b in zip(s,s[1:]))", "def tidyNumber(n):\n return n == int(''.join(sorted(str(n))))", "def tidyNumber(n):\n n = str(n)\n for i in range(0, len(n) - 1):\n if n[i] > n[i +...
{"fn_name": "tidyNumber", "inputs": [[12], [102], [9672], [2789], [2335]], "outputs": [[true], [false], [false], [true], [true]]}
introductory
https://www.codewars.com/kata/5a87449ab1710171300000fd
def tidyNumber(n):
3,976
Find the last element of the given argument(s). ## Examples ```python last([1, 2, 3, 4]) ==> 4 last("xyz") ==> "z" last(1, 2, 3, 4) ==> 4 ``` In **javascript** and **CoffeeScript** a **list** will be an `array`, a `string` or the list of `arguments`. (courtesy of [haskell.org](http://www.haskell.org/haske...
["def last(*args):\n return args[-1] if not hasattr(args[-1], \"__getitem__\") else args[-1][-1]", "def last(*args): \n try:\n return args[-1][-1]\n except:\n return args[-1]", "def last(*x):\n try:\n return x[-1][-1]\n except TypeError:\n return x[-1]", "def last(*arr): ...
{"fn_name": "last", "inputs": [[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [["a", "b", "c", "k", "x", "y", "z"]], ["abckxyz"], ["a", "b", "c", "z"]], "outputs": [[10], [10], ["z"], ["z"], ["z"]]}
introductory
https://www.codewars.com/kata/541629460b198da04e000bb9
def last(*args):
3,988
[Run-length encoding](http://en.wikipedia.org/wiki/Run-length_encoding) (RLE) is a very simple form of lossless data compression in which runs of data are stored as a single data value and count. A simple form of RLE would encode the string `"AAABBBCCCD"` as `"3A3B3C1D"` meaning, first there are `3 A`, then `3 B`, the...
["from re import sub\n\ndef encode(string):\n return sub(r'(.)\\1*', lambda m: str(len(m.group(0))) + m.group(1),string)\n \ndef decode(string): \n return sub(r'(\\d+)(\\D)', lambda m: m.group(2) * int(m.group(1)),string)", "encode=lambda s: \"\".join(f\"{len(list(group))}{char}\" for char, group in __import__...
{"fn_name": "encode", "inputs": [["A"], ["AAA"], ["AB"], ["AAABBBCCCA"], ["QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ...
introductory
https://www.codewars.com/kata/578bf2d8daa01a4ee8000046
def encode(string):
3,993
Given an array, return the difference between the count of even numbers and the count of odd numbers. `0` will be considered an even number. ``` For example: solve([0,1,2,3]) = 0 because there are two even numbers and two odd numbers. Even - Odd = 2 - 2 = 0. ``` Let's now add two letters to the last example: ``` ...
["def solve(a):\n return sum(1 if v % 2 == 0 else -1 for v in a if type(v) == int)", "def solve(a):\n return sum( isinstance(x, int) and [1, -1][x % 2] for x in a )", "def solve(a):\n diff = 0\n for e in a:\n if type(e) == int:\n if e % 2:\n diff -= 1\n else:\n ...
{"fn_name": "solve", "inputs": [[[0, 1, 2, 3]], [[0, 1, 2, 3, "a", "b"]], [[0, 15, "z", 16, "m", 13, 14, "c", 9, 10, 13, "u", 4, 3]], [[13, 6, 8, 15, 4, 8, 13]], [[1, "a", 17, 8, "e", 3, "i", 12, 1]], [[5, 15, 16, 10, 6, 4, 16, "t", 13, "n", 14, "k", "n", 0, "q", "d", 7, 9]]], "outputs": [[0], [0], [0], [1], [-2], [2]]...
introductory
https://www.codewars.com/kata/59c62f1bdcc40560a2000060
def solve(a):
3,994
Two Joggers === Description --- Bob and Charles are meeting for their weekly jogging tour. They both start at the same spot called "Start" and they each run a different lap, which may (or may not) vary in length. Since they know each other for a long time already, they both run at the exact same speed. Illustration -...
["from fractions import gcd\n\ndef nbr_of_laps(x, y):\n return (y / gcd(x,y), x / gcd(x,y))", "from fractions import gcd\n\ndef nbr_of_laps(x, y):\n lcm = x / gcd(x, y) * y\n return lcm/x, lcm/y", "def nbr_of_laps(x, y):\n for i in range(min(x, y), 0, -1):\n if x % i == 0 and y % i == 0:\n ...
{"fn_name": "nbr_of_laps", "inputs": [[5, 3], [4, 6], [5, 5]], "outputs": [[[3, 5]], [[3, 2]], [[1, 1]]]}
introductory
https://www.codewars.com/kata/5274d9d3ebc3030802000165
def nbr_of_laps(x, y):
3,995
Everybody knows the classic ["half your age plus seven"](https://en.wikipedia.org/wiki/Age_disparity_in_sexual_relationships#The_.22half-your-age-plus-seven.22_rule) dating rule that a lot of people follow (including myself). It's the 'recommended' age range in which to date someone. ```minimum age <= your age <= ...
["def dating_range(age):\n if age <= 14:\n min = age - 0.10 * age\n max = age + 0.10 * age\n else:\n min = (age/2)+7\n max = (age-7)*2\n \n return str(int(min))+'-'+str(int(max))", "def dating_range(age):\n if age <= 14:\n return \"{}-{}\".format(int(age-0.1*age), i...
{"fn_name": "dating_range", "inputs": [[17], [40], [15], [35], [10], [53], [19], [12], [7], [33]], "outputs": [["15-20"], ["27-66"], ["14-16"], ["24-56"], ["9-11"], ["33-92"], ["16-24"], ["10-13"], ["6-7"], ["23-52"]]}
introductory
https://www.codewars.com/kata/5803956ddb07c5c74200144e
def dating_range(age):
3,997
Consider the string `"1 2 36 4 8"`. Lets take pairs of these numbers, concatenate each pair and determine how many of them of divisible by `k`. ```Pearl If k = 3, we get following numbers ['12', '18', '21', '24', '42', '48', '81', '84'], all divisible by 3. Note: -- 21 and 12 are different pairs. -- Elements mus...
["from itertools import permutations\n\ndef solve(s,k):\n return sum(not v%k for v in map(int, map(''.join, permutations(s.split(),2))))", "from itertools import permutations\n\ndef solve(stg, k):\n return sum(1 for m, n in permutations(stg.split(), 2) if int(f\"{m}{n}\") % k == 0)", "from itertools import permut...
{"fn_name": "solve", "inputs": [["1 2 36 4 8", 2], ["1 2 36 4 8", 3], ["1 2 36 4 8", 4], ["1 2 36 4 8", 8]], "outputs": [[16], [8], [11], [4]]}
introductory
https://www.codewars.com/kata/5b8be3ae36332f341e00015e
def solve(s,k):
3,998
Write the following function: ```python def area_of_polygon_inside_circle(circle_radius, number_of_sides): ``` It should calculate the area of a regular polygon of `numberOfSides`, `number-of-sides`, or `number_of_sides` sides inside a circle of radius `circleRadius`, `circle-radius`, or `circle_radius` which passes ...
["from math import sin, pi\n\ndef area_of_polygon_inside_circle(r, n):\n return round(0.5 * n * r ** 2 * sin(2 * pi / n), 3)", "from math import sin, pi\n\ndef area_of_polygon_inside_circle(r, n):\n return round(n*r*r*sin(2*pi/n)/2, 3)", "import math\ndef area_of_polygon_inside_circle(circle_radius, number_of_sid...
{"fn_name": "area_of_polygon_inside_circle", "inputs": [[3, 3], [2, 4], [2.5, 5]], "outputs": [[11.691], [8], [14.86]]}
introductory
https://www.codewars.com/kata/5a58ca28e626c55ae000018a
def area_of_polygon_inside_circle(r, n):
4,000
# Definition **_Strong number_** is the number that *the sum of the factorial of its digits is equal to number itself*. ## **_For example_**: **_145_**, since ``` 1! + 4! + 5! = 1 + 24 + 120 = 145 ``` So, **_145_** is a **_Strong number_**. ____ # Task **_Given_** a number, **_Find if it is Strong or not_**. ___...
["import math\n\ndef strong_num(number):\n return \"STRONG!!!!\" if sum(math.factorial(int(i)) for i in str(number)) == number else \"Not Strong !!\"", "STRONGS = {1, 2, 145, 40585}\n\ndef strong_num(number):\n return \"STRONG!!!!\" if number in STRONGS else \"Not Strong !!\"", "from math import factorial\ndef st...
{"fn_name": "strong_num", "inputs": [[40585], [2999999]], "outputs": [["STRONG!!!!"], ["Not Strong !!"]]}
introductory
https://www.codewars.com/kata/5a4d303f880385399b000001
def strong_num(number):
4,009
Given an integer, take the (mean) average of each pair of consecutive digits. Repeat this process until you have a single integer, then return that integer. e.g. Note: if the average of two digits is not an integer, round the result **up** (e.g. the average of 8 and 9 will be 9) ## Examples ``` digitsAverage(246) =...
["def digits_average(input):\n digits = [int(c) for c in str(input)]\n while len(digits) > 1:\n digits = [(a + b + 1) // 2 for a, b in zip(digits, digits[1:])]\n return digits[0]", "digits_average=a=lambda n:n>9and a(int(''.join(str(-~int(a)+int(b)>>1)for a,b in zip(str(n),str(n)[1:]))))or n", "import m...
{"fn_name": "digits_average", "inputs": [[246], [89], [2], [245], [345], [346], [3700]], "outputs": [[4], [9], [2], [4], [5], [5], [4]]}
introductory
https://www.codewars.com/kata/5a32526ae1ce0ec0f10000b2
def digits_average(input):
4,011
# How many urinals are free? In men's public toilets with urinals, there is this unwritten rule that you leave at least one urinal free between you and the next person peeing. For example if there are 3 urinals and one person is already peeing in the left one, you will choose the urinal on the right and not the one in...
["def get_free_urinals(urinals):\n return -1 if '11' in urinals else sum(((len(l)-1)//2 for l in f'0{urinals}0'.split('1')))", "def get_free_urinals(urinals):\n if '11' in urinals: return -1\n if urinals == '0': return 1\n free = 0\n i = 0\n while (i < len(urinals)):\n if i == 0 and urinals[i:i...
{"fn_name": "get_free_urinals", "inputs": [["10001"], ["1001"], ["00000"], ["0000"], ["01000"], ["00010"], ["10000"], ["1"], ["0"], ["10"], ["110"], ["1011000001"]], "outputs": [[1], [0], [3], [2], [1], [1], [2], [0], [1], [0], [-1], [-1]]}
introductory
https://www.codewars.com/kata/5e2733f0e7432a000fb5ecc4
def get_free_urinals(urinals):
4,012
### Background In classical cryptography, the Hill cipher is a polygraphic substitution cipher based on linear algebra. It was invented by Lester S. Hill in 1929. ### Task This cipher involves a text key which has to be turned into a matrix and text which needs to be encoded. The text key can be of any perfect squ...
["import numpy as np\nfrom itertools import zip_longest\nfrom string import ascii_lowercase as lower, ascii_uppercase as upper\n\nD = {c:i%26 for i,c in enumerate(lower+upper)}\n\ndef encrypt(text, key):\n result = []\n text = ''.join(filter(str.isalpha, text))\n key = np.array(([D[key[0]], D[key[1]]], [D[key[...
{"fn_name": "encrypt", "inputs": [["", "azyb"], ["hello", "hill"], ["This is a good day", "bbaa"], ["CODEWARS IS GREAT", "wxyz"], ["Five + Seven = Twelve", "math"], ["+-*/ &*%^$", "azyb"]], "outputs": [[""], ["DRJIMN"], ["AAAAAAGACAGAYA"], ["CICQQIIASSDXKSFP"], ["IVSLIGSLAQEECSWR"], [""]]}
introductory
https://www.codewars.com/kata/5e958a9bbb01ec000f3c75d8
def encrypt(text,key):
4,013
A spoonerism is a spoken phrase in which the first letters of two of the words are swapped around, often with amusing results. In its most basic form a spoonerism is a two word phrase in which only the first letters of each word are swapped: ```"not picking" --> "pot nicking"``` Your task is to create a function tha...
["def spoonerize(words):\n a, b = words.split()\n return '{}{} {}{}'.format(b[0], a[1:], a[0], b[1:])\n", "def spoonerize(words):\n a, b = words.split()\n return f\"{b[0]}{a[1:]} {a[0]}{b[1:]}\"", "def spoonerize(words):\n a, b = words.split()\n return ' '.join((b[0]+a[1:], a[0]+b[1:])) ", "def spoone...
{"fn_name": "spoonerize", "inputs": [["not picking"], ["wedding bells"], ["jelly beans"], ["pop corn"]], "outputs": [["pot nicking"], ["bedding wells"], ["belly jeans"], ["cop porn"]]}
introductory
https://www.codewars.com/kata/56b8903933dbe5831e000c76
def spoonerize(words):
4,019
# Task **_Given_** a **_Divisor and a Bound_** , *Find the largest integer N* , Such That , # Conditions : * **_N_** is *divisible by divisor* * **_N_** is *less than or equal to bound* * **_N_** is *greater than 0*. ___ # Notes * The **_parameters (divisor, bound)_** passed to the function are *only posit...
["def max_multiple(divisor, bound):\n return bound - (bound % divisor)", "def max_multiple(divisor, bound):\n return bound // divisor * divisor", "max_multiple = lambda divisor, bound: bound - (bound % divisor)", "def max_multiple(divisor, bound):\n l = []\n for int in range(bound + 1):\n if int % di...
{"fn_name": "max_multiple", "inputs": [[2, 7], [3, 10], [7, 17], [10, 50], [37, 200], [7, 100]], "outputs": [[6], [9], [14], [50], [185], [98]]}
introductory
https://www.codewars.com/kata/5aba780a6a176b029800041c
def max_multiple(divisor, bound):