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,164
Write a function named `first_non_repeating_letter` that takes a string input, and returns the first character that is not repeated anywhere in the string. For example, if given the input `'stress'`, the function should return `'t'`, since the letter *t* only occurs once in the string, and occurs first in the string. ...
["def first_non_repeating_letter(string):\n string_lower = string.lower()\n for i, letter in enumerate(string_lower):\n if string_lower.count(letter) == 1:\n return string[i]\n \n return \"\"", "from collections import Counter\ndef first_non_repeating_letter(string):\n cnt = Cou...
{"fn_name": "first_non_repeating_letter", "inputs": [["a"], ["stress"], ["moonmen"], [""], ["abba"], ["aa"], ["~><#~><"], ["hello world, eh?"], ["sTreSS"], ["Go hang a salami, I'm a lasagna hog!"]], "outputs": [["a"], ["t"], ["e"], [""], [""], [""], ["#"], ["w"], ["T"], [","]]}
introductory
https://www.codewars.com/kata/52bc74d4ac05d0945d00054e
def first_non_repeating_letter(string):
4,165
You'll be given a string, and have to return the total of all the unicode characters as an int. Should be able to handle any characters sent at it. examples: uniTotal("a") == 97 uniTotal("aaa") == 291
["def uni_total(string):\n return sum(map(ord, string))", "def uni_total(s):\n return sum(ord(c) for c in s)\n", "def uni_total(string):\n return sum(ord(c) for c in string)", "def uni_total(string):\n return sum(ord(x) for x in string)", "def uni_total(string):\n return sum([ord(i) for i in string])\n",...
{"fn_name": "uni_total", "inputs": [["a"], ["b"], ["c"], [""], ["aaa"], ["abc"], ["Mary Had A Little Lamb"], ["Mary had a little lamb"], ["CodeWars rocks"], ["And so does Strive"]], "outputs": [[97], [98], [99], [0], [291], [294], [1873], [2001], [1370], [1661]]}
introductory
https://www.codewars.com/kata/572b6b2772a38bc1e700007a
def uni_total(string):
4,166
Consider the following well known rules: - A number is divisible by 3 if the sum of its digits is divisible by 3. Let's call '3' a "1-sum" prime - For 37, we take numbers in groups of threes from the right and check if the sum of these groups is divisible by 37. Example: 37 * 123456787 = 4567901119 => 4 + 567 + 901...
["import math\n\ndef divisors(n):\n divs = [1]\n for i in range(2,int(math.sqrt(n))+1):\n if n%i == 0:\n divs.extend([i,n//i])\n divs.extend([n])\n return list(set(divs))\n\ndef solve(p):\n for d in sorted(divisors(p-1)):\n if pow(10, d, p) == 1:\n return \"{}-sum\".fo...
{"fn_name": "solve", "inputs": [[3], [7], [11], [13], [37], [47], [73], [239], [376049], [999883], [24701723], [45939401]], "outputs": [["1-sum"], ["3-altsum"], ["1-altsum"], ["3-altsum"], ["3-sum"], ["23-altsum"], ["4-altsum"], ["7-sum"], ["47006-altsum"], ["499941-sum"], ["12350861-sum"], ["11484850-altsum"]]}
introductory
https://www.codewars.com/kata/5cfe4465ac68b86026b09c77
def solve(p):
4,167
# Task A range-collapse representation of an array of integers looks like this: `"1,3-6,8"`, where `3-6` denotes the range from `3-6`, i.e. `[3,4,5,6]`. Hence `"1,3-6,8"` = `[1,3,4,5,6,8]`. Some other range-collapse representations of `[1,3,4,5,6,8]` include `"1,3-5,6,8", "1,3,4,5,6,8", etc`. Each range is writt...
["def descriptions(arr):\n return 2**sum(a+1==b for a,b in zip(arr,arr[1:]))", "\ndef pair_apply(a, fn): \n \"\"\"\n Apply a funtion to each pair of consecutive \n values in the array and return the resultant array\n \"\"\"\n return [fn(x, y) for x, y in zip(a, a[1:])]\n\ndef run_length_encode(a):\n ...
{"fn_name": "descriptions", "inputs": [[[1, 3, 4, 5, 6, 8]], [[1, 2, 3]], [[11, 43, 66, 123]], [[3, 4, 5, 8, 9, 10, 11, 23, 43, 66, 67]]], "outputs": [[8], [4], [1], [64]]}
introductory
https://www.codewars.com/kata/589d6bc33b368ea992000035
def descriptions(arr):
4,168
Implement a function which takes a string, and returns its hash value. Algorithm steps: * `a` := sum of the ascii values of the input characters * `b` := sum of every difference between the consecutive characters of the input (second char minus first char, third minus second, ...) * `c` := (`a` OR `b`) AND ((NOT `a`)...
["def string_hash(s):\n a = sum(ord(c) for c in s)\n b = sum(ord(b) - ord(a) for a, b in zip(s, s[1:]))\n c = (a | b) & (~a << 2)\n return c ^ (32 * (s.count(\" \") + 1))\n", "def string_hash(s):\n a, b = sum(ord(x) for x in s), sum(ord(y) - ord(x) for x, y in zip(s, s[1:]))\n return (a | b) & (~a << ...
{"fn_name": "string_hash", "inputs": [["int main(int argc, char *argv[]) { return 0; }"], [" Yo - What's Good?! "], [" df af asd "], ["global hash"], ["section .text"], ["hash:"], [" xor eax, eax"], [" ret"], ["; -----> end of hash <-----"], ["int hash(const char *str);"], [""], [" "], [" "], [" "], [" "]],...
introductory
https://www.codewars.com/kata/596d93bd9b6a5df4de000049
def string_hash(s):
4,169
### Task: Your job is to take a pair of parametric equations, passed in as strings, and convert them into a single rectangular equation by eliminating the parameter. Both parametric halves will represent linear equations of x as a function of time and y as a function of time respectively. The format of the final equ...
["from fractions import gcd\nimport re\n\n\nINSERTER = re.compile(r'(?<!\\d)(?=[xyt])')\nFINDER = re.compile(r'-?\\d+')\n\n\ndef lcm(a,b): return a*b//gcd(a,b)\ndef simplify(s): return INSERTER.sub('1', s.replace(' ',''))\n\n\ndef para_to_rect(*equations):\n coefs = [ list(map(int, FINDER.findall(eq))) for eq i...
{"fn_name": "para_to_rect", "inputs": [["x = 12t + 18", "y = 8t + 7"], ["x = -12t + 18", "y = 8t + 7"], ["x = 12t + 18", "y = -8t + 7"], ["x = -12t + 18", "y = -8t + 7"], ["x = -t + 12", "y = 12t - 1"], ["x = -12t - 18", "y = 8t - 7"], ["x = -12t + 18", "y = 8t - 7"], ["x = -18t + 12", "y = 7t - 8"], ["x = 18t + 12", "...
introductory
https://www.codewars.com/kata/5b13530f828fab68820000c4
def para_to_rect(eqn1, eqn2):
4,170
Given an D-dimension array, where each axis is of length N, your goal is to find the sum of every index in the array starting from 0. For Example if D=1 and N=10 then the answer would be 45 ([0,1,2,3,4,5,6,7,8,9]) If D=2 and N = 3 the answer is 18 which would be the sum of every number in the following: ```python [ [(...
["def super_sum(D, N):\n #Number of possible combinations of D length from set [0...N]\n num = pow(N,D)\n #2x average value of a combination; 2x because dividing results in float and loss of precision\n dblAvg = D*(N-1)\n #Multiply number of possible combinations by the avergae value; now use true divisi...
{"fn_name": "super_sum", "inputs": [[2, 2], [2, 3], [3, 2], [3, 3], [1, 101], [10, 10], [10, 11], [11, 10], [11, 11], [15, 8], [19, 84], [17, 76]], "outputs": [[4], [18], [12], [81], [5050], [450000000000], [1296871230050], [4950000000000], [15692141883605], [1847179534663680], [2871495452512585452340652014195036913664...
introductory
https://www.codewars.com/kata/5966ec8e62d030d8530000a7
def super_sum(D, N):
4,171
**This Kata is intended as a small challenge for my students** All Star Code Challenge #16 Create a function called noRepeat() that takes a string argument and returns a single letter string of the **first** not repeated character in the entire string. ``` haskell noRepeat "aabbccdde" `shouldBe` 'e' noRepeat "wxyz" ...
["def no_repeat(s):\n return next(c for c in s if s.count(c) == 1)", "def no_repeat(string):\n return [x for x in string if string.count(x) == 1][0]", "from collections import Counter\n\n# Only work in 3.6+ because dicts are ordered\ndef no_repeat(string):\n return next(k for k,v in Counter(string).items() if ...
{"fn_name": "no_repeat", "inputs": [["aabbccdde"], ["wxyz"], ["testing"], ["codewars"], ["Testing"]], "outputs": [["e"], ["w"], ["e"], ["c"], ["T"]]}
introductory
https://www.codewars.com/kata/586566b773bd9cbe2b000013
def no_repeat(string):
4,172
Given a string, return the minimal number of parenthesis reversals needed to make balanced parenthesis. For example: ```Javascript solve(")(") = 2 Because we need to reverse ")" to "(" and "(" to ")". These are 2 reversals. solve("(((())") = 1 We need to reverse just one "(" parenthesis to make it balanced. solve("(...
["def solve(s):\n t = None\n while t != s:\n t, s = s, s.replace('()', '')\n return -1 if len(s) % 2 else sum(1 + (a == tuple(')(')) for a in zip(*[iter(s)] * 2))", "class Stack:\n def __init__(self):\n self.items = []\n\n def is_empty(self):\n return self.items == []\n\n def push...
{"fn_name": "solve", "inputs": [[")()("], ["((()"], ["((("], ["())((("], ["())()))))()()("]], "outputs": [[2], [1], [-1], [3], [4]]}
introductory
https://www.codewars.com/kata/5a3f2925b6cfd78fb0000040
def solve(s):
4,173
[Langton's ant](https://en.wikipedia.org/wiki/Langton%27s_ant) is a two-dimensional Turing machine invented in the late 1980s. The ant starts out on a grid of black and white cells and follows a simple set of rules that has complex emergent behavior. ## Task Complete the function and return the `n`th iteration of Lan...
["BLACK = 0\nWHITE = 1\n# N, E, S, W\nCARDINALS = [(-1, 0), (0, 1), (1, 0), (0, -1)]\n\ndef ant(grid, column, row, n, direction=0):\n r, c, d = row, column, direction\n for _ in range(n):\n # Handle direction change and current cell colour flip\n if grid[r][c] == BLACK:\n grid[r][c] = WHI...
{"fn_name": "ant", "inputs": [[[[1]], 0, 0, 1, 0], [[[0]], 0, 0, 1, 0], [[[1]], 0, 0, 3, 0], [[[1]], 0, 0, 1]], "outputs": [[[[0, 0]]], [[[0, 1]]], [[[0, 1], [0, 1]]], [[[0, 0]]]]}
introductory
https://www.codewars.com/kata/58e6996019af2cff71000081
def ant(grid, column, row, n, direction = 0):
4,174
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. Task: Write ``` smallest(n) ``` that will find the smallest positive number that is evenly divisible by all of the numbers from 1 to n (n <= 40). E.g ```python smallest(5) == 60 # 1 to 5 can all divide evenly int...
["def smallest(n):\n x, y, m = 1, 1, 1\n while m <= n:\n if x % m == 0:\n m += 1\n y = int(x)\n else:\n x += y\n return x\n", "from functools import reduce\nfrom math import gcd\nlcm = lambda x,y: x*y//gcd(x, y)\n\n# Note: there is a lcm function in numpy 1.17 but...
{"fn_name": "smallest", "inputs": [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20]], "outputs": [[1], [2], [6], [12], [60], [60], [420], [840], [2520], [2520], [27720], [27720], [360360], [360360], [360360], [720720], [12252240], [12252240], [232792560], [23...
introductory
https://www.codewars.com/kata/55e7d9d63bdc3caa2500007d
def smallest(n):
4,175
Write a function named `repeater()` that takes two arguments (a string and a number), and returns a new string where the input string is repeated that many times. ## Example: should return
["def repeater(string, n):\n return string * n\n", "repeater=str.__mul__", "repeater=lambda s,n:s*n", "def repeater(string, n):\n counter = 0\n new_string = ''\n while(counter < n):\n counter += 1\n new_string = new_string + string\n return new_string", "repeater = lambda a,n : a*n", "def r...
{"fn_name": "repeater", "inputs": [["a", 5], ["Na", 16], ["Wub ", 6]], "outputs": [["aaaaa"], ["NaNaNaNaNaNaNaNaNaNaNaNaNaNaNaNa"], ["Wub Wub Wub Wub Wub Wub "]]}
introductory
https://www.codewars.com/kata/585a1a227cb58d8d740001c3
def repeater(string, n):
4,176
It's your Birthday. Your colleagues buy you a cake. The numbers of candles on the cake is provided (x). Please note this is not reality, and your age can be anywhere up to 1,000. Yes, you would look a mess. As a surprise, your colleagues have arranged for your friend to hide inside the cake and burst out. They pretend...
["cake=lambda c,d:['That was close!','Fire!'][c!=0and c*0.7<sum(ord(e)-96*(i%2!=0)for i,e in enumerate(d))]", "def cake(candles,debris):\n return 'Fire!' if candles and sum(ord(c) if i%2==0 else ord(c)-96 for i,c in enumerate(debris))>candles*0.7 else 'That was close!'", "def cake(candles,debris):\n s = sum(ord(c...
{"fn_name": "cake", "inputs": [[900, "abcdef"], [56, "ifkhchlhfd"], [256, "aaaaaddddr"], [333, "jfmgklfhglbe"], [12, "jaam"], [808, "alfbpmmpz"], [660, "zyxsqwh"], [651, "hmgoltyy"], [349, "nxls"], [958, "hovzfsxbmwu"], [301, "doda"], [383, "zwwl"], [871, "gnlyvknjga"], [583, "slhacx"], [0, "jpipe"]], "outputs": [["Tha...
introductory
https://www.codewars.com/kata/5805ed25c2799821cb000005
def cake(candles,debris):
4,177
# Scenario *Now that the competition gets tough it will* **_Sort out the men from the boys_** . **_Men_** are the **_Even numbers_** and **_Boys_** are the **_odd_** ![!alt](https://i.imgur.com/mdX8dJP.png) ![!alt](https://i.imgur.com/mdX8dJP.png) ___ # Task **_Given_** an *array/list [] of n integers* , **_Se...
["def men_from_boys(arr):\n men = []\n boys = []\n for i in sorted(set(arr)):\n if i % 2 == 0:\n men.append(i)\n else:\n boys.append(i)\n return men + boys[::-1]", "def men_from_boys(arr):\n return sorted(set(arr), key=lambda n: (n%2, n * (-1)**(n%2)))", "def men_from_...
{"fn_name": "men_from_boys", "inputs": [[[7, 3, 14, 17]], [[2, 43, 95, 90, 37]], [[20, 33, 50, 34, 43, 46]], [[82, 91, 72, 76, 76, 100, 85]], [[2, 15, 17, 15, 2, 10, 10, 17, 1, 1]], [[-32, -39, -35, -41]], [[-64, -71, -63, -66, -65]], [[-94, -99, -100, -99, -96, -99]], [[-53, -26, -53, -27, -49, -51, -14]], [[-17, -45,...
introductory
https://www.codewars.com/kata/5af15a37de4c7f223e00012d
def men_from_boys(arr):
4,178
# 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 of integers_** , **_Find the minimum sum_** which is obtained *from summing each Two integers product* . ___ # Notes * **_Ar...
["def min_sum(arr):\n arr = sorted(arr)\n return sum(arr[i]*arr[-i-1] for i in range(len(arr)//2))", "def min_sum(arr):\n arr.sort()\n left, right, res = 0, len(arr) - 1, 0\n while left < right:\n res += arr[left] * arr[right]\n left += 1\n right -= 1\n return res", "def min_sum(a...
{"fn_name": "min_sum", "inputs": [[[5, 4, 2, 3]], [[12, 6, 10, 26, 3, 24]], [[9, 2, 8, 7, 5, 4, 0, 6]]], "outputs": [[22], [342], [74]]}
introductory
https://www.codewars.com/kata/5a523566b3bfa84c2e00010b
def min_sum(arr):
4,179
With a friend we used to play the following game on a chessboard (8, rows, 8 columns). On the first row at the *bottom* we put numbers: `1/2, 2/3, 3/4, 4/5, 5/6, 6/7, 7/8, 8/9` On row 2 (2nd row from the bottom) we have: `1/3, 2/4, 3/5, 4/6, 5/7, 6/8, 7/9, 8/10` On row 3: `1/4, 2/5, 3/6, 4/7, 5/8, 6/9, 7/10, 8/11`...
["def game(n):\n return [n * n // 2] if n % 2 == 0 else [n * n, 2]", "'''\n n t(i) n-1 (n + i + 1) * (n - i)\ns(n) = \u03a3 ----- + \u03a3 ---------------------\n i=1 i + 1 i=1 2 * (n + i + 1)\n\n n i n-1 n - i\n = \u03a3 --- + \u03a3 -----\n ...
{"fn_name": "game", "inputs": [[0], [1], [8], [40], [101], [204], [807], [1808], [5014], [120000], [750000], [750001], [3000000], [3000001]], "outputs": [[[0]], [[1, 2]], [[32]], [[800]], [[10201, 2]], [[20808]], [[651249, 2]], [[1634432]], [[12570098]], [[7200000000]], [[281250000000]], [[562501500001, 2]], [[45000000...
introductory
https://www.codewars.com/kata/55ab4f980f2d576c070000f4
def game(n):
4,180
Your task is to write an update for a lottery machine. Its current version produces a sequence of random letters and integers (passed as a string to the function). Your code must filter out all letters and return **unique** integers as a string, in their order of first appearance. If there are no integers in the string...
["def lottery(s):\n return \"\".join(dict.fromkeys(filter(str.isdigit, s))) or \"One more run!\"", "def lottery(s):\n \n result = ''\n \n for i in s:\n if i.isdigit() and i not in result:\n result += i\n \n return result or 'One more run!'", "def lottery(s):\n cifers = ''\n ...
{"fn_name": "lottery", "inputs": [["wQ8Hy0y5m5oshQPeRCkG"], ["ffaQtaRFKeGIIBIcSJtg"], ["555"], ["HappyNewYear2020"], ["20191224isXmas"], [""]], "outputs": [["805"], ["One more run!"], ["5"], ["20"], ["20194"], ["One more run!"]]}
introductory
https://www.codewars.com/kata/5832db03d5bafb7d96000107
def lottery(s):
4,181
Failed Filter - Bug Fixing #3 Oh no, Timmy's filter doesn't seem to be working? Your task is to fix the FilterNumber function to remove all the numbers from the string.
["def filter_numbers(string):\n return \"\".join(x for x in string if not x.isdigit())", "def filter_numbers(st):\n return \"\".join(x for x in st if x not in '1234567890')", "filter_numbers = lambda s: \"\".join(x for x in s if not x.isdigit())", "def filter_numbers(stg):\n return \"\".join(x for x in stg if ...
{"fn_name": "filter_numbers", "inputs": [["test123"], ["a1b2c3"], ["aa1bb2cc3dd"], ["CodeWars"], ["99234"]], "outputs": [["test"], ["abc"], ["aabbccdd"], ["CodeWars"], [""]]}
introductory
https://www.codewars.com/kata/55c606e6babfc5b2c500007c
def filter_numbers(string):
4,182
# Task Changu and Mangu are great buddies. Once they found an infinite paper which had 1,2,3,4,5,6,7,8,......... till infinity, written on it. Both of them did not like the sequence and started deleting some numbers in the following way. ``` First they deleted every 2nd number. So remaining numbers on the paper: 1,...
["def survivor(n):\n k = 2\n while n >= k and n % k:\n n -= n // k\n k += 1\n return n % k > 0", "def survivor(n):\n i=2\n while i<=n:\n if n%i==0:return False\n n-=n//i\n i+=1\n return True", "from itertools import count\n\ndef survivor(n):\n for i in count(2):\n...
{"fn_name": "survivor", "inputs": [[1], [5], [8], [9], [13], [15], [134], [289]], "outputs": [[true], [false], [false], [false], [true], [false], [false], [true]]}
introductory
https://www.codewars.com/kata/58aa6141c9eb047fec000133
def survivor(n):
4,183
The goal of this Kata is to return the greatest distance of index positions between matching number values in an array or 0 if there are no matching values. Example: In an array with the values [0, 2, 1, 2, 4, 1] the greatest index distance is between the matching '1' values at index 2 and 5. Executing greatestDist...
["def greatest_distance(arr):\n return max(i - arr.index(x) for i,x in enumerate(arr))", "def greatest_distance(arr):\n indexes, d = {}, 0\n for i,n in enumerate(arr):\n if n in indexes: d = max(d, i-indexes[n])\n else: indexes[n] = i\n return d", "def greatest_distance(lst):\n r...
{"fn_name": "greatest_distance", "inputs": [[[9, 7, 1, 2, 3, 7, 0, -1, -2]], [[0, 7, 0, 2, 3, 7, 0, -1, -2]], [[1, 2, 3, 4]]], "outputs": [[4], [6], [0]]}
introductory
https://www.codewars.com/kata/5442e4fc7fc447653a0000d5
def greatest_distance(arr):
4,184
As most of you might know already, a prime number is an integer `n` with the following properties: * it must be greater than 1 * it must be divisible only by itself and 1 And that's it: -15 or 8 are not primes, 5 or 97 are; pretty easy, isn't it? Well, turns out that primes are not just a mere mathematical curiosity...
["primes = [2, 3, 5, 7]\n\ndef is_prime(n):\n if n < 2:\n return False\n m = int(n ** .5) + 1\n for p in primes:\n if p >= m: break\n if not n % p:\n return False\n q, d = primes[-1], 4 if (n + 1) % 6 else 2\n while q < m:\n q, d = q + d, 4 - d\n if is_prime(...
{"fn_name": "is_prime", "inputs": [[1], [2], [5], [143], [-1], [29], [53], [529]], "outputs": [[false], [true], [true], [false], [false], [true], [true], [false]]}
introductory
https://www.codewars.com/kata/58603c898989d15e9e000475
def is_prime(n):
4,185
This is the simple version of Shortest Code series. If you need some challenges, please try the [challenge version](http://www.codewars.com/kata/570f45fab29c705d330004e3) ## Task: There is a rectangular land and we need to plant trees on the edges of that land. I will give you three parameters: ```width``` and ```l...
["def sc(width,length,gaps):\n #your code here\n a, b = divmod(2*width + 2*length - 4, gaps+1)\n return 0 if b else a", "def sc(width,length,gaps):\n places = width*2 + (length-2)*2\n if gaps == 0:\n return places\n div, mod = divmod(places, gaps+1)\n if mod:\n return 0\n return di...
{"fn_name": "sc", "inputs": [[3, 3, 1], [3, 3, 3], [3, 3, 2], [7, 7, 3], [3, 3, 0], [3, 3, 10], [2, 2, 1], [2, 2, 0], [200, 2, 1], [2, 200, 1]], "outputs": [[4], [2], [0], [6], [8], [0], [2], [4], [200], [200]]}
introductory
https://www.codewars.com/kata/5710443187a36a9cee0005a1
def sc(width,length,gaps):
4,186
# Task Given a number `n`, return a string representing it as a sum of distinct powers of three, or return `"Impossible"` if that's not possible to achieve. # Input/Output `[input]` integer `n` A positive integer n. `1 ≤ n ≤ 10^16`. `[output]` a string A string representing the sum of powers of three which ad...
["import numpy as np\n\ndef sum_of_threes(n):\n s=np.base_repr(n,3)\n if '2' in s: return 'Impossible'\n return '+'.join(['3^{}'.format(i) for i,d in enumerate(s[::-1]) if d=='1'][::-1])\n", "def sum_of_threes(n):\n k, p = 0, []\n while n >= 3 ** k:\n k += 1\n while k >= 0:\n k -= 1\n ...
{"fn_name": "sum_of_threes", "inputs": [[4], [2], [28], [84], [1418194818], [87754], [531441], [8312964441463288], [5559060566575209], [243]], "outputs": [["3^1+3^0"], ["Impossible"], ["3^3+3^0"], ["3^4+3^1"], ["Impossible"], ["3^10+3^9+3^8+3^7+3^5+3^3+3^1+3^0"], ["3^12"], ["Impossible"], ["3^33+3^9+3^1"], ["3^5"]]}
introductory
https://www.codewars.com/kata/591d3375e51f4a0940000052
def sum_of_threes(n):
4,187
Background ---------- In another dimension, there exist two immortal brothers: Solomon and Goromon. As sworn loyal subjects to the time elemental, Chronixus, both Solomon and Goromon were granted the power to create temporal folds. By sliding through these temporal folds, one can gain entry to parallel dimensions where...
["def solomons_quest(arr):\n pos, lvl = [0,0], 0\n for dilat,dir,dist in arr:\n lvl += dilat\n pos[dir in [0,2]] += dist * 2**lvl * (-1)**( dir in [2,3] )\n return pos", "def solomons_quest(arr):\n level = 0\n ds = [1j, 1, -1j, -1]\n pos = 0\n for level_shift, direction, distance in a...
{"fn_name": "solomons_quest", "inputs": [[[[1, 3, 5], [2, 0, 10], [-3, 1, 4], [4, 2, 4], [1, 1, 5], [-3, 0, 12], [2, 1, 12], [-2, 2, 6]]], [[[4, 0, 8], [2, 1, 2], [1, 0, 5], [-3, 3, 16], [2, 2, 2], [-1, 1, 7], [0, 0, 5], [-4, 3, 14]]], [[[1, 1, 20], [1, 2, 30], [1, 3, 8], [1, 0, 2], [1, 1, 6], [1, 2, 4], [1, 3, 6], [-7...
introductory
https://www.codewars.com/kata/59d7c910f703c460a2000034
def solomons_quest(arr):
4,188
Spin-off of this kata, here you will have to figure out an efficient strategy to solve the problem of finding the sole duplicate number among an unsorted array/list of numbers starting from 1 up to n. Hints: a solution in linear time can be found; using the most intuitive ones to search for duplicates that can run in ...
["def find_dup(arr):\n return sum(arr) - sum(range(1, max(arr)+1))", "def find_dup(arr):\n seen = set()\n for a in arr:\n if a in seen:\n return a\n seen.add(a)\n", "find_dup=lambda arr: sum(arr)-len(arr)*(len(arr)-1)/2", "from collections import Counter\n\n\ndef find_dup(lst):\n re...
{"fn_name": "find_dup", "inputs": [[[1, 1, 2, 3]], [[1, 2, 2, 3]], [[5, 4, 3, 2, 1, 1]], [[1, 3, 2, 5, 4, 5, 7, 6]], [[8, 2, 6, 3, 7, 2, 5, 1, 4]]], "outputs": [[1], [2], [1], [5], [2]]}
introductory
https://www.codewars.com/kata/558f0553803bc3c4720000af
def find_dup(arr):
4,189
You will be given two ASCII strings, `a` and `b`. Your task is write a function to determine which one of these strings is "worth" more, and return it. A string's worth is determined by the sum of its ASCII codepoint indexes. So, for example, the string `HELLO` has a value of 372: H is codepoint 72, E 69, L 76, and O ...
["def highest_value(a, b):\n return max(a, b, key=lambda s: sum(map(ord, s)))", "def highest_value(a, b):\n return a if sum(map(ord, a)) >= sum(map(ord, b)) else b", "def highest_value(a, b):\n return b if sum(ord(x) for x in b) > sum(ord(x) for x in a) else a", "def worth(s):\n return sum(map(ord, s))\n ...
{"fn_name": "highest_value", "inputs": [["AaBbCcXxYyZz0189", "KkLlMmNnOoPp4567"], ["ABcd", "0123"], ["!\"?$%^&*()", "{}[]@~'#:;"], ["ABCD", "DCBA"]], "outputs": [["KkLlMmNnOoPp4567"], ["ABcd"], ["{}[]@~'#:;"], ["ABCD"]]}
introductory
https://www.codewars.com/kata/5840586b5225616069000001
def highest_value(a, b):
4,190
Create a function `isAlt()` that accepts a string as an argument and validates whether the vowels (a, e, i, o, u) and consonants are in alternate order. ```python is_alt("amazon") // true is_alt("apple") // false is_alt("banana") // true ``` Arguments consist of only lowercase letters.
["import re\n\ndef is_alt(s):\n return not re.search('[aeiou]{2}|[^aeiou]{2}',s)", "def is_alt(s):\n vowels = list(\"aeiou\")\n v = s[0] in vowels\n \n for i in s:\n if (i in vowels) != v:\n return False\n v = not(v)\n return True", "def is_alt(s):\n a = s[::2]\n b = s[1...
{"fn_name": "is_alt", "inputs": [["amazon"], ["apple"], ["banana"], ["orange"], ["helipad"], ["yay"]], "outputs": [[true], [false], [true], [false], [true], [true]]}
introductory
https://www.codewars.com/kata/59325dc15dbb44b2440000af
def is_alt(s):
4,191
Write a function, `persistence`, that takes in a positive parameter `num` and returns its multiplicative persistence, which is the number of times you must multiply the digits in `num` until you reach a single digit. For example: ```python persistence(39) => 3 # Because 3*9 = 27, 2*7 = 14, 1*4=4 ...
["def persistence(n):\n n = str(n)\n count = 0\n while len(n) > 1:\n p = 1\n for i in n:\n p *= int(i)\n n = str(p)\n count += 1\n return count\n # your code\n", "def persistence(n):\n if n < 10: return 0\n mult = 1\n while(n > 0):\n mult = n%10 * mu...
{"fn_name": "persistence", "inputs": [[39], [4], [25], [999], [444]], "outputs": [[3], [0], [2], [4], [3]]}
introductory
https://www.codewars.com/kata/55bf01e5a717a0d57e0000ec
def persistence(n):
4,192
# Task Given an array `arr` and a number `n`. Call a pair of numbers from the array a `Perfect Pair` if their sum is equal to `n`. Find all of the perfect pairs and return the sum of their **indices**. Note that any element of the array can only be counted in one Perfect Pair. Also if there are multiple correct ...
["def pairwise(arr, n):\n s=[]\n for i in range(len(arr)-1):\n for j in range(i+1,len(arr)):\n if j in s or i in s: continue\n if arr[i]+arr[j] ==n:\n s.append(i)\n s.append(j)\n return sum(s)", "def pairwise(arr, n):\n\n iMap, s = {}, 0\n for i,...
{"fn_name": "pairwise", "inputs": [[[1, 4, 2, 3, 0, 5], 7], [[1, 3, 2, 4], 4], [[1, 1, 1], 2], [[0, 0, 0, 0, 1, 1], 1], [[15, 1, 1], 5]], "outputs": [[11], [1], [1], [10], [0]]}
introductory
https://www.codewars.com/kata/58afa8185eb02ea2a7000094
def pairwise(arr, n):
4,193
The number ```1331``` is the first positive perfect cube, higher than ```1```, having all its digits odd (its cubic root is ```11```). The next one is ```3375```. In the interval [-5000, 5000] there are six pure odd digit perfect cubic numbers and are: ```[-3375,-1331, -1, 1, 1331, 3375]``` Give the numbers of this...
["from bisect import bisect_left, bisect\n\nss = set('13579')\nns = [i ** 3 for i in range(1, int((10 ** 17) ** (1/3)) + 3, 2) if set(str(i ** 3)) <= ss]\nns = [-n for n in ns[::-1]] + ns\n\ndef odd_dig_cubic(a, b):\n return ns[bisect_left(ns, a):bisect(ns, b)]", "import math\n\ndef odd_dig_cubic(a, b):\n ret = []\...
{"fn_name": "odd_dig_cubic", "inputs": [[-5000, 5000], [0, 5000], [-1, 5000], [-5000, -2]], "outputs": [[[-3375, -1331, -1, 1, 1331, 3375]], [[1, 1331, 3375]], [[-1, 1, 1331, 3375]], [[-3375, -1331]]]}
introductory
https://www.codewars.com/kata/59f04228e63f8ceb92000038
def odd_dig_cubic(a, b):
4,194
You're fed up about changing the version of your software manually. Instead, you will create a little script that will make it for you. # Exercice Create a function `nextVersion`, that will take a string in parameter, and will return a string containing the next version number. For example: # Rules All numbers, ex...
["def next_version(version):\n ns = version.split('.')\n i = len(ns) - 1\n while i > 0 and ns[i] == '9':\n ns[i] = '0'\n i -= 1\n ns[i] = str(int(ns[i]) + 1)\n return '.'.join(ns)", "def next_version(version):\n tab = list(map(int, version.split('.')))\n for x in range(1, len(tab)+1):...
{"fn_name": "next_version", "inputs": [["1.2.3"], ["0.9.9"], ["1"], ["1.2.3.4.5.6.7.8"], ["9.9"]], "outputs": [["1.2.4"], ["1.0.0"], ["2"], ["1.2.3.4.5.6.7.9"], ["10.0"]]}
introductory
https://www.codewars.com/kata/56c0ca8c6d88fdb61b000f06
def next_version(version):
4,195
Remember the game 2048? The main part of this game is merging identical tiles in a row. * Implement a function that models the process of merging all of the tile values in a single row. * This function takes the array line as a parameter and returns a new array with the tile values from line slid towards the front...
["from itertools import groupby\n\ndef merge(line):\n merged = []\n for k,g in groupby( v for v in line if v ):\n g = list(g)\n n,r = divmod(len(g),2)\n if n: merged.extend([k*2]*n)\n if r: merged.append(k)\n return merged + [0]*(len(line)-len(merged))", "def merge(line):\n line ...
{"fn_name": "merge", "inputs": [[[2, 0, 2, 2]], [[2, 0, 2, 4]], [[0, 0, 2, 2]], [[2, 2, 0, 0]], [[2, 2, 2, 2, 2]], [[8, 16, 16, 8]]], "outputs": [[[4, 2, 0, 0]], [[4, 4, 0, 0]], [[4, 0, 0, 0]], [[4, 0, 0, 0]], [[4, 4, 2, 0, 0]], [[8, 32, 8, 0]]]}
introductory
https://www.codewars.com/kata/55e1990978c60e5052000011
def merge(line):
4,196
# Summation Of Primes The sum of the primes below or equal to 10 is **2 + 3 + 5 + 7 = 17**. Find the sum of all the primes **_below or equal to the number passed in_**. From Project Euler's [Problem #10](https://projecteuler.net/problem=10 "Project Euler - Problem 10").
["from bisect import bisect\n\ndef sieve(n):\n sieve, primes = [0]*(n+1), []\n for i in range(2, n+1):\n if not sieve[i]:\n primes.append(i) \n for j in range(i**2, n+1, i): sieve[j] = 1\n return primes\n\nPRIMES = sieve(1000000)\n\ndef summationOfPrimes(n):\n return sum(PRIMES[...
{"fn_name": "summationOfPrimes", "inputs": [[5], [6], [7], [8], [9], [10], [20], [30], [40], [50], [100], [200], [300], [400], [500], [1000], [2000], [3000], [4000], [5000], [25000]], "outputs": [[10], [10], [17], [17], [17], [17], [77], [129], [197], [328], [1060], [4227], [8275], [13887], [21536], [76127], [277050], ...
introductory
https://www.codewars.com/kata/59ab0ca4243eae9fec000088
def summationOfPrimes(primes):
4,197
You work in the best consumer electronics corporation, and your boss wants to find out which three products generate the most revenue. Given 3 lists of the same length like these: * products: `["Computer", "Cell Phones", "Vacuum Cleaner"]` * amounts: `[3, 24, 8]` * prices: `[199, 299, 399]` return the three product ...
["def top3(*args):\n return [item[0] for item in sorted(zip(*args), key=lambda x: x[1]*x[2], reverse=True)[:3]]", "import heapq\n\ndef top3(products, amounts, prices):\n items = zip(products, amounts, prices)\n return [product for product, _, _ in heapq.nlargest(3, items, key=lambda item: item[1] * item[2])]",...
{"fn_name": "top3", "inputs": [[["Computer", "Cell Phones", "Vacuum Cleaner"], [3, 24, 8], [199, 299, 399]], [["Cell Phones", "Vacuum Cleaner", "Computer", "Autos", "Gold", "Fishing Rods", "Lego", " Speakers"], [5, 25, 2, 7, 10, 3, 2, 24], [51, 225, 22, 47, 510, 83, 82, 124]], [["Cell Phones", "Vacuum Cleaner", "Comput...
introductory
https://www.codewars.com/kata/5e16ffb7297fe00001114824
def top3(products, amounts, prices):
4,198
### What is simplifying a square root? If you have a number, like 80, for example, you would start by finding the greatest perfect square divisible by 80. In this case, that's 16. Find the square root of 16, and multiply it by 80 / 16. Answer = 4 √5. ##### The above example: ![simplify_roots_example.png](https://i....
["def simplify(n):\n for d in range(int(n ** .5), 0, -1):\n if not n % d ** 2: break\n if d*d == n: return '%d' % d\n elif d == 1: return 'sqrt %d' % n\n else: return '%d sqrt %d' % (d, n // d ** 2)\n\ndef desimplify(s):\n x, _, y = s.partition('sqrt')\n return int(x or '1') ** 2 * int(y or '1'...
{"fn_name": "simplify", "inputs": [[1], [2], [3], [8], [15], [16], [18], [20], [24], [32], [4], [7], [9], [10], [12], [13], [14], [50], [80], [200]], "outputs": [["1"], ["sqrt 2"], ["sqrt 3"], ["2 sqrt 2"], ["sqrt 15"], ["4"], ["3 sqrt 2"], ["2 sqrt 5"], ["2 sqrt 6"], ["4 sqrt 2"], ["2"], ["sqrt 7"], ["3"], ["sqrt 10"]...
introductory
https://www.codewars.com/kata/5850e85c6e997bddd300005d
def simplify(n):
4,199
Complete the function that returns an array of length `n`, starting with the given number `x` and the squares of the previous number. If `n` is negative or zero, return an empty array/list. ## Examples ``` 2, 5 --> [2, 4, 16, 256, 65536] 3, 3 --> [3, 9, 81] ```
["def squares(x,n):\n return [x**(2**i) for i in range(n)]", "from itertools import accumulate, repeat\ndef squares(x, n):\n return list(accumulate(repeat(x, n), lambda a, _: a * a))", "def squares(x, n):\n result = [x] if n > 0 else []\n for i in range(0, n-1):\n result.append(result[-1]**2)\n re...
{"fn_name": "squares", "inputs": [[2, 5], [3, 3], [5, 3], [10, 4], [2, 0], [2, -4]], "outputs": [[[2, 4, 16, 256, 65536]], [[3, 9, 81]], [[5, 25, 625]], [[10, 100, 10000, 100000000]], [[]], [[]]]}
introductory
https://www.codewars.com/kata/5546180ca783b6d2d5000062
def squares(x, n):
4,200
You get a "text" and have to shift the vowels by "n" positions to the right. (Negative value for n should shift to the left.) "Position" means the vowel's position if taken as one item in a list of all vowels within the string. A shift by 1 would mean, that every vowel shifts to the place of the next vowel. Shifting ov...
["import re\nfrom collections import deque\n\ndef vowel_shift(text,n):\n try:\n tokens = re.split(r'([aeiouAEIOU])', text)\n if len(tokens) > 1:\n vowels = deque(tokens[1::2])\n vowels.rotate(n)\n tokens[1::2] = vowels\n return ''.join(tokens)\n except TypeErr...
{"fn_name": "vowel_shift", "inputs": [[null, 0], ["", 0], ["This is a test!", 0], ["This is a test!", 1], ["This is a test!", 3], ["This is a test!", 4], ["This is a test!", -1], ["This is a test!", -5], ["Brrrr", 99], ["AEIOUaeiou", 1]], "outputs": [[null], [""], ["This is a test!"], ["Thes is i tast!"], ["This as e t...
introductory
https://www.codewars.com/kata/577e277c9fb2a5511c00001d
def vowel_shift(text, n):
4,201
An Arithmetic Progression is defined as one in which there is a constant difference between the consecutive terms of a given series of numbers. You are provided with consecutive elements of an Arithmetic Progression. There is however one hitch: exactly one term from the original series is missing from the set of number...
["def find_missing(sequence):\n t = sequence\n return (t[0] + t[-1]) * (len(t) + 1) / 2 - sum(t)\n", "def find_missing(sequence):\n interval = (sequence[-1] - sequence[0])/len(sequence)\n for previous, item in enumerate(sequence[1:]):\n if item - sequence[previous] != interval:\n return it...
{"fn_name": "find_missing", "inputs": [[[1, 2, 3, 4, 6, 7, 8, 9]]], "outputs": [[5]]}
introductory
https://www.codewars.com/kata/52de553ebb55d1fca3000371
def find_missing(sequence):
4,202
The Ulam sequence `U` is defined by `u0 = u`, `u1 = v`, with the general term `uN` for `N > 2` given by the least integer expressible uniquely as the sum of two distinct earlier terms. In other words, the next number is always the smallest, unique sum of any two previous terms. Complete the function that creates an Ul...
["from itertools import combinations\nfrom collections import defaultdict\n\ndef ulam_sequence(u0, u1, n):\n seq = [u0, u1, u0 + u1]\n \n while len(seq) < n:\n candidates = defaultdict(int)\n \n for a, b in combinations(seq, 2):\n candidates[a + b] += 1\n \n for nu...
{"fn_name": "ulam_sequence", "inputs": [[1, 2, 5], [3, 4, 5], [5, 6, 8]], "outputs": [[[1, 2, 3, 4, 6]], [[3, 4, 7, 10, 11]], [[5, 6, 11, 16, 17, 21, 23, 26]]]}
introductory
https://www.codewars.com/kata/5995ff073acba5fa3a00011d
def ulam_sequence(u0, u1, n):
4,203
Complete the function ```caffeineBuzz```, which takes a non-zero integer as it's one argument. If the integer is divisible by 3, return the string ```"Java"```. If the integer is divisible by 3 and divisible by 4, return the string ```"Coffee"``` If the integer is one of the above and is even, add ```"Script"``` to ...
["def caffeineBuzz(n):\n if n%12 == 0:\n return \"CoffeeScript\"\n elif n%6 == 0:\n return \"JavaScript\"\n elif n%3 == 0:\n return \"Java\"\n else:\n return \"mocha_missing!\"", "def caffeineBuzz(n):\n result = \"mocha_missing!\"\n if not n % 3:\n if not n % 4:\n ...
{"fn_name": "caffeineBuzz", "inputs": [[1], [3], [6], [12]], "outputs": [["mocha_missing!"], ["Java"], ["JavaScript"], ["CoffeeScript"]]}
introductory
https://www.codewars.com/kata/5434283682b0fdb0420000e6
def caffeineBuzz(n):
4,204
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are: 2332 110011 54322345 For a given number ```num```, return its closest numerical palindrome which can either be smaller or larger than ```num```. If there are 2 poss...
["def palindrome(num):\n if type(num) is not int or num < 0:\n return \"Not valid\"\n else:\n c =0\n for i in range(num,num**2):\n if is_pal(i):\n return i\n elif is_pal(i-c):\n return i-c\n else:\n c +=2\n \ndef...
{"fn_name": "palindrome", "inputs": [[8], [281], [1029], [1221], ["BGHHGB"], ["11029"], [-1029]], "outputs": [[11], [282], [1001], [1221], ["Not valid"], ["Not valid"], ["Not valid"]]}
introductory
https://www.codewars.com/kata/58df8b4d010a9456140000c7
def palindrome(num):
4,205
Ahoy Matey! Welcome to the seven seas. You are the captain of a pirate ship. You are in battle against the royal navy. You have cannons at the ready.... or are they? Your task is to check if the gunners are loaded and ready, if they are: ```Fire!``` If they aren't ready: ```Shiver me timbers!``` Your gunners for...
["def cannons_ready(gunners):\n return 'Shiver me timbers!' if 'nay' in gunners.values() else 'Fire!'", "def cannons_ready(gunners):\n for i in gunners:\n if gunners[i] == 'nay':\n return 'Shiver me timbers!'\n return 'Fire!'", "def cannons_ready(g):\n return ['Fire!','Shiver me timbers!']['na...
{"fn_name": "cannons_ready", "inputs": [[{"Joe": "nay", "Johnson": "nay", "Peter": "aye"}]], "outputs": [["Shiver me timbers!"]]}
introductory
https://www.codewars.com/kata/5748a883eb737cab000022a6
def cannons_ready(gunners):
4,206
# Task Dudka has `n` details. He must keep exactly 3 of them. To do this, he performs the following operations until he has only 3 details left: ``` He numbers them. He keeps those with either odd or even numbers and throws the others away.``` Dudka wants to know how many ways there are to get exactly 3 details. Y...
["from functools import lru_cache\n\n@lru_cache(maxsize=None)\ndef three_details(n):\n if n <= 3: return n==3\n q, r = divmod(n, 2)\n return three_details(q) + three_details(q+r)", "from functools import lru_cache\n\n@lru_cache(maxsize=None)\ndef three_details(n):\n if n in (3,5,7):\n return 1\n e...
{"fn_name": "three_details", "inputs": [[3], [6], [4], [10], [15]], "outputs": [[1], [2], [0], [2], [1]]}
introductory
https://www.codewars.com/kata/58c212c6f130b7c4660000a5
def three_details(n):
4,207
Write a function that takes a positive integer n, sums all the cubed values from 1 to n, and returns that sum. Assume that the input n will always be a positive integer. Examples: ```python sum_cubes(2) > 9 # sum of the cubes of 1 and 2 is 1 + 8 ```
["def sum_cubes(n):\n return sum(i**3 for i in range(0,n+1))", "def sum_cubes(n):\n return (n*(n+1)/2)**2", "def sum_cubes(n):\n return sum(x ** 3 for x in range(n+1))", "def sum_cubes(n):\n return (n*(n+1)//2)**2", "def sum_cubes(n):\n return sum([i**3 for i in range(1,n+1)])", "def sum_cubes(n):\n r...
{"fn_name": "sum_cubes", "inputs": [[1], [2], [3], [4], [10], [123]], "outputs": [[1], [9], [36], [100], [3025], [58155876]]}
introductory
https://www.codewars.com/kata/59a8570b570190d313000037
def sum_cubes(n):
4,208
## Task Generate a sorted list of all possible IP addresses in a network. For a subnet that is not a valid IPv4 network return `None`. ## Examples ``` ipsubnet2list("192.168.1.0/31") == ["192.168.1.0", "192.168.1.1"] ipsubnet2list("213.256.46.160/28") == None ```
["import ipaddress as ip\n\ndef ipsubnet2list(subnet):\n try: return list(map(str,ip.ip_network(subnet).hosts()))\n except: pass", "def ip_to_int(ip):\n return sum(int(i[0]) << i[1]*8 for i in zip(ip.split('.'), range(3,-1,-1)))\ndef int_to_ip(num):\n return '.'.join(str(num >> i*8 & 0xff) for i in range(3,...
{"fn_name": "ipsubnet2list", "inputs": [["192.168.1.0/31"], ["195.20.15.0/28"], ["174.0.153.152/29"], ["213.192.46.160/28"], ["213.256.46.160/28"]], "outputs": [[["192.168.1.0", "192.168.1.1"]], [["195.20.15.1", "195.20.15.2", "195.20.15.3", "195.20.15.4", "195.20.15.5", "195.20.15.6", "195.20.15.7", "195.20.15.8", "19...
introductory
https://www.codewars.com/kata/5980d4e258a9f5891e000062
def ipsubnet2list(subnet):
4,209
# Largest Rectangle in Background Imagine a photo taken to be used in an advertisement. The background on the left of the motive is whitish and you want to write some text on that background. So you scan the photo with a high resolution scanner and, for each line, count the number of pixels from the left that are suff...
["def largest_rect(h):\n st=[]; m=0; i=0\n while i<len(h):\n if len(st)==0 or h[st[-1]]<=h[i]: st.append(i); i+=1\n else: l=st.pop(); m=max(m, h[l]*(i if len(st)==0 else i-st[-1]-1))\n while len(st)>0: l=st.pop(); m=max(m, h[l]*(i if len(st)==0 else i-st[-1]-1))\n return m", "def largest_rect(...
{"fn_name": "largest_rect", "inputs": [[[3, 5, 12, 4, 10]], [[6, 2, 5, 4, 5, 1, 6]], [[9, 7, 5, 4, 2, 5, 6, 7, 7, 5, 7, 6, 4, 4, 3, 2]], [[]], [[0]], [[0, 0, 0]], [[1, 1, 1]], [[1, 2, 3]], [[3, 2, 1]], [[100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 1...
introductory
https://www.codewars.com/kata/595db7e4c1b631ede30004c4
def largest_rect(histogram):
4,210
You have a two-dimensional list in the following format: ```python data = [[2, 5], [3, 4], [8, 7]] ``` Each sub-list contains two items, and each item in the sub-lists is an integer. Write a function `process_data()` that processes each sub-list like so: * `[2, 5]` --> `2 - 5` --> `-3` * `[3, 4]` --> `3 - 4` --> ...
["def process_data(data):\n r = 1\n for d in data:\n r *= d[0] - d[1]\n return r", "from functools import reduce\nfrom itertools import starmap\nfrom operator import mul, sub\n\ndef process_data(data):\n return reduce(mul, starmap(sub, data))", "def process_data(data):\n product = 1\n \n for...
{"fn_name": "process_data", "inputs": [[[[2, 5], [3, 4], [8, 7]]], [[[2, 9], [2, 4], [7, 5]]], [[[5, 4], [6, 4]]], [[[2, 1], [5, 3], [7, 4], [10, 6]]]], "outputs": [[3], [28], [2], [24]]}
introductory
https://www.codewars.com/kata/586e1d458cb711f0a800033b
def process_data(data):
4,211
You are going to be given a word. Your job will be to make sure that each character in that word has the exact same number of occurrences. You will return `true` if it is valid, or `false` if it is not. For example: `"abcabc"` is a valid word because `'a'` appears twice, `'b'` appears twice, and`'c'` appears twice. ...
["from collections import Counter\n\ndef validate_word(word):\n return len(set(Counter(word.lower()).values())) == 1", "from collections import Counter\n\n\ndef validate_word(word):\n return 1 == len(set(Counter(word.upper()).values()))\n", "def validate_word(word):\n word = word.lower()\n return len(set(wo...
{"fn_name": "validate_word", "inputs": [["abcabc"], ["Abcabc"], ["AbcabcC"], ["AbcCBa"], ["pippi"], ["?!?!?!"], ["abc123"], ["abcabcd"], ["abc!abc!"], ["abc:abc"]], "outputs": [[true], [true], [false], [true], [false], [true], [true], [false], [true], [false]]}
introductory
https://www.codewars.com/kata/56786a687e9a88d1cf00005d
def validate_word(word):
4,212
Write a function that takes one or more arrays and returns a new array of unique values in the order of the original provided arrays. In other words, all values present from all arrays should be included in their original order, but with no duplicates in the final array. The unique numbers should be sorted by their o...
["def unite_unique(*arg):\n res = []\n for arr in arg:\n for val in arr:\n if not val in res: res.append(val)\n return res", "from itertools import chain\n\ndef unite_unique(*args):\n return list(dict.fromkeys(chain.from_iterable(args)))", "from itertools import chain\n\ndef unite_unique(*...
{"fn_name": "unite_unique", "inputs": [[[1, 2], [3, 4]], [[1, 3, 2], [5, 2, 1, 4], [2, 1]], [[4, 3, 2, 2]], [[4, "a", 2], []], [[], [4, "a", 2]], [[], [4, "a", 2], []], [[]], [[], []], [[], [1, 2]], [[], [1, 2, 1, 2], [2, 1, 1, 2, 1]]], "outputs": [[[1, 2, 3, 4]], [[1, 3, 2, 5, 4]], [[4, 3, 2]], [[4, "a", 2]], [[4, "a"...
introductory
https://www.codewars.com/kata/5729c30961cecadc4f001878
def unite_unique(*args):
4,213
Brief ===== Sometimes we need information about the list/arrays we're dealing with. You'll have to write such a function in this kata. Your function must provide the following informations: * Length of the array * Number of integer items in the array * Number of float items in the array * Number of string character ...
["def array_info(x):\n if not x:\n return 'Nothing in the array!'\n return [\n [len(x)],\n [sum(isinstance(i, int) for i in x) or None],\n [sum(isinstance(i, float) for i in x) or None],\n [sum(isinstance(i, str) and not i.isspace() for i in x) or None],\n [sum(isinstance...
{"fn_name": "array_info", "inputs": [[[1, 2, 3.33, 4, 5.01, "bass", "kick", " "]], [[0.001, 2, " "]], [[]], [[" "]], [[" ", " "]], [["jazz"]], [[4]], [[3.1416]], [[11, 22, 33.33, 44.44, "hasan", "ahmad"]], [["a", "b", "c", "d", " "]], [[1, 2, 3, 4, 5, 6, 7, 8, 9]], [[1, 2.23, "string", " "]]], "outputs": [[[[8], [3], [...
introductory
https://www.codewars.com/kata/57f12b4d5f2f22651c00256d
def array_info(x):
4,214
In this kata you will have to modify a sentence so it meets the following rules: convert every word backwards that is: longer than 6 characters OR has 2 or more 'T' or 't' in it convert every word uppercase that is: exactly 2 characters long OR before a comma convert every word to a "0" tha...
["import re\n\ndef spiner(s,p):\n return ( s[::-1] if len(s) > 6 or s.lower().count('t') > 1\n else s.upper() if len(s) == 2 or p == ','\n else '0' if len(s) == 1\n else s) + p\n\ndef spin_solve(sentence):\n return re.sub(r\"((?:\\w|['-])+)(\\W)?\", lambda m: spiner(m.group(1), m.grou...
{"fn_name": "spin_solve", "inputs": [["Welcome."], ["If a man does not keep pace with his companions, perhaps it is because he hears a different drummer."], ["As Grainier drove along in the wagon behind a wide, slow, sand-colored mare, clusters of orange butterflies exploded off the purple blackish piles of bear sign a...
introductory
https://www.codewars.com/kata/5a3277005b2f00a11b0011c4
def spin_solve(sentence):
4,215
# Task Let's consider a table consisting of `n` rows and `n` columns. The cell located at the intersection of the i-th row and the j-th column contains number i × j. The rows and columns are numbered starting from 1. You are given a positive integer `x`. Your task is to count the number of cells in a table that cont...
["def count_number(n, x):\n return len([j for j in range(1,n+1) if x%j==0 and x/j <= n]) ", "from math import ceil\n\ndef count_number(n, x):\n return sum(x % i == 0 for i in range(max(int(ceil(x / n)), 1), min(n,x) + 1))", "def count_number(n, x):\n #your code here\n return sum(1 for i in range(1,n+1) if x...
{"fn_name": "count_number", "inputs": [[5, 5], [10, 5], [6, 12], [6, 169], [100000, 1000000000]], "outputs": [[2], [2], [4], [0], [16]]}
introductory
https://www.codewars.com/kata/58b635903e78b34958000056
def count_number(n, x):
4,216
Create a method (**JS**: function) `every` which returns every nth element of an array. ### Usage With no arguments, `array.every` it returns every element of the array. With one argument, `array.every(interval)` it returns every `interval`th element. With two arguments, `array.every(interval, start_index)` it re...
["def every(lst, n=1, start=0):\n return lst[start::n]", "#code here\ndef every(array, interval=None, start=None):\n return array[start::interval]", "def every(arr, n = 1, m = 0):\n return arr[m::n]\n", "#code here\ndef every(arr,n=1,s=0):\n return arr[s::n]", "def every(arr, n = 1, i = 0):\n return arr[...
{"fn_name": "every", "inputs": [[[null, null, null, null, null], 2]], "outputs": [[[null, null, null]]]}
introductory
https://www.codewars.com/kata/5753b987aeb792508d0010e2
def every(array, interval = 1, start_index = 0):
4,217
If the first day of the month is a Friday, it is likely that the month will have an `Extended Weekend`. That is, it could have five Fridays, five Saturdays and five Sundays. In this Kata, you will be given a start year and an end year. Your task will be to find months that have extended weekends and return: ``` - The...
["from calendar import month_abbr\nfrom datetime import datetime \ndef solve(a,b):\n res = [month_abbr[month]\n for year in range(a, b+1) \n for month in [1,3,5,7,8,10,12] \n if datetime(year, month, 1).weekday() == 4]\n return (res[0],res[-1], len(res))", "from datetime import date\n\ndef solve(a, b):...
{"fn_name": "solve", "inputs": [[2016, 2020], [1900, 1950], [1800, 2500]], "outputs": [[["Jan", "May", 5]], [["Mar", "Dec", 51]], [["Aug", "Oct", 702]]]}
introductory
https://www.codewars.com/kata/5be7f613f59e0355ee00000f
def solve(a,b):
4,218
It's the most hotly anticipated game of the school year - Gryffindor vs Slytherin! Write a function which returns the winning team. You will be given two arrays with two values. The first given value is the number of points scored by the team's Chasers and the second a string with a 'yes' or 'no' value if the team ...
["def game_winners(gryffindor, slytherin):\n g, s = (team[0] + 150 * (team[1] == 'yes') for team in [gryffindor, slytherin])\n return 'Gryffindor wins!' if g > s else 'Slytherin wins!' if s > g else \"It's a draw!\"", "def game_winners(gryffindor, slytherin):\n g = gryffindor[0]\n s = slytherin[0]\n if g...
{"fn_name": "game_winners", "inputs": [[[100, "yes"], [100, "no"]], [[350, "no"], [250, "yes"]], [[100, "yes"], [250, "no"]], [[0, "yes"], [150, "no"]], [[150, "no"], [0, "yes"]]], "outputs": [["Gryffindor wins!"], ["Slytherin wins!"], ["It's a draw!"], ["It's a draw!"], ["It's a draw!"]]}
introductory
https://www.codewars.com/kata/5840946ea3d4c78e90000068
def game_winners(gryffindor, slytherin):
4,219
Imagine that you are given two sticks. You want to end up with three sticks of equal length. You are allowed to cut either or both of the sticks to accomplish this, and can throw away leftover pieces. Write a function, maxlen, that takes the lengths of the two sticks (L1 and L2, both positive values), that will return...
["def maxlen(s1, s2):\n sm, lg = sorted((s1, s2))\n return min(max(lg / 3, sm), lg / 2)", "def maxlen(l1, l2):\n return max(min(l1 / 2, l2), min(l1, l2 / 2), max(l1, l2) / 3)", "def maxlen(*args):\n x,y = sorted(args)\n return [y/2, x, y/3][ (y>2*x) + (y>3*x) ]", "def maxlen(*s):\n a, b = min(s), max(...
{"fn_name": "maxlen", "inputs": [[5, 12], [12, 5], [5, 17], [17, 5], [7, 12], [12, 7]], "outputs": [[5], [5], [5.666666666666667], [5.666666666666667], [6.0], [6.0]]}
introductory
https://www.codewars.com/kata/57c1f22d8fbb9fd88700009b
def maxlen(l1, l2):
4,220
A triangle is called an equable triangle if its area equals its perimeter. Return `true`, if it is an equable triangle, else return `false`. You will be provided with the length of sides of the triangle. Happy Coding!
["def equable_triangle(a, b, c):\n p = a + b + c\n ph = p / 2\n return p * p == ph * (ph - a) * (ph - b) * (ph - c)", "def equable_triangle(a,b,c):\n p = (a + b + c) / 2\n return (p * (p - a) * (p - b) * (p - c)) ** .5 == 2 * p", "def equable_triangle(a,b,c):\n return (a + b + c) * 16 == (a + b - c) *...
{"fn_name": "equable_triangle", "inputs": [[5, 12, 13], [2, 3, 4], [6, 8, 10], [7, 15, 20], [17, 17, 30], [7, 10, 12], [6, 11, 12], [25, 25, 45], [13, 37, 30], [6, 25, 29], [10, 11, 18], [73, 9, 80], [12, 35, 37], [120, 109, 13], [9, 10, 17]], "outputs": [[true], [false], [true], [true], [false], [false], [false], [fal...
introductory
https://www.codewars.com/kata/57d0089e05c186ccb600035e
def equable_triangle(a,b,c):
4,221
From Wikipedia : "The n-back task is a continuous performance task that is commonly used as an assessment in cognitive neuroscience to measure a part of working memory and working memory capacity. [...] The subject is presented with a sequence of stimuli, and the task consists of indicating when the current stimulus ma...
["def count_targets(n, sequence):\n return sum(a == b for a, b in zip(sequence, sequence[n:]))", "def count_targets(n, s):\n return sum(s[i] == s[i-n] for i in range(n,len(s)))", "def count_targets(n, sequence):\n return sum(1 for a, b in zip(sequence, sequence[n:]) if a == b)", "def count_targets(n, seq):\n ...
{"fn_name": "count_targets", "inputs": [[1, [1, 1, 1, 1, 1]], [2, [1, 1, 1, 1, 1]], [1, [1, 2, 1, 2, 1]], [2, [1, 2, 1, 2, 1]], [9, [1, 2, 3, 4, 5, 6, 7, 8, 9, 1]], [1, []], [1, [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...
introductory
https://www.codewars.com/kata/599c7f81ca4fa35314000140
def count_targets(n, sequence):
4,222
```if-not:julia,racket Write a function that returns the total surface area and volume of a box as an array: `[area, volume]` ``` ```if:julia Write a function that returns the total surface area and volume of a box as a tuple: `(area, volume)` ``` ```if:racket Write a function that returns the total surface area and vo...
["def get_size(w, h, d):\n area = 2*(w*h + h*d + w*d)\n volume = w*h*d\n return [area, volume]", "def get_size(w,h,l):\n return [2*(w*l+h*l+h*w), w*h*l]", "def get_size(w,h,d):\n return [2 * (w * d + h * d + h * w), w * h * d]", "def get_size(w, h, d):\n return [2 * (w*h + w*d + h*d), w * h * d]", "ge...
{"fn_name": "get_size", "inputs": [[4, 2, 6], [1, 1, 1], [1, 2, 1], [1, 2, 2], [10, 10, 10]], "outputs": [[[88, 48]], [[6, 1]], [[10, 2]], [[16, 4]], [[600, 1000]]]}
introductory
https://www.codewars.com/kata/565f5825379664a26b00007c
def get_size(w,h,d):
4,223
Given two arrays `a` and `b` write a function `comp(a, b)` (`compSame(a, b)` in Clojure) that checks whether the two arrays have the "same" elements, with the same multiplicities. "Same" means, here, that the elements in `b` are the elements in `a` squared, regardless of the order. ## Examples ## Valid arrays ``` a = ...
["def comp(array1, array2):\n try:\n return sorted([i ** 2 for i in array1]) == sorted(array2)\n except:\n return False", "def comp(a1, a2):\n return None not in (a1,a2) and [i*i for i in sorted(a1)]==sorted(a2)", "def comp(array1, array2):\n if array1 and array2:\n return sorted([x*x f...
{"fn_name": "comp", "inputs": [[[], [1]]], "outputs": [[false]]}
introductory
https://www.codewars.com/kata/550498447451fbbd7600041c
def comp(array1, array2):
4,224
# Don't give me five! In this kata you get the start number and the end number of a region and should return the count of all numbers except numbers with a 5 in it. The start and the end number are both inclusive! Examples: ``` 1,9 -> 1,2,3,4,6,7,8,9 -> Result 8 4,17 -> 4,6,7,8,9,10,11,12,13,14,16,17 -> Result 12 ``...
["def dont_give_me_five(start, end):\n return sum('5' not in str(i) for i in range(start, end + 1))", "def dont_give_me_five(start,end):\n return len([num for num in range(start, end+1) if '5' not in str(num)])", "def dont_give_me_five(start,end):\n tick = 0\n for x in range(start, end+1):\n if '5' n...
{"fn_name": "dont_give_me_five", "inputs": [[1, 9], [4, 17], [1, 90], [-4, 17], [-4, 37], [-14, -1], [-14, -6]], "outputs": [[8], [12], [72], [20], [38], [13], [9]]}
introductory
https://www.codewars.com/kata/5813d19765d81c592200001a
def dont_give_me_five(start,end):
4,225
Ronny the robot is watching someone perform the Cups and Balls magic trick. The magician has one ball and three cups, he shows Ronny which cup he hides the ball under (b), he then mixes all the cups around by performing multiple two-cup switches (arr). Ronny can record the switches but can't work out where the ball is....
["from functools import reduce\n\ndef cup_and_balls(b, arr):\n return reduce(lambda x, y: y[1] if x == y[0] else y[0] if x == y[1] else x, arr, b)", "def cup_and_balls(b, a):\n for l, r in a:\n b = r if b == l else l if b == r else b\n return b", "def cup_and_balls(b, arr):\n for switch in arr:\n ...
{"fn_name": "cup_and_balls", "inputs": [[2, [[1, 2]]], [1, [[2, 3], [1, 2], [1, 2]]], [2, [[1, 3], [1, 2], [2, 1], [2, 3]]]], "outputs": [[1], [1], [3]]}
introductory
https://www.codewars.com/kata/5b715fd11db5ce5912000019
def cup_and_balls(b, arr):
4,226
# The museum of incredible dull things The museum of incredible dull things wants to get rid of some exhibitions. Miriam, the interior architect, comes up with a plan to remove the most boring exhibitions. She gives them a rating, and then removes the one with the lowest rating. However, just as she finished rating a...
["def remove_smallest(numbers):\n a = numbers[:]\n if a:\n a.remove(min(a))\n return a", "def remove_smallest(numbers):\n if len(numbers) < 1: \n return numbers\n idx = numbers.index(min(numbers))\n return numbers[0:idx] + numbers[idx+1:]\n", "def remove_smallest(n):\n return n[:n.ind...
{"fn_name": "remove_smallest", "inputs": [[[1, 2, 3, 4, 5]], [[1, 2, 3, 4]], [[5, 3, 2, 1, 4]], [[1, 2, 3, 1, 1]], [[]]], "outputs": [[[2, 3, 4, 5]], [[2, 3, 4]], [[5, 3, 2, 4]], [[2, 3, 1, 1]], [[]]]}
introductory
https://www.codewars.com/kata/563cf89eb4747c5fb100001b
def remove_smallest(numbers):
4,227
Your program will receive an array of complex numbers represented as strings. Your task is to write the `complexSum` function which have to return the sum as a string. Complex numbers can be written in the form of `a+bi`, such as `2-3i` where `2` is the real part, `3` is the imaginary part, and `i` is the "imaginary ...
["def complexSum(arr, sub={'1i': 'i', '-1i': '-i', '0i': '0'}):\n s = str(sum(complex(x.replace('i', 'j')) for x in arr)).replace('j', 'i')\n s = s.strip('()')\n s = s.replace('+0i', '')\n return sub.get(s, s) ", "def complexSum(arr):\n a = [complex(i.replace(\"i\", \"j\")) for i in arr]\n s = 0\n ...
{"fn_name": "complexSum", "inputs": [[["2+3i", "3-i"]], [["2-3i", "3+i"]], [["3", "-3+i"]], [[]], [["3+4i"]], [["123+456i"]], [["0"]], [["-i"]], [["1", "1"]], [["-5", "5"]], [["1", "10", "100", "1000"]], [["5+4i", "11+3i"]], [["-2-4i", "-8+6i"]], [["-1-i", "7+10i"]], [["3+4i", "3-4i"]], [["10+i", "10-i", "9"]], [["2+3i...
introductory
https://www.codewars.com/kata/5a981424373c2e479c00017f
def complexSum(arr):
4,228
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are: 2332 110011 54322345 For a given number ```num```, write a function which returns the number of numerical palindromes within each number. For this kata, single digi...
["def palindrome(num):\n if not isinstance(num, int) or num < 0:\n return 'Not valid'\n s = str(num)\n return sum(sum(s[i:i+n] == s[i:i+n][::-1] for i in range(len(s)-n+1)) for n in range(2, len(s)+1))\n", "def palindrome(num):\n \n if not isinstance(num, int) or num < 0:\n return \"Not...
{"fn_name": "palindrome", "inputs": [[2], [141221001], [1551], [13598], ["ACCDDCCA"], ["1551"], [-4505]], "outputs": [[0], [5], [2], [0], ["Not valid"], ["Not valid"], ["Not valid"]]}
introductory
https://www.codewars.com/kata/58df62fe95923f7a7f0000cc
def palindrome(num):
4,229
Variation of this nice kata, the war has expanded and become dirtier and meaner; both even and odd numbers will fight with their pointy `1`s. And negative integers are coming into play as well, with, ça va sans dire, a negative contribution (think of them as spies or saboteurs). Again, three possible outcomes: `odds w...
["def bits_war(numbers):\n odd, even = 0, 0\n for number in numbers:\n if number % 2 == 0:\n if number > 0:\n even += bin(number).count('1')\n else:\n even -= bin(number).count('1')\n else:\n if number > 0:\n odd += bin(nu...
{"fn_name": "bits_war", "inputs": [[[1, 5, 12]], [[7, -3, 20]], [[7, -3, -2, 6]], [[-3, -5]], [[]]], "outputs": [["odds win"], ["evens win"], ["tie"], ["evens win"], ["tie"]]}
introductory
https://www.codewars.com/kata/58865bfb41e04464240000b0
def bits_war(numbers):
4,230
# Task Given a string `str`, reverse it omitting all non-alphabetic characters. # Example For `str = "krishan"`, the output should be `"nahsirk"`. For `str = "ultr53o?n"`, the output should be `"nortlu"`. # Input/Output - `[input]` string `str` A string consists of lowercase latin letters, digits and sym...
["def reverse_letter(s):\n return ''.join([i for i in s if i.isalpha()])[::-1]\n\n", "reverse_letter = lambda s: ''.join([i for i in s if i.isalpha()])[::-1]\n", "def reverse_letter(string):\n return ''.join(filter(str.isalpha, reversed(string)))", "import re\ndef reverse_letter(string):\n return re.sub(\"[^a-zA...
{"fn_name": "reverse_letter", "inputs": [["krishan"], ["ultr53o?n"], ["ab23c"], ["krish21an"]], "outputs": [["nahsirk"], ["nortlu"], ["cba"], ["nahsirk"]]}
introductory
https://www.codewars.com/kata/58b8c94b7df3f116eb00005b
def reverse_letter(string):
4,231
- Input: Integer `n` - Output: String Example: `a(4)` prints as ``` A A A A A A A A ``` `a(8)` prints as ``` A A A A A A A A A A A A A A A A A A ``` `a(12)` prints as ``` A A A...
["def a(n):\n \"\"\"\n \"\"\"\n if n % 2 != 0:\n n = n - 1\n if n < 4:\n return ''\n side = \" \" * (n - 1)\n li = [side + \"A\" + side]\n for i in range(1, n):\n side = side[1:]\n middle = \"A \" * (i - 1) if i == (n / 2) else \" \" * (i - 1)\n li.append(side + ...
{"fn_name": "a", "inputs": [[4], [7], [11], [30], [-5], [0], [3]], "outputs": [[" A \n A A \n A A A \nA A"], [" A \n A A \n A A \n A A A A \n A A \nA A"], [" A \n A A \n A A \n A A \n A A \n A A A A ...
introductory
https://www.codewars.com/kata/55de3f83e92c3e521a00002a
def a(n):
4,232
In Math, an improper fraction is a fraction where the numerator (the top number) is greater than or equal to the denominator (the bottom number) For example: ```5/3``` (five third). A mixed numeral is a whole number and a fraction combined into one "mixed" number. For example: ```1 1/2``` (one and a half) is a mixed n...
["def convert_to_mixed_numeral(parm):\n a, b = list(map(int, parm.split('/')))\n d, r = divmod(abs(a), b)\n s = (0 < a) - (a < 0)\n return parm if d == 0 else ('{}' + ' {}/{}' * (r != 0)).format(d * s, r, b)\n", "def convert_to_mixed_numeral(parm):\n sign, parm = parm[:(\"-\" in parm)], parm[(\"-\" in pa...
{"fn_name": "convert_to_mixed_numeral", "inputs": [["74/3"], ["9999/24"], ["74/30"], ["13/5"], ["5/3"], ["1/1"], ["10/10"], ["900/10"], ["9920/124"], ["6/2"], ["9/77"], ["96/100"], ["12/18"], ["6/36"], ["1/18"], ["-64/8"], ["-6/8"], ["-9/78"], ["-504/26"], ["-47/2"], ["-21511/21"]], "outputs": [["24 2/3"], ["416 15/24"...
introductory
https://www.codewars.com/kata/574e4175ff5b0a554a00000b
def convert_to_mixed_numeral(parm):
4,233
Goldbach's conjecture is one of the oldest and best-known unsolved problems in number theory and all of mathematics. It states: Every even integer greater than 2 can be expressed as the sum of two primes. For example: `6 = 3 + 3` `8 = 3 + 5` `10 = 3 + 7 = 5 + 5` `12 = 5 + 7` Some rules for the conjecture: - pairs...
["def goldbach(n):\n if n < 2:\n return []\n if n == 4:\n return [[2, 2]]\n l = n - 2\n sieve = [True] * (l // 2)\n for i in range(3, int(l**0.5) + 1, 2):\n if sieve[i // 2]:\n sieve[i * i // 2::i] = [False] * ((l - i * i - 1) // (2 * i) + 1)\n primes = [(2 * i + 1) for...
{"fn_name": "goldbach", "inputs": [[2], [4], [6], [8], [10], [52], [54], [56], [58], [100], [200], [1000], [5000]], "outputs": [[[]], [[[2, 2]]], [[[3, 3]]], [[[3, 5]]], [[[3, 7], [5, 5]]], [[[5, 47], [11, 41], [23, 29]]], [[[7, 47], [11, 43], [13, 41], [17, 37], [23, 31]]], [[[3, 53], [13, 43], [19, 37]]], [[[5, 53], ...
introductory
https://www.codewars.com/kata/56cf0eb69e14db4897000b97
def goldbach(n):
4,234
Consider a pyramid made up of blocks. Each layer of the pyramid is a rectangle of blocks, and the dimensions of these rectangles increment as you descend the pyramid. So, if a layer is a `3x6` rectangle of blocks, then the next layer will be a `4x7` rectangle of blocks. A `1x10` layer will be on top of a `2x11` layer o...
["def num_blocks(w, l, h):\n return w*l*h + (w+l)*h*(h-1)/2 + h*(h-1)*(2*h-1)/6", "def num_blocks(w, l, h):\n return w*l*h + (w+l) * (h-1)*h//2 + (h-1)*h*(2*h-1)//6\n \n\"\"\"\nFor those who wonder:\n\nfirst layer being of size w*l, the total number of blocks, SB, is:\n\n SB = w*l + (w+1)*(l+1) + (w+2)*(...
{"fn_name": "num_blocks", "inputs": [[1, 1, 2], [2, 4, 3], [1, 10, 10], [20, 30, 40]], "outputs": [[5], [47], [880], [83540]]}
introductory
https://www.codewars.com/kata/5ca6c0a2783dec001da025ee
def num_blocks(w, l, h):
4,235
Implement a function, so it will produce a sentence out of the given parts. Array of parts could contain: - words; - commas in the middle; - multiple periods at the end. Sentence making rules: - there must always be a space between words; - there must not be a space between a comma and word on the left; - there must ...
["def make_sentences(parts):\n return ' '.join(parts).replace(' ,', ',').strip(' .') + '.'", "import re\n\ndef make_sentences(parts):\n return re.sub(' ([,.])', r'\\1', ' '.join(parts).replace(' ,', ',')).rstrip('.') + '.'", "import re\n\ndef make_sentences(parts):\n return re.match(r'[^\\.]+', ' '.join(parts)...
{"fn_name": "make_sentences", "inputs": [[["hello", "world"]], [["Quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"]], [["hello", ",", "my", "dear"]], [["one", ",", "two", ",", "three"]], [["One", ",", "two", "two", ",", "three", "three", "three", ",", "4", "4", "4", "4"]], [["hello", "world", "."]], [["By...
introductory
https://www.codewars.com/kata/5297bf69649be865e6000922
def make_sentences(parts):
4,236
You're a statistics professor and the deadline for submitting your students' grades is tonight at midnight. Each student's grade is determined by their mean score across all of the tests they took this semester. You've decided to automate grade calculation by writing a function `calculate_grade()` that takes a list of...
["from bisect import bisect\nfrom statistics import mean\n\n\ndef calculate_grade(scores):\n return 'FDCBA'[bisect([60, 70, 80, 90], mean(scores))]\n", "def calculate_grade(scores):\n for score in scores:\n mean = sum(scores)/len(scores)\n if mean >= 90 and mean <= 100:\n return \"A\"\n ...
{"fn_name": "calculate_grade", "inputs": [[[92, 94, 99]], [[50, 60, 70, 80, 90]], [[50, 55]]], "outputs": [["A"], ["C"], ["F"]]}
introductory
https://www.codewars.com/kata/586e0dc9b98de0064b000247
def calculate_grade(scores):
4,237
Converting a 24-hour time like "0830" or "2030" to a 12-hour time (like "8:30 am" or "8:30 pm") sounds easy enough, right? Well, let's see if you can do it! You will have to define a function named "to12hourtime", and you will be given a four digit time string (in "hhmm" format) as input. Your task is to return a 12...
["from datetime import datetime\n\ndef to12hourtime(t):\n return datetime.strptime(t, '%H%M').strftime('%I:%M %p').lstrip('0').lower()", "def to12hourtime(t):\n hour = int(t[:2])\n \n if hour >= 12:\n hour -= 12\n suf = 'pm'\n else:\n suf = 'am'\n \n if hour == 0:\n hour...
{"fn_name": "to12hourtime", "inputs": [["0000"], ["0001"], ["0002"], ["0003"], ["0004"], ["0005"], ["0006"], ["0007"], ["0008"], ["0009"], ["0010"], ["0011"], ["0012"], ["0013"], ["0014"], ["0015"], ["0016"], ["0017"], ["0018"], ["0019"], ["0020"], ["0021"], ["0022"], ["0023"], ["0024"], ["0025"], ["0026"], ["0027"], [...
introductory
https://www.codewars.com/kata/59b0ab12cf3395ef68000081
def to12hourtime(t):
4,238
I assume most of you are familiar with the ancient legend of the rice (but I see wikipedia suggests [wheat](https://en.wikipedia.org/wiki/Wheat_and_chessboard_problem), for some reason) problem, but a quick recap for you: a young man asks as a compensation only `1` grain of rice for the first square, `2` grains for the...
["squares_needed = int.bit_length", "def squares_needed(grains):\n return grains.bit_length()", "def squares_needed(grains):\n if grains < 1:\n return 0\n else:\n return 1 + squares_needed(grains // 2)", "from math import log2, ceil\n\ndef squares_needed(grains):\n return grains and ceil(log2(...
{"fn_name": "squares_needed", "inputs": [[0], [1], [2], [3], [4]], "outputs": [[0], [1], [2], [2], [3]]}
introductory
https://www.codewars.com/kata/5b0d67c1cb35dfa10b0022c7
def squares_needed(grains):
4,239
Write a function called "filterEvenLengthWords". Given an array of strings, "filterEvenLengthWords" returns an array containing only the elements of the given array whose length is an even number. var output = filterEvenLengthWords(['word', 'words', 'word', 'words']); console.log(output); // --> ['word', 'word']
["def filter_even_length_words(words):\n return [word for word in words if len(word) % 2 == 0]", "def filter_even_length_words(words):\n even_words_array=[]\n for i in words:\n if len(i)%2==0:\n even_words_array.append(i)\n return even_words_array\n", "def filter_even_length_words(words):\n r...
{"fn_name": "filter_even_length_words", "inputs": [[["Hello", "World"]], [["One", "Two", "Three", "Four"]]], "outputs": [[[]], [["Four"]]]}
introductory
https://www.codewars.com/kata/59564f3bcc15b5591a00004a
def filter_even_length_words(words):
4,241
Your task is to make function, which returns the sum of a sequence of integers. The sequence is defined by 3 non-negative values: **begin**, **end**, **step**. If **begin** value is greater than the **end**, function should returns **0** *Examples* ~~~if-not:nasm ~~~ This is the first kata in the series: 1) Sum ...
["def sequence_sum(start, end, step):\n return sum(range(start, end+1, step))", "def sequence_sum(begin_number, end_number, step):\n return sum(range(begin_number, end_number+1, step))", "def sequence_sum(b, e, s):\n k = (e - b) // s\n return (1 + k) * (b + s * k / 2) if b <= e else 0", "def sequence_sum(begin,...
{"fn_name": "sequence_sum", "inputs": [[2, 6, 2], [1, 5, 1], [1, 5, 3], [0, 15, 3], [16, 15, 3], [2, 24, 22], [2, 2, 2], [2, 2, 1], [1, 15, 3], [15, 1, 3]], "outputs": [[12], [15], [5], [45], [0], [26], [2], [2], [35], [0]]}
introductory
https://www.codewars.com/kata/586f6741c66d18c22800010a
def sequence_sum(begin_number, end_number, step):
4,242
# Task You're standing at the top left corner of an `n × m` grid and facing towards the `right`. Then you start walking one square at a time in the direction you are facing. If you reach the border of the grid or if the next square you are about to visit has already been visited, you turn right. You stop w...
["def direction_in_grid(n, m):\n return \"LR\"[n%2] if m >= n else \"UD\"[m%2]\n", "def direction_in_grid(n,m):\n return \"LRUD\"[n%2 if m>=n else 2+m%2]\n", "NEXT = {'R': 'D', 'D': 'L', 'L': 'U', 'U': 'R'}\n\ndef direction_in_grid(n, m, d='R'):\n while n > 1:\n n, m, d = m, n-1, NEXT[d]\n return d", "...
{"fn_name": "direction_in_grid", "inputs": [[1, 1], [2, 2], [2, 3], [2, 4], [3, 1], [3, 2], [3, 3], [3, 4], [3, 5], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [5, 4], [5, 5], [5, 6], [100, 100]], "outputs": [["R"], ["L"], ["L"], ["L"], ["D"], ["U"], ["R"], ["R"], ["R"], ["U"], ["D"], ["L"], ["L"], ["L"], ["U"], ["R"], ["R...
introductory
https://www.codewars.com/kata/58bcd7f2f6d3b11fce000025
def direction_in_grid(n,m):
4,243
Write function avg which calculates average of numbers in given list.
["def find_average(array):\n return sum(array) / len(array) if array else 0", "def find_average(array):\n return 0 if not array else sum(array) / len(array)\n", "def find_average(array):\n try:\n return sum(array) / len(array)\n except ZeroDivisionError:\n return 0", "def find_average(array):\...
{"fn_name": "find_average", "inputs": [[[1, 2, 3]]], "outputs": [[2]]}
introductory
https://www.codewars.com/kata/57a2013acf1fa5bfc4000921
def find_average(array):
4,244
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are: * 232 * 110011 * 54322345 Complete the function to test if the given number (`num`) **can be rearranged** to form a numerical palindrome or not. Return a boolean (`...
["from collections import Counter\ndef palindrome(num):\n if not isinstance(num, int) or num < 0:\n return 'Not valid'\n return num > 10 and sum(1 for v in Counter(map(int, str(num))).values() if v % 2) <= 1", "def palindrome(num):\n s = str(num)\n return \"Not valid\" if not isinstance(num, int) or ...
{"fn_name": "palindrome", "inputs": [[5], [1212], ["ololo"], [1331], [194], [111222], ["Hello world!"], [3357665], ["357665"], [-42]], "outputs": [[false], [true], ["Not valid"], [true], [false], [false], ["Not valid"], [true], ["Not valid"], ["Not valid"]]}
introductory
https://www.codewars.com/kata/58e26b5d92d04c7a4f00020a
def palindrome(num):
4,245
You are given an initial 2-value array (x). You will use this to calculate a score. If both values in (x) are numbers, the score is the sum of the two. If only one is a number, the score is that number. If neither is a number, return 'Void!'. Once you have your score, you must return an array of arrays. Each sub arr...
["def explode(arr): \n return [arr] * sum(v for v in arr if isinstance(v,int)) or 'Void!'", "def explode(arr): \n numbers = [n for n in arr if type(n) == int]\n return [arr] * sum(numbers) if numbers else \"Void!\"", "def explode(arr): \n a,b,c = arr[0],arr[1],0\n if type(a) == int: c+=a\n if type(...
{"fn_name": "explode", "inputs": [[[9, 3]], [["a", 3]], [[6, "c"]], [["a", "b"]], [[1, 0]]], "outputs": [[[[9, 3], [9, 3], [9, 3], [9, 3], [9, 3], [9, 3], [9, 3], [9, 3], [9, 3], [9, 3], [9, 3], [9, 3]]], [[["a", 3], ["a", 3], ["a", 3]]], [[[6, "c"], [6, "c"], [6, "c"], [6, "c"], [6, "c"], [6, "c"]]], ["Void!"], [[[1, ...
introductory
https://www.codewars.com/kata/57eb936de1051801d500008a
def explode(arr):
4,246
# Covfefe Your are given a string. You must replace the word(s) `coverage` by `covfefe`, however, if you don't find the word `coverage` in the string, you must add `covfefe` at the end of the string with a leading space. For the languages where the string is not immutable (such as ruby), don't modify the given strin...
["def covfefe(s):\n return s.replace(\"coverage\",\"covfefe\") if \"coverage\" in s else s+\" covfefe\"", "def covfefe(s):\n if 'coverage' in s:\n return s.replace('coverage', 'covfefe')\n else:\n return s + ' ' + 'covfefe'\n", "def covfefe(s):\n return \"\".join(s.replace(\"coverage\", \"covf...
{"fn_name": "covfefe", "inputs": [["coverage"], ["coverage coverage"], ["nothing"], ["double space "], ["covfefe"]], "outputs": [["covfefe"], ["covfefe covfefe"], ["nothing covfefe"], ["double space covfefe"], ["covfefe covfefe"]]}
introductory
https://www.codewars.com/kata/592fd8f752ee71ac7e00008a
def covfefe(s):
4,247
# Task Mr.Odd is my friend. Some of his common dialogues are “Am I looking odd?” , “It’s looking very odd” etc. Actually “odd” is his favorite word. In this valentine when he went to meet his girlfriend. But he forgot to take gift. Because of this he told his gf that he did an odd thing. His gf became angry and gave...
["import re\n\npattern = re.compile('o(.*?)d(.*?)d')\n\ndef odd(s):\n n = 0\n while pattern.search(s):\n n += 1\n s = pattern.sub(r'\\1\\2', s, count=1)\n return n", "import re\n\no = re.compile(r\"o(.*?)d(.*?)d\")\n\ndef odd(stg):\n count = 0\n while o.search(stg):\n count += 1\n ...
{"fn_name": "odd", "inputs": [["oudddbo"], ["ouddddbo"], ["ooudddbd"], ["qoddoldfoodgodnooofostorodrnvdmddddeidfoi"]], "outputs": [[1], [1], [2], [6]]}
introductory
https://www.codewars.com/kata/589d74722cae97a7260000d9
def odd(s):
4,248
## Description You've been working with a lot of different file types recently as your interests have broadened. But what file types are you using the most? With this question in mind we look at the following problem. Given a `List/Array` of Filenames (strings) `files` return a `List/Array of string(s)` contatining ...
["from collections import Counter\nimport re\n\ndef solve(files):\n c = Counter(re.match('.*(\\.[^.]+)$', fn).group(1) for fn in files)\n m = max(c.values(),default=0)\n return sorted(k for k in c if c[k] == m)", "from collections import Counter\n\ndef solve(files):\n c = Counter(f[f.rfind(\".\"):] for f in...
{"fn_name": "solve", "inputs": [[["direful.pr", "festive.html", "historical.wav", "holistic.mp3", "impossible.jar", "gentle.cpp", "gleaming.xml", "inconclusive.js", "erect.jar", "befitting.mp3", "brief.wp", "beautiful.jar", "energetic.pt", "careful.wp", "defective.cpp", "icky.wav", "gorgeous.txt", "good.pt", "fat.pt", ...
introductory
https://www.codewars.com/kata/5c7254fcaccda64d01907710
def solve(files):
4,249
# Base64 Numeric Translator Our standard numbering system is (Base 10). That includes 0 through 9. Binary is (Base 2), only 1’s and 0’s. And Hexadecimal is (Base 16) (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F). A hexadecimal “F” has a (Base 10) value of 15. (Base 64) has 64 individual characters which translate ...
["DIGITS = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\"\n\ndef base64_to_base10(string):\n return sum(DIGITS.index(digit) * 64**i\n for i, digit in enumerate(string[::-1]))", "base64_to_base10=lambda strr:int(''.join([('0'*6+bin('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvw...
{"fn_name": "base64_to_base10", "inputs": [["WIN"], ["b64"], ["B64"], ["/+/"], ["HelloWorld"]], "outputs": [[90637], [114360], [7864], [262079], [134710352538679645]]}
introductory
https://www.codewars.com/kata/5632e12703e2037fa7000061
def base64_to_base10(string):
4,250
This kata aims to show the vulnerabilities of hashing functions for short messages. When provided with a SHA-256 hash, return the value that was hashed. You are also given the characters that make the expected value, but in alphabetical order. The returned value is less than 10 characters long. Return `nil` for Ruby ...
["from hashlib import sha256\nfrom itertools import permutations\n\n\ndef sha256_cracker(hash, chars):\n for p in permutations(chars, len(chars)):\n current = ''.join(p)\n if sha256(current.encode('utf-8')).hexdigest() == hash:\n return current\n", "import hashlib\nimport itertools\n\ndef sh...
{"fn_name": "sha256_cracker", "inputs": [["b8c49d81cb795985c007d78379e98613a4dfc824381be472238dbd2f974e37ae", "deGioOstu"], ["f58262c8005bb64b8f99ec6083faf050c502d099d9929ae37ffed2fe1bb954fb", "abc"]], "outputs": [["GoOutside"], [null]]}
introductory
https://www.codewars.com/kata/587f0abdd8730aafd4000035
def sha256_cracker(hash, chars):
4,251
*Recreation of [Project Euler problem #6](https://projecteuler.net/problem=6)* Find the difference between the sum of the squares of the first `n` natural numbers `(1 <= n <= 100)` and the square of their sum. ## Example For example, when `n = 10`: * The square of the sum of the numbers is: (1 + 2 + 3 + 4 + 5 + 6...
["def difference_of_squares(x):\n r = range(1,x+1,1)\n return (sum(r) ** 2) - (sum( z**2 for z in r))", "difference_of_squares = lambda n: n ** 2 * (n + 1) ** 2 / 4 - n * (n + 1) * (2 * n + 1) / 6", "def difference_of_squares(x):\n \n # Initialize\n square_sum = 0\n sum_squares = 0\n \n # Loop o...
{"fn_name": "difference_of_squares", "inputs": [[5], [10], [100]], "outputs": [[170], [2640], [25164150]]}
introductory
https://www.codewars.com/kata/558f9f51e85b46e9fa000025
def difference_of_squares(n):
4,252
Write a function that merges two sorted arrays into a single one. The arrays only contain integers. Also, the final outcome must be sorted and not have any duplicate.
["def merge_arrays(a, b): \n return sorted(set(a + b))", "def merge_arrays(first, second): \n return sorted(set(first + second))", "def merge_arrays(first, second): \n working = []\n for e in first:\n if e not in working:\n working.append(e)\n for i in second:\n if i not in worki...
{"fn_name": "merge_arrays", "inputs": [[[1, 3, 5], [2, 4, 6]], [[2, 4, 8], [2, 4, 6]], [[1, 2, 3], []], [[], []]], "outputs": [[[1, 2, 3, 4, 5, 6]], [[2, 4, 6, 8]], [[1, 2, 3]], [[]]]}
introductory
https://www.codewars.com/kata/573f5c61e7752709df0005d2
def merge_arrays(first, second):
4,253
In this Kata, you will be given two numbers, n and k and your task will be to return the k-digit array that sums to n and has the maximum possible GCD. For example, given `n = 12, k = 3`, there are a number of possible `3-digit` arrays that sum to `12`, such as `[1,2,9], [2,3,7], [2,4,6], ...` and so on. Of all the po...
["def solve(n,k):\n maxGcd = 2*n // (k * (k+1))\n for gcd in range(maxGcd, 0, -1):\n last = n-gcd * k*(k-1)//2\n if not last % gcd:\n return [gcd*x if x != k else last for x in range(1,k+1)]\n return []", "solve=lambda n,k: [n] if k==1 else (lambda r: r[-1] if len(r) else [])(list(filt...
{"fn_name": "solve", "inputs": [[12, 7], [12, 3], [12, 4], [18, 3], [18, 5], [24, 3], [24, 4], [24, 5], [24, 6], [276, 12]], "outputs": [[[]], [[2, 4, 6]], [[1, 2, 3, 6]], [[3, 6, 9]], [[1, 2, 3, 4, 8]], [[4, 8, 12]], [[2, 4, 6, 12]], [[1, 2, 3, 4, 14]], [[1, 2, 3, 4, 5, 9]], [[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, ...
introductory
https://www.codewars.com/kata/59f61aada01431e8c200008d
def solve(n,k):
4,254
Given a mathematical equation that has `*,+,-,/`, reverse it as follows: ```Haskell solve("100*b/y") = "y/b*100" solve("a+b-c/d*30") = "30*d/c-b+a" ``` More examples in test cases. Good luck! Please also try: [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2) [Simple remove duplicat...
["import re\n\ndef solve(eq):\n return ''.join(reversed(re.split(r'(\\W+)', eq)))", "def solve(eq):\n #\n # implemantation takes advantage of abscence of spaces\n #\n leq = (eq.replace('*', ' * ')\n .replace('/', ' / ')\n .replace('+', ' + ')\n .replace('-', ' - ')\n ...
{"fn_name": "solve", "inputs": [["100*b/y"], ["a+b-c/d*30"], ["a*b/c+50"]], "outputs": [["y/b*100"], ["30*d/c-b+a"], ["50+c/b*a"]]}
introductory
https://www.codewars.com/kata/5aa3af22ba1bb5209f000037
def solve(eq):
4,255
Write a function which converts the input string to uppercase. ~~~if:bf For BF all inputs end with \0, all inputs are lowercases and there is no space between. ~~~
["def make_upper_case(s): return s.upper()", "make_upper_case = str.upper", "def make_upper_case(strng):\n return strng.upper()", "def make_upper_case(s):\n return \"\".join(i.capitalize() for i in s)", "def make_upper_case(s):\n if isinstance(s,str):\n return s.upper()\n else:\n return", "def...
{"fn_name": "make_upper_case", "inputs": [["hello"], ["hello world"], ["hello world !"], ["heLlO wORLd !"], ["1,2,3 hello world!"]], "outputs": [["HELLO"], ["HELLO WORLD"], ["HELLO WORLD !"], ["HELLO WORLD !"], ["1,2,3 HELLO WORLD!"]]}
introductory
https://www.codewars.com/kata/57a0556c7cb1f31ab3000ad7
def make_upper_case(s):
4,256
You have to create a function,named `insertMissingLetters`, that takes in a `string` and outputs the same string processed in a particular way. The function should insert **only after the first occurrence** of each character of the input string, all the **alphabet letters** that: -**are NOT** in the original string ...
["def insert_missing_letters(s):\n s, lst, found, inside = s.lower(), [], set(), set(s.upper())\n for a in s:\n lst.append(a if a in found else\n a + ''.join(c for c in map(chr, range(ord(a)-31,91)) if c not in inside) )\n found.add(a)\n \n return ''.join(lst)", "from str...
{"fn_name": "insert_missing_letters", "inputs": [["hello"], ["abcdefghijklmnopqrstuvwxyz"], ["hellllllllllllooooo"], ["pixxa"], ["xpixax"], ["z"]], "outputs": [["hIJKMNPQRSTUVWXYZeFGIJKMNPQRSTUVWXYZlMNPQRSTUVWXYZloPQRSTUVWXYZ"], ["abcdefghijklmnopqrstuvwxyz"], ["hIJKMNPQRSTUVWXYZeFGIJKMNPQRSTUVWXYZlMNPQRSTUVWXYZlllllll...
introductory
https://www.codewars.com/kata/5ad1e412cc2be1dbfb000016
def insert_missing_letters(st):
4,257
Given n number of people in a room, calculate the probability that any two people in that room have the same birthday (assume 365 days every year = ignore leap year). Answers should be two decimals unless whole (0 or 1) eg 0.05
["def calculate_probability(n):\n return round(1 - (364 / 365) ** (n * (n - 1) / 2), 2)", "def calculate_probability(n, p=1):\n for i in range(n):\n p *= 365 - i\n return round(1 - p / 365**n, 2)", "from math import factorial\n\ndef calculate_probability(n):\n return round(1 - factorial(365) / (facto...
{"fn_name": "calculate_probability", "inputs": [[5], [15], [1], [365], [366]], "outputs": [[0.03], [0.25], [0], [1], [1]]}
introductory
https://www.codewars.com/kata/5419cf8939c5ef0d50000ef2
def calculate_probability(n):
4,258
## Task: Your task is to write a function which returns the sum of following series upto nth term(parameter). Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +... ## Rules: * You need to round the answer to 2 decimal places and return it as String. * If the given value is 0 then it should return 0.00 * You will ...
["def series_sum(n):\n return '{:.2f}'.format(sum(1.0/(3 * i + 1) for i in range(n)))", "def series_sum(n):\n sum = 0.0\n for i in range(0,n):\n sum += 1 / (1 + 3 * float(i))\n return '%.2f' % sum", "def series_sum(n):\n seriesSum = 0.0\n for x in range(n):\n seriesSum += 1 / (1 + x * 3)...
{"fn_name": "series_sum", "inputs": [[1], [2], [3], [4], [5], [6], [7], [8], [9], [15], [39], [58], [0]], "outputs": [["1.00"], ["1.25"], ["1.39"], ["1.49"], ["1.57"], ["1.63"], ["1.68"], ["1.73"], ["1.77"], ["1.94"], ["2.26"], ["2.40"], ["0.00"]]}
introductory
https://www.codewars.com/kata/555eded1ad94b00403000071
def series_sum(n):
4,259
## Task: You have to write a function `pattern` which returns the following Pattern(See Examples) upto desired number of rows. * Note:`Returning` the pattern is not the same as `Printing` the pattern. ### Parameters: pattern( n , x ); ^ ^ ...
["def pattern(n, *x):\n if n < 1:\n return \"\"\n x = x[0] if x and x[0] > 0 else 1\n result = []\n for i in range(1, n + 1):\n line = \" \" * (i - 1) + str(i % 10) + \" \" * (n - i)\n result.append((line + line[::-1][1:]) + (line[1:] + line[::-1][1:]) * (x - 1))\n return \"\\n\".joi...
{"fn_name": "pattern", "inputs": [[3, 7], [15, 3], [10, -29], [5], [4, 2, 3, 5, 7, -8], [-3, 5], [-11, -1], [-9999999], [-25, -11, 9], [-25, 5, -9, 55, -8, -7, 8]], "outputs": [["1 1 1 1 1 1 1 1\n 2 2 2 2 2 2 2 2 2 2 2 2 2 2 \n 3 3 3 3 3 3 3 \n 2 2 2 2 2 2 2 2 2 2 2 2 2 2 \n1 1 1 1 1...
introductory
https://www.codewars.com/kata/5592e5d3ede9542ff0000057
def pattern(n, x=1, *args):
4,260
You've made it through the moat and up the steps of knowledge. You've won the temples games and now you're hunting for treasure in the final temple run. There's good news and bad news. You've found the treasure but you've triggered a nasty trap. You'll surely perish in the temple chamber. With your last movements, you...
["def mark_spot(n):\n if not isinstance(n, int) or not n%2 or n<1: return '?'\n\n spots = [[' ']*n for _ in range(n)]\n for i,row in enumerate(spots):\n row[i],row[-1-i] = 'XX'\n\n return '\\n'.join( ' '.join(row).rstrip() for row in spots+[\"\"] )", "def mark_spot(n):\n if type(n) is not int or n...
{"fn_name": "mark_spot", "inputs": [[5], [1], [[]], [11], ["treasure"], ["5"], [-1], [3], [2], [0.5]], "outputs": [["X X\n X X\n X\n X X\nX X\n"], ["X\n"], ["?"], ["X X\n X X\n X X\n X X\n X X\n X\n X X\n X ...
introductory
https://www.codewars.com/kata/56648a2e2c464b8c030000bf
def mark_spot(n):
4,261
# Task A robot is standing at the `(0, 0)` point of the Cartesian plane and is oriented towards the vertical (y) axis in the direction of increasing y values (in other words, he's facing up, or north). The robot executes several commands each of which is a single positive integer. When the robot is given a positive in...
["def robot_walk(a):\n i=3\n while(i<len(a) and a[i] < a[i-2]): i+=1\n return i<len(a)\n", "def robot_walk(a):\n return any(x <= y for x,y in zip(a[1:], a[3:]))", "def robot_walk(a):\n if len(set(a)) == 1:\n return True\n movings = []\n p = (0, 0) # x, y\n dir = (0, 1)\n for k in a: \n ...
{"fn_name": "robot_walk", "inputs": [[[4, 4, 3, 2, 2, 3]], [[7, 5, 4, 5, 2, 3]], [[10, 3, 10, 2, 5, 1, 2]], [[11, 8, 6, 6, 4, 3, 7, 2, 1]], [[5, 5, 5, 5]], [[34241, 23434, 2341]], [[9348, 2188, 9348]]], "outputs": [[true], [true], [false], [true], [true], [false], [false]]}
introductory
https://www.codewars.com/kata/58a64b48586e9828df000109
def robot_walk(a):
4,262
Dee is lazy but she's kind and she likes to eat out at all the nice restaurants and gastropubs in town. To make paying quick and easy she uses a simple mental algorithm she's called The Fair %20 Rule. She's gotten so good she can do this in a few seconds and it always impresses her dates but she's perplexingly still si...
["def calc_tip(p, r):\n if p % 10 < 5:\n p //= 10\n else:\n p = p // 10 + 1\n if r == 1:\n tip = p + 1\n elif r == 0:\n tip = p - 1\n else:\n tip = int(p/2) - 1\n return tip if tip >= 0 else 0", "def calc_tip(p, r):\n if p%10<5: p-=p%10\n else: p+=(10-p%10)\n ...
{"fn_name": "calc_tip", "inputs": [[4, 1], [4, 0], [4, -1], [5, 1], [5, 0], [5, -1], [14, 1], [14, 0], [14, -1], [15, 1], [15, 0], [15, -1], [24, 1], [24, 0], [24, -1], [25, 1], [25, 0], [25, -1], [125, 1], [125, 0], [125, -1], [144, 1], [144, 0], [144, -1]], "outputs": [[1], [0], [0], [2], [0], [0], [2], [0], [0], [3]...
introductory
https://www.codewars.com/kata/568c3498e48a0231d200001f
def calc_tip(p, r):
4,263
For every string, after every occurrence of `'and'` and `'but'`, insert the substring `'apparently'` directly after the occurrence. If input does not contain 'and' or 'but', return the original string. If a blank string, return `''`. If substring `'apparently'` is already directly after an `'and'` and/or `'but'`, do ...
["import re\n\ndef apparently(string):\n return re.sub(r'(?<=\\b(and|but)\\b(?! apparently\\b))', ' apparently', string)", "import re\napparently=lambda Q:re.sub(r'(?<=\\band|\\bbut)\\b(?! apparently\\b)',' apparently',Q)", "import re\nfrom functools import partial\n\napparently = partial(re.sub, r'(?<=\\b(and|but)\...
{"fn_name": "apparently", "inputs": [["A fast-food resteraunt down the street was grumbling my tummy but I could not go."], ["apparently"], ["and"], ["but"], ["but apparently"], ["and apparently"], ["but but but and and and"], [""], ["but and apparently apparently apparently apparently"], ["and apparentlybutactuallynot...
introductory
https://www.codewars.com/kata/5b049d57de4c7f6a6c0001d7
def apparently(string):
4,264
You are given two positive integers ```a``` and ```b```. You can perform the following operations on ```a``` so as to obtain ```b``` : ``` (a-1)/2 (if (a-1) is divisible by 2) a/2 (if a is divisible by 2) a*2 ``` ```b``` will always be a power of 2. You are to write a function ```operation(a,b)``` that effici...
["from math import log2\n\ndef operation(a,b, n = 0):\n while log2(a) % 1:\n n += 1\n a //= 2\n return n + abs(log2(a/b))", "def operation(a,b):\n res = 0\n while a != 1 << a.bit_length()-1:\n a, res = a>>1, res+1\n return res + abs(a.bit_length() - b.bit_length())", "from math impor...
{"fn_name": "operation", "inputs": [[1, 1], [2, 4], [3, 8], [4, 16], [4, 1], [1, 4]], "outputs": [[0], [1], [4], [2], [2], [2]]}
introductory
https://www.codewars.com/kata/579ef9607cb1f38113000100
def operation(a,b):