problem_id
int64
2.36k
5k
question
stringlengths
52
14k
solutions
stringlengths
79
675k
input_output
stringlengths
37
505k
difficulty
stringclasses
1 value
url
stringlengths
36
94
starter_code
stringlengths
0
952
4,265
# 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: ``` 3 p 2 4 ...
["def tops(msg):\n i,d,s = 1,5, ''\n while i < len(msg):\n s += msg[i]\n i += d\n d += 4\n return s[::-1]", "def tops(msg):\n if len(msg) < 2:\n return ''\n g = 2\n k = ''\n ni = 0\n k += msg[1]\n for i in msg[1:]:\n if ni == g * 2 + 1:\n k += i\n...
{"fn_name": "tops", "inputs": [[""], ["12"], ["abcdefghijklmnopqrstuvwxyz12345"], ["abcdefghijklmnopqrstuvwxyz1236789ABCDEFGHIJKLMN"]], "outputs": [[""], ["2"], ["3pgb"], ["M3pgb"]]}
introductory
https://www.codewars.com/kata/59b7571bbf10a48c75000070
def tops(msg):
4,266
### Task The __dot product__ is usually encountered in linear algebra or scientific computing. It's also called __scalar product__ or __inner product__ sometimes: > In mathematics, the __dot product__, or __scalar product__ (or sometimes __inner product__ in the context of Euclidean space), is an algebraic operation t...
["def min_dot(a, b):\n return sum(x * y for (x, y) in zip(sorted(a), sorted(b, reverse = True)))", "from numpy import dot\n\ndef min_dot(a, b):\n return dot(sorted(a), sorted(b, reverse=True))", "def min_dot(a, b):\n return sum(map(int.__mul__, sorted(a), sorted(b)[::-1]))", "def min_dot(a, b):\n a, b = sor...
{"fn_name": "min_dot", "inputs": [[[], []], [[1, 2, 3, 4, 5], [0, 1, 1, 1, 0]], [[1, 2, 3, 4, 5], [0, 0, 1, 1, -4]], [[1, 3, 5], [4, -2, 1]]], "outputs": [[0], [6], [-17], [-3]]}
introductory
https://www.codewars.com/kata/5457ea88aed18536fc000a2c
def min_dot(a, b):
4,267
In Dark Souls, players level up trading souls for stats. 8 stats are upgradable this way: vitality, attunement, endurance, strength, dexterity, resistance, intelligence, and faith. Each level corresponds to adding one point to a stat of the player's choice. Also, there are 10 possible classes each having their own star...
["from itertools import accumulate\n\nCHARACTERS = {\n \"warrior\": (4, [11, 8, 12, 13, 13, 11, 9, 9]),\n \"knight\": (5, [14, 10, 10, 11, 11, 10, 9, 11]),\n \"wanderer\": (3, [10, 11, 10, 10, 14, 12, 11, 8]),\n \"thief\": (5, [9, 11, 9, 9, 15, 10, 12, 11]),\n \"bandit\": (4, [12, 8, 14, 14, 9, 11, 8, 10...
{"fn_name": "souls", "inputs": [["deprived", [11, 11, 11, 11, 11, 11, 11, 11]], ["pyromancer", [10, 12, 11, 12, 9, 12, 11, 8]], ["pyromancer", [16, 12, 11, 12, 9, 12, 10, 8]], ["pyromancer", [16, 12, 11, 12, 9, 12, 13, 8]], ["pyromancer", [16, 12, 11, 12, 9, 12, 13, 10]]], "outputs": [["Starting as a deprived, level 6 ...
introductory
https://www.codewars.com/kata/592a5f9fa3df0a28730000e7
def souls(character, build):
4,268
Given a non-negative number, return the next bigger polydivisible number, or an empty value like `null` or `Nothing`. A number is polydivisible if its first digit is cleanly divisible by `1`, its first two digits by `2`, its first three by `3`, and so on. There are finitely many polydivisible numbers.
["d, polydivisible, arr = 1, [], list(range(1, 10))\nwhile arr:\n d += 1\n polydivisible.extend(arr)\n arr = [n for x in arr for n in\n range(-(-x*10 // d) * d, (x+1) * 10, d)]\n\ndef next_num(n):\n from bisect import bisect\n idx = bisect(polydivisible, n)\n if idx < len(polydivisible):\n ...
{"fn_name": "next_num", "inputs": [[0], [10], [11], [1234], [123220], [998], [999], [1234567890], [3608528850368400786036724], [3608528850368400786036725]], "outputs": [[1], [12], [12], [1236], [123252], [1020], [1020], [1236004020], [3608528850368400786036725], [null]]}
introductory
https://www.codewars.com/kata/5e4a1a43698ef0002d2a1f73
def next_num(n):
4,269
You are currently in the United States of America. The main currency here is known as the United States Dollar (USD). You are planning to travel to another country for vacation, so you make it today's goal to convert your USD (all bills, no cents) into the appropriate currency. This will help you be more prepared for w...
["def convert_my_dollars(usd, currency):\n curs = {\n 'Ar':478, 'Ba':82, 'Cr':6, 'Cz':21, 'Do':48, 'Ph':50,\n 'Uz':10000, 'Ha':64, 'Gu':7, 'Ta':32, 'Ro':4, 'Eg':18,\n 'Vi':22573, 'In':63, 'Ni':31, 'Ve':10, 'No':8, 'Ja':111,\n 'Sa':3, 'Th':32, 'Ke':102, 'So':1059}\n return f\"You now ha...
{"fn_name": "convert_my_dollars", "inputs": [[7, "Armenian Dram"], [322, "Armenian Dram"], [25, "Bangladeshi Taka"], [730, "Bangladeshi Taka"], [37, "Croatian Kuna"], [40, "Croatian Kuna"], [197, "Czech Koruna"], [333, "Czech Koruna"], [768, "Dominican Peso"], [983, "Dominican Peso"]], "outputs": [["You now have 3346 o...
introductory
https://www.codewars.com/kata/5a5c118380eba8a53d0000ce
def convert_my_dollars(usd, currency):
4,270
You are given an array with several `"even"` words, one `"odd"` word, and some numbers mixed in. Determine if any of the numbers in the array is the index of the `"odd"` word. If so, return `true`, otherwise `false`.
["def odd_ball(arr):\n return arr.index(\"odd\") in arr", "def odd_ball(xs):\n return xs.index('odd') in xs", "def odd_ball(arr):\n i = arr.index('odd')\n return i in arr", "def odd_ball(arr):\n g=arr.index('odd')\n if g in arr:\n return True\n else:\n return False", "#krishp\ndef odd...
{"fn_name": "odd_ball", "inputs": [[["even", 4, "even", 7, "even", 55, "even", 6, "even", 10, "odd", 3, "even"]], [["even", 4, "even", 7, "even", 55, "even", 6, "even", 9, "odd", 3, "even"]], [["even", 10, "odd", 2, "even"]]], "outputs": [[true], [false], [true]]}
introductory
https://www.codewars.com/kata/5a941f4e1a60f6e8a70025fe
def odd_ball(arr):
4,271
We all know about Roman Numerals, and if not, here's a nice [introduction kata](http://www.codewars.com/kata/5580d8dc8e4ee9ffcb000050). And if you were anything like me, you 'knew' that the numerals were not used for zeroes or fractions; but not so! I learned something new today: the [Romans did use fractions](https:/...
["FRACTIONS = \" . : :. :: :.: S S. S: S:. S:: S:.:\".split(\" \")\nUNITS = \" I II III IV V VI VII VIII IX\" .split(\" \")\nTENS = \" X XX XXX XL L LX LXX LXXX XC\" .split(\" \")\nHUNDREDS = \" C CC CCC CD D DC DCC DCCC CM\" .split(\" \")\nTHOUSANDS = \" M MM MMM MMMM MMMMM\" .sp...
{"fn_name": "roman_fractions", "inputs": [[-12], [0, -1], [0, 12], [0], [1], [1, 5], [1, 9], [1632, 2], [5000], [5001], [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [0, 5], [0, 6], [0, 7], [0, 8], [0, 9], [0, 10], [0, 11]], "outputs": [["NaR"], ["NaR"], ["NaR"], ["N"], ["I"], ["I:.:"], ["IS:."], ["MDCXXXII:"], ["MMMMM"], ["...
introductory
https://www.codewars.com/kata/55832eda1430b01275000059
def roman_fractions(integer, fraction=None):
4,272
Jenny has written a function that returns a greeting for a user. However, she's in love with Johnny, and would like to greet him slightly different. She added a special case to her function, but she made a mistake. Can you help her?
["def greet(name):\n if name == \"Johnny\":\n return \"Hello, my love!\"\n return \"Hello, {name}!\".format(name=name)", "def greet(name):\n if name == \"Johnny\":\n return \"Hello, my love!\"\n else:\n return \"Hello, {name}!\".format(name=name)\n", "def greet(name):\n return \"Hell...
{"fn_name": "greet", "inputs": [["James"], ["Jane"], ["Jim"], ["Johnny"]], "outputs": [["Hello, James!"], ["Hello, Jane!"], ["Hello, Jim!"], ["Hello, my love!"]]}
introductory
https://www.codewars.com/kata/55225023e1be1ec8bc000390
def greet(name):
4,273
You're re-designing a blog and the blog's posts have the following format for showing the date and time a post was made: *Weekday* *Month* *Day*, *time* e.g., Friday May 2, 7pm You're running out of screen real estate, and on some pages you want to display a shorter format, *Weekday* *Month* *Day* that omits the ti...
["def shorten_to_date(long_date):\n return long_date.split(',')[0]", "def shorten_to_date(long_date):\n return long_date[:long_date.index(',')]", "def shorten_to_date(long_date):\n return long_date[:long_date.rfind(',')]\n", "def shorten_to_date(long_date):\n index = long_date.index(',')\n new_string = l...
{"fn_name": "shorten_to_date", "inputs": [["Monday February 2, 8pm"], ["Tuesday May 29, 8pm"], ["Wed September 1, 3am"], ["Friday May 2, 9am"], ["Tuesday January 29, 10pm"]], "outputs": [["Monday February 2"], ["Tuesday May 29"], ["Wed September 1"], ["Friday May 2"], ["Tuesday January 29"]]}
introductory
https://www.codewars.com/kata/56b0ff16d4aa33e5bb00008e
def shorten_to_date(long_date):
4,274
Your task is to write a function named `do_math` that receives a single argument. This argument is a string that contains multiple whitespace delimited numbers. Each number has a single alphabet letter somewhere within it. ``` Example : "24z6 1x23 y369 89a 900b" ``` As shown above, this alphabet letter can appear anyw...
["from functools import reduce\nfrom itertools import cycle\nfrom operator import add, truediv, mul, sub\n\n\ndef do_math(s):\n xs = sorted(s.split(), key=lambda x: next(c for c in x if c.isalpha()))\n xs = [int(''.join(filter(str.isdigit, x))) for x in xs]\n ops = cycle([add, sub, mul, truediv])\n return r...
{"fn_name": "do_math", "inputs": [["24z6 1z23 y369 89z 900b"], ["24z6 1x23 y369 89a 900b"], ["10a 90x 14b 78u 45a 7b 34y"], ["111a 222c 444y 777u 999a 888p"], ["1z 2t 3q 5x 6u 8a 7b"]], "outputs": [[1414], [1299], [60], [1459], [8]]}
introductory
https://www.codewars.com/kata/5782dd86202c0e43410001f6
def do_math(s) :
4,275
###Task: You have to write a function `pattern` which creates the following pattern (see examples) up to the desired number of rows. * If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string. * If any even number is passed as argument then the pattern should last upto the largest odd nu...
["def pattern(n):\n return '\\n'.join(str(i)*i for i in range(1,n+1,2))", "def pattern(n):\n string = \"\"\n a = n;\n if a % 2 == 0:\n a -= 1;\n for x in range (1, a + 1):\n if x % 2 != 0:\n string += str(x) * x\n \n if x != a:\n string += \"\...
{"fn_name": "pattern", "inputs": [[4], [1], [5], [0], [-25]], "outputs": [["1\n333"], ["1"], ["1\n333\n55555"], [""], [""]]}
introductory
https://www.codewars.com/kata/5574940eae1cf7d520000076
def pattern(n):
4,276
Round any given number to the closest 0.5 step I.E. ``` solution(4.2) = 4 solution(4.3) = 4.5 solution(4.6) = 4.5 solution(4.8) = 5 ``` Round **up** if number is as close to previous and next 0.5 steps. ``` solution(4.75) == 5 ```
["import math\ndef solution(n):\n d=0\n if n - 0.25< math.floor(n):\n d=math.floor(n)\n elif n - 0.75< math.floor(n):\n d=math.floor(n)+0.5\n else:\n d=math.ceil(n)\n return d", "def solution(n):\n return round(n * 2) / 2 if n != 4.25 else 4.5", "def solution(n):\n #your code h...
{"fn_name": "solution", "inputs": [[4.2], [4.25], [4.4], [4.6], [4.75], [4.8], [4.5], [4.55], [4.74], [4.74999999999], [4.74999999991]], "outputs": [[4], [4.5], [4.5], [4.5], [5], [5], [4.5], [4.5], [4.5], [4.5], [4.5]]}
introductory
https://www.codewars.com/kata/51f1342c76b586046800002a
def solution(n):
4,277
At the annual family gathering, the family likes to find the oldest living family member’s age and the youngest family member’s age and calculate the difference between them. You will be given an array of all the family members' ages, in any order. The ages will be given in whole numbers, so a baby of 5 months, will ...
["def difference_in_ages(ages):\n # your code here\n return (min(ages) , max(ages) , max(ages) - min(ages))", "def difference_in_ages(ages):\n x, y = min(ages), max(ages)\n return x, y, y-x", "def difference_in_ages(ages):\n age = sorted(ages)\n return (age[0], age[-1], (age[-1]-age[0]))", "def differ...
{"fn_name": "difference_in_ages", "inputs": [[[16, 22, 31, 44, 3, 38, 27, 41, 88]], [[5, 8, 72, 98, 41, 16, 55]], [[57, 99, 14, 32]], [[62, 0, 3, 77, 88, 102, 26, 44, 55]], [[2, 44, 34, 67, 88, 76, 31, 67]], [[46, 86, 33, 29, 87, 47, 28, 12, 1, 4, 78, 92]], [[66, 73, 88, 24, 36, 65, 5]], [[12, 76, 49, 37, 29, 17, 3, 65...
introductory
https://www.codewars.com/kata/5720a1cb65a504fdff0003e2
def difference_in_ages(ages):
4,278
**Principal Diagonal** -- The principal diagonal in a matrix identifies those elements of the matrix running from North-West to South-East. **Secondary Diagonal** -- the secondary diagonal of a matrix identifies those elements of the matrix running from North-East to South-West. For example: ``` matrix: [...
["def diagonal(m):\n P = sum(m[i][i] for i in range(len(m)))\n S = sum(m[i][-i-1] for i in range(len(m)))\n if P > S:\n return \"Principal Diagonal win!\"\n elif S > P:\n return \"Secondary Diagonal win!\"\n else:\n return 'Draw!'\n", "def diagonal(matrix):\n sp, ss = map(sum, zip...
{"fn_name": "diagonal", "inputs": [[[[2, 2, 2], [4, 2, 6], [8, 8, 2]]], [[[7, 2, 2], [4, 2, 6], [1, 8, 1]]], [[[1, 2, 3], [4, 5, 6], [7, 8, 9]]], [[[1, 2, 2, 5, 1], [4, 1, 6, 1, 1], [1, 8, 5, 6, 2], [1, 5, 2, 1, 2], [1, 8, 2, 6, 1]]], [[[88, 2, 2, 5, 1, 1, 2, 2, 5, 1], [4, 1, 6, 1, 1, 1, 2, 2, 7, 1], [1, 8, 1, 6, 2, 1,...
introductory
https://www.codewars.com/kata/5a8c1b06fd5777d4c00000dd
def diagonal(matrix):
4,279
Write a function groupIn10s which takes any number of arguments, and groups them into sets of 10s and sorts each group in ascending order. The return value should be an array of arrays, so that numbers between 0-9 inclusive are in position 0 and numbers 10-19 are in position 1, etc. Here's an example of the required...
["from collections import defaultdict\ndef group_in_10s(*args):\n if not args: return []\n tens = defaultdict(list)\n for n in sorted(args): tens[n//10].append(n)\n return [tens.get(d, None) for d in range(max(tens) + 1)]", "from itertools import groupby\n\ndef group_in_10s(*args):\n if not args:\n ...
{"fn_name": "group_in_10s", "inputs": [[100]], "outputs": [[[null, null, null, null, null, null, null, null, null, null, [100]]]]}
introductory
https://www.codewars.com/kata/5694d22eb15d78fe8d00003a
def group_in_10s(*args):
4,280
Determine the **area** of the largest square that can fit inside a circle with radius *r*.
["def area_largest_square(r):\n return 2 * r ** 2", "def area_largest_square(r):\n return 2 * r * r", "def area_largest_square(r):\n return r*r*2", "area_largest_square = lambda r: r*(r+r)", "area_largest_square = lambda r: r*r*2", "def area_largest_square(r):\n return r ** 2 * 2", "area_largest_square = lam...
{"fn_name": "area_largest_square", "inputs": [[5], [7], [50]], "outputs": [[50], [98], [5000]]}
introductory
https://www.codewars.com/kata/5887a6fe0cfe64850800161c
def area_largest_square(r):
4,281
To introduce the problem think to my neighbor who drives a tanker truck. The level indicator is down and he is worried because he does not know if he will be able to make deliveries. We put the truck on a horizontal ground and measured the height of the liquid in the tank. Fortunately the tank is a perfect cylinder ...
["import math\ndef tankvol(h, d, vt):\n r = d/2.0\n if h == r: return vt/2 # is the tank half full?\n half = h>r # is it more than half full\n h = d-h if half else h # adjust h accordingly\n a = r-h # perpendicular intercept of the chord\n b = math.sqrt(r**2-...
{"fn_name": "tankvol", "inputs": [[5, 7, 3848], [2, 7, 3848], [2, 8, 5026], [4, 9, 6361], [3, 10, 7853], [3, 5, 1963], [4, 7, 3848], [0, 7, 3848], [7, 7, 3848], [2, 5, 1963], [2, 4, 1256], [4, 10, 7853], [3, 9, 6361], [2, 10, 7853], [5, 9, 6361], [5, 6, 2827], [1, 4, 1256]], "outputs": [[2940], [907], [982], [2731], [1...
introductory
https://www.codewars.com/kata/55f3da49e83ca1ddae0000ad
def tankvol(h, d, vt):
4,282
Seven is a hungry number and its favourite food is number 9. Whenever it spots 9 through the hoops of 8, it eats it! Well, not anymore, because you are going to help the 9 by locating that particular sequence (7,8,9) in an array of digits and tell 7 to come after 9 instead. Seven "ate" nine, no more! (If 9 is not in d...
["import re\n\ndef hungry_seven(arr):\n ss,s = '', ''.join(map(str,arr))\n while ss!=s:\n ss,s = s,re.sub(r'(7+)(89)',r'\\2\\1', s)\n return list(map(int,s))", "def hungry_seven(arr):\n s = str(arr)\n if '7, 8, 9' in s:\n return hungry_seven(s.replace('7, 8, 9', '8, 9, 7'))\n return eval...
{"fn_name": "hungry_seven", "inputs": [[[7, 8, 9]], [[7, 7, 7, 8, 9]], [[8, 7, 8, 9, 8, 9, 7, 8]], [[8, 7, 8, 7, 9, 8]]], "outputs": [[[8, 9, 7]], [[8, 9, 7, 7, 7]], [[8, 8, 9, 8, 9, 7, 7, 8]], [[8, 7, 8, 7, 9, 8]]]}
introductory
https://www.codewars.com/kata/59e61c577905df540000016b
def hungry_seven(arr):
4,283
Help Johnny! He can't make his code work! Easy Code Johnny is trying to make a function that adds the sum of two encoded strings, but he can't find the error in his code! Help him!
["def add(s1, s2):\n return sum(ord(x) for x in s1+s2)", "def add(s1, s2):\n s1 = s1.encode()\n s2 = s2.encode()\n return sum(s1+s2)", "def add(s1, s2):\n s1 = s1.encode()\n s2 = s2.encode()\n s1 = sum(list(s1))\n s2 = sum(list(s2))\n return s1+s2", "def add(s1, s2):\n return sum(map(ord, ...
{"fn_name": "add", "inputs": [["a", "b"]], "outputs": [[195]]}
introductory
https://www.codewars.com/kata/5848cd33c3689be0dc00175c
def add(s1, s2):
4,284
# Definition An **_element is leader_** *if it is greater than The Sum all the elements to its right side*. ____ # Task **_Given_** an *array/list [] of integers* , **_Find_** *all the **_LEADERS_** in the array*. ___ # Notes * **_Array/list_** size is *at least 3* . * **_Array/list's numbers_** Will be **_mixt...
["def array_leaders(numbers):\n return [n for (i,n) in enumerate(numbers) if n>sum(numbers[(i+1):])]\n", "def array_leaders(numbers):\n res = []\n s = 0\n for n in reversed(numbers):\n if n > s:\n res.append(n)\n s += n\n res.reverse()\n return res\n\narrayLeaders = array_lead...
{"fn_name": "array_leaders", "inputs": [[[1, 2, 3, 4, 0]], [[16, 17, 4, 3, 5, 2]], [[-1, -29, -26, -2]], [[-36, -12, -27]], [[5, 2]], [[0, -1, -29, 3, 2]]], "outputs": [[[4]], [[17, 5, 2]], [[-1]], [[-36, -12]], [[5, 2]], [[0, -1, 3, 2]]]}
introductory
https://www.codewars.com/kata/5a651865fd56cb55760000e0
def array_leaders(numbers):
4,285
Given an array of 4 integers ```[a,b,c,d]``` representing two points ```(a, b)``` and ```(c, d)```, return a string representation of the slope of the line joining these two points. For an undefined slope (division by 0), return ```undefined``` . Note that the "undefined" is case-sensitive. ``` a:x1 b:y1 ...
["def find_slope(points):\n x1, y1, x2, y2 = points\n if x2 - x1 == 0:\n return \"undefined\"\n return str((y2 - y1) // (x2 - x1))", "def find_slope(points):\n x1, y1, x2, y2 = points\n dx = x2 - x1\n dy = y2 - y1\n if dx != 0:\n return str(int(dy / dx))\n else:\n return 'un...
{"fn_name": "find_slope", "inputs": [[[12, -18, -15, -18]], [[3, -20, 5, 8]], [[17, -3, 17, 8]], [[1, -19, -2, -7]], [[19, 3, 20, 3]], [[6, -12, 15, -3]], [[15, -3, 15, -3]], [[9, 3, 19, -17]], [[3, 6, 4, 10]], [[2, 7, 4, -7]], [[1, 24, 2, 88]], [[4, 384, 8, 768]], [[4, 16, 4, 18]], [[7, 28, 9, 64]], [[18, -36, 12, 36]...
introductory
https://www.codewars.com/kata/55a75e2d0803fea18f00009d
def find_slope(points):
4,286
In this Kata, you will be given a number and your task will be to return the nearest prime number. ```Haskell solve(4) = 3. The nearest primes are 3 and 5. If difference is equal, pick the lower one. solve(125) = 127 ``` We'll be testing for numbers up to `1E10`. `500` tests. More examples in test cases. Good lu...
["def solve(n):\n print('starting with {0}'.format(n), flush=True)\n\n def is_prime(p):\n if p % 2 == 0 :\n return False\n for x in range(3,int(p**.5)):\n if p % x == 0:\n return False\n return True\n #return not any([p%x==0 for x in range(3,int(p**...
{"fn_name": "solve", "inputs": [[3], [11], [4], [110], [1110], [3000], [35000], [350000], [3500000], [10000000000]], "outputs": [[3], [11], [3], [109], [1109], [2999], [34981], [350003], [3499999], [10000000019]]}
introductory
https://www.codewars.com/kata/5a9078e24a6b340b340000b8
def solve(n):
4,287
Johnny is a farmer and he annually holds a beet farmers convention "Drop the beet". Every year he takes photos of farmers handshaking. Johnny knows that no two farmers handshake more than once. He also knows that some of the possible handshake combinations may not happen. However, Johnny would like to know the minima...
["from math import ceil\n\ndef get_participants(h):\n return int(ceil(0.5 + (0.25 + 2 * h) ** 0.5))\n", "def get_participants(handshakes, n = 1):\n return get_participants(handshakes, n + 1) if (n * n - n)/2 < handshakes else n", "def get_participants(handshakes):\n from math import ceil\n \n \"\"\"\n ...
{"fn_name": "get_participants", "inputs": [[0], [1], [3], [6], [7]], "outputs": [[1], [2], [3], [4], [5]]}
introductory
https://www.codewars.com/kata/5574835e3e404a0bed00001b
def get_participants(h):
4,288
This is a beginner friendly kata especially for UFC/MMA fans. It's a fight between the two legends: Conor McGregor vs George Saint Pierre in Madison Square Garden. Only one fighter will remain standing, and after the fight in an interview with Joe Rogan the winner will make his legendary statement. It's your job to r...
["statements = {\n 'george saint pierre': \"I am not impressed by your performance.\",\n 'conor mcgregor': \"I'd like to take this chance to apologize.. To absolutely NOBODY!\"\n}\n\ndef quote(fighter):\n return statements[fighter.lower()]", "h = {\n 'george saint pierre': \"I am not impressed by your perfo...
{"fn_name": "quote", "inputs": [["George Saint Pierre"], ["Conor McGregor"], ["george saint pierre"], ["conor mcgregor"]], "outputs": [["I am not impressed by your performance."], ["I'd like to take this chance to apologize.. To absolutely NOBODY!"], ["I am not impressed by your performance."], ["I'd like to take this ...
introductory
https://www.codewars.com/kata/582dafb611d576b745000b74
def quote(fighter):
4,289
# Task Let's say that `"g" is happy` in the given string, if there is another "g" immediately to the right or to the left of it. Find out if all "g"s in the given string are happy. # Example For `str = "gg0gg3gg0gg"`, the output should be `true`. For `str = "gog"`, the output should be `false`. # Input/Output...
["import re\n\ndef happy_g(s):\n return not re.search(r'(?<!g)g(?!g)',s)", "import re\n\ndef happy_g(s):\n return re.sub(\"g{2,}\", \"\", s).count(\"g\") < 1", "import re\n\ndef happy_g(s):\n return not re.search(r'(^|[^g])g([^g]|$)', s)", "import re\ndef happy_g(s):\n return bool(re.match(\"^(g{2,}|[^g])+$\"...
{"fn_name": "happy_g", "inputs": [["gg0gg3gg0gg"], ["gog"], ["ggg ggg g ggg"], ["A half of a half is a quarter."], ["good grief"], ["bigger is ggooder"], ["gggggggggg"]], "outputs": [[true], [false], [false], [true], [false], [true], [true]]}
introductory
https://www.codewars.com/kata/58bcd27b7288983803000002
def happy_g(s):
4,290
Create a program that will return whether an input value is a str, int, float, or bool. Return the name of the value. ### Examples - Input = 23 --> Output = int - Input = 2.3 --> Output = float - Input = "Hello" --> Output = str - Input = True --> Output = bool
["def types(x):\n return type(x).__name__", "def types(x):\n return str(type(x).__name__)", "def types(x):\n return str(type(x))[8:-2]", "types = lambda x: type(x).__name__", "types = lambda d: type(d).__name__", "def types(n):\n return type(n).__name__", "def types(x):\n return str(type(x)).split('\\'')...
{"fn_name": "types", "inputs": [[10], [9.7], ["Hello World!"], [[1, 2, 3, 4]], [1023], [true], ["True"], [{"name": "John", "age": 32}], [null], [3.141], [false], ["8.6"], ["*&^"], [4.5]], "outputs": [["int"], ["float"], ["str"], ["list"], ["int"], ["bool"], ["str"], ["dict"], ["NoneType"], ["float"], ["bool"], ["str"],...
introductory
https://www.codewars.com/kata/55a89dd69fdfb0d5ce0000ac
def types(x):
4,291
# Introduction The first century spans from the **year 1** *up to* and **including the year 100**, **The second** - *from the year 101 up to and including the year 200*, etc. # Task : Given a year, return the century it is in.
["def century(year):\n return (year + 99) // 100", "import math\n\ndef century(year):\n return math.ceil(year / 100)", "def century(year):\n return (year / 100) if year % 100 == 0 else year // 100 + 1", "def century(year):\n if year%100==0:\n return year//100\n else:\n return year//100+1", ...
{"fn_name": "century", "inputs": [[1705], [1900], [1601], [2000], [356], [89]], "outputs": [[18], [19], [17], [20], [4], [1]]}
introductory
https://www.codewars.com/kata/5a3fe3dde1ce0e8ed6000097
def century(year):
4,292
Your boss decided to save money by purchasing some cut-rate optical character recognition software for scanning in the text of old novels to your database. At first it seems to capture words okay, but you quickly notice that it throws in a lot of numbers at random places in the text. For example: ```python string_clea...
["def string_clean(s):\n return ''.join(x for x in s if not x.isdigit())", "import re\n\ndef string_clean(s):\n return re.sub(r'\\d', '', s)", "def string_clean(s):\n return \"\".join(c for c in s if not c.isdigit())", "string_clean = lambda s: __import__('re').sub(r'\\d', '', s)", "def string_clean(s):\n i...
{"fn_name": "string_clean", "inputs": [[""], ["! !"], ["123456789"], ["(E3at m2e2!!)"], ["Dsa32 cdsc34232 csa!!! 1I 4Am cool!"], ["A1 A1! AAA 3J4K5L@!!!"], ["Adgre2321 A1sad! A2A3A4 fv3fdv3J544K5L@"], ["Ad2dsad3ds21 A 1$$s122ad! A2A3Ae24 f44K5L@222222 "], ["33333Ad2dsad3ds21 A3333 1$$s122a!d! A2!A!3Ae$24 f2##222 "]...
introductory
https://www.codewars.com/kata/57e1e61ba396b3727c000251
def string_clean(s):
4,293
You just got done with your set at the gym, and you are wondering how much weight you could lift if you did a single repetition. Thankfully, a few scholars have devised formulas for this purpose (from [Wikipedia](https://en.wikipedia.org/wiki/One-repetition_maximum)) : ### Epley ### McGlothin ### Lombardi Your ...
["def calculate_1RM(w, r):\n if r == 0: return 0\n if r == 1: return w\n \n return round(max([\n w * (1 + r / 30), # Epley\n 100 * w / (101.3 - 2.67123 * r), # McGlothin\n w * r**0.10 # Lombardi\n ]))", "def calculate_1RM(w, r):\n return (\n ...
{"fn_name": "calculate_1RM", "inputs": [[135, 20], [200, 8], [270, 2], [360, 1], [400, 0]], "outputs": [[282], [253], [289], [360], [0]]}
introductory
https://www.codewars.com/kata/595bbea8a930ac0b91000130
def calculate_1RM(w, r):
4,294
Write ```python remove(text, what) ``` that takes in a string ```str```(```text``` in Python) and an object/hash/dict/Dictionary ```what``` and returns a string with the chars removed in ```what```. For example: ```python remove('this is a string',{'t':1, 'i':2}) == 'hs s a string' # remove from 'this is a string' the ...
["def remove(text, what):\n for char in what:\n text = text.replace(char,'',what[char])\n return text", "def remove(text, what):\n for c, n in what.items():\n text = text.replace(c, '', n)\n return text", "def remove(text, what):\n for char, count in list(what.items()):\n text = \"\".join(te...
{"fn_name": "remove", "inputs": [["this is a string", {"t": 1, "i": 2}], ["hello world", {"x": 5, "i": 2}], ["apples and bananas", {"a": 50, "n": 1}], ["a", {"a": 1, "n": 1}], ["codewars", {"c": 5, "o": 1, "d": 1, "e": 1, "w": 1, "z": 1, "a": 1, "r": 1, "s": 1}]], "outputs": [["hs s a string"], ["hello world"], ["pples...
introductory
https://www.codewars.com/kata/564ab935de55a747d7000040
def remove(text, what):
4,295
# Definition **_Balanced number_** is the number that * **_The sum of_** all digits to the **_left of the middle_** digit(s) and the sum of all digits to the **_right of the middle_** digit(s) are **_equal_***. ____ # Task **_Given_** a number, **_Find if it is Balanced or not_** . ____ # Warm-up (Highly recommen...
["def balancedNum(n):\n s = str(n)\n l = (len(s)-1)//2\n same = len(s) < 3 or sum(map(int, s[:l])) == sum(map(int, s[-l:]))\n return \"Balanced\" if same else \"Not Balanced\"\n\nbalanced_num = balancedNum", "def balanced_num(number):\n number = [int(n) for n in str(number)]\n left, right = 0, 0\n \n...
{"fn_name": "balanced_num", "inputs": [[56239814]], "outputs": [["Balanced"]]}
introductory
https://www.codewars.com/kata/5a4e3782880385ba68000018
def balanced_num(number):
4,296
Write a program that outputs the `n` largest elements from a list. Example: ```python largest(2, [7,6,5,4,3,2,1]) # => [6,7] ```
["def largest(n, xs):\n \"Find the n highest elements in a list\"\n \n return sorted(xs)[-n:];", "def largest(n,xs):\n import heapq\n return heapq.nlargest(n,xs)[::-1]", "def largest(n,xs):\n xs.sort()\n return xs[-n:]", "def largest(n,xs):\n list = sorted(xs)\n return list[-n:]", "import heapq\n\ndef largest(...
{"fn_name": "largest", "inputs": [[2, [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]]], "outputs": [[[9, 10]]]}
introductory
https://www.codewars.com/kata/53d32bea2f2a21f666000256
def largest(n,xs):
4,297
Write a function getMean that takes as parameters an array (arr) and 2 integers (x and y). The function should return the mean between the mean of the the first x elements of the array and the mean of the last y elements of the array. The mean should be computed if both x and y have values higher than 1 but less or eq...
["def get_mean(arr,x,y):\n if 1 < x <= len(arr) and 1 < y <= len(arr):\n return (sum(arr[:x])/x+sum(arr[-y:])/y)/2\n return -1", "from operator import truediv\n\n\ndef mean(arr):\n return truediv(sum(arr), len(arr))\n\n\ndef get_mean(arr, x, y):\n if min(x, y) < 2 or max(x, y) > len(arr):\n ret...
{"fn_name": "get_mean", "inputs": [[[1, 3, 2, 4], 2, 3], [[1, 3, 2], 2, 2], [[1, 3, 2, 4], 1, 2], [[1, 3, 2, 4], 2, 8], [[1, -1, 2, -1], 2, 3]], "outputs": [[2.5], [2.25], [-1], [-1], [0]]}
introductory
https://www.codewars.com/kata/583df40bf30065fa9900010c
def get_mean(arr,x,y):
4,298
The internet is a very confounding place for some adults. Tom has just joined an online forum and is trying to fit in with all the teens and tweens. It seems like they're speaking in another language! Help Tom fit in by translating his well-formatted English into n00b language. The following rules should be observed: ...
["import re\nbase = \"too?|fore?|oo|be|are|you|please|people|really|have|know|s|[.,']\".split('|')\nnoob = \"2|4|00|b|r|u|plz|ppl|rly|haz|no|z|\".split('|')\n\ndef n00bify(text):\n for b, n in zip(base, noob):\n keep_casing = lambda m: n.upper() if m.group().isupper() else n\n text = re.sub(b, keep_cas...
{"fn_name": "n00bify", "inputs": [["Hi, how are you today?"], ["I think it would be nice if we could all get along."], ["Let's eat, Grandma!"], ["Woot woot woot woot woot woot!"], ["Hi, I can have cheeseburger?"], ["Sometimes I use ? in the middle of a sentence; is that ok?!"], ["Unto us a child is born."], ["What happ...
introductory
https://www.codewars.com/kata/552ec968fcd1975e8100005a
def n00bify(text):
4,299
A number `n` is called `prime happy` if there is at least one prime less than `n` and the `sum of all primes less than n` is evenly divisible by `n`. Write `isPrimeHappy(n)` which returns `true` if `n` is `prime happy` else `false`.
["def is_prime_happy(n):\n return n in [5, 25, 32, 71, 2745, 10623, 63201, 85868]", "is_prime_happy=lambda n:n>2and(2+sum(p*all(p%d for d in range(3,int(p**.5)+1,2))for p in range(3,n,2)))%n<1", "from itertools import compress\nimport numpy as np\n\ns = np.ones(100000)\ns[:2] = s[4::2] = 0\nfor i in range(3, int(len...
{"fn_name": "is_prime_happy", "inputs": [[5], [8], [25], [32], [2], [0]], "outputs": [[true], [false], [true], [true], [false], [false]]}
introductory
https://www.codewars.com/kata/59b2ae6b1b5ca3ca240000c1
def is_prime_happy(n):
4,300
In this Kata, you will count the number of times the first string occurs in the second. ```Haskell solve("zaz","zazapulz") = 4 because they are ZAZapulz, ZAzapulZ, ZazApulZ, zaZApulZ ``` More examples in test cases. Good luck! Please also try [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9...
["def solve(a, b):\n if len(a) is 1:\n return b.count(a)\n index = [x for x in range(len(b)-1) if b[x] is a[0]]\n return sum(solve(a[1:], b[x+1:]) for x in index)", "def solve(a, b, i=0, j=0):\n return i == len(a) or sum(solve(a,b,i+1,x+1) for x in range(j, len(b)-(len(a)-i-1)) if a[i] == b[x])", "fr...
{"fn_name": "solve", "inputs": [["zaz", "zazapulz"], ["rat", "ratatoulie"], ["kata", "katakatak"], ["code", "codeodecode"], ["kata", "kataxxxxkatak"], ["code", "cozzdezodeczzode"], ["zaaz", "zazaapulz"], ["defg", "dsedsfsgsg"], ["defg", "dvsxvevdvsvfvsvgvsvgg"]], "outputs": [[4], [3], [7], [11], [7], [11], [4], [2], [3...
introductory
https://www.codewars.com/kata/5a942c461a60f677730032df
def solve(a, b):
4,301
The Menger Sponge is a three-dimensional fractal, first described by Karl Menger in 1926. ![Mengers Sponge (Level 0-3)](http://i.imgur.com/V6Rb4Za.jpg) ###### _An illustration of the iterative construction of a Menger sponge_ A method of constructing a Menger Sponge can be visualized as follows: 1. Start from a cube ...
["def calc_ms(n):\n return 20 ** n", "def calc_ms(n):\n return pow(20,n)", "calc_ms = (20).__pow__", "from functools import partial\n\ncalc_ms = partial(pow, 20)", "from functools import partial\nfrom operator import pow\n\ncalc_ms = partial(pow, 20)", "def calc_ms(n):\n a = n * '0'\n return int(str(pow(2, n)) + ...
{"fn_name": "calc_ms", "inputs": [[0], [1], [2], [3], [4], [5], [6]], "outputs": [[1], [20], [400], [8000], [160000], [3200000], [64000000]]}
introductory
https://www.codewars.com/kata/59d28768a25c8c51a6000057
def calc_ms(n):
4,302
There was a test in your class and you passed it. Congratulations! But you're an ambitious person. You want to know if you're better than the average student in your class. You receive an array with your peers' test scores. Now calculate the average and compare your score! ~~~if-not:nasm,racket Return `True` if you'r...
["def better_than_average(class_points, your_points):\n return your_points > sum(class_points) / len(class_points)", "def better_than_average(class_points, your_points):\n average = (sum(class_points) + your_points) / (len(class_points) + 1)\n return your_points > average\n", "import statistics\ndef better_tha...
{"fn_name": "better_than_average", "inputs": [[[2, 3], 5], [[100, 40, 34, 57, 29, 72, 57, 88], 75], [[12, 23, 34, 45, 56, 67, 78, 89, 90], 69]], "outputs": [[true], [true], [true]]}
introductory
https://www.codewars.com/kata/5601409514fc93442500010b
def better_than_average(class_points, your_points):
4,303
## Description The task is described in the title: find the sum of all numbers with the same digits(permutations) **including** duplicates. However, due to the fact that this is a performance edition kata, `num` can go up to `10**10000`. That's a number with 10001 digits(at most). Be sure to use efficient algorithms a...
["from math import factorial as fact\n\ndef sum_arrangements(n):\n s = str(n)\n perms = fact(len(s)-1)\n coefAll = int('1'*len(s))\n return coefAll*perms*sum(map(int,s))", "def sum_arrangements(num):\n import math\n numLength = len(str(num))\n scaleFactor = int(\"1\"*numLength) * math.factorial(n...
{"fn_name": "sum_arrangements", "inputs": [[123], [1185]], "outputs": [[1332], [99990]]}
introductory
https://www.codewars.com/kata/5eb9a92898f59000184c8e34
def sum_arrangements(num):
4,304
Introduction Mr. Safety loves numeric locks and his Nokia 3310. He locked almost everything in his house. He is so smart and he doesn't need to remember the combinations. He has an algorithm to generate new passcodes on his Nokia cell phone. Task Can you crack his numeric locks? Mr. Safety's treasures wait for ...
["def unlock(message): return message.lower().translate(message.maketrans(\"abcdefghijklmnopqrstuvwxyz\",\"22233344455566677778889999\"))", "from string import ascii_lowercase as alc\ndef unlock(message):\n return message.lower().translate(str.maketrans(alc, '22233344455566677778889999'))", "def unlock(message):\n ...
{"fn_name": "unlock", "inputs": [["Nokia"], ["Valut"], ["toilet"], ["waterheater"], ["birdhouse"]], "outputs": [["66542"], ["82588"], ["864538"], ["92837432837"], ["247346873"]]}
introductory
https://www.codewars.com/kata/592c1dfb912f22055b000099
def unlock(message):
4,305
My friend John and I are members of the "Fat to Fit Club (FFC)". John is worried because each month a list with the weights of members is published and each month he is the last on the list which means he is the heaviest. I am the one who establishes the list so I told him: "Don't worry any more, I will modify the or...
["def order_weight(_str):\n return ' '.join(sorted(sorted(_str.split(' ')), key=lambda x: sum(int(c) for c in x)))", "def sum_string(s):\n sum = 0\n for digit in s:\n sum += int(digit)\n return sum\n\ndef order_weight(strng):\n # your code\n initial_list = sorted(strng.split())\n result = \"...
{"fn_name": "order_weight", "inputs": [["103 123 4444 99 2000"], ["2000 10003 1234000 44444444 9999 11 11 22 123"], [""], ["10003 1234000 44444444 9999 2000 123456789"], ["3 16 9 38 95 1131268 49455 347464 59544965313 496636983114762 85246814996697"], ["71899703 200 6 91 425 4 67407 7 96488 6 4 2 7 31064 9 7920 1 34608...
introductory
https://www.codewars.com/kata/55c6126177c9441a570000cc
def order_weight(strng):
4,306
Write a simple function that takes polar coordinates (an angle in degrees and a radius) and returns the equivalent cartesian coordinates (rouded to 10 places). ``` For example: coordinates(90,1) => (0.0, 1.0) coordinates(45, 1) => (0.7071067812, 0.7071067812) ```
["from math import cos, sin, radians\n\ndef coordinates(deg, r, precision=10):\n x, y = r * cos(radians(deg)), r * sin(radians(deg))\n return round(x, precision), round(y, precision)", "from math import cos,sin,radians\n\ndef coordinates(d, r):\n convert = lambda x: round(r*x(radians(d)),10)\n return ( conv...
{"fn_name": "coordinates", "inputs": [[90, 1], [90, 2], [0, 1], [45, 1], [1090, 10000], [-270, 1]], "outputs": [[[0.0, 1.0]], [[0.0, 2.0]], [[1.0, 0.0]], [[0.7071067812, 0.7071067812]], [[9848.0775301221, 1736.4817766693]], [[0.0, 1.0]]]}
introductory
https://www.codewars.com/kata/555f43d8140a6df1dd00012b
def coordinates(degrees, radius):
4,307
Given few numbers, you need to print out the digits that are not being used. Example: ```python unused_digits(12, 34, 56, 78) # "09" unused_digits(2015, 8, 26) # "3479" ``` Note: - Result string should be sorted - The test case won't pass Integer with leading zero
["def unused_digits(*args):\n return \"\".join(number for number in \"0123456789\" if number not in str(args))", "def unused_digits(*l):\n digits_set = set(list(\"0123456789\"))\n test_set = set(\"\".join(str(i) for i in l))\n d = digits_set.difference(test_set)\n r = \"\".join(sorted(d))\n return r",...
{"fn_name": "unused_digits", "inputs": [[12, 34, 56, 78], [2015, 8, 26], [276, 575], [643], [864, 896, 744], [364, 500, 715, 730], [93, 10, 11, 40], [1, 11, 111, 1111, 11111], [9, 87, 654, 3210]], "outputs": [["09"], ["3479"], ["013489"], ["0125789"], ["01235"], ["289"], ["25678"], ["023456789"], [""]]}
introductory
https://www.codewars.com/kata/55de6173a8fbe814ee000061
def unused_digits(*args):
4,308
Implement a function called makeAcronym that returns the first letters of each word in a passed in string. Make sure the letters returned are uppercase. If the value passed in is not a string return 'Not a string'. If the value passed in is a string which contains characters other than spaces and alphabet letters, r...
["def make_acronym(phrase):\n try:\n return ''.join(word[0].upper() if word.isalpha() else 0 for word in phrase.split())\n except AttributeError:\n return 'Not a string'\n except TypeError:\n return 'Not letters'", "from operator import itemgetter\n\ndef make_acronym(phrase):\n if type(...
{"fn_name": "make_acronym", "inputs": [["My aunt sally"], ["Please excuse my dear aunt Sally"], ["How much wood would a woodchuck chuck if a woodchuck could chuck wood"], ["Unique New York"], ["a42"], ["1111"], [64], [[]], [{}], [""]], "outputs": [["MAS"], ["PEMDAS"], ["HMWWAWCIAWCCW"], ["UNY"], ["Not letters"], ["Not ...
introductory
https://www.codewars.com/kata/557efeb04effce569d000022
def make_acronym(phrase):
4,309
# Description: Replace the pair of exclamation marks and question marks to spaces(from the left to the right). A pair of exclamation marks and question marks must has the same number of "!" and "?". That is: "!" and "?" is a pair; "!!" and "??" is a pair; "!!!" and "???" is a pair; and so on.. # Examples ``` re...
["from itertools import groupby\n\ndef replace(s):\n queue, rle = {}, [[i, k, len(list(g))] for i, (k, g) in enumerate(groupby(s))]\n for i, k, l in reversed(rle):\n if l not in queue: queue[l] = {}\n queue[l].setdefault(k, []).append(i)\n for l in queue:\n while sum(map(bool, queue[l].val...
{"fn_name": "replace", "inputs": [["!!?!!?!!?!!?!!!??!!!??!!!??"], ["??!??!??!??!???!!???!!???!!"], ["?!!?!!?!!?!!!??!!!??!!!??!!!??!!!??"]], "outputs": [[" ? ? ?!!?!!! !!! !!! "], [" ! ! !??!??? ??? ??? "], ["? ? ? ?!!! !!! !!! !!!??!!!??"]]}
introductory
https://www.codewars.com/kata/57fb2c822b5314e2bb000027
def replace(s):
4,310
When provided with a String, capitalize all vowels For example: Input : "Hello World!" Output : "HEllO WOrld!" Note: Y is not a vowel in this kata.
["def swap(st):\n tr = str.maketrans('aeiou', 'AEIOU')\n return st.translate(tr);", "def swap(st):\n return \"\".join( c.upper() if c in \"aeiou\" else c for c in st )", "def swap(string_):\n return string_.translate(str.maketrans('aeiou', 'AEIOU'))", "import re\n\ndef swap(st):\n return re.sub(r'[aeiou]', l...
{"fn_name": "swap", "inputs": [["HelloWorld!"], ["Sunday"], ["Codewars"], ["Monday"], ["Friday"], ["abracadabra"]], "outputs": [["HEllOWOrld!"], ["SUndAy"], ["COdEwArs"], ["MOndAy"], ["FrIdAy"], ["AbrAcAdAbrA"]]}
introductory
https://www.codewars.com/kata/5831c204a31721e2ae000294
def swap(st):
4,311
Consider the range `0` to `10`. The primes in this range are: `2, 3, 5, 7`, and thus the prime pairs are: `(2,2), (2,3), (2,5), (2,7), (3,3), (3,5), (3,7),(5,5), (5,7), (7,7)`. Let's take one pair `(2,7)` as an example and get the product, then sum the digits of the result as follows: `2 * 7 = 14`, and `1 + 4 = 5`. W...
["import itertools\n\ndef solve(a, b):\n primes = set([2] + [n for n in range(3, b, 2) if all(n % r for r in range(3, int(n**0.5)+1, 2))])\n return sum( sum(map(int, str(x*y))) in primes for x, y in itertools.combinations_with_replacement([p for p in primes if a <= p < b], 2) )", "from bisect import bisect_left\n...
{"fn_name": "solve", "inputs": [[0, 20], [2, 200], [2, 2000], [1000, 3000], [2000, 5000]], "outputs": [[14], [457], [17705], [12801], [25005]]}
introductory
https://www.codewars.com/kata/59b46276afcda204ed000094
def solve(a, b):
4,312
In this kata, you will write a function that returns the positions and the values of the "peaks" (or local maxima) of a numeric array. For example, the array `arr = [0, 1, 2, 5, 1, 0]` has a peak at position `3` with a value of `5` (since `arr[3]` equals `5`). ~~~if-not:php,cpp,java,csharp The output will be returned...
["def pick_peaks(arr):\n pos = []\n prob_peak = False\n for i in range(1, len(arr)):\n if arr[i] > arr[i-1]:\n prob_peak = i\n elif arr[i] < arr[i-1] and prob_peak:\n pos.append(prob_peak)\n prob_peak = False\n return {'pos':pos, 'peaks':[arr[i] for i in pos]}"...
{"fn_name": "pick_peaks", "inputs": [[[1, 2, 3, 6, 4, 1, 2, 3, 2, 1]], [[3, 2, 3, 6, 4, 1, 2, 3, 2, 1, 2, 3]], [[3, 2, 3, 6, 4, 1, 2, 3, 2, 1, 2, 2, 2, 1]], [[2, 1, 3, 1, 2, 2, 2, 2, 1]], [[2, 1, 3, 1, 2, 2, 2, 2]], [[2, 1, 3, 2, 2, 2, 2, 5, 6]], [[2, 1, 3, 2, 2, 2, 2, 1]], [[1, 2, 5, 4, 3, 2, 3, 6, 4, 1, 2, 3, 3, 4, 5...
introductory
https://www.codewars.com/kata/5279f6fe5ab7f447890006a7
def pick_peaks(arr):
4,313
Your company, [Congo Pizza](http://interesting-africa-facts.com/Africa-Landforms/Congo-Rainforest-Facts.html), is the second-largest online frozen pizza retailer. You own a number of international warehouses that you use to store your frozen pizzas, and you need to figure out how many crates of pizzas you can store at ...
["def box_capacity(length, width, height):\n return (length * 12 // 16) * (width * 12 // 16) * (height * 12 // 16)\n", "def box_capacity(l, w, h):\n return ((l * 3) // 4) * ((w * 3) // 4) * ((h * 3) // 4)\n", "def box_capacity(length, width, height):\n # Your code here.\n length_capacity = (length * 12) // ...
{"fn_name": "box_capacity", "inputs": [[32, 64, 16], [20, 20, 20], [80, 40, 20], [70, 60, 15], [90, 7, 5], [53, 21, 13]], "outputs": [[13824], [3375], [27000], [25740], [1005], [5265]]}
introductory
https://www.codewars.com/kata/5862e7c63f8628a126000e18
def box_capacity(length, width, height):
4,314
# Task In ChessLand there is a small but proud chess bishop with a recurring dream. In the dream the bishop finds itself on an `n × m` chessboard with mirrors along each edge, and it is not a bishop but a ray of light. This ray of light moves only along diagonals (the bishop can't imagine any other types of moves ...
["def chess_bishop_dream(b,p,d,k):\n yq,yr=divmod(p[0]+k*d[0],2*b[0])\n xq,xr=divmod(p[1]+k*d[1],2*b[1])\n return [min(yr, 2*b[0]-yr-1), min(xr, 2*b[1]-xr-1)]", "chess_bishop_dream=lambda b,p,d,k:[c-abs((q+k*e)%(2*c)-c+.5)-.5for c,q,e in zip(b,p,d)]", "def chess_bishop_dream(board_size, init_position, init_dir...
{"fn_name": "chess_bishop_dream", "inputs": [[[3, 7], [1, 2], [-1, 1], 13], [[1, 2], [0, 0], [1, 1], 6], [[2, 2], [1, 0], [1, 1], 12], [[1, 1], [0, 0], [1, -1], 1000000000], [[2, 3], [1, 2], [-1, -1], 41], [[17, 19], [14, 8], [1, -1], 239239], [[17, 19], [16, 18], [1, 1], 239239239]], "outputs": [[[0, 1]], [[0, 1]], [[...
introductory
https://www.codewars.com/kata/5897ea323387497f460001a0
def chess_bishop_dream(board_size, init_position, init_direction, k):
4,315
For all x in the range of integers [0, 2 ** n), let y[x] be the binary exclusive-or of x and x // 2. Find the sum of all numbers in y. Write a function sum_them that, given n, will return the value of the above sum. This can be implemented a simple loop as shown in the initial code. But once n starts getting to highe...
["def sum_them(n):\n return 2 ** (n - 1) * (2 ** n - 1)", "sum_them=lambda n: int('1'*n, 2)*(int('1'*n, 2)+1)//2 if n else 0", "def sum_them(n):\n return 2 ** (n*2-1) - 2 ** (n-1)", "sum_them=lambda n:int(n*'1'+~-n*'0'or'0',2)", "def sum_them(n):\n return 2**n*(2**n-1)>>1", "def sum_them(n):\n return n and i...
{"fn_name": "sum_them", "inputs": [[0], [1], [2], [3], [4]], "outputs": [[0], [1], [6], [28], [120]]}
introductory
https://www.codewars.com/kata/549c7ae26d86c7c3ed000b87
def sum_them(n):
4,316
# Do you speak retsec? You and your friends want to play undercover agents. In order to exchange your *secret* messages, you've come up with the following system: you take the word, cut it in half, and place the first half behind the latter. If the word has an uneven number of characters, you leave the middle at its pr...
["def reverse_by_center(s):n=len(s)//2;return s[-n:]+s[n:-n]+s[:n]", "import re\n\ndef reverse_by_center(s):\n half = len(s) // 2\n return re.sub(\"(.{%s})(.?)(.{%s})\" % (half, half), r\"\\3\\2\\1\", s)", "def reverse_by_center(s):\n q, r = divmod(len(s), 2)\n return s[-q:] + s[q:q+r] + s[:q]", "def revers...
{"fn_name": "reverse_by_center", "inputs": [["secret"], ["agent"], ["raw"], ["onion"]], "outputs": [["retsec"], ["nteag"], ["war"], ["onion"]]}
introductory
https://www.codewars.com/kata/5516ab668915478845000780
def reverse_by_center(s):
4,317
Lеt's create function to play cards. Our rules: We have the preloaded `deck`: ``` deck = ['joker','2♣','3♣','4♣','5♣','6♣','7♣','8♣','9♣','10♣','J♣','Q♣','K♣','A♣', '2♦','3♦','4♦','5♦','6♦','7♦','8♦','9♦','10♦','J♦','Q♦','K♦','A♦', '2♥','3♥','4♥','5♥','6♥','7♥','8♥','9♥','10♥','J♥','Q♥...
["vals='2345678910JQKA'\ndef card_game(card_1, card_2, trump):\n print((card_1, card_2, trump))\n if card_1==card_2: return 'Someone cheats.'\n elif 'joker' in [card_1,card_2]:\n return ['The first card won.', 'The second card won.'][card_1!='joker']\n elif card_1[-1]==card_2[-1]:\n return ['T...
{"fn_name": "card_game", "inputs": [["Q\u2663", "3\u2663", "\u2666"], ["3\u2663", "Q\u2663", "\u2666"], ["5\u2665", "A\u2663", "\u2666"], ["8\u2660", "8\u2660", "\u2663"], ["2\u2666", "A\u2660", "\u2666"], ["A\u2660", "2\u2666", "\u2666"], ["joker", "joker", "\u2666"], ["joker", "10\u2663", "\u2660"], ["10\u2663", "jok...
introductory
https://www.codewars.com/kata/5a3141fe55519e04d90009d8
def card_game(card_1, card_2, trump):
4,318
Write a function that takes two arguments, and returns a new array populated with the elements **that only appear once, in either one array or the other, taken only once**; display order should follow what appears in arr1 first, then arr2: ```python hot_singles([1, 2, 3, 3], [3, 2, 1, 4, 5]) # [4, 5] hot_singles(["ta...
["def hot_singles(arr1, arr2):\n a = []\n for x in arr1 + arr2:\n if x in set(arr1) ^ set(arr2) and x not in a: a.append(x)\n return a", "from collections import OrderedDict\nfrom itertools import chain\n\n\ndef hot_singles(arr1, arr2):\n diff = set(arr1).symmetric_difference(arr2)\n return [a for...
{"fn_name": "hot_singles", "inputs": [[["tartar", "blanket", "domino"], ["blanket"]], [[77, "basketweave"], [78, 42, "basketweave"]], [[100, 45, "ciao"], [100, 2, 3, 45, 5]], [[10, 200, 30], [10, 20, 3, 4, 5, 5, 5, 200]], [[1, 2, 3, 3], [3, 2, 1, 4, 5, 4]]], "outputs": [[["tartar", "domino"]], [[77, 78, 42]], [["ciao",...
introductory
https://www.codewars.com/kata/57475353facb0e7431000651
def hot_singles(arr1, arr2):
4,319
Gigi is a clever monkey, living in the zoo, his teacher (animal keeper) recently taught him some knowledge of "0". In Gigi's eyes, "0" is a character contains some circle(maybe one, maybe two). So, a is a "0",b is a "0",6 is also a "0",and 8 have two "0" ,etc... Now, write some code to count how many "0"s in the tex...
["def countzero(s):\n return sum(1 if c in 'abdegopq069DOPQR' else 2 if c in '%&B8' else 0 for c in s.replace('()', '0'))", "def countzero(string):\n return sum(1 if c in 'abdegopq069DOPQR' else 2 if c in '%&B8' else 0 for c in string) + string.count('()')", "def countzero(string):\n return sum(map(\"abdegopq0...
{"fn_name": "countzero", "inputs": [[""], ["0"], ["0oO0oO"], ["1234567890"], ["abcdefghijklmnopqrstuvwxyz"], ["()"], ["E"], ["aA"], ["BRA"], ["%%"]], "outputs": [[0], [1], [6], [5], [8], [1], [0], [1], [3], [4]]}
introductory
https://www.codewars.com/kata/56c2acc8c44a3ad6e400050a
def countzero(string):
4,320
Write a comparator for a list of phonetic words for the letters of the [greek alphabet](https://en.wikipedia.org/wiki/Greek_alphabet). A comparator is: > *a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is...
["def greek_comparator(lhs, rhs):\n greek_alphabet = [\n 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta',\n 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu',\n 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma',\n 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega']\n l = len(greek_alphabet)\n...
{"fn_name": "greek_comparator", "inputs": [["chi", "chi"]], "outputs": [[0]]}
introductory
https://www.codewars.com/kata/56bc1acf66a2abc891000561
def greek_comparator(lhs, rhs):
4,321
You are the Dungeon Master for a public DnD game at your local comic shop and recently you've had some trouble keeping your players' info neat and organized so you've decided to write a bit of code to help keep them sorted! The goal of this code is to create an array of objects that stores a player's name and contact ...
["import re\n\ndef player_manager(players):\n return players and [ {'player': who, 'contact': int(num)}\n for who,num in re.findall(r'(.+?), (\\d+)(?:, )?', players)] or []", "def player_manager(players):\n return [{'player': a, 'contact': int(b)} for a, b in zip(*[iter(players.split(', ')...
{"fn_name": "player_manager", "inputs": [["a, 5"], ["jane, 801, dave, 123"], ["Amelia, 8165254325, Jessie, 9187162345, Marcus Kaine, 8018273245"], [""], [null]], "outputs": [[[{"player": "a", "contact": 5}]], [[{"player": "jane", "contact": 801}, {"player": "dave", "contact": 123}]], [[{"player": "Amelia", "contact": 8...
introductory
https://www.codewars.com/kata/5b203de891c7469b520000b4
def player_manager(players):
4,322
Chuck has lost count of how many asses he has kicked... Chuck stopped counting at 100,000 because he prefers to kick things in the face instead of counting. That's just who he is. To stop having to count like a mere mortal chuck developed his own special code using the hairs on his beard. You do not need to know the ...
["from re import search\n\n\ndef body_count(code):\n return bool(search(r'(?:[A-Z]\\d){5}\\.-[A-Z]%\\d\\.\\d{2}\\.', code))", "import re\n\npattern = re.compile('A8A8A8A8A8.-A%8.88.'.replace('A', '[A-Z]').replace('8', '[0-9]').replace('.', r'\\.'))\n\ndef body_count(code):\n return bool(pattern.search(code))", "i...
{"fn_name": "body_count", "inputs": [["A6C2E5Z9A4.-F%8.08."], ["PP P6A6T5F5S3.-Z%1.11.hgr"], ["A6A1E3A8M2.-Q%8.88."], ["d G8H1E2O9N3.-W%8.56. f"], ["B4A1D1I8B4.-E%8.76."], ["ffr65A C8K4D9U7V5.-Y%8.00."], [" 76 B2L4D0A8C6.-T%8.90. lkd"], ["B2L4D0A8C6.-T%8.90"], ["B2L4D0AFC6.-T%8.90."], ["B4A1D1I8B4"], ["B4A666...
introductory
https://www.codewars.com/kata/57066ad6cb72934c8400149e
def body_count(code):
4,323
Implement a function which behaves like the uniq command in UNIX. It takes as input a sequence and returns a sequence in which all duplicate elements following each other have been reduced to one instance. Example: ``` ["a", "a", "b", "b", "c", "a", "b", "c"] => ["a", "b", "c", "a", "b", "c"] ```
["from itertools import groupby\n\ndef uniq(seq): \n return [k for k,_ in groupby(seq)]", "def uniq(seq):\n if len(seq) == 0:\n return []\n rez = [seq[0]]\n for i in range(1, len(seq)):\n if seq[i] != rez[-1]:\n rez.append(seq[i])\n return rez", "from itertools import groupby\n\n...
{"fn_name": "uniq", "inputs": [[["a", "a", "b", "b", "c", "a", "b", "c", "c"]], [["a", "a", "a", "b", "b", "b", "c", "c", "c"]], [[]], [["foo"]], [["bar"]], [[""]], [[null, "a", "a"]]], "outputs": [[["a", "b", "c", "a", "b", "c"]], [["a", "b", "c"]], [[]], [["foo"]], [["bar"]], [[""]], [[null, "a"]]]}
introductory
https://www.codewars.com/kata/52249faee9abb9cefa0001ee
def uniq(seq):
4,324
Do you have in mind the good old TicTacToe? Assuming that you get all the data in one array, you put a space around each value, `|` as a columns separator and multiple `-` as rows separator, with something like `["O", "X", " ", " ", "X", " ", "X", "O", " "]` you should be returning this structure (inclusive of new lin...
["def display_board(board, width):\n board = [c.center(3) for c in board]\n rows = [\"|\".join(board[n:n+width]) for n in range(0, len(board), width)]\n return (\"\\n\" + \"-\"*(4*width - 1) + \"\\n\").join(rows)", "def display_board(board, width):\n line = f'\\n{\"-\"*(4*width-1)}\\n'\n return line.join...
{"fn_name": "display_board", "inputs": [[["O", "X", "X", "O"], 2], [["O", "X", " ", " ", "X", " ", "X", "O", " "], 3], [["O", "X", " ", " ", "X", " ", "X", "O", " ", "O"], 5], [["O", "X", " ", " ", "X", " ", "X", "O", " ", "O"], 2], [["1", "2", "3", "4", "5", "1", "2", "3", "4", "5", "1", "2", "3", "4", "5", "1", "2", ...
introductory
https://www.codewars.com/kata/5b817c2a0ce070ace8002be0
def display_board(board, width):
4,325
# Task You are the manager of the famous rescue team: The Knights. Your task is to assign your knights to a rescue missions on an infinite 2D-plane. Your knights can move only by `n-knight` jumps. For example, if a knight has n = 2, they can only move exactly as a knight on a chess board. If n = 3, they can ...
["def knight_rescue(N,x,y):\n return (y - x) % 2 == 0 or any(n % 2 == 0 for n in N)\n", "def knight_rescue(N, x, y):\n return (x - y) % 2 == 0 or any(n % 2 == 0 for n in N)", "def knight_rescue(N,x,y):\n if x%2 == 0 and y%2==0:\n return True if any([i%2!=0 for i in N]) else (True if all([i%2==0 for i in...
{"fn_name": "knight_rescue", "inputs": [[[2], 2, 1], [[1], 10, 10], [[1], 1, 0], [[1, 2], 1, 0], [[1, 2, 3], 456546, 23532], [[1, 5, 3, 7, 9], 7, 8], [[1, 1, 1, 1, 1, 1, 1, 1, 1], 0, 1]], "outputs": [[true], [true], [false], [true], [true], [false], [false]]}
introductory
https://www.codewars.com/kata/58ad0159c9e5b0399b0001b8
def knight_rescue(N,x,y):
4,326
You are given a sequence of a journey in London, UK. The sequence will contain bus **numbers** and TFL tube names as **strings** e.g. ```python ['Northern', 'Central', 243, 1, 'Victoria'] ``` Journeys will always only contain a combination of tube names and bus numbers. Each tube journey costs `£2.40` and each bus jou...
["def london_city_hacker(journey): \n # your code here\n tube = 2.40\n bus = 1.50\n total_cost = 0.00\n count = 0\n for link in journey:\n if isinstance(link, str):\n total_cost += tube\n count = 0\n else:\n if count == 0:\n total_cost += b...
{"fn_name": "london_city_hacker", "inputs": [[[12, "Central", "Circle", 21]], [["Piccidilly", 56]], [["Northern", "Central", "Circle"]], [["Piccidilly", 56, 93, 243]], [[386, 56, 1, 876]], [[]]], "outputs": [["\u00a37.80"], ["\u00a33.90"], ["\u00a37.20"], ["\u00a35.40"], ["\u00a33.00"], ["\u00a30.00"]]}
introductory
https://www.codewars.com/kata/5bce125d3bb2adff0d000245
def london_city_hacker(journey):
4,327
**Story** On some island lives a chameleon population. Chameleons here can be of only one of three colors - red, green and blue. Whenever two chameleons of different colors meet, they can change their colors to a third one (i.e. when red and blue chameleons meet, they can both become green). There is no other way for...
["def chameleon(chameleons, color):\n (_,a), (_,b), (_,c) = sorted((i==color, v) for i,v in enumerate(chameleons))\n return -1 if not a and not c or (b-a) % 3 else b", "def chameleon(chameleons, desiredColor):\n \n color_count = dict(list(zip(['r', 'g', 'b'], chameleons)))\n target = ['r', 'g', 'b'][desi...
{"fn_name": "chameleon", "inputs": [[[0, 0, 17], 1], [[1, 1, 15], 2], [[34, 32, 35], 0], [[34, 32, 35], 1], [[33, 0, 35], 2], [[673905669, 673905681, 174867657], 2], [[74356, 0, 0], 0], [[1, 2147483646, 1], 1], [[0, 1, 0], 2], [[0, 1, 0], 1], [[0, 333, 0], 0]], "outputs": [[-1], [1], [35], [-1], [33], [673905681], [0],...
introductory
https://www.codewars.com/kata/553ba31138239b9bc6000037
def chameleon(chameleons, desiredColor):
4,328
Your friend has invited you to a party, and tells you to meet them in the line to get in. The one problem is it's a masked party. Everyone in line is wearing a colored mask, including your friend. Find which people in line could be your friend. Your friend has told you that he will be wearing a `RED` mask, and has **T...
["def redWith2Blues(i, line):\n return any(line[i-2+x:i+1+x].count('blue')==2 for x in range(3))\n\ndef friend_find(line):\n return sum( p=='red' and redWith2Blues(i,line) for i,p in enumerate(line))", "def friend_find(line):\n N = len(line)\n A = lambda i: line[i] == \"red\" and B(i)\n B = lambda i: C(i...
{"fn_name": "friend_find", "inputs": [[["blue", "blue", "red", "red", "blue", "green"]], [["blue", "red", "blue", "blue", "red", "blue", "red"]], [["brown", "brown", "red", "green"]], [["red", "blue", "blue", "red"]], [["red", "blue"]], [["blue", "green", "red", "green", "blue", "blue", "red"]], [["blue", "blue", "blue...
introductory
https://www.codewars.com/kata/5357edc90d9c5df39a0013bc
def friend_find(line):
4,329
Pig Latin is an English language game where the goal is to hide the meaning of a word from people not aware of the rules. So, the goal of this kata is to wite a function that encodes a single word string to pig latin. The rules themselves are rather easy: 1) The word starts with a vowel(a,e,i,o,u) -> return the orig...
["VOWELS = set('aeiou')\n\ndef pig_latin(st):\n s = st.lower()\n if s.isalpha():\n if set(s) & VOWELS:\n if s[0] in VOWELS:\n s += 'w'\n while s[0] not in VOWELS:\n s = s[1:] + s[:1]\n return s + 'ay'", "def pig_latin(s):\n vowels = ['a', 'e', '...
{"fn_name": "pig_latin", "inputs": [["Hello"], ["CCCC"], ["tes3t5"], ["ay"], [""], ["YA"], ["123"], ["ya1"], ["yaYAya"], ["YayayA"]], "outputs": [["ellohay"], ["ccccay"], [null], ["ayway"], [null], ["ayay"], [null], [null], ["ayayayay"], ["ayayayay"]]}
introductory
https://www.codewars.com/kata/558878ab7591c911a4000007
def pig_latin(s):
4,330
Mrs Jefferson is a great teacher. One of her strategies that helped her to reach astonishing results in the learning process is to have some fun with her students. At school, she wants to make an arrangement of her class to play a certain game with her pupils. For that, she needs to create the arrangement with **the mi...
["def shortest_arrang(n):\n # For odd n, we can always construct n with 2 consecutive integers.\n if n % 2 == 1:\n return [n//2 + 1, n//2]\n\n # For even n, n is the sum of either an odd number or even number of\n # consecutive positive integers. Moreover, this property is exclusive.\n\n for i in ...
{"fn_name": "shortest_arrang", "inputs": [[10], [14], [16], [22], [65]], "outputs": [[[4, 3, 2, 1]], [[5, 4, 3, 2]], [[-1]], [[7, 6, 5, 4]], [[33, 32]]]}
introductory
https://www.codewars.com/kata/59321f29a010d5aa80000066
def shortest_arrang(n):
4,331
Your retro heavy metal band, VÄxën, originally started as kind of a joke, just because why would anyone want to use the crappy foosball table in your startup's game room when they could be rocking out at top volume in there instead? Yes, a joke, but now all the top tech companies are paying you top dollar to play at th...
["UMLAUTS = {'A': '\u00c4', 'E': '\u00cb', 'I': '\u00cf', 'O': '\u00d6', 'U': '\u00dc', 'Y': '\u0178',\n 'a': '\u00e4', 'e': '\u00eb', 'i': '\u00ef', 'o': '\u00f6', 'u': '\u00fc', 'y': '\u00ff'}\n\n\ndef heavy_metal_umlauts(s):\n return ''.join(UMLAUTS.get(a, a) for a in s)", "# -*- coding: utf-8 -*-\ndef ...
{"fn_name": "heavy_metal_umlauts", "inputs": [["Announcing the Macbook Air Guitar"], ["Facebook introduces new heavy metal reaction buttons"], ["Strong sales of Google's VR Metalheadsets send tech stock prices soaring"], ["Vegan Black Metal Chef hits the big time on Amazon TV"]], "outputs": [["\u00c4nn\u00f6\u00fcnc\u0...
introductory
https://www.codewars.com/kata/57d4e99bec16701a67000033
def heavy_metal_umlauts(boring_text):
4,332
*This kata is based on [Project Euler Problem #349](https://projecteuler.net/problem=349). You may want to start with solving [this kata](https://www.codewars.com/kata/langtons-ant) first.* --- [Langton's ant](https://en.wikipedia.org/wiki/Langton%27s_ant) moves on a regular grid of squares that are coloured either b...
["move = [lambda p: (p[0]+1, p[1]), lambda p: (p[0], p[1]+1), lambda p: (p[0]-1, p[1]), lambda p: (p[0], p[1]-1)]\nstart, loop, size = 9977, 104, 12\n\ndef langtons_ant(n):\n pos, d, black, res = (0, 0), 0, set(), 0\n if n > start:\n x = (n - start)%loop\n res = size * (n-start-x)//loop\n n =...
{"fn_name": "langtons_ant", "inputs": [[0], [1], [2], [10], [100], [1000], [10000], [100000], [1000000], [10000000]], "outputs": [[0], [1], [2], [6], [20], [118], [720], [11108], [114952], [1153412]]}
introductory
https://www.codewars.com/kata/5c99553d5c67244b60cb5722
def langtons_ant(n):
4,333
**Introduction**  Little Petya very much likes sequences. However, recently he received a sequence as a gift from his mother.  Petya didn't like it at all! He decided to make a single replacement. After this replacement, Petya would like to the sequence in increasing order.  He asks himself: What is the lowest possible...
["def sort_number(a): \n a = sorted(a)\n return [1]+a if a.pop()!=1 else a+[2]", "def sort_number(a): \n if max(a) != 1:\n a.remove(max(a))\n a.append(1)\n else:\n a.remove(max(a))\n a.append(2)\n \n return sorted(a)\n", "def sort_number(a): \n a = sorted(a)\n m =...
{"fn_name": "sort_number", "inputs": [[[1, 2, 3, 4, 5]], [[4, 2, 1, 3, 5]], [[2, 3, 4, 5, 6]], [[2, 2, 2]], [[42]], [[5, 6, 1, 2, 3, 1, 3, 45, 7, 1000000000]], [[1, 1, 1]], [[1]], [[134]]], "outputs": [[[1, 1, 2, 3, 4]], [[1, 1, 2, 3, 4]], [[1, 2, 3, 4, 5]], [[1, 2, 2]], [[1]], [[1, 1, 1, 2, 3, 3, 5, 6, 7, 45]], [[1, 1...
introductory
https://www.codewars.com/kata/598d89971928a085c000001a
def sort_number(a):
4,334
Your task is to generate the Fibonacci sequence to `n` places, with each alternating value as `"skip"`. For example: `"1 skip 2 skip 5 skip 13 skip 34"` Return the result as a string You can presume that `n` is always a positive integer between (and including) 1 and 64.
["def skiponacci(n):\n s = '1'\n num = 1\n prv = 0\n for i in range(1,n):\n new = num + prv\n prv = num\n num = new\n if i%2 == 0:\n s = s + ' ' + str(num)\n else:\n s += ' skip'\n\n return s", "def skiponacci(n):\n fib = [1, 1][:n]\n for _ i...
{"fn_name": "skiponacci", "inputs": [[1], [5], [7]], "outputs": [["1"], ["1 skip 2 skip 5"], ["1 skip 2 skip 5 skip 13"]]}
introductory
https://www.codewars.com/kata/580777ee2e14accd9f000165
def skiponacci(n):
4,335
What is an anagram? Well, two words are anagrams of each other if they both contain the same letters. For example: ``` 'abba' & 'baab' == true 'abba' & 'bbaa' == true 'abba' & 'abbba' == false 'abba' & 'abca' == false ``` Write a function that will find all the anagrams of a word from a list. You will be given two...
["def anagrams(word, words): return [item for item in words if sorted(item)==sorted(word)]", "from collections import Counter\n\ndef anagrams(word, words):\n counts = Counter(word)\n return [w for w in words if Counter(w) == counts]", "def anagrams(word, words):\n match = sorted(word)\n return [w for w in w...
{"fn_name": "anagrams", "inputs": [["abba", ["aabb", "abcd", "bbaa", "dada"]], ["racer", ["crazer", "carer", "racar", "caers", "racer"]], ["a", ["a", "b", "c", "d"]], ["ab", ["cc", "ac", "bc", "cd", "ab", "ba", "racar", "caers", "racer"]], ["abba", ["a", "b", "c", "d", "aabb", "bbaa", "abab", "baba", "baab", "abcd", "a...
introductory
https://www.codewars.com/kata/523a86aa4230ebb5420001e1
def anagrams(word, words):
4,336
*Shamelessly stolen from Here :)* Your server has sixteen memory banks; each memory bank can hold any number of blocks. You must write a routine to balance the blocks between the memory banks. The reallocation routine operates in cycles. In each cycle, it finds the memory bank with the most blocks (ties won by the lo...
["def mem_alloc(banks):\n seen = set()\n while tuple(banks) not in seen:\n seen.add(tuple(banks))\n number = max(banks)\n index = banks.index(number)\n banks[index] = 0\n while number:\n index = (index + 1) % 16\n banks[index] += 1\n number -= 1\...
{"fn_name": "mem_alloc", "inputs": [[[5, 1, 10, 0, 1, 7, 13, 14, 3, 12, 8, 10, 7, 12, 0, 600]], [[53, 21, 10, 0, 1, 7, 13, 14, 3, 12, 8, 10, 7, 12, 0, 60]], [[14, 21, 10, 0, 1, 7, 0, 14, 3, 12, 8, 10, 17, 12, 0, 19]], [[5, 1, 10, 0, 1, 7, 13, 14, 3, 12, 8, 10, 7, 12, 0, 6]], [[17, 17, 3, 5, 1, 10, 6, 2, 0, 12, 8, 11, 1...
introductory
https://www.codewars.com/kata/5ad927c932d79e34fb000091
def mem_alloc(banks):
4,337
You need to swap the head and the tail of the specified array: the head (the first half) of array moves to the end, the tail (the second half) moves to the start. The middle element (if it exists) leaves on the same position. Return new array. For example: ``` [ 1, 2, 3, 4, 5 ] => [ 4, 5, 3, 1, 2 ] \...
["def swap_head_tail(a):\n r, l = (len(a)+1)//2, len(a)//2\n return a[r:] + a[l:r] + a[:l]", "def swap_head_tail(lst):\n n, d = divmod(len(lst), 2)\n return lst[n+d:] + [lst[n]] * d + lst[:n]", "def swap_head_tail(arr):\n if len(arr) == 1: return arr\n n = len(arr)//2\n res,res2 = arr[:n],arr[-n:]...
{"fn_name": "swap_head_tail", "inputs": [[[-1, 2]], [[1, 2, -3, 4, 5, 6, -7, 8]]], "outputs": [[[2, -1]], [[5, 6, -7, 8, 1, 2, -3, 4]]]}
introductory
https://www.codewars.com/kata/5a34f087c5e28462d9000082
def swap_head_tail(arr):
4,338
# Task Given a square `matrix`, your task is to reverse the order of elements on both of its longest diagonals. The longest diagonals of a square matrix are defined as follows: * the first longest diagonal goes from the top left corner to the bottom right one; * the second longest diagonal goes from the top right cor...
["def reverse_on_diagonals(matrix):\n copy = [ line[:] for line in matrix ]\n for i in range(len(matrix)):\n copy[i][i] = matrix[-1-i][-1-i]\n copy[i][-1-i] = matrix[-1-i][i]\n \n return copy", "def reverse_on_diagonals(matrix):\n l = len(matrix)\n for i in range(l // 2):\n j =...
{"fn_name": "reverse_on_diagonals", "inputs": [[[[1, 2, 3], [4, 5, 6], [7, 8, 9]]], [[[239]]], [[[1, 10], [100, 1000]]], [[[43, 455, 32, 103], [102, 988, 298, 981], [309, 21, 53, 64], [2, 22, 35, 291]]]], "outputs": [[[[9, 2, 7], [4, 5, 6], [3, 8, 1]]], [[[239]]], [[[1000, 100], [10, 1]]], [[[291, 455, 32, 2], [102, 53...
introductory
https://www.codewars.com/kata/5889a6b653ad4a22710000d0
def reverse_on_diagonals(matrix):
4,339
Implement function which will return sum of roots of a quadratic equation rounded to 2 decimal places, if there are any possible roots, else return **None/null/nil/nothing**. If you use discriminant,when discriminant = 0, x1 = x2 = root => return sum of both roots. There will always be valid arguments. Quadratic equa...
["def roots(a,b,c):\n if b**2>=4*a*c:\n return round(-b/a,2)", "def roots(a,b,c):\n import math\n d = b ** 2 - 4 * a * c\n if d > 0:\n return round(-2 * b / (2 * a), 2)\n elif d == 0:\n x = -b / (2 * a)\n return x * 2\n else:\n return None", "def roots(a,b,c):\n r...
{"fn_name": "roots", "inputs": [[1, -35, -23], [6, 0, -24], [-5, 21, 0], [6, 4, 8], [1, 5, -24], [3, 11, 6], [2, 2, 9], [1, -1.6666666666666667, -26], [1, 6, 10], [7, -2, -5], [1, 8, 20], [2, 3, -2], [1, 4, 12], [3, -2, -5], [3, 4, 9], [5, 4, 0], [4, -5, 0], [1, 4, 9], [1, 0, -49], [2, 8, 8], [1, 0, -0.16], [1, 6, 12],...
introductory
https://www.codewars.com/kata/57d448c6ba30875437000138
def roots(a,b,c):
4,340
## Story There are four warriors, they need to go through a dark tunnel. Tunnel is very narrow, every time only can let two warriors through, and there are lot of dangerous traps. Fortunately, they have a lamp that can illuminate the tunnel to avoid being trapped by the trap. In order to pass this tunnel, they need f...
["def shortest_time(speed):\n a,b,c,d = sorted(speed)\n return a+b+d + min(2*b, a+c)", "from itertools import combinations\n\ndef shortest_time(xs, ys=[]):\n if len(xs) == 2:\n return max(xs)\n result = 999999999\n for i, j in combinations(range(len(xs)), 2):\n m = max(xs[i], xs[j])\n ...
{"fn_name": "shortest_time", "inputs": [[[3, 4, 5, 6]], [[3, 7, 10, 18]], [[5, 5, 6, 7]], [[5, 6, 30, 40]]], "outputs": [[21], [41], [27], [63]]}
introductory
https://www.codewars.com/kata/57bff92049324c0fd00012fd
def shortest_time(speed):
4,341
In this Kata, you will be given two positive integers `a` and `b` and your task will be to apply the following operations: ``` i) If a = 0 or b = 0, return [a,b]. Otherwise, go to step (ii); ii) If a ≥ 2*b, set a = a - 2*b, and repeat step (i). Otherwise, go to step (iii); iii) If b ≥ 2*a, set b = b - 2*a, and repeat ...
["def solve(a,b):\n if not (a and b): return [a, b]\n if a >= 2*b: return solve(a%(2*b), b)\n if b >= 2*a: return solve(a, b%(2*a))\n return [a, b]", "def solve(a,b):\n '''\n Used the % operator instead of repeated subtraction of a - 2*b or b - 2*a\n Because as long as a > 2*b, the repeated subtrac...
{"fn_name": "solve", "inputs": [[6, 19], [2, 1], [22, 5], [2, 10], [8796203, 7556], [7, 11], [19394, 19394]], "outputs": [[[6, 7]], [[0, 1]], [[0, 1]], [[2, 2]], [[1019, 1442]], [[7, 11]], [[19394, 19394]]]}
introductory
https://www.codewars.com/kata/5b752a42b11814b09c00005d
def solve(a,b):
4,342
Simple, remove the spaces from the string, then return the resultant string. ~~~if:c For C, you must return a new dynamically allocated string. ~~~
["def no_space(x):\n return x.replace(' ' ,'')", "def no_space(s):\n return s.replace(' ', '')\n", "def no_space(x):\n return \"\".join(x.split())", "def no_space(x):\n str_char = ''\n for i in range(len(x)):\n if x[i] == ' ':\n continue\n else:\n str_char = str_char +...
{"fn_name": "no_space", "inputs": [["8 j 8 mBliB8g imjB8B8 jl B"], ["8 8 Bi fk8h B 8 BB8B B B B888 c hl8 BhB fd"], ["8aaaaa dddd r "], ["jfBm gk lf8hg 88lbe8 "], ["8j aam"]], "outputs": [["8j8mBliB8gimjB8B8jlB"], ["88Bifk8hB8BB8BBBB888chl8BhBfd"], ["8aaaaaddddr"], ["jfBmgklf8hg88lbe8"], ["8jaam"]]}
introductory
https://www.codewars.com/kata/57eae20f5500ad98e50002c5
def no_space(x):
4,343
Some languages like Chinese, Japanese, and Thai do not have spaces between words. However, most natural languages processing tasks like part-of-speech tagging require texts that have segmented words. A simple and reasonably effective algorithm to segment a sentence into its component words is called "MaxMatch". ## Max...
["def max_match(s):\n result = []\n \n while s:\n for size in range(len(s), 0, -1):\n word = s[:size]\n if word in VALID_WORDS:\n break\n \n result.append(word)\n s = s[size:]\n \n return result", "# KenKamau's solution\ndef max_match(st):\...
{"fn_name": "max_match", "inputs": [[""]], "outputs": [[[]]]}
introductory
https://www.codewars.com/kata/5be350bcce5afad8020000d6
def max_match(sentence):
4,344
# Task Imagine `n` horizontal lines and `m` vertical lines. Some of these lines intersect, creating rectangles. How many rectangles are there? # Examples For `n=2, m=2,` the result should be `1`. there is only one 1x1 rectangle. For `n=2, m=3`, the result should be `3`. there are two 1x1 rectangles and one 1x2 r...
["def rectangles(n, m):\n return m * n * (m - 1) * (n - 1) / 4", "def rectangles(n, m):\n return n*m*(n-1)*(m-1)//4", "rectangles=lambda n,m:n*~-n*m*~-m//4", "def rectangles(n, m):\n return ((m-1) * (n-1) * n * m) / 4;", "def rectangles(n, m):\n result = 0\n \n if n < 2 or m < 2:\n return result\...
{"fn_name": "rectangles", "inputs": [[2, 3], [2, 2], [1, 1], [0, 1], [3, 3], [100, 100]], "outputs": [[3], [1], [0], [0], [9], [24502500]]}
introductory
https://www.codewars.com/kata/589a8d9b729e7abd9a0000ed
def rectangles(n, m):
4,345
You will be given a fruit which a farmer has harvested, your job is to see if you should buy or sell. You will be given 3 pairs of fruit. Your task is to trade your harvested fruit back into your harvested fruit via the intermediate pair, you should return a string of 3 actions. if you have harvested apples, you woul...
["def buy_or_sell(pairs, harvested_fruit):\n \n currentFruit = harvested_fruit\n actions = list()\n \n for pair in pairs:\n \n if currentFruit not in pair: return 'ERROR'\n \n if currentFruit == pair[0]:\n \n actions.append('buy')\n currentFruit = pair[1]\...
{"fn_name": "buy_or_sell", "inputs": [[[["apple", "orange"], ["orange", "pear"], ["apple", "pear"]], "apple"], [[["orange", "apple"], ["orange", "pear"], ["pear", "apple"]], "apple"], [[["apple", "orange"], ["pear", "orange"], ["apple", "pear"]], "apple"], [[["orange", "apple"], ["pear", "orange"], ["pear", "apple"]], ...
introductory
https://www.codewars.com/kata/597ab747d1ba5b843f0000ca
def buy_or_sell(pairs, harvested_fruit):
4,346
Maya writes weekly articles to a well known magazine, but she is missing one word each time she is about to send the article to the editor. The article is not complete without this word. Maya has a friend, Dan, and he is very good with words, but he doesn't like to just give them away. He texts Maya a number and she ne...
["hidden=lambda n: \"\".join(\"oblietadnm\"[int(d)] for d in str(n))", "trans = dict(zip('6174329805','abdeilmnot'))\n\ndef hidden(num):\n return ''.join( trans[char] for char in str(num) )", "def hidden(num):\n return str(num).translate(str.maketrans(\"6174329805\", \"abdeilmnot\"))", "def hidden(num):\n d = ...
{"fn_name": "hidden", "inputs": [[637], [7468], [49632], [1425], [6250], [12674], [4735], [7345], [3850], [2394], [2068], [137], [1065], [6509], [3549], [5394], [56124], [968], [103247], [67935], [7415], [2687], [261], [8054], [942547]], "outputs": [["aid"], ["dean"], ["email"], ["belt"], ["alto"], ["blade"], ["edit"],...
introductory
https://www.codewars.com/kata/5906a218dfeb0dbb52000005
def hidden(num):
4,347
# Task Call two arms equally strong if the heaviest weights they each are able to lift are equal. Call two people equally strong if their strongest arms are equally strong (the strongest arm can be both the right and the left), and so are their weakest arms. Given your and your friend's arms' lifting capabilities ...
["def are_equally_strong(your_left, your_right, friends_left, friends_right):\n return sorted([your_left, your_right]) == sorted([friends_left, friends_right])", "def are_equally_strong(yl,yr,fl,fr):\n return (yl==fl and yr==fr) or (yl==fr and yr==fl)", "def are_equally_strong(yl, yr, fl, fr):\n return {yl, yr} ==...
{"fn_name": "are_equally_strong", "inputs": [[10, 15, 15, 10], [15, 10, 15, 10], [10, 10, 10, 10], [15, 10, 15, 9], [10, 5, 5, 10], [1, 10, 10, 0], [10, 5, 11, 4]], "outputs": [[true], [true], [true], [false], [true], [false], [false]]}
introductory
https://www.codewars.com/kata/5894017082b9fb62c50000df
def are_equally_strong(your_left, your_right, friends_left, friends_right):
4,348
Just another day in the world of Minecraft, Steve is getting ready to start his next exciting project -- building a railway system! ![Alt text](http://static.planetminecraft.com/files/resource_media/screenshot/1506/2015-02-02_0156508603066.jpg) But first, Steve needs to melt some iron ores in the furnace to get the m...
["t = ((800, \"lava\"), (120, \"blaze rod\"), (80, \"coal\"), (15, \"wood\"), (1, \"stick\"))\n\n\ndef calc_fuel(n):\n s, r = n * 11, {}\n for d, e in t:\n r[e], s = divmod(s, d)\n return r", "def calc_fuel(n):\n time = n * 11\n lava, blaze = divmod(time, 800)\n blaze, coal = divmod(blaze, 120)...
{"fn_name": "calc_fuel", "inputs": [[37], [21], [123]], "outputs": [[{"lava": 0, "blaze rod": 3, "coal": 0, "wood": 3, "stick": 2}], [{"lava": 0, "blaze rod": 1, "coal": 1, "wood": 2, "stick": 1}], [{"lava": 1, "blaze rod": 4, "coal": 0, "wood": 4, "stick": 13}]]}
introductory
https://www.codewars.com/kata/583a02740b0a9fdf5900007c
def calc_fuel(n):
4,349
One of the first algorithm used for approximating the integer square root of a positive integer `n` is known as "Hero's method", named after the first-century Greek mathematician Hero of Alexandria who gave the first description of the method. Hero's method can be obtained from Newton's method which came 16 centuries ...
["def int_rac(n, guess):\n \"\"\"Integer Square Root of an Integer\"\"\"\n x = guess\n cnt = 1\n while True:\n newx = (x + n // x) // 2 \n if abs(x - newx) < 1:\n return cnt\n x = newx\n cnt += 1", "def int_rac(n, guess):\n cnt = 0\n \n while True:\n cn...
{"fn_name": "int_rac", "inputs": [[25, 1], [125348, 300], [125348981764, 356243], [236, 12], [48981764, 8000], [6999, 700], [16000, 400], [16000, 100], [2500, 60], [250000, 600], [95367431640625, 1], [9094947017729282379150390625, 1], [835871232077058, 1], [246391990316004, 1], [403832254158749, 1], [217414278071071, 1...
introductory
https://www.codewars.com/kata/55efecb8680f47654c000095
def int_rac(n, guess):
4,350
This is the first step to understanding FizzBuzz. Your inputs: a positive integer, n, greater than or equal to one. n is provided, you have NO CONTROL over its value. Your expected output is an array of positive integers from 1 to n (inclusive). Your job is to write an algorithm that gets you from the input to the...
["def pre_fizz(n):\n #your code here\n return list(range(1, n+1))", "def pre_fizz(n):\n return [i + 1 for i in range(0, n)]", "def pre_fizz(n):\n \"\"\"Make a list from 1 to n\"\"\"\n return list(range(1, n+1))", "def pre_fizz(n):\n return [x for x in range(1, n+1)]", "pre_fizz=lambda n: list(range(1,...
{"fn_name": "pre_fizz", "inputs": [[1], [2], [3], [4], [5]], "outputs": [[[1]], [[1, 2]], [[1, 2, 3]], [[1, 2, 3, 4]], [[1, 2, 3, 4, 5]]]}
introductory
https://www.codewars.com/kata/569e09850a8e371ab200000b
def pre_fizz(n):
4,351
Given a string of characters, I want the function `findMiddle()`/`find_middle()` to return the middle number in the product of each digit in the string. Example: 's7d8jd9' -> 7, 8, 9 -> 7\*8\*9=504, thus 0 should be returned as an integer. Not all strings will contain digits. In this case and the case for any non-str...
["from operator import mul\nfrom functools import reduce\n\ndef find_middle(s):\n if not s or not isinstance(s,str): return -1\n \n lstDig = [int(c) for c in s if c.isnumeric()]\n if not lstDig: return -1\n \n prod = str( reduce(mul,lstDig) )\n i = (len(prod) - 1) // 2\n return int(prod[i:-i ...
{"fn_name": "find_middle", "inputs": [["s7d8jd9"], ["58jd9fgh/fgh6s.,sdf"], ["s7d8jd9dfg4d"], ["s7d8j"], ["asd.fasd.gasdfgsdfgh-sdfghsdfg/asdfga=sdfg"], ["44555"], [null], [[1, 2, 3, 4, 5, 6]], [["a", "b", "c"]], ["5d8jd9fgh/fgh6s.,sdf8sdf9sdf98 3 0"], [" "], ["e^6*9=#asdfd7-4"], ["s7d8jd9qwertqwrt v654ed1frg6...
introductory
https://www.codewars.com/kata/5ac54bcbb925d9b437000001
def find_middle(string):
4,352
The most basic encryption method is to map a char to another char by a certain math rule. Because every char has an ASCII value, we can manipulate this value with a simple math expression. For example 'a' + 1 would give us 'b', because 'a' value is 97 and 'b' value is 98. You will need to write a method which does ex...
["def encrypt(text, rule):\n return \"\".join(chr((ord(i)+rule)%256) for i in text)", "def encrypt(text, rule):\n return \"\".join(chr((ord(c) + rule) % 256) for c in text)", "def encrypt(text, key):\n return \"\".join(chr((ord(ch) + key) & 255) for ch in text)", "def encrypt(text, rule):\n return ''.join(c...
{"fn_name": "encrypt", "inputs": [["", 1], ["a", 1], ["please encrypt me", 2]], "outputs": [[""], ["b"], ["rngcug\"gpet{rv\"og"]]}
introductory
https://www.codewars.com/kata/5862fb364f7ab46270000078
def encrypt(text, rule):
4,353
The objective is to disambiguate two given names: the original with another Let's start simple, and just work with plain ascii strings. The function ```could_be``` is given the original name and another one to test against. ```python # should return True if the other name could be the same person > could_be("Chuc...
["def could_be(original, another):\n if not another.strip(): return False\n return all(name in original.split() for name in another.split())", "def could_be(original, another):\n original, another = (set(s.split()) for s in (original, another))\n return bool(another) and another <= original", "def could_be(...
{"fn_name": "could_be", "inputs": [["Carlos Ray Norris", "Carlos Ray Norris"], ["Carlos Ray Norris", "Carlos Ray"], ["Carlos Ray Norris", "Ray Norris"], ["Carlos Ray Norris", "Carlos Norris"], ["Carlos Ray Norris", "Norris"], ["Carlos Ray Norris", "Carlos"], ["Carlos Ray Norris", "Norris Carlos"], ["Carlos Ray Norris",...
introductory
https://www.codewars.com/kata/580a429e1cb4028481000019
def could_be(original, another):
4,354
The Padovan sequence is the sequence of integers `P(n)` defined by the initial values `P(0)=P(1)=P(2)=1` and the recurrence relation `P(n)=P(n-2)+P(n-3)` The first few values of `P(n)` are `1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37, 49, 65, 86, 114, 151, 200, 265, ...` ### Task The task is to write a met...
["def padovan(n):\n p0 = p1 = p2 = 1\n for i in range(n):\n p0, p1, p2 = p1, p2, p0 + p1\n return p0", "from functools import lru_cache\n\n@lru_cache(maxsize=None)\ndef padovan(n):\n return n<3 or padovan(n-2) + padovan(n-3)", "from functools import lru_cache\n\n@lru_cache()\ndef padovan(n):\n ret...
{"fn_name": "padovan", "inputs": [[100]], "outputs": [[1177482265857]]}
introductory
https://www.codewars.com/kata/5803ee0ed5438edcc9000087
def padovan(n):
4,355
## Euler's Method We want to calculate the shape of an unknown curve which starts at a given point with a given slope. This curve satisfies an ordinary differential equation (ODE): ```math \frac{dy}{dx} = f(x, y);\\ y(x_0) = y_0 ``` The starting point `$ A_0 (x_0, y_0) $` is known as well as the slope to the curve ...
["from math import floor, exp\n \ndef ex_euler(n):\n # fct to study\n F = lambda t,y : 2 - exp(-4 * t) - 2 * y\n # initial conditions\n t0 = 0; y0 = 1; # pt A0\n T = 1; \n # variables\n h = T / float(n); X = [t0]; Y = [y0]; Z = []; R = []\n # points A1 ... An\n for k in range(0, n):\n ...
{"fn_name": "ex_euler", "inputs": [[1], [10], [17], [50], [100], [200], [400], [800], [1000], [1200], [1500], [2000]], "outputs": [[0.5], [0.026314], [0.015193], [0.005073], [0.002524], [0.001259], [0.000628], [0.000314], [0.000251], [0.000209], [0.000167], [0.000125]]}
introductory
https://www.codewars.com/kata/56347fcfd086de8f11000014
def ex_euler(n):
4,356
## Problem Determine whether a positive integer number is **colorful** or not. `263` is a colorful number because `[2, 6, 3, 2*6, 6*3, 2*6*3]` are all different; whereas `236` is not colorful, because `[2, 3, 6, 2*3, 3*6, 2*3*6]` have `6` twice. So take all consecutive subsets of digits, take their product and ensur...
["def colorful(number):\n base_result = []\n for x in str(number):\n base_result.append(int(x))\n for y in range(len(base_result) - 1):\n temp = base_result[y] * base_result[y + 1]\n base_result.append(temp)\n # Should you really eval the last value ? :shrug: If so, would use eval\n ...
{"fn_name": "colorful", "inputs": [[5], [23], [263], [235789], [50], [13], [236], [2357893]], "outputs": [[true], [true], [true], [true], [false], [false], [false], [false]]}
introductory
https://www.codewars.com/kata/5441310626bc6a1e61000f2c
def colorful(number):
4,357
# 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* , **_Find_** *the Nth smallest element in this array of integers* ___ # Notes * **_Array/list_** size is...
["def nth_smallest(arr, pos):\n return sorted(arr)[pos-1] # Gotta love Python", "def nth_smallest(arr, pos):\n return sorted(arr)[pos-1]", "from heapq import nsmallest\ndef nth_smallest(arr, pos):\n return nsmallest(pos, arr)[-1]", "def nth_smallest(arr, pos):\n arr.sort()\n return arr[pos-1]", "\"\"\"\n...
{"fn_name": "nth_smallest", "inputs": [[[3, 1, 2], 2], [[15, 20, 7, 10, 4, 3], 3], [[-5, -1, -6, -18], 4], [[-102, -16, -1, -2, -367, -9], 5], [[2, 169, 13, -5, 0, -1], 4]], "outputs": [[2], [7], [-1], [-2], [2]]}
introductory
https://www.codewars.com/kata/5a512f6a80eba857280000fc
def nth_smallest(arr, pos):
4,358
You are given a length of string and two thumbtacks. On thumbtack goes into the focus point *F₀* with coordinates *x₀* and *y₀*, and the other does into point *F₁* with points *x₁* and *y₁*. The string is then tied at the ends to the thumbtacks and has length *l* excluding the knots at the ends. If you pull the string ...
["dist = lambda p1, p2: ((p1['x']-p2['x'])**2+(p1['y']-p2['y'])**2)**0.5\nellipse_contains_point = lambda f0, f1, l, p : dist(p, f0)+dist(p, f1)<=l", "from math import hypot\n\ndef ellipse_contains_point(f0, f1, l, p): \n d0 = hypot(f0[\"x\"] - p[\"x\"], f0[\"y\"] - p[\"y\"])\n d1 = hypot(f1[\"x\"] - p[\"x\"], f1...
{"fn_name": "ellipse_contains_point", "inputs": [[{"x": 0, "y": 0}, {"x": 0, "y": 0}, 2, {"x": 0, "y": 0}], [{"x": 0, "y": 0}, {"x": 0, "y": 0}, 2, {"x": 1, "y": 1}]], "outputs": [[true], [false]]}
introductory
https://www.codewars.com/kata/5b01abb9de4c7f3c22000012
def ellipse_contains_point(f0, f1, l, p):
4,359
Speedcubing is the hobby involving solving a variety of twisty puzzles, the most famous being the 3x3x3 puzzle or Rubik's Cube, as quickly as possible. In the majority of Speedcubing competitions, a Cuber solves a scrambled cube 5 times, and their result is found by taking the average of the middle 3 solves (ie. the s...
["def cube_times(times):\n return (round((sum(times) - (min(times) + max(times)))/3 , 2), min(times))", "def cube_times(times):\n times = sorted(times)\n return (round(sum(times[1:-1])/3,2), times[0])", "from statistics import mean\n\ndef cube_times(times):\n return (round(mean(sorted(times)[1:4]), 2), min(...
{"fn_name": "cube_times", "inputs": [[[9.5, 7.6, 11.4, 10.5, 8.1]], [[13.4, 12.3, 9.5, 11.9, 20.8]], [[28.3, 14.5, 17.3, 8.9, 10.1]]], "outputs": [[[9.37, 7.6]], [[12.53, 9.5]], [[13.97, 8.9]]]}
introductory
https://www.codewars.com/kata/5d7c7697e8ad48001e642964
def cube_times(times):
4,360
Have a look at the following numbers. ``` n | score ---+------- 1 | 50 2 | 150 3 | 300 4 | 500 5 | 750 ``` Can you find a pattern in it? If so, then write a function `getScore(n)`/`get_score(n)`/`GetScore(n)` which returns the score for any positive number `n`: ```c++ int getScore(1) = return 50; int getS...
["def get_score(n):\n return n * (n + 1) * 25", "def get_score(n):\n return 50*(n*(n+1))/2\n \n \n \n", "get_score = lambda n: 25 * n * (n + 1)", "get_score = lambda n, a=0: sum(a+i*50 for i in range(n+1))", "def get_score(n):\n return sum([x*50 for x in range(n+1)])", "def get_score(n):\n return 2...
{"fn_name": "get_score", "inputs": [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [20], [30], [100], [123], [1000], [1234], [10000], [12345]], "outputs": [[50], [150], [300], [500], [750], [1050], [1400], [1800], [2250], [2750], [10500], [23250], [252500], [381300], [25025000], [38099750], [2500250000], [381028425...
introductory
https://www.codewars.com/kata/5254bd1357d59fbbe90001ec
def get_score(n):
4,361
There are some perfect squares with a particular property. For example the number ```n = 256``` is a perfect square, its square root is ```16```. If we change the position of the digits of n, we may obtain another perfect square``` 625``` (square root = 25). With these three digits ```2```,```5``` and ```6``` we can ge...
["from itertools import count, permutations\n\ndef next_perfectsq_perm(limit_below, k):\n for n in count(int(limit_below**.5)+1):\n s = str(n**2)\n if '0' not in s:\n sq_set = {x for x in (int(''.join(p)) for p in permutations(s)) if (x**.5).is_integer()}\n if len(sq_set) == k:\n ...
{"fn_name": "next_perfectsq_perm", "inputs": [[100, 2], [100, 3], [100, 4], [500, 2], [1000, 3], [100000, 4], [144, 2], [145, 2], [440, 2], [441, 2], [257, 2]], "outputs": [[441], [961], [81796], [625], [9216], [298116], [625], [625], [441], [625], [441]]}
introductory
https://www.codewars.com/kata/5b2cd515553292a4ff0000c2
def next_perfectsq_perm(lower_limit, k):
4,362
A little weird green frog speaks in a very strange variation of English: it reverses sentence, omitting all puntuation marks `, ; ( ) - ` except the final exclamation, question or period. We urgently need help with building a proper translator. To simplify the task, we always use lower-case letters. Apostrophes are fo...
["import re\n\ndef frogify(s):\n return ' '.join( ' '.join(re.findall(r'[a-z]+', sentence)[::-1]) + punct for sentence,punct in re.findall(r'(.*?)([.!?])', s) )", "import re\n\ndef frogify(s):\n delimiters = set([\".\", \"!\", \"?\"])\n sentences = re.split(\"([\\!\\.\\?])\", re.sub(\"[,\\;\\)\\(-]\", \"\", s)...
{"fn_name": "frogify", "inputs": [["i am a frog."], ["can you do it?"], ["seems like you understand!"], ["multisentence is good. is not it?"], ["green, red or orange - we all just frogs, do not you think so?"]], "outputs": [["frog a am i."], ["it do you can?"], ["understand you like seems!"], ["good is multisentence. i...
introductory
https://www.codewars.com/kata/59f6d96d27402f9329000081
def frogify(s):
4,363
Take a sentence (string) and reverse each word in the sentence. Do not reverse the order of the words, just the letters in each word. If there is punctuation, it should be interpreted as a regular character; no special rules. If there is spacing before/after the input string, leave them there. String will not be emp...
["def reverser(sentence):\n return ' '.join(i[::-1] for i in sentence.split(' '))", "def reverser(s):\n return \" \".join(w[::-1] for w in s.split(\" \"))", "import re\ndef reverser(sentence):\n return ''.join(w[::-1] if ' ' not in w else w for w in re.findall(r'(?:\\w+)|(?:\\s+)', sentence)) ", "from re impo...
{"fn_name": "reverser", "inputs": [["How now brown cow"], ["racecar"], ["Hi mom"], [" "], [" "], ["go away"], ["I like noodles"], ["The red pen wrote on the wall"], ["Green trucks drive fast"], ["Pink trucks drive slow"]], "outputs": [["woH won nworb woc"], ["racecar"], ["iH mom"], [" "], [" "], ["og yawa"], ["I ekil...
introductory
https://www.codewars.com/kata/57ebdf944cde58f973000405
def reverser(sentence):
4,364
# Task: Given a list of numbers, determine whether the sum of its elements is odd or even. Give your answer as a string matching `"odd"` or `"even"`. If the input array is empty consider it as: `[0]` (array with a zero). ## Example: ``` odd_or_even([0]) == "even" odd_or_even([0, 1, 4]) == "odd" odd_or...
["def odd_or_even(arr):\n return 'even' if sum(arr) % 2 == 0 else 'odd'", "def odd_or_even(arr):\n if sum(arr)%2==0:\n return 'even'\n else:\n return 'odd'", "def odd_or_even(arr):\n return ('even', 'odd')[sum(arr) % 2]", "def odd_or_even(arr):\n return ['even','odd'][sum(arr)%2]", "def odd...
{"fn_name": "odd_or_even", "inputs": [[[0, 1, 2]], [[0, 1, 3]], [[1023, 1, 2]]], "outputs": [["odd"], ["even"], ["even"]]}
introductory
https://www.codewars.com/kata/5949481f86420f59480000e7
def odd_or_even(arr):