problem_id
stringlengths
32
32
name
stringclasses
1 value
problem
stringlengths
200
14k
solutions
stringlengths
12
1.12M
test_cases
stringlengths
37
74M
difficulty
stringclasses
3 values
language
stringclasses
1 value
source
stringclasses
7 values
num_solutions
int64
12
1.12M
starter_code
stringlengths
0
956
01ac2a8f983de4294cb668172eab3df5
UNKNOWN
Number is a palindrome if it is equal to the number with digits in reversed order. For example, 5, 44, 171, 4884 are palindromes and 43, 194, 4773 are not palindromes. Write a method `palindrome_chain_length` which takes a positive number and returns the number of special steps needed to obtain a palindrome. The speci...
["def palindrome_chain_length(n):\n steps = 0\n while str(n) != str(n)[::-1]:\n n = n + int(str(n)[::-1])\n steps += 1\n return steps", "def palindrome_chain_length(n, count=0):\n if str(n) == str(n)[::-1]: return count\n else: return palindrome_chain_length(n + int(str(n)[::-1]), count+1)"...
{"fn_name": "palindrome_chain_length", "inputs": [[87], [1], [88], [89], [10]], "outputs": [[4], [0], [0], [24], [1]]}
INTRODUCTORY
PYTHON3
CODEWARS
21,849
def palindrome_chain_length(n):
f80f6ac6817410669d7708c3bda27ec5
UNKNOWN
## Check Digits Some numbers are more important to get right during data entry than others: a common example is product codes. To reduce the possibility of mistakes, product codes can be crafted in such a way that simple errors are detected. This is done by calculating a single-digit value based on the product number...
["from itertools import cycle\n\ndef add_check_digit(number):\n fact = cycle([2,3,4,5,6,7])\n r = sum( int(c) * next(fact) for c in number[::-1]) % 11\n return number + ('0' if not r else 'X' if r == 1 else str(11-r))", "from itertools import cycle\n\n\ndef add_check_digit(s):\n rem = 11 - sum(int(a) * b fo...
{"fn_name": "add_check_digit", "inputs": [["036532"], ["12388878"], ["111111111"], ["9735597355"], ["2356"], ["6789"]], "outputs": [["0365327"], ["123888782"], ["1111111118"], ["97355973550"], ["23566"], ["6789X"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,685
def add_check_digit(number):
371905b0b855d6badf88098f85c37b77
UNKNOWN
# Introduction Fish are an integral part of any ecosystem. Unfortunately, fish are often seen as high maintenance. Contrary to popular belief, fish actually reduce pond maintenance as they graze on string algae and bottom feed from the pond floor. They also make very enjoyable pets, providing hours of natural enterta...
["def fish(shoal):\n eaten, size, target = 0, 1, 4\n for f in sorted(map(int, shoal)):\n if f > size: break\n eaten += f\n if eaten >= target:\n size += 1\n target += 4 * size\n return size", "from collections import Counter\n\ndef fish(shoal):\n size, eaten = 1, 0...
{"fn_name": "fish", "inputs": [[""], ["0"], ["6"], ["1111"], ["11112222"], ["111122223333"], ["111111111111"], ["111111111111111111112222222222"], ["151128241212192113722321331"]], "outputs": [[1], [1], [1], [2], [3], [4], [3], [5], [5]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,791
def fish(shoal):
c1fd298107c99c75abc6a32d749171f6
UNKNOWN
# Task You got a `scratch lottery`, you want to know how much money you win. There are `6` sets of characters on the lottery. Each set of characters represents a chance to win. The text has a coating on it. When you buy the lottery ticket and then blow it off, you can see the text information below the coating. Each...
["def scratch(lottery):\n return sum(int(n) for lot in lottery for a,b,c,n in [lot.split()] if a==b==c)", "def scratch(lottery):\n return sum(int(i.split()[-1]) for i in lottery if len(set(i.split()))==2)", "def scratch(l):\n c = 0\n for i in l:\n i = i.split()\n if i[0] == i[1] == i[2]:\n ...
{"fn_name": "scratch", "inputs": [[["tiger tiger tiger 100", "rabbit dragon snake 100", "rat ox pig 1000", "dog cock sheep 10", "horse monkey rat 5", "dog dog dog 1000"]]], "outputs": [[1100]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,804
def scratch(lottery):
76093916332178f9734d18c895b4df9d
UNKNOWN
The description is rather long but it tries to explain what a financing plan is. The fixed monthly payment for a fixed rate mortgage is the amount paid by the borrower every month that ensures that the loan is paid off in full with interest at the end of its term. The monthly payment formula is based on the annuit...
["def amort(rate, bal, term, num_payments):\n monthlyRate = rate / (12 * 100)\n c = bal * (monthlyRate * (1 + monthlyRate) ** term) / (((1 + monthlyRate) ** term) - 1)\n newBalance = bal\n for i in range(num_payments):\n interest = newBalance * monthlyRate\n princ = c - interest\n newBa...
{"fn_name": "amort", "inputs": [[7.4, 10215, 24, 20], [7.9, 107090, 48, 41], [6.8, 105097, 36, 4], [3.8, 48603, 24, 10], [1.9, 182840, 48, 18], [1.9, 19121, 48, 2], [2.2, 112630, 60, 11], [5.6, 133555, 60, 53], [9.8, 67932, 60, 34], [3.7, 64760, 36, 24], [4.6, 85591, 36, 5], [7.0, 168742, 48, 16], [9.6, 17897, 60, 23],...
INTRODUCTORY
PYTHON3
CODEWARS
3,512
def amort(rate, bal, term, num_payments):
44088e6221f30534b2c229cdaffc8a46
UNKNOWN
Every natural number, ```n```, may have a prime factorization like: We define the **geometric derivative of n**, as a number with the following value: For example: calculate the value of ```n*``` for ```n = 24500```. ``` 24500 = 2²5³7² n* = (2*2) * (3*5²) * (2*7) = 4200 ``` Make a function, ```f``` that can perfo...
["def f(n):\n res = 1\n i = 2\n while n != 1:\n k = 0\n while n % i == 0:\n k += 1\n n //= i\n if k != 0:\n res *= k * i**(k-1)\n i += 1\n return res", "def f(n):\n p, n_, m = 2, 1, int(n ** .5)\n while n > 1 and p <= m:\n k = 0\n ...
{"fn_name": "f", "inputs": [[24500], [997]], "outputs": [[4200], [1]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,632
def f(n):
7ef17727137c494382911da2b5b6611f
UNKNOWN
Finish the solution so that it sorts the passed in array of numbers. If the function passes in an empty array or null/nil value then it should return an empty array. For example: ```python solution([1,2,3,10,5]) # should return [1,2,3,5,10] solution(None) # should return [] ``` ```Hakell sortNumbers [1, 2, 10, 50, 5...
["def solution(nums):\n return sorted(nums) if nums else []", "solution = lambda l: sorted(l) if l else []\n", "def solution(nums):\n return sorted(nums or [])", "def solution(nums):\n return [] if nums is None else sorted(nums)", "def solution(nums):\n return sorted(nums) if isinstance(nums, list) else []"...
{"fn_name": "solution", "inputs": [[[1, 2, 3, 10, 5]], [null], [[]], [[20, 2, 10]], [[2, 20, 10]]], "outputs": [[[1, 2, 3, 5, 10]], [[]], [[]], [[2, 10, 20]], [[2, 10, 20]]]}
INTRODUCTORY
PYTHON3
CODEWARS
15,350
def solution(nums):
2f9dce8e0fd1379e8b627b2c2ad63d15
UNKNOWN
# Introduction: Reversi is a game usually played by 2 people on a 8x8 board. Here we're only going to consider a single 8x1 row. Players take turns placing pieces, which are black on one side and white on the other, onto the board with their colour facing up. If one or more of the opponents pieces are sandwiched by ...
["import re\ndef reversi_row(moves):\n row = '........'\n stones = '*O'\n for i, m in enumerate(moves):\n L, M, R = row[:m], stones[i%2], row[m+1:]\n if R!='' and R[0] == stones[(i+1)%2] and R.find(stones[i%2])>0 and '.' not in R[:R.find(stones[i%2])]:\n R = R.replace(stones[(i+1)%2], ...
{"fn_name": "reversi_row", "inputs": [[[]], [[0]], [[0, 1]], [[0, 7, 4]], [[3]], [[3, 4]], [[3, 4, 5]], [[2, 1, 0]], [[0, 1, 4, 3, 2]], [[0, 1, 7, 2, 3]], [[3, 2, 7, 1, 0]], [[3, 4, 5, 6, 0, 2]], [[0, 1, 2, 3, 4, 5, 6, 7]], [[7, 0, 1]], [[0, 7, 6]], [[1, 0, 2, 3, 4, 5, 6, 7]], [[5, 1, 3, 4, 6]], [[1, 7, 0, 5, 6, 4]]], ...
INTRODUCTORY
PYTHON3
CODEWARS
5,374
def reversi_row(moves):
79517ebda9c084a5823aa8ee9b178849
UNKNOWN
# Task Given a string `str`, find the shortest possible string which can be achieved by adding characters to the end of initial string to make it a palindrome. # Example For `str = "abcdc"`, the output should be `"abcdcba"`. # Input/Output - `[input]` string `str` A string consisting of lowercase latin let...
["def build_palindrome(strng):\n n = 0\n while strng[n:] != strng[n:][::-1]: n += 1\n return strng + strng[:n][::-1]", "def build_palindrome(str):\n suf = \"\"\n for c in str:\n pal = str + suf\n if pal == pal[::-1]:\n return pal\n suf = c + suf", "def build_palindrome(s):...
{"fn_name": "build_palindrome", "inputs": [["abcdc"], ["ababab"]], "outputs": [["abcdcba"], ["abababa"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,461
def build_palindrome(s):
1f4d529a29384327d7ca9faf4ba37c3f
UNKNOWN
John is developing a system to report fuel usage but needs help with the coding. First, he needs you to write a function that, given the actual consumption (in l/100 km) and remaining amount of petrol (in l), will give you how many kilometers you'll be able to drive. Second, he needs you to write a function that, giv...
["def total_kilometers(cons, petrol):\n return round(100*petrol/cons, 2)\n\ndef check_distance(dist, cons, petrol):\n return (\"You will need to refuel\" if dist > total_kilometers(cons, petrol) else\n [ [n*100, dist-100*n, round(petrol-cons*n, 2)] for n in range(dist//100+1)])", "def total_kilometers(...
{"fn_name": "total_kilometers", "inputs": [[10, 60], [8, 0], [6.4, 54], [9.3, 87.3], [11.7, 63.4]], "outputs": [[600], [0], [843.75], [938.71], [541.88]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,112
def total_kilometers(cons, petrol):
08c8eec0f7a1fe5247627f2d1e4e10fd
UNKNOWN
# Task You are given `N` ropes, where the length of each rope is a positive integer. At each step, you have to reduce all the ropes by the length of the smallest rope. The step will be repeated until no ropes are left. Given the length of N ropes, print the number of ropes that are left before each step. # Example...
["def cut_the_ropes(arr):\n results = [len(arr)]\n while arr:\n m = min(arr)\n arr = [elem - m for elem in arr if elem != m]\n results.append(len(arr))\n return results[:-1]\n \n", "def cut_the_ropes(arr):\n qty = len(arr)\n sorted_ropes = sorted(arr)\n return [qty - sorted_rop...
{"fn_name": "cut_the_ropes", "inputs": [[[3, 3, 2, 9, 7]], [[1, 2, 3, 4, 3, 3, 2, 1]], [[13035, 6618, 13056, 20912, 1119, 13035, 6618, 6618, 8482, 13056]], [[9, 9, 9, 9, 7]]], "outputs": [[[5, 4, 2, 1]], [[8, 6, 4, 1]], [[10, 9, 6, 5, 3, 1]], [[5, 4]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,757
def cut_the_ropes(arr):
2c1a1edcbeadba6f23b3da1ffc7947cf
UNKNOWN
In this kata you will create a function that takes in a list and returns a list with the reverse order. ### Examples ```python reverse_list([1,2,3,4]) == [4,3,2,1] reverse_list([3,1,5,4]) == [4,5,1,3] ```
["def reverse_list(l):\n return l[::-1]", "def reverse_list(l):\n \"\"\"return a list with the reverse order of l\"\"\"\n return list(reversed(l))", "def reverse_list(l):\n l.reverse()\n return l", "def reverse_list(l):\n \"\"\" Returns reversed list. \"\"\"\n return list(reversed(l))", "def reverse_list(l):\n ...
{"fn_name": "reverse_list", "inputs": [[[1, 2, 3, 4]], [[3, 1, 5, 4]], [[3, 6, 9, 2]], [[1]]], "outputs": [[[4, 3, 2, 1]], [[4, 5, 1, 3]], [[2, 9, 6, 3]], [[1]]]}
INTRODUCTORY
PYTHON3
CODEWARS
11,317
def reverse_list(l):
2b52ae51b9e0a0f58995a7217c8dda86
UNKNOWN
Write a function that will encrypt a given sentence into International Morse Code, both the input and out puts will be strings. Characters should be separated by a single space. Words should be separated by a triple space. For example, "HELLO WORLD" should return -> ".... . .-.. .-.. --- .-- --- .-. .-.. -.." To f...
["#CHAR_TO_MORSE preloaded to convert characters into Morse code\nCODE = {'A': '.-', 'B': '-...', 'C': '-.-.', \n 'D': '-..', 'E': '.', 'F': '..-.',\n 'G': '--.', 'H': '....', 'I': '..',\n 'J': '.---', 'K': '-.-', 'L': '.-..',\n 'M': '--', 'N': '-.', 'O': '---...
{"fn_name": "encryption", "inputs": [["HELLO WORLD"], ["SOS"], ["1836"], ["THE QUICK BROWN FOX"], ["JUMPED OVER THE"], ["LAZY DOG"], ["WOLFRAM ALPHA 1"], ["CodeWars Rocks"], [""], ["Final basic test"]], "outputs": [[".... . .-.. .-.. --- .-- --- .-. .-.. -.."], ["... --- ..."], [".---- ---.. ...-- -...."], ["- .... ....
INTRODUCTORY
PYTHON3
CODEWARS
852
def encryption(string):
7e76fb7b6cf7f308bf86e19672bffbb4
UNKNOWN
# Task Given a sorted array of integers `A`, find such an integer x that the value of `abs(A[0] - x) + abs(A[1] - x) + ... + abs(A[A.length - 1] - x)` is the smallest possible (here abs denotes the `absolute value`). If there are several possible answers, output the smallest one. # Example For `A = [2, 4, 7]`, th...
["from statistics import median_low as absolute_values_sum_minimization", "def absolute_values_sum_minimization(A):\n d = {x: sum(abs(n-x) for n in A) for x in A}\n return min(d, key=lambda x: (d[x], x))", "import numpy as np\ndef absolute_values_sum_minimization(A):\n return np.median(A) if len(A) % 2 else A[le...
{"fn_name": "absolute_values_sum_minimization", "inputs": [[[2, 4, 7]], [[1, 1, 3, 4]], [[23]], [[-10, -10, -10, -10, -10, -9, -9, -9, -8, -8, -7, -6, -5, -4, -3, -2, -1, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37...
INTRODUCTORY
PYTHON3
CODEWARS
1,033
def absolute_values_sum_minimization(A):
c37b828377290d75d1f54658e12b6925
UNKNOWN
> When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said # Description: In this Kata, we have to try to create a mysterious pattern. Given a positive integer `m`, you can generate a Fibonacci sequence with a length of `m`: ``...
["def mysterious_pattern(m, n):\n rows = [[' '] * m for _ in range(n)]\n a, b = 1, 1\n for i in range(m):\n rows[a % n][i] = 'o'\n a, b = b, a + b\n rows = [''.join(r).rstrip() for r in rows]\n return '\\n'.join(rows).strip('\\n')", "def genFib():\n a,b = 1,0\n while 1:\n yield...
{"fn_name": "mysterious_pattern", "inputs": [[5, 5], [12, 4], [4, 5], [10, 1]], "outputs": [[" o\noo\n o\n o"], [" o o\noo o oo o\n o o\n o o"], ["oo\n o\n o"], ["oooooooooo"]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,703
def mysterious_pattern(m, n):
8bcc50aec2b2d13febe813176112a4e2
UNKNOWN
Jamie is a programmer, and James' girlfriend. She likes diamonds, and wants a diamond string from James. Since James doesn't know how to make this happen, he needs your help. ## Task You need to return a string that looks like a diamond shape when printed on the screen, using asterisk (`*`) characters. Trailing space...
["def diamond(n):\n if n < 0 or n % 2 == 0:\n return None\n \n result = \"*\" * n + \"\\n\";\n spaces = 1;\n n = n - 2\n while n > 0:\n current = \" \" * spaces + \"*\" * n + \"\\n\"\n spaces = spaces + 1\n n = n - 2\n result = current + result + current\n \n r...
{"fn_name": "diamond", "inputs": [[3], [0], [2], [-1], [-2]], "outputs": [[" *\n***\n *\n"], [null], [null], [null], [null]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,749
def diamond(n):
48c9ff91addec6936a2830584291882f
UNKNOWN
In this Kata, you will be given an array of numbers and a number `n`, and your task will be to determine if `any` array elements, when summed (or taken individually), are divisible by `n`. For example: * `solve([1,3,4,7,6],9) == true`, because `3 + 6` is divisible by `9` * `solve([1,2,3,4,5],10) == true` for sim...
["from itertools import combinations\n\ndef solve(a, n):\n return any(sum(c) % n == 0 for i in range(len(a)) for c in combinations(a, i+1))", "def solve(xs, n):\n rs = set()\n for x in xs:\n for r in list(rs):\n rs.add((r + x) % n)\n rs.add(x % n)\n return 0 in rs", "from itertools ...
{"fn_name": "solve", "inputs": [[[1, 2, 3, 4, 5], 8], [[7, 2, 8, 5], 16], [[1, 2, 3, 4, 5], 10], [[3, 1, 5, 7], 14], [[1, 2, 3, 4, 5], 15], [[8, 5, 3, 9], 7], [[8, 5, 3], 7]], "outputs": [[true], [false], [true], [false], [true], [true], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,660
def solve(arr,n):
c3b0ddc27a572a3ed13a7b792971f8d7
UNKNOWN
A [Word Square](https://en.wikipedia.org/wiki/Word_square) is a set of words written out in a square grid, such that the same words can be read both horizontally and vertically. The number of words, equal to the number of letters in each word, is known as the *order* of the square. For example, this is an *order* `5` ...
["from collections import Counter\ndef word_square(ls):\n n = int(len(ls)**0.5)\n return n*n==len(ls) and sum(i%2 for i in list(Counter(ls).values())) <= n\n", "def word_square(letters):\n root = int(len(letters)**0.5)\n return len(letters)**0.5 == root and sum([ letters.count(i)%2 for i in set(letters) ]) ...
{"fn_name": "word_square", "inputs": [["SATORAREPOTENETOPERAROTAS"], ["NOTSQUARE"], ["BITICETEN"], ["CARDAREAREARDART"], ["CODEWARS"], ["AAAAACEEELLRRRTT"], ["AAACCEEEEHHHMMTT"], ["AAACCEEEEHHHMMTTXXX"], ["ABCD"], ["GHBEAEFGCIIDFHGG"], ["AAHHFDKIHHFCXZBFDERRRTXXAA"], ["AABBCCDDEEFFGGGG"], ["ABCABCABC"], ["FRACTUREOUTLI...
INTRODUCTORY
PYTHON3
CODEWARS
2,420
def word_square(letters):
b48d86c73314e652168643b1fc1ca298
UNKNOWN
Write a function to calculate compound tax using the following table: For $10 and under, the tax rate should be 10%. For $20 and under, the tax rate on the first $10 is %10, and the tax on the rest is 7%. For $30 and under, the tax rate on the first $10 is still %10, the rate for the next $10 is still 7%, and everythi...
["def tax_calculator(total):\n if not isinstance(total, (int, float)) or total < 0: return 0\n \n tax = 0\n \n if total > 30: tax = 2.2 + (total - 30) * 0.03\n elif total > 20: tax = 1.7 + (total - 20) * 0.05\n elif total > 10: tax = 1 + (total-10) * 0.07\n elif total > 0: tax = total / 10.0\n\n...
{"fn_name": "tax_calculator", "inputs": [[1], [10], [11], [15], [18], [21], [26], [30], [30.49], [35], [100], [1000000], [0], [-3], [null], ["monkey"], [[]], [{}]], "outputs": [[0.1], [1], [1.07], [1.35], [1.56], [1.75], [2], [2.2], [2.21], [2.35], [4.3], [30001.3], [0], [0], [0], [0], [0], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,680
def tax_calculator(total):
cd96e45d99842ec075ddd718f2a80d20
UNKNOWN
There is an array with some numbers. All numbers are equal except for one. Try to find it! ```python find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2 find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55 ``` It’s guaranteed that array contains at least 3 numbers. The tests contain some very huge arrays, so think about performance. This is t...
["def find_uniq(arr):\n a, b = set(arr)\n return a if arr.count(a) == 1 else b", "def find_uniq(arr):\n if (arr[0]==arr[1]):\n return([x for x in arr[2:] if x!=arr[0] ][0])\n return(arr[0] if arr[1]==arr[2] else arr[1])\n", "def find_uniq(arr):\n s = set(arr)\n for e in s:\n if arr.coun...
{"fn_name": "find_uniq", "inputs": [[[1, 1, 1, 2, 1, 1]], [[0, 0, 0.55, 0, 0]], [[4, 4, 4, 3, 4, 4, 4, 4]], [[5, 5, 5, 5, 4, 5, 5, 5]], [[6, 6, 6, 6, 6, 5, 6, 6]], [[7, 7, 7, 7, 7, 7, 6, 7]], [[8, 8, 8, 8, 8, 8, 8, 7]], [[3, 3, 3, 3, 3, 3, 3, 2]], [[2, 2, 2, 2, 2, 2, 2, 1]], [[0, 1, 1, 1, 1, 1, 1, 1]]], "outputs": [[2]...
INTRODUCTORY
PYTHON3
CODEWARS
1,479
def find_uniq(arr):
4d896e6878954696be7a5c0062355812
UNKNOWN
*Translations appreciated* # Overview Your task is to decode a qr code. You get the qr code as 2 dimensional array, filled with numbers. 1 is for a black field and 0 for a white field. It is always a qr code of version 1 (21*21), it is always using mask 0 ((x+y)%2), it is always using byte mode and it always has erro...
["def scanner(qrc):\n bits = ''.join( str(qrc[x][y] ^ ((x+y)%2==0)) for x,y in ticTocGen())\n size = int(bits[4:12],2)\n return ''.join( chr(int(bits[i:i+8],2)) for i in range(12,12+8*size,8))\n\n\ndef ticTocGen():\n x,y,dx = 20,20,-1\n while y>13: \n yield from ( (x,y-dy) for dy in range(2) )\n ...
{"fn_name": "scanner", "inputs": [[[[1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1], [1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1], [1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1], [1, 0, 1, 1, 1, 0, 1, 0,...
INTRODUCTORY
PYTHON3
CODEWARS
9,004
def scanner(qrcode):
4f31cd509b2eb8c4c459859753fc8841
UNKNOWN
Complete the function ```circleArea``` so that it will return the area of a circle with the given ```radius```. Round the returned number to two decimal places (except for Haskell). If the radius is not positive or not a number, return ```false```. Example: ```python circleArea(-1485.86) #returns false circleArea...
["from math import pi\n\ndef circleArea(r):\n return round(pi * r ** 2, 2) if type(r) in (int, float) and r > 0 else False\n", "import math\n\ndef circleArea(r):\n try:\n if (r > 0):\n return round(math.pi*r**2, 2)\n else:\n return False\n except TypeError:\n return F...
{"fn_name": "circleArea", "inputs": [[0], ["An integer"]], "outputs": [[false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,301
def circleArea(r):
10158e942d19a39c271049f50e8d7813
UNKNOWN
# A wolf in sheep's clothing Wolves have been reintroduced to Great Britain. You are a sheep farmer, and are now plagued by wolves which pretend to be sheep. Fortunately, you are good at spotting them. Warn the sheep in front of the wolf that it is about to be eaten. Remember that you are standing **at the front of ...
["def warn_the_sheep(queue):\n n = len(queue) - queue.index('wolf') - 1\n return f'Oi! Sheep number {n}! You are about to be eaten by a wolf!' if n else 'Pls go away and stop eating my sheep'\n", "def warn_the_sheep(queue):\n i = queue[::-1].index('wolf')\n if i == 0:\n return 'Pls go away and stop e...
{"fn_name": "warn_the_sheep", "inputs": [[["sheep", "sheep", "sheep", "sheep", "sheep", "wolf", "sheep", "sheep"]], [["sheep", "wolf", "sheep", "sheep", "sheep", "sheep", "sheep"]], [["wolf", "sheep", "sheep", "sheep", "sheep", "sheep", "sheep"]], [["sheep", "wolf", "sheep"]], [["sheep", "sheep", "wolf"]]], "outputs": ...
INTRODUCTORY
PYTHON3
CODEWARS
14,374
def warn_the_sheep(queue):
441a15a2d69e91c115567a1d655c1996
UNKNOWN
You have been presented with a cipher, your goal is to re-create the cipher with little information. Use the examples provided to see if you can find a solution to how this cipher is made. You will be given no hints, only the handful of phrases that have already been deciphered for you. Your only hint: Spaces are lef...
["def cipher(p):\n return ''.join(chr((ord(j)+i%3+(i-1)//3-97)%26+97) if j!=' 'and i!=0 else j for i,j in enumerate(p))", "from itertools import count\n\nBASE = ord('a')\n\ndef deltas():\n for i in count(-1):\n yield max(i, 0)\n yield i + 2\n yield i + 3\n\ndef cipher(phrase):\n return ''....
{"fn_name": "cipher", "inputs": [["this will probably not be fun"], ["hopefully you will find satisfaction at least"], ["really this is very tedious"], ["if you made it this far you are a better programmer than i am"]], "outputs": [["tiks zjop twrggfrf uwz kl pcx"], ["hprehxmoc ctx cmrs mqtl zjdqcqjnfsaa nh ztnhj"], ["...
INTRODUCTORY
PYTHON3
CODEWARS
3,804
def cipher(phrase:
f49b1adc4c905cf36831374465d9d6cc
UNKNOWN
Given an array containing only zeros and ones, find the index of the zero that, if converted to one, will make the longest sequence of ones. For instance, given the array: ``` [1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1] ``` replacing the zero at index 10 (counting from 0) forms a sequence of 9 ones: `...
["def replace_zero(arr):\n m, im, i, lst = 0, -1, -1, ''.join(map(str,arr)).split('0')\n for a,b in zip(lst,lst[1:]):\n i += len(a) + 1 \n candidate = len(a)+len(b)+1\n if m <= candidate:\n im, m = i, candidate\n return im", "def replace_zero(arr):\n ret = [0,0]\n arr = [N...
{"fn_name": "replace_zero", "inputs": [[[1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1]], [[1, 1, 0, 1, 1, 0, 1, 1]], [[1, 1, 1, 0, 1, 1, 0, 1, 1, 1]], [[0, 1, 1, 1]], [[1, 1, 1, 0]], [[1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1]], [[0, 0, 0, 0, 0, 1]], [[0, 0, 0, 0, 1, 0]], [[1, 0, 0, 0, 0, 0]], [[0, 1, 0, 0, 0, 0]]...
INTRODUCTORY
PYTHON3
CODEWARS
5,266
def replace_zero(arr):
6cd9872b951e263f0c8da1630be0b5f7
UNKNOWN
You will be given two numbers `m,n`. The numbers could span from `0` to `10000`. We can get their product by using binary reduction as show in the table below. Example (to understand the table please read the description below it) real value of m(r) m n (r*n) 0 100 15 0 0 50 30 0 1 25 60 60 0 12 120 0 0...
["def bin_mul(m,n):\n if m < n: return bin_mul(n,m)\n if n == 0: return []\n res = []\n while m > 0:\n if m % 2 == 1: res.append(n)\n m = m//2; n *=2\n return res[::-1]", "def bin_mul(m, n):\n if m < n:\n m, n = n, m\n xs = []\n while m >= 1:\n m, m_r = divmod(m, 2)\n...
{"fn_name": "bin_mul", "inputs": [[100, 15], [15, 0], [0, 0]], "outputs": [[[960, 480, 60]], [[]], [[]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,400
def bin_mul(m,n):
73284294ee4bcb3e238e3c88fb4530df
UNKNOWN
# Introduction There is a war and nobody knows - the alphabet war! There are two groups of hostile letters. The tension between left side letters and right side letters was too high and the war began. The letters called airstrike to help them in war - dashes and dots are spreaded everywhere on the battlefield. # Ta...
["import re\n\npowers = {\n 'w': -4, 'p': -3, 'b': -2, 's': -1,\n 'm': +4, 'q': +3, 'd': +2, 'z': +1,\n}\n\ndef alphabet_war(fight):\n fight = re.sub('.(?=\\*)|(?<=\\*).', '', fight)\n result = sum(powers.get(c, 0) for c in fight)\n if result < 0:\n return 'Left side wins!'\n elif result > 0:\n...
{"fn_name": "alphabet_war", "inputs": [["z"], ["z*dq*mw*pb*s"], ["zdqmwpbs"], ["zz*zzs"], ["sz**z**zs"], ["z*z*z*zs"], ["*wwwwww*z*"]], "outputs": [["Right side wins!"], ["Let's fight again!"], ["Let's fight again!"], ["Right side wins!"], ["Left side wins!"], ["Left side wins!"], ["Left side wins!"]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,403
def alphabet_war(fight):
e000a3e337f8b7829a7c487f57ab5d0d
UNKNOWN
Description In English we often use "neutral vowel sounds" such as "umm", "err", "ahh" as fillers in conversations to help them run smoothly. Bob always finds himself saying "err". Infact he adds an "err" to every single word he says that ends in a consonant! Because Bob is odd, he likes to stick to this habit even w...
["def err_bob(s):\n res = \"\"\n for i, c in enumerate(s):\n res += c\n if i == len(s)-1 or s[i+1] in \" .,:;!?\":\n if c.islower() and c not in \"aeiou\":\n res += \"err\"\n if c.isupper() and c not in \"AEIOU\":\n res += \"ERR\"\n return res",...
{"fn_name": "err_bob", "inputs": [["r r r r r r r r"], ["THIS, is crazy!"], ["hI, hi. hI hi skY! sky? skY sky"], ["Hello, I am Mr Bob."], ["This, is. another! test? case to check your beautiful code."], ["Hello from the other siiiiideeee"], ["Punctuation? is, important! double space also"]], "outputs": [["rerr rerr re...
INTRODUCTORY
PYTHON3
CODEWARS
2,111
def err_bob(s):
544e40eed6936210fc7cc415593ca1e0
UNKNOWN
You are given a secret message you need to decipher. Here are the things you need to know to decipher it: For each word: - the second and the last letter is switched (e.g. `Hello` becomes `Holle`) - the first letter is replaced by its character code (e.g. `H` becomes `72`) Note: there are no special characters used, ...
["def decipher_word(word):\n i = sum(map(str.isdigit, word))\n decoded = chr(int(word[:i]))\n if len(word) > i + 1:\n decoded += word[-1]\n if len(word) > i:\n decoded += word[i+1:-1] + word[i:i+1]\n return decoded\n\ndef decipher_this(string):\n return ' '.join(map(decipher_word, string...
{"fn_name": "decipher_this", "inputs": [["65 119esi 111dl 111lw 108dvei 105n 97n 111ka"], ["84eh 109ero 104e 115wa 116eh 108sse 104e 115eokp"], ["84eh 108sse 104e 115eokp 116eh 109ero 104e 104dare"], ["87yh 99na 119e 110to 97ll 98e 108eki 116tah 119esi 111dl 98dri"], ["84kanh 121uo 80roti 102ro 97ll 121ruo 104ple"]], "...
INTRODUCTORY
PYTHON3
CODEWARS
4,512
def decipher_this(string):
73af21e30f44ba09cb3247a04136cdf5
UNKNOWN
If we multiply the integer `717 (n)` by `7 (k)`, the result will be equal to `5019`. Consider all the possible ways that this last number may be split as a string and calculate their corresponding sum obtained by adding the substrings as integers. When we add all of them up,... surprise, we got the original numbe...
["def sum_part(n):\n m, p, q, r, s = 1, 1, 1, 0, n\n while n > 9:\n n, d = divmod(n, 10)\n r += d * p\n p *= 10\n if d: m = 1\n else: m*= 2\n s += q*n + m*memo[r]\n q *= 2\n return s\n\nfrom collections import defaultdict\nqualified = defaultdict(list)\nmemo = {...
{"fn_name": "next_higher", "inputs": [[100, 3], [200, 4], [300, 5], [500, 7], [717, 7], [1611, 3]], "outputs": [[162], [260], [846], [717], [861], [1989]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,529
def next_higher(start,k):
57d103069bce0a12d6353cf1277b85ae
UNKNOWN
Given an integer `n`, find two integers `a` and `b` such that: ```Pearl A) a >= 0 and b >= 0 B) a + b = n C) DigitSum(a) + Digitsum(b) is maximum of all possibilities. ``` You will return the digitSum(a) + digitsum(b). ``` For example: solve(29) = 11. If we take 15 + 14 = 29 and digitSum = 1 + 5 + 1 + 4 = 11. There...
["def solve(n):\n if n < 10:\n return n\n a = int((len(str(n)) - 1) * '9')\n b = n - a\n return sum([int(i) for i in (list(str(a)) + list(str(b)))])\n", "def solve(n):\n a = (len(str(n)) - 1) * '9' or '0'\n return sum(map(int, a + str(n - int(a))))", "def solve(n):\n a = 0\n while a * 10 ...
{"fn_name": "solve", "inputs": [[18], [29], [45], [1140], [7019], [50000000], [15569047737], [2452148459], [1], [0]], "outputs": [[18], [11], [18], [33], [35], [68], [144], [116], [1], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,325
def solve(n):
21884cd3c88aac759c1c95f31646c578
UNKNOWN
# Description Given a number `n`, you should find a set of numbers for which the sum equals `n`. This set must consist exclusively of values that are a power of `2` (eg: `2^0 => 1, 2^1 => 2, 2^2 => 4, ...`). The function `powers` takes a single parameter, the number `n`, and should return an array of unique numbers. ...
["def powers(n):\n return [1<<i for i, x in enumerate(reversed(bin(n))) if x == \"1\"]", "def powers(n):\n return [2**i for i, d in enumerate(f\"{n:b}\"[::-1]) if d == \"1\"]", "def powers(n):\n tmp = []\n i = 0\n res = []\n while 2 ** i <= n:\n tmp.append(2 ** i)\n i += 1\n for j in ...
{"fn_name": "powers", "inputs": [[1], [2], [4], [32], [128], [512], [6], [14], [688], [8197], [1966], [9007199254740991]], "outputs": [[[1]], [[2]], [[4]], [[32]], [[128]], [[512]], [[2, 4]], [[2, 4, 8]], [[16, 32, 128, 512]], [[1, 4, 8192]], [[2, 4, 8, 32, 128, 256, 512, 1024]], [[1, 2, 4, 8, 16, 32, 64, 128, 256, 512...
INTRODUCTORY
PYTHON3
CODEWARS
1,411
def powers(n):
2c3f2e4832fc19e193e9a4e571ea8ca8
UNKNOWN
It's the academic year's end, fateful moment of your school report. The averages must be calculated. All the students come to you and entreat you to calculate their average for them. Easy ! You just need to write a script. Return the average of the given array rounded **down** to its nearest integer. The array will n...
["def get_average(marks):\n return sum(marks) // len(marks)\n", "def get_average(marks):\n average = sum(marks) / len(marks) \n return int(average)\n", "import numpy\n\ndef get_average(marks):\n return int(numpy.mean(marks))", "get_average = lambda marks: sum(marks)//len(marks)\n \n", "def get_average...
{"fn_name": "get_average", "inputs": [[[2, 2, 2, 2]], [[1, 5, 87, 45, 8, 8]], [[2, 5, 13, 20, 16, 16, 10]], [[1, 2, 15, 15, 17, 11, 12, 17, 17, 14, 13, 15, 6, 11, 8, 7]]], "outputs": [[2], [25], [11], [11]]}
INTRODUCTORY
PYTHON3
CODEWARS
14,171
def get_average(marks):
e17eea77536d1ecbbc938e6d996f8a17
UNKNOWN
In genetics 2 differents DNAs sequences can code for the same protein. This is due to the redundancy of the genetic code, in fact 2 different tri-nucleotide can code for the same amino-acid. For example the tri-nucleotide 'TTT' and the tri-nucleotide 'TTC' both code for the amino-acid 'F'. For more information you ca...
["def code_for_same_protein(seq1,seq2):\n if seq1 == seq2:\n return True\n lista = [['GCT','GCC','GCA','GCG'],['CGT','CGC','CGA','CGG','AGA','AGG'],['AAT','AAC'],['GAT','GAC'],['AAT','AAC','GAT','GAC'],['TGT','TGC'],['CAA','CAG'],['GAA','GAG'],['CAA','CAG','GAA','GAG'],['GGT','GGC','GGA','GGG'],['CAT','CAC...
{"fn_name": "code_for_same_protein", "inputs": [["ATGTCGTCAATTTAA", "ATGTCGTCAATTTAA"], ["ATGTTTTAA", "ATGTTCTAA"], ["ATGTTTTAA", "ATGATATAA"], ["ATGTTTGGGAATAATTAAGGGTAA", "ATGTTCGGGAATAATGGGAGGTAA"]], "outputs": [[true], [true], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
784
def code_for_same_protein(seq1,seq2):
1033451b8cde0ec1b1704592c0f35ac5
UNKNOWN
A system is transmitting messages in binary, however it is not a perfect transmission, and sometimes errors will occur which result in a single bit flipping from 0 to 1, or from 1 to 0. To resolve this, A 2-dimensional Parity Bit Code is used: https://en.wikipedia.org/wiki/Multidimensional_parity-check_code In this s...
["def correct(m, n, bits):\n l = m*n\n row = next((i for i in range(m) if f\"{bits[i*n:(i+1)*n]}{bits[l+i]}\".count(\"1\") % 2), None)\n col = next((i for i in range(n) if f\"{bits[i:l:n]}{bits[l+m+i]}\".count(\"1\") % 2), None)\n if row is col is None:\n return bits\n err = (l + row) if col is No...
{"fn_name": "correct", "inputs": [[1, 1, "111"], [1, 1, "011"], [1, 1, "101"], [1, 1, "110"], [2, 3, "11111010001"], [2, 3, "11011010001"], [2, 3, "11111011001"], [2, 3, "11111010011"]], "outputs": [["111"], ["111"], ["111"], ["111"], ["11111010001"], ["11111010001"], ["11111010001"], ["11111010001"]]}
INTRODUCTORY
PYTHON3
CODEWARS
8,109
def correct(m, n, bits):
7dbeebcc678a96831c8797f54fccc884
UNKNOWN
# Task You're given a substring s of some cyclic string. What's the length of the smallest possible string that can be concatenated to itself many times to obtain this cyclic string? # Example For` s = "cabca"`, the output should be `3` `"cabca"` is a substring of a cycle string "abcabcabcabc..." that can be obta...
["def cyclic_string(s):\n return next((i for i, _ in enumerate(s[1:], 1) if s.startswith(s[i:])), len(s))", "import math\n\ndef cyclic_string(s):\n for l in [i for i,ch in enumerate(s) if ch==s[0]][1:]:\n if (s[:l]*math.ceil(len(s)/l))[:len(s)] == s:\n return l\n return len(s)\n \n", "from itertools...
{"fn_name": "cyclic_string", "inputs": [["cabca"], ["aba"], ["ccccccccccc"], ["abaca"]], "outputs": [[3], [2], [1], [4]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,606
def cyclic_string(s):
fd8421c6be7f1dcb0ba6e3d4df9fb58c
UNKNOWN
Given the sum and gcd of two numbers, return those two numbers in ascending order. If the numbers do not exist, return `-1`, (or `NULL` in C, `tuple (-1,-1)` in C#, `pair (-1,-1)` in C++,`None` in Rust, `array {-1,-1} ` in Java and Golang). ``` For example: Given sum = 12 and gcd = 4... solve(12,4) = [4,8]. The two ...
["def solve(s,g):\n return -1 if s % g else (g, s - g)", "def solve(s,g):\n return not s%g and (g, s-g) or -1", "def solve(s,g):\n if s % g != 0:\n return -1\n else:\n b = s - g\n a = g\n return (a,b)", "import math\n\ndef solve(s,g):\n if s % g != 0:\n return -1\n e...
{"fn_name": "solve", "inputs": [[6, 3], [8, 2], [10, 3], [12, 4], [12, 5], [50, 10], [50, 4], [10, 5], [100, 5], [1000, 5]], "outputs": [[[3, 3]], [[2, 6]], [-1], [[4, 8]], [-1], [[10, 40]], [-1], [[5, 5]], [[5, 95]], [[5, 995]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,700
def solve(s,g):
8b463fa4c4ae8e4660a8288874400020
UNKNOWN
#### Task: Your job here is to implement a method, `approx_root` in Ruby/Python/Crystal and `approxRoot` in JavaScript/CoffeeScript, that takes one argument, `n`, and returns the approximate square root of that number, rounded to the nearest hundredth and computed in the following manner. 1. Start with `n = 213`...
["def approx_root(n):\n base = int(n**0.5)\n return round( base + (n - base**2) / ((base + 1)**2 - base**2) , 2)", "def approx_root(n):\n m = n**0.5\n a, b = [int(x) for x in [m, m + 1]]\n c = a**2\n return round(a + ((n - c) / (b**2 - c)), 2)", "def approx_root(n):\n b = int(n ** 0.5)\n diff_gn...
{"fn_name": "approx_root", "inputs": [[400], [401], [2], [4], [5], [6], [7], [8], [9], [100], [120], [106], [111], [121], [168]], "outputs": [[20], [20.02], [1.33], [2], [2.2], [2.4], [2.6], [2.8], [3], [10], [10.95], [10.29], [10.52], [11], [12.96]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,452
def approx_root(n):
f0ebf842bc32403708d402f94b96e1ee
UNKNOWN
Write a function name `nextPerfectSquare` that returns the first perfect square that is greater than its integer argument. A `perfect square` is a integer that is equal to some integer squared. For example 16 is a perfect square because `16=4*4`. ``` example n next perfect sqare 6 9 36 49 0 1 -5 0 ``` ...
["def next_perfect_square(n):\n return n>=0 and (int(n**0.5)+1)**2", "next_perfect_square=lambda n:(n>=0and int(n**.5)+1)**2", "def next_perfect_square(n):\n return n >= 0 and (int(n**.5)+1)**2", "import math\ndef next_perfect_square(n):\n return math.ceil((n + 1) ** 0.5) ** 2 if n > -1 else 0\n", "from bisect...
{"fn_name": "next_perfect_square", "inputs": [[6], [36], [0], [-5]], "outputs": [[9], [49], [1], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,009
def next_perfect_square(n):
c1c3156fbdf0e704196b87592ddd29d7
UNKNOWN
Due to another of his misbehaved, the primary school's teacher of the young Gauß, Herr J.G. Büttner, to keep the bored and unruly young schoolboy Karl Friedrich Gauss busy for a good long time, while he teaching arithmetic to his mates, assigned him the problem of adding up all the whole numbers from 1 through a give...
["def f(n):\n return n * (n + 1) // 2 if (isinstance(n, int) and n > 0) else None\n", "def f(n):\n return sum(range(1, n + 1)) if type(n) is int and n > 0 else None", "def f(n):\n try:\n return None if n <= 0 else sum(range(1,(n+1)))\n except:\n return None", "def f(n):\n return ((n+1)/2)*n...
{"fn_name": "f", "inputs": [[100], [300], [303], [50000], ["n"], [3.14], [0], [-10]], "outputs": [[5050], [45150], [46056], [1250025000], [null], [null], [null], [null]]}
INTRODUCTORY
PYTHON3
CODEWARS
13,527
def f(n):
347bf24b83c38793fa446be349eb948f
UNKNOWN
The snail crawls up the column. During the day it crawls up some distance. During the night she sleeps, so she slides down for some distance (less than crawls up during the day). Your function takes three arguments: 1. The height of the column (meters) 2. The distance that the snail crawls during the day (meters) 3. T...
["from math import ceil\n\n\ndef snail(column, day, night):\n return max(ceil((column-night)/(day-night)), 1)", "snail=lambda c,d,n:-(min(0,d-c)//(d-n))+1", "def snail(height, day, night):\n n,r = divmod(max(0,height-day), day-night)\n return n + 1 + (r!=0)", "def snail(column, day, night):\n count = 0\n ...
{"fn_name": "snail", "inputs": [[3, 2, 1], [10, 3, 1], [10, 3, 2], [100, 20, 5], [5, 10, 3]], "outputs": [[2], [5], [8], [7], [1]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,570
def snail(column, day, night):
681c6fcf336aedda0d0b4c1cd5c27901
UNKNOWN
You will be given an array that contains two strings. Your job is to create a function that will take those two strings and transpose them, so that the strings go from top to bottom instead of left to right. A few things to note: 1. There should be one space in between the two characters 2. You don't have to modify th...
["import itertools\ndef transpose_two_strings(arr):\n return '\\n'.join( ' '.join(elt) for elt in itertools.zip_longest(arr[0],arr[1],fillvalue=' ') )", "from itertools import*;transpose_two_strings=lambda a:'\\n'.join(map(' '.join,zip_longest(*a,fillvalue=' ')))", "def transpose_two_strings(arr):\n p = arr[:]\n ...
{"fn_name": "transpose_two_strings", "inputs": [[["Hello", "World"]], [["joey", "louise"]], [["a", "cat"]], [["cat", ""]], [["!a!a!", "?b?b"]]], "outputs": [["H W\ne o\nl r\nl l\no d"], ["j l\no o\ne u\ny i\n s\n e"], ["a c\n a\n t"], ["c \na \nt "], ["! ?\na b\n! ?\na b\n! "]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,450
def transpose_two_strings(arr):
8801c80818ac40a971d1cf9d02d79695
UNKNOWN
Description overhauled by V --- I've invited some kids for my son's birthday, during which I will give to each kid some amount of candies. Every kid hates receiving less amount of candies than any other kids, and I don't want to have any candies left - giving it to my kid would be bad for his teeth. However, not ev...
["from fractions import gcd\nfrom functools import reduce\n\ndef candies_to_buy(n):\n return reduce(lambda a,b:a*b//gcd(a,b), range(1,n+1))", "def candies_to_buy(n):\n xx = 1\n for i in range(n):\n x = xx\n while xx % (i+1):\n xx += x\n return xx", "from functools import reduce\nfro...
{"fn_name": "candies_to_buy", "inputs": [[1], [2], [5], [6], [9], [10], [60], [61], [100], [101]], "outputs": [[1], [2], [60], [60], [2520], [2520], [9690712164777231700912800], [591133442051411133755680800], [69720375229712477164533808935312303556800], [7041757898200960193617914702466542659236800]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,746
def candies_to_buy(n):
28fd91051bbf54dc8d834d5c29f2078a
UNKNOWN
This challenge extends the previous [repeater()](https://www.codewars.com/kata/thinkful-string-drills-repeater) challenge. Just like last time, your job is to write a function that accepts a string and a number as arguments. This time, however, you should format the string you return like this: ```python >>> repeater('...
["def repeater(string, n):\n return '\"{}\" repeated {} times is: \"{}\"'.format(string, n, string * n)\n", "def repeater(string, n):\n return '\"{0}\" repeated {1} times is: \"{2}\"'.format(string, n, string * n)\n", "def repeater(s, n):\n return '\"{}\" repeated {} times is: \"{}\"'.format(s, n, s * n)", "def ...
{"fn_name": "repeater", "inputs": [["yo", 3], ["WuB", 6], ["code, eat, code, sleep... ", 2]], "outputs": [["\"yo\" repeated 3 times is: \"yoyoyo\""], ["\"WuB\" repeated 6 times is: \"WuBWuBWuBWuBWuBWuB\""], ["\"code, eat, code, sleep... \" repeated 2 times is: \"code, eat, code, sleep... code, eat, code, sleep... \""]]...
INTRODUCTORY
PYTHON3
CODEWARS
1,215
def repeater(string, n):
f8a6037e1856e4d25dff2bef9cba6c9b
UNKNOWN
Create a function finalGrade, which calculates the final grade of a student depending on two parameters: a grade for the exam and a number of completed projects. This function should take two arguments: exam - grade for exam (from 0 to 100); projects - number of completed projects (from 0 and above); This function sh...
["def final_grade(exam, projects):\n if exam > 90 or projects > 10: return 100\n if exam > 75 and projects >= 5: return 90\n if exam > 50 and projects >= 2: return 75\n return 0", "def final_grade(exam, projects):\n if exam > 90 or projects > 10:\n return 100\n elif exam > 75 and projects >= 5:\n ...
{"fn_name": "final_grade", "inputs": [[100, 12], [99, 0], [10, 15], [85, 5], [55, 3], [55, 0], [20, 2]], "outputs": [[100], [100], [100], [90], [75], [0], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
25,590
def final_grade(exam, projects):
a6e31df2bfbc76fc6fa81480f089799f
UNKNOWN
Create a function that accepts dimensions, of Rows x Columns, as parameters in order to create a multiplication table sized according to the given dimensions. **The return value of the function must be an array, and the numbers must be Fixnums, NOT strings. Example: multiplication_table(3,3) 1 2 3 ...
["def multiplication_table(row,col):\n return [[(i+1)*(j+1) for j in range(col)] for i in range(row)]", "def multiplication_table(row,col):\n return [[x*y for y in range(1,col+1)] for x in range(1,row+1)]", "def multiplication_table(row,col):\n res = []\n for i in range(1, row+1):\n item = []\n ...
{"fn_name": "multiplication_table", "inputs": [[2, 2], [3, 3], [3, 4], [4, 4], [2, 5]], "outputs": [[[[1, 2], [2, 4]]], [[[1, 2, 3], [2, 4, 6], [3, 6, 9]]], [[[1, 2, 3, 4], [2, 4, 6, 8], [3, 6, 9, 12]]], [[[1, 2, 3, 4], [2, 4, 6, 8], [3, 6, 9, 12], [4, 8, 12, 16]]], [[[1, 2, 3, 4, 5], [2, 4, 6, 8, 10]]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,023
def multiplication_table(row,col):
5dfdb7f278c7742f41183b29fd96019c
UNKNOWN
In this Kata, you will be given two integers `n` and `k` and your task is to remove `k-digits` from `n` and return the lowest number possible, without changing the order of the digits in `n`. Return the result as a string. Let's take an example of `solve(123056,4)`. We need to remove `4` digits from `123056` and retur...
["from itertools import combinations\n\ndef solve(n, k):\n return ''.join(min(combinations(str(n), len(str(n))-k)))", "from itertools import combinations\n\ndef solve(n,k):\n return min((''.join(c) for c in combinations(str(n), len(str(n))-k)), key=int)", "from itertools import combinations as c\ndef solve(n,k):\...
{"fn_name": "solve", "inputs": [[123056, 1], [123056, 2], [123056, 3], [123056, 4], [1284569, 1], [1284569, 2], [1284569, 3], [1284569, 4]], "outputs": [["12056"], ["1056"], ["056"], ["05"], ["124569"], ["12456"], ["1245"], ["124"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,232
def solve(n, k):
afea6f0129823fc84ac5896fac76f974
UNKNOWN
Given a string ``string`` that contains only letters, you have to find out the number of **unique** strings (including ``string`` itself) that can be produced by re-arranging the letters of the ``string``. Strings are case **insensitive**. HINT: Generating all the unique strings and calling length on that isn't a gre...
["from operator import mul\nfrom functools import reduce\nfrom collections import Counter\nfrom math import factorial as fact\n\ndef uniq_count(s):\n return fact(len(s)) // reduce(mul, map(fact, Counter(s.lower()).values()), 1)", "from collections import Counter\nfrom functools import reduce\nfrom math import factor...
{"fn_name": "uniq_count", "inputs": [["AB"], ["ABC"], ["AbA"], ["ABBb"], ["AbcD"], ["AAA"], [""], ["ASTON"], ["BEST"], ["ABcDEFgHIJ"], ["ABcDEFgHIJbaslidbailsbdilasbdkanmsdklhkbHSJKHVDASH"], ["ABcDEFgHIJbaslidbailsbdilasbdkanmsdklhkbHSJKHVDASHVVYQVWKDVDWQUV"]], "outputs": [[2], [6], [3], [4], [24], [1], [1], [120], [24...
INTRODUCTORY
PYTHON3
CODEWARS
1,825
def uniq_count(s):
c24b9fb34855532e2cfb4e3ef1453200
UNKNOWN
# Two samurai generals are discussing dinner plans after a battle, but they can't seem to agree. The discussion gets heated and you are cannot risk favoring either of them as this might damage your political standing with either of the two clans the samurai generals belong to. Thus, the only thing left to do is find w...
["def common_ground(s1,s2):\n lst = []\n for w in s2.split():\n if w in s1.split() and w not in lst:\n lst.append(w)\n return ' '.join(lst) if lst else \"death\"", "def common_ground(s1,s2):\n words = s2.split()\n return ' '.join(sorted((a for a in set(s1.split()) if a in words),\n ...
{"fn_name": "common_ground", "inputs": [["eat chicken", "eat chicken and rice"], ["eat a burger and drink a coke", "drink a coke"], ["i like turtles", "what are you talking about"], ["aa bb", "aa bb cc"], ["aa bb cc", "bb cc"], ["aa bb cc", "bb cc bb aa"], ["aa bb", "cc dd"], ["aa bb", ""], ["", "cc dd"], ["", ""]], "o...
INTRODUCTORY
PYTHON3
CODEWARS
1,849
def common_ground(s1,s2):
24ed311254483a6a52ed4ac33b5bf8a3
UNKNOWN
Introduction to Disjunctions In logic and mathematics, a disjunction is an operation on 2 or more propositions. A disjunction is true if and only if 1 or more of its operands is true. In programming, we typically denote a disjunction using "||", but in logic we typically use "v". Example of disjunction: p = 1 > 2 = f...
["from functools import reduce\n\n\ndef disjunction(operands, is_exclusive):\n return reduce(bool.__xor__ if is_exclusive else bool.__or__, operands)", "from functools import reduce\n\ndef disjunction(operands, is_exclusive):\n op = int.__xor__ if is_exclusive else int.__or__\n return reduce(op, operands)", "f...
{"fn_name": "disjunction", "inputs": [[[false, true, true], false], [[false, true, false], false], [[false, true, true, true], true], [[true, true, true], false], [[true, true, true, true], false]], "outputs": [[true], [true], [true], [true], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,361
def disjunction(operands, is_exclusive):
bec64490f45e65895e28758adbb62dcc
UNKNOWN
Write a function `sumTimesTables` which sums the result of the sums of the elements specified in `tables` multiplied by all the numbers in between `min` and `max` including themselves. For example, for `sumTimesTables([2,5],1,3)` the result should be the same as ``` 2*1 + 2*2 + 2*3 + 5*1 + 5*2 + 5*3 ``` i.e. the table...
["def sum_times_tables(table,a,b):\n return sum(table) * (a + b) * (b - a + 1) // 2 \n", "def sum_times_tables(table,a,b):\n s = 0\n for i in range(a,b+1):\n s = s+i*sum(table)\n return s ", "def sum_times_tables(table,a,b):\n return sum(table) * sum(range(a, b+1))", "def T(n):\n return n * (n ...
{"fn_name": "sum_times_tables", "inputs": [[[2, 3], 1, 3], [[1, 3, 5], 1, 1], [[1, 3, 5], 1, 10], [[], 1, 10], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 1, 10], [[10, 9, 8, 7, 6, 5, 4, 3, 2, 1], 1, 10], [[5, 4, 7, 8, 9, 6, 3, 2, 10, 1], 1, 10], [[-2], -1, 3], [[-2, 2], -1, 3], [[-2, 3], -1, 3], [[2, -3], -1, 3], [[2, 4, 7], -1...
INTRODUCTORY
PYTHON3
CODEWARS
1,109
def sum_times_tables(table,a,b):
8f68008d0ed2d49f1c9a514abfce110e
UNKNOWN
In this kata you should simply determine, whether a given year is a leap year or not. In case you don't know the rules, here they are: * years divisible by 4 are leap years * but years divisible by 100 are **not** leap years * but years divisible by 400 are leap years Additional Notes: * Only valid years (positive i...
["def isLeapYear(year):\n return (year % 100 != 0 and year % 4 == 0) or year % 400 == 0", "from calendar import isleap as isLeapYear", "def isLeapYear(year):\n return year % 4 == 0 and year % 100 != 0 or year % 400 == 0", "def isLeapYear(year):\n return year % 4 is 0 and year % 100 is not 0 or year % 400 == 0"...
{"fn_name": "isLeapYear", "inputs": [[1984], [2000], [2004], [8], [0], [1234], [1100], [1194]], "outputs": [[true], [true], [true], [true], [true], [false], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
980
def isLeapYear(year):
36c2e3c30beb68d0bb6ca14be7186f59
UNKNOWN
# Description Write a function that checks whether a credit card number is correct or not, using the Luhn algorithm. The algorithm is as follows: * From the rightmost digit, which is the check digit, moving left, double the value of every second digit; if the product of this doubling operation is greater than 9 (e.g....
["def valid_card(card):\n s = list(map(int, str(card.replace(' ', ''))))\n s[0::2] = [d * 2 - 9 if d * 2 > 9 else d * 2 for d in s[0::2]]\n return sum(s) % 10 == 0", "def valid_card(card_number):\n total = 0\n for i, a in enumerate(reversed(card_number.replace(' ', ''))):\n if i % 2:\n ...
{"fn_name": "valid_card", "inputs": [["5457 6238 9823 4311"], ["8895 6238 9323 4311"], ["5457 6238 5568 4311"], ["5457 6238 9323 4311"], ["2222 2222 2222 2224"], ["5457 1125 9323 4311"], ["1252 6238 9323 4311"], ["9999 9999 9999 9995"], ["0000 0300 0000 0000"], ["4444 4444 4444 4448"], ["5457 6238 9323 1252"], ["5457 6...
INTRODUCTORY
PYTHON3
CODEWARS
1,863
def valid_card(card):
1e3848eefb92d080a4c7651c12d0421f
UNKNOWN
Create a function that will return ```true``` if the input is in the following date time format ```01-09-2016 01:20``` and ```false``` if it is not. This Kata has been inspired by the Regular Expressions chapter from the book Eloquent JavaScript.
["from re import match\n\n\ndef date_checker(date):\n return bool(match(r'\\d{2}-\\d{2}-\\d{4}\\s\\d{2}:\\d{2}', date))\n", "import re\n\ndef date_checker(date):\n return bool(re.fullmatch(\"\\d\\d-\\d\\d-\\d\\d\\d\\d \\d\\d:\\d\\d\", date))", "# Really, nothing to check if days and motnhs and zeroes or too high?...
{"fn_name": "date_checker", "inputs": [["01-09-2016 01:20"], ["01-09-2016 01;20"], ["01_09_2016 01:20"], ["14-10-1066 12:00"], ["Tenth of January"], ["20 Sep 1988"], ["19-12-2050 13:34"], ["Tue Sep 06 2016 01:46:38 GMT+0100"], ["01-09-2016 00:00"], ["01-09-2016 2:00"]], "outputs": [[true], [false], [false], [true], [fa...
INTRODUCTORY
PYTHON3
CODEWARS
1,281
def date_checker(date):
8060b2fb2e57bd8510c08aaf0e6b143d
UNKNOWN
Create a function that finds the [integral](https://en.wikipedia.org/wiki/Integral) of the expression passed. In order to find the integral all you need to do is add one to the `exponent` (the second argument), and divide the `coefficient` (the first argument) by that new number. For example for `3x^2`, the integral ...
["def integrate(coef, exp):\n exp = exp + 1\n coef = coef / exp if coef % exp else coef // exp\n return f\"{coef}x^{exp}\"", "def integrate(coefficient, exponent):\n return (str(coefficient // (exponent + 1)) + 'x^' + str(exponent + 1)) ", "def integrate(coefficient, exponent):\n return f'{coefficient /...
{"fn_name": "integrate", "inputs": [[3, 2], [12, 5], [20, 1], [40, 3], [90, 2]], "outputs": [["1x^3"], ["2x^6"], ["10x^2"], ["10x^4"], ["30x^3"]]}
INTRODUCTORY
PYTHON3
CODEWARS
13,302
def integrate(coefficient, exponent):
7fb237472dbda3b1db118290a11b9a48
UNKNOWN
Complete the function `scramble(str1, str2)` that returns `true` if a portion of ```str1``` characters can be rearranged to match ```str2```, otherwise returns ```false```. **Notes:** * Only lower case letters will be used (a-z). No punctuation or digits will be included. * Performance needs to be considered ## Exam...
["def scramble(s1,s2):\n for c in set(s2):\n if s1.count(c) < s2.count(c):\n return False\n return True", "from collections import Counter\ndef scramble(s1,s2):\n # Counter basically creates a dictionary of counts and letters\n # Using set subtraction, we know that if anything is left over...
{"fn_name": "scramble", "inputs": [["rkqodlw", "world"], ["cedewaraaossoqqyt", "codewars"], ["katas", "steak"], ["scriptjavx", "javascript"], ["scriptingjava", "javascript"], ["scriptsjava", "javascripts"], ["javscripts", "javascript"], ["aabbcamaomsccdd", "commas"], ["commas", "commas"], ["sammoc", "commas"]], "output...
INTRODUCTORY
PYTHON3
CODEWARS
27,427
def scramble(s1, s2):
df25ca56ff5b8d43a211da84a25b1020
UNKNOWN
Complete the function that counts the number of unique consonants in a string (made up of printable ascii characters). Consonants are letters used in English other than `"a", "e", "i", "o", "u"`. We will count `"y"` as a consonant. Remember, your function needs to return the number of unique consonants - disregarding...
["CONSONANTS = set('bcdfghjklmnpqrstvwxyz')\n\ndef count_consonants(text):\n return len(CONSONANTS.intersection(text.lower()))", "def count_consonants(text):\n return len(set(filter(str.isalpha,text.lower())) - set(\"aeiou\"))", "def count_consonants(s):\n return len({c for c in s.lower() if c in 'bcdfghjklmnp...
{"fn_name": "count_consonants", "inputs": [["sillystring"], ["aeiou"], ["abcdefghijklmnopqrstuvwxyz"], ["Count my unique consonants!!"]], "outputs": [[7], [0], [21], [7]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,408
def count_consonants(text):
c2013404746688fc24eced08c27bf45e
UNKNOWN
The goal is to write a pair of functions the first of which will take a string of binary along with a specification of bits, which will return a numeric, signed complement in two's complement format. The second will do the reverse. It will take in an integer along with a number of bits, and return a binary string. ht...
["def to_twos_complement(binary, bits):\n return int(binary.replace(' ', ''), 2) - 2 ** bits * int(binary[0])\n\ndef from_twos_complement(n, bits):\n return '{:0{}b}'.format(n & 2 ** bits - 1, bits)", "def to_twos_complement(b, bits):\n b = b.replace(\" \",\"\")\n return int(b,2) if int(b,2) < 2**(bits-1) e...
{"fn_name": "to_twos_complement", "inputs": [["00000001", 8], ["00000010", 8], ["01111110", 8], ["01111111", 8], ["11111111", 8], ["11111110", 8], ["10000010", 8], ["1000 0000", 8], ["1010 1010 0010 0010 1110 1010 0010 1110", 32], ["1000 0000 1110 1111 0011 0100 1100 1010", 32], ["10110001000100000101100011111000", 32]...
INTRODUCTORY
PYTHON3
CODEWARS
3,033
def to_twos_complement(binary, bits):
754a2e7b82de0cf97f34f12fb1015dee
UNKNOWN
# MOD 256 without the MOD operator The MOD-operator % (aka mod/modulus/remainder): ``` Returns the remainder of a division operation. The sign of the result is the same as the sign of the first operand. (Different behavior in Python!) ``` The short unbelievable mad story for this kata: I wrote a program and needed th...
["def mod256_without_mod(number):\n return number & 255 ", "def mod256_without_mod(number):\n return number-number//256*256", "def mod256_without_mod(number):\n return number.__mod__(256)\n", "def mod256_without_mod(number):\n return divmod(number, 256)[1]\n", "def mod256_without_mod(num):\n return num & 255"...
{"fn_name": "mod256_without_mod", "inputs": [[254], [256], [258], [-254], [-256], [-258]], "outputs": [[254], [0], [2], [2], [0], [254]]}
INTRODUCTORY
PYTHON3
CODEWARS
765
def mod256_without_mod(number):
f1ba3de1ebfe330343fe915b2308577d
UNKNOWN
# Task You have set an alarm for some of the week days. Days of the week are encoded in binary representation like this: ``` 0000001 - Sunday 0000010 - Monday 0000100 - Tuesday 0001000 - Wednesday 0010000 - Thursday 0100000 - Friday 1000000 - Saturday``` For example, if your alarm is set only for Sunday and Friday...
["def next_day_of_week(current_day, available_week_days):\n x = 2 ** current_day\n while not x & available_week_days:\n x = max(1, (x * 2) % 2 ** 7)\n return x.bit_length()", "def next_day_of_week(c, a):\n return next((weekday - 1) % 7 + 1 for weekday in range(c+1, c+8) if (1 << ((weekday-1) % 7)) & ...
{"fn_name": "next_day_of_week", "inputs": [[4, 42], [6, 42], [7, 42]], "outputs": [[6], [2], [2]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,702
def next_day_of_week(current_day, available_week_days):
7e3eaa1fb0e779af0d16a639d2063996
UNKNOWN
In this Kata, you will write a function `doubles` that will remove double string characters that are adjacent to each other. For example: `doubles('abbcccdddda') = 'aca'`, because, from left to right: ```Haskell a) There is only one 'a' on the left hand side, so it stays. b) The 2 b's disappear because we are removin...
["def doubles(s):\n cs = []\n for c in s:\n if cs and cs[-1] == c:\n cs.pop()\n else:\n cs.append(c)\n return ''.join(cs)", "def doubles(s):\n for i in s:\n if i*2 in s:\n \n s = s.replace(i*2, '')\n return s", "import re\n\ndef doubles(s):...
{"fn_name": "doubles", "inputs": [["abbbzz"], ["zzzzykkkd"], ["abbcccdddda"], ["vvvvvoiiiiin"], ["rrrmooomqqqqj"], ["xxbnnnnnyaaaaam"], ["qqqqqqnpppgooooonpppppqmmmmmc"], ["qqqqqwwwx"], ["jjjfzzzzzzsddgrrrrru"], ["jjjjjfuuuutgggggqppdaaas"], ["iiiiibllllllyqqqqqbiiiiiituuf"], ["mmmmmmuzzqllllmqqqp"]], "outputs": [["ab"...
INTRODUCTORY
PYTHON3
CODEWARS
1,665
def doubles(s):
2a47007c9ebe69ea0532d8bedd4796ae
UNKNOWN
## Task Using `n` as a parameter in the function `pattern`, where `n>0`, complete the codes to get the pattern (take the help of examples): **Note:** There is no newline in the end (after the pattern ends) ### Examples `pattern(3)` should return `"1\n1*2\n1**3"`, e.g. the following: ``` 1 1*2 1**3 ``` `pattern(10...
["def pattern(n):\n return '\\n'.join(['1'] + ['1' + '*' * (i-1) + str(i) for i in range(2, n+1)])\n", "def pattern(n):\n s = ''\n for i in range(n):\n if i == 0:\n s += '1\\n'\n else:\n s += '1{}{}\\n'.format('*' * i, i + 1)\n \n return s.rstrip('\\n')\n", "def patter...
{"fn_name": "pattern", "inputs": [[3], [7], [20]], "outputs": [["1\n1*2\n1**3"], ["1\n1*2\n1**3\n1***4\n1****5\n1*****6\n1******7"], ["1\n1*2\n1**3\n1***4\n1****5\n1*****6\n1******7\n1*******8\n1********9\n1*********10\n1**********11\n1***********12\n1************13\n1*************14\n1**************15\n1**************...
INTRODUCTORY
PYTHON3
CODEWARS
1,218
def pattern(n):
a9c7bb32178bde4acc66512f5c8895ac
UNKNOWN
Implement a function/class, which should return an integer if the input string is in one of the formats specified below, or `null/nil/None` otherwise. Format: * Optional `-` or `+` * Base prefix `0b` (binary), `0x` (hexadecimal), `0o` (octal), or in case of no prefix decimal. * Digits depending on base Any extra char...
["import re\n\ndef to_integer(s):\n if re.match(\"\\A[+-]?(\\d+|0b[01]+|0o[0-7]+|0x[0-9a-fA-F]+)\\Z\", s):\n return int(s, 10 if s[1:].isdigit() else 0)", "from re import compile, match\n\nREGEX = compile(r'[+-]?(0(?P<base>[bxo]))?[\\d\\w]+\\Z')\n\n\ndef to_integer(strng):\n try:\n return int(strng,...
{"fn_name": "to_integer", "inputs": [["123"], ["0x123"], ["0o123"], ["0123"], ["123 "], [" 123"], ["0b1010"], ["+123"], ["-123"], ["0B1010"], ["0b12"], ["-0x123"], ["-0o123"], ["-0123"], ["123\n"], ["\n123"], ["-0b1010"], ["0xDEADbeef"], ["0X123"], ["0O123"], ["0o18"]], "outputs": [[123], [291], [83], [123], [null], [n...
INTRODUCTORY
PYTHON3
CODEWARS
3,135
def to_integer(string):
ade3aba1c5f83e5fda3f033632d12ac3
UNKNOWN
# Task The number is considered to be `unlucky` if it does not have digits `4` and `7` and is divisible by `13`. Please count all unlucky numbers not greater than `n`. # Example For `n = 20`, the result should be `2` (numbers `0 and 13`). For `n = 100`, the result should be `7` (numbers `0, 13, 26, 39, 52, 65, a...
["def unlucky_number(n):\n return sum(not ('4' in s or '7' in s) for s in map(str, range(0, n+1, 13)))", "def unlucky_number(n):\n return sum(1 for k in range(0, n+1, 13) if not set(str(k)) & {\"4\", \"7\"})\n", "def unlucky_number(n):\n return sum(x % 13 == 0 and '4' not in str(x) and '7' not in str(x) for x in...
{"fn_name": "unlucky_number", "inputs": [[20], [100], [1000], [1000000]], "outputs": [[2], [7], [40], [20182]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,089
def unlucky_number(n):
acbc3d1bcd7e79942c44364952f6a6bd
UNKNOWN
Define a method that accepts 2 strings as parameters. The method returns the first string sorted by the second. ```python sort_string("foos", "of") == "oofs" sort_string("string", "gnirts") == "gnirts" sort_string("banana", "abn") == "aaabnn" ``` To elaborate, the second string defines the ordering. It is po...
["def sort_string(s, ordering):\n answer = ''\n for o in ordering:\n answer += o * s.count(o)\n s = s.replace(o,'')\n return answer + s ", "def sort_string(s, ordering):\n dct = {c:-i for i,c in enumerate(reversed(ordering))}\n return ''.join(sorted(s,key=lambda c:dct.get(c,1)))", "sort_str...
{"fn_name": "sort_string", "inputs": [["banana", "abn"], ["banana", "xyz"], ["banana", "an"], ["foos", "of"], ["string", "gnirts"], ["banana", "a"], ["bungholio", "aacbuoldiiaoh"], ["fumyarhncujlj", "nsejcwn"]], "outputs": [["aaabnn"], ["banana"], ["aaannb"], ["oofs"], ["gnirts"], ["aaabnn"], ["buoolihng"], ["njjcfumya...
INTRODUCTORY
PYTHON3
CODEWARS
1,692
def sort_string(s, ordering):
e6523a65f01e265f87ec7a2d65176790
UNKNOWN
Magic The Gathering is a collectible card game that features wizards battling against each other with spells and creature summons. The game itself can be quite complicated to learn. In this series of katas, we'll be solving some of the situations that arise during gameplay. You won't need any prior knowledge of the gam...
["from itertools import zip_longest\n\ndef battle(player1, player2):\n result = {'player1': [], 'player2': []}\n for (p1, t1), (p2, t2) in zip_longest(player1, player2, fillvalue=[0,0]):\n if t1 > p2:\n result['player1'].append([p1,t1])\n if t2 > p1:\n result['player2'].append(...
{"fn_name": "battle", "inputs": [[[[2, 3], [1, 4]], [[3, 3], [4, 1]]], [[], []], [[[1, 1]], [[1, 1]]], [[[2, 1]], [[2, 1]]], [[[1, 2]], [[1, 2]]], [[[2, 3]], [[3, 2]]], [[[2, 7]], [[3, 5]]], [[[2, 5]], [[6, 6]]], [[[6, 6]], [[2, 5]]], [[], [[1, 1], [2, 2]]], [[[1, 1], [2, 2]], []], [[[1, 3], [3, 5], [4, 6], [5, 2]], [[...
INTRODUCTORY
PYTHON3
CODEWARS
2,769
def battle(player1, player2):
148f955786eefbb98e89aba8993078ea
UNKNOWN
We need a function (for commercial purposes) that may perform integer partitions with some constraints. The function should select how many elements each partition should have. The function should discard some "forbidden" values in each partition. So, create ```part_const()```, that receives three arguments. ```part_co...
["def p(t,k,n,l=1):\n if t<l: pass\n elif k==1 and t!=n: yield [t]\n else: yield from ([m]+s for m in range(l,t-l+1) for s in p(t-m,k-1,n,m) if m!=n)\n\ndef part_const(t,k,n): return sum(1 for _ in p(t,k,n))", "def part_const(n, k, num):\n return part(n, k) - part(n-(num or n), k-1)\n\ndef part(n, k):\n ...
{"fn_name": "part_const", "inputs": [[10, 3, 2], [10, 3, 0], [10, 4, 1], [10, 5, 3], [15, 5, 3], [15, 5, 4], [15, 3, 3]], "outputs": [[4], [8], [2], [4], [15], [19], [13]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,235
def part_const(n, k, num):
e25bf05ae9ea52d911738488b62f78d5
UNKNOWN
As the title suggests, this is the hard-core version of another neat kata. The task is simple to explain: simply sum all the numbers from the first parameter being the beginning to the second parameter being the upper limit (possibly included), going in steps expressed by the third parameter: ```python sequence_sum(...
["# from math import copysign\ndef sequence_sum(a, b, step):\n n = (b-a)//step\n return 0 if n<0 else (n+1)*(n*step+a+a)//2", "def sequence_sum(b, e, s):\n q, r = divmod(e - b, s)\n return (b + e - r) * max(q + 1, 0) // 2", "def sequence_sum(start, stop, step):\n n = (stop - start) // step\n last = st...
{"fn_name": "sequence_sum", "inputs": [[2, 6, 2], [1, 5, 1], [1, 5, 3], [-1, -5, -3], [16, 15, 3], [-24, -2, 22], [-2, 4, 658], [780, 6851543, 5], [9383, 71418, 2], [20, 673388797, 5]], "outputs": [[12], [15], [5], [-5], [0], [-26], [-2], [4694363402480], [1253127200], [45345247259849570]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,469
def sequence_sum(b, e, s):
ea55ac8b0c46ffaf5deab76fcf3e8026
UNKNOWN
Write a method that takes a string as an argument and groups the number of time each character appears in the string as a hash sorted by the highest number of occurrences. The characters should be sorted alphabetically e.g: ```python get_char_count("cba") == {1: ["a", "b", "c"]} ``` You should ignore spaces, special...
["def get_char_count(s):\n counts = {}\n for c in (c.lower() for c in s if c.isalnum()):\n counts[c] = counts[c] + 1 if c in counts else 1\n m = {}\n for k, v in counts.items():\n m[v] = sorted(m[v] + [k]) if v in m else [k]\n return m", "from collections import Counter, defaultdict\nfrom b...
{"fn_name": "get_char_count", "inputs": [["Get me the bacon!"], ["Codewars is bacon"], ["France is also bacon"], ["AaAAaAAabB!B!B3b23jdc"], [""], ["!!!@@@"], ["Mississippi"], ["Hello. Hello? HELLO!"], ["aaa...bb...c!"], ["abc123"], ["aaabbbccc"]], "outputs": [[{"3": ["e"], "2": ["t"], "1": ["a", "b", "c", "g", "h", "m"...
INTRODUCTORY
PYTHON3
CODEWARS
2,875
def get_char_count(s):
87f9668de271b0d8a435e9433abf38c1
UNKNOWN
Create a program that will take in a string as input and, if there are duplicates of more than two alphabetical characters in the string, returns the string with all the extra characters in a bracket. For example, the input "aaaabbcdefffffffg" should return "aa[aa]bbcdeff[fffff]g" Please also ensure that the input ...
["import re\ndef string_parse(string):\n return re.sub(r'(.)\\1(\\1+)', r'\\1\\1[\\2]', string) if isinstance(string, str) else 'Please enter a valid string'", "import re\ndef string_parse(s):\n if not isinstance(s, str): return \"Please enter a valid string\"\n for l in set(s):\n s = re.sub(r\"(%s%s)(%...
{"fn_name": "string_parse", "inputs": [["aaaabbcdefffffffg"], [3], ["boopdedoop"], ["helloookat"], [true], [""], ["aAAabbcdeffFfFffg"], ["aAAabbcdeFFFffffg"], [{}], [[5.3]]], "outputs": [["aa[aa]bbcdeff[fffff]g"], ["Please enter a valid string"], ["boopdedoop"], ["helloo[o]kat"], ["Please enter a valid string"], [""], ...
INTRODUCTORY
PYTHON3
CODEWARS
7,522
def string_parse(string):
b0d3d7f168ce77bfed77fc8edc9ee777
UNKNOWN
This kata requires you to convert minutes (`int`) to hours and minutes in the format `hh:mm` (`string`). If the input is `0` or negative value, then you should return `"00:00"` **Hint:** use the modulo operation to solve this challenge. The modulo operation simply returns the remainder after a division. For example t...
["def time_convert(num):\n return \"{:02d}:{:02d}\".format(*divmod(max(num, 0), 60))", "def time_convert(num):\n if num <= 0:\n return '00:00'\n return f'{num//60:02}:{num%60:02}'", "def time_convert(num):\n a=num//60\n b=num%60\n if num<=0:\n return '00:00'\n elif 0<num<10:\n ...
{"fn_name": "time_convert", "inputs": [[0], [-6], [8], [32], [75], [63], [134], [180], [970], [565757]], "outputs": [["00:00"], ["00:00"], ["00:08"], ["00:32"], ["01:15"], ["01:03"], ["02:14"], ["03:00"], ["16:10"], ["9429:17"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,449
def time_convert(num):
92fd3273aefdc5c86cf9d8305592b79b
UNKNOWN
Don't Drink the Water Given a two-dimensional array representation of a glass of mixed liquids, sort the array such that the liquids appear in the glass based on their density. (Lower density floats to the top) The width of the glass will not change from top to bottom. ``` ====================== | Density Chart ...
["DENSITY = {'H': 1.36, 'W': 1, 'A': 0.87, 'O': 0.8}\n\n\ndef separate_liquids(glass):\n if not glass:\n return []\n column = len(glass[0])\n liquids = sorted((b for a in glass for b in a), key=lambda c: DENSITY[c])\n return [liquids[d:d + column] for d in range(0, len(liquids), column)]\n", "def sep...
{"fn_name": "separate_liquids", "inputs": [[[["H", "H", "W", "O"], ["W", "W", "O", "W"], ["H", "H", "O", "O"]]], [[["A", "A", "O", "H"], ["A", "H", "W", "O"], ["W", "W", "A", "W"], ["H", "H", "O", "O"]]], [[["A", "H", "W", "O"]]], [[["A"], ["H"], ["W"], ["O"]]], [[]]], "outputs": [[[["O", "O", "O", "O"], ["W", "W", "W"...
INTRODUCTORY
PYTHON3
CODEWARS
2,133
def separate_liquids(glass):
be9e19272cbb1579ee470d9ddbf44ff8
UNKNOWN
# Task The game starts with `n` people standing in a circle. The presenter counts `m` people starting with the first one, and gives `1` coin to each of them. The rest of the players receive `2` coins each. After that, the last person who received `1` coin leaves the circle, giving everything he had to the next partici...
["def find_last(n, m):\n li, start = [[0, i + 1] for i in range(n)], 0 # form list of circle with numbers\n while len(li) != 1:\n prev, l_ = li[start][1], len(li) # starting point and length of circle\n for k in range(m): # adding 1 to first m players i...
{"fn_name": "find_last", "inputs": [[5, 1], [8, 3], [75, 34], [82, 49], [73, 38], [86, 71], [61, 17], [42, 38], [29, 5], [64, 49], [61, 20], [88, 52]], "outputs": [[[5, 24]], [[7, 51]], [[35, 4238]], [[48, 5091]], [[61, 3996]], [[10, 6275]], [[26, 3000]], [[12, 1578]], [[28, 740]], [[43, 3327]], [[32, 2922]], [[59, 585...
INTRODUCTORY
PYTHON3
CODEWARS
4,872
def find_last(n, m):
245f9add176990d59d13a90400efb502
UNKNOWN
Let's pretend your company just hired your friend from college and paid you a referral bonus. Awesome! To celebrate, you're taking your team out to the terrible dive bar next door and using the referral bonus to buy, and build, the largest three-dimensional beer can pyramid you can. And then probably drink those beers,...
["def beeramid(bonus, price):\n beers = bonus // price\n levels = 0\n \n while beers >= (levels + 1) ** 2:\n levels += 1\n beers -= levels ** 2\n \n return levels", "from itertools import count\n\ndef beeramid(bonus, price):\n bonus = max(bonus,0)\n n = bonus//price\n return n...
{"fn_name": "beeramid", "inputs": [[9, 2], [10, 2], [11, 2], [21, 1.5], [454, 5], [455, 5], [4, 4], [3, 4], [0, 4], [-1, 4]], "outputs": [[1], [2], [2], [3], [5], [6], [1], [0], [0], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,967
def beeramid(bonus, price):
a9425c5253540d09f03214d4d2a94846
UNKNOWN
Your task is to determine how many files of the copy queue you will be able to save into your Hard Disk Drive. The files must be saved in the order they appear in the queue. ### Input: * Array of file sizes `(0 <= s <= 100)` * Capacity of the HD `(0 <= c <= 500)` ### Output: * Number of files that can be fully sav...
["def save(sizes, hd): \n for i,s in enumerate(sizes):\n if hd < s: return i\n hd -= s\n return len(sizes)", "def save(sizes, hd): \n return save(sizes[:-1], hd) if sum(sizes) > hd else len(sizes)", "from bisect import bisect\nfrom itertools import accumulate\n\n\ndef save(sizes, hd): \n retur...
{"fn_name": "save", "inputs": [[[4, 4, 4, 3, 3], 12], [[4, 4, 4, 3, 3], 11], [[4, 8, 15, 16, 23, 42], 108], [[13], 13], [[1, 2, 3, 4], 250], [[100], 500], [[11, 13, 15, 17, 19], 8], [[45], 12]], "outputs": [[3], [2], [6], [1], [4], [1], [0], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,414
def save(sizes, hd):
475da70f540dd11c6134aae54ac4ce6d
UNKNOWN
Given an array of positive integers, replace every element with the least greater element to its right. If there is no greater element to its right, replace it with -1. For instance, given the array `[8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28]`, the desired output is `[18, 63, 80, 25, 32, 43,...
["def array_manip(array):\n return [min([a for a in array[i+1:] if a > array[i]], default=-1) for i in range(len(array))]", "def array_manip(array):\n return [min((r for r in array[i:] if r > n), default=-1) for i, n in enumerate(array, 1)]\n", "# This is O(n\u00b2), it's a bad solution\n# You can do it in O(n*lo...
{"fn_name": "array_manip", "inputs": [[[8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28]], [[2, 4, 18, 16, 7, 3, 9, 13, 18, 10]]], "outputs": [[[18, 63, 80, 25, 32, 43, 80, 93, 80, 25, 93, -1, 28, -1, -1]], [[3, 7, -1, 18, 9, 9, 10, 18, -1, -1]]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,258
def array_manip(array):
c694d3d6ce66f84ca1b2d9fc3b7c0fa2
UNKNOWN
Find the longest substring within a string that contains at most 2 unique characters. ``` substring("a") => "a" substring("aaa") => "aaa" substring("abacd") => "aba" substring("abacddcd") => "cddcd" substring("cefageaacceaccacca") => "accacca" ``` This function will take alphanumeric characters as input. In cases wh...
["def substring(s):\n r, rm = [], []\n for i, x in enumerate(s):\n if x in r or len(set(r)) < 2:\n r += x;\n else:\n if len(r) > len(rm): rm = r[:]\n r = [y for y in r[-1::-1] if y == r[-1]] + [x]\n if len(r) > len(rm): rm = r[:]\n return ''.join(rm)", "def sub...
{"fn_name": "substring", "inputs": [[""], ["a"], ["aa"], ["aaa"], ["ab"], ["aba"], ["abc"], ["abcba"], ["bbacc"], ["ccddeeff"], ["bbacddddcdd"], ["abcddeejabbedsajaajjaajjajajajjajjaaacedajajaj"], ["aaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbccccccccccccccccccccddddddddddddddddddddeeeeeeeeeeeeeeeeeeeeffffffffffffffffffffg...
INTRODUCTORY
PYTHON3
CODEWARS
3,009
def substring(s):
586559ea0869e78bc6ed7646bbcb870d
UNKNOWN
There are 32 letters in the Polish alphabet: 9 vowels and 23 consonants. Your task is to change the letters with diacritics: ``` ą -> a, ć -> c, ę -> e, ł -> l, ń -> n, ó -> o, ś -> s, ź -> z, ż -> z ``` and print out the string without the use of the Polish letters. For example: ``` "Jędrzej Błądziński" --> "J...
["def correct_polish_letters(s):\n return s.translate(str.maketrans(\"\u0105\u0107\u0119\u0142\u0144\u00f3\u015b\u017a\u017c\", \"acelnoszz\"))", "def correct_polish_letters(st):\n l = \"\u0105\u0107\u0119\u0142\u0144\u00f3\u015b\u017a\u017c\"\n lt = \"acelnoszz\"\n for i in range(len(l)):\n st = st....
{"fn_name": "correct_polish_letters", "inputs": [["J\u0119drzej B\u0142\u0105dzi\u0144ski"], ["Lech Wa\u0142\u0119sa"], ["Maria Sk\u0142odowska-Curie"], ["W\u0142adys\u0142aw Reymont"], ["Miko\u0142aj Kopernik"], ["J\u00f3zef Pi\u0142sudski"], ["Czes\u0142aw Mi\u0142osz"], ["Agnieszka Radwa\u0144ska"], ["Wojciech Szcz\...
INTRODUCTORY
PYTHON3
CODEWARS
38,280
def correct_polish_letters(st):
7217fe130a3e5857b83958ec332b04ec
UNKNOWN
You've been collecting change all day, and it's starting to pile up in your pocket, but you're too lazy to see how much you've found. Good thing you can code! Create ```change_count()``` to return a dollar amount of how much change you have! Valid types of change include: ``` penny: 0.01 nickel: 0.05 dime: 0.10 quar...
["#Remember you have a CHANGE dictionary to work with ;)\n\ndef change_count(change):\n money = {'penny' : 0.01, 'nickel' : 0.05, 'dime' : 0.10, 'quarter' : 0.25, 'dollar' : 1.00}\n count = 0\n for coin in change.split():\n count += money[coin]\n result = \"%.2f\" % count\n return '$' + result\n ...
{"fn_name": "change_count", "inputs": [["dime penny dollar"], ["dime penny nickel"], ["quarter quarter"], ["dollar penny dollar"], ["dollar dollar dollar dollar dollar dollar dollar dollar dollar dollar penny"]], "outputs": [["$1.11"], ["$0.16"], ["$0.50"], ["$2.01"], ["$10.01"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,086
def change_count(change):
ee9055907a00b80dc058ee759c7a99cd
UNKNOWN
Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks untouched. ## Examples ```python pig_it('Pig latin is cool') # igPay atinlay siay oolcay pig_it('Hello world !') # elloHay orldway ! ``` ```C++ pig_it("Pig latin is cool"); // igPay atinlay siay oo...
["def pig_it(text):\n lst = text.split()\n return ' '.join( [word[1:] + word[:1] + 'ay' if word.isalpha() else word for word in lst])\n", "def pig_it(text):\n return \" \".join(x[1:] + x[0] + \"ay\" if x.isalnum() else x for x in text.split())", "def pig_it(text):\n res = []\n \n for i in text.split()...
{"fn_name": "pig_it", "inputs": [["Pig latin is cool"], ["This is my string"]], "outputs": [["igPay atinlay siay oolcay"], ["hisTay siay ymay tringsay"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,610
def pig_it(text):
b3d8e47f781553ea8fb0d4856f59b059
UNKNOWN
In this Kata, we are going to see how a Hash (or Map or dict) can be used to keep track of characters in a string. Consider two strings `"aabcdefg"` and `"fbd"`. How many characters do we have to remove from the first string to get the second string? Although not the only way to solve this, we could create a Hash of...
["from collections import Counter\n\ndef solve(a,b):\n return 0 if Counter(b) - Counter(a) else len(a) - len(b)", "def solve(a,b):\n for x in set(b):\n if a.count(x) >= b.count(x):\n continue\n else:\n return 0\n return len(a)-len(b)", "def solve(a,b):\n print((a,b))\n ...
{"fn_name": "solve", "inputs": [["xyz", "yxz"], ["abcxyz", "ayxz"], ["abcdexyz", "yxz"], ["xyz", "yxxz"], ["abdegfg", "ffdb"], ["aabcdefg", "fbd"]], "outputs": [[0], [2], [5], [0], [0], [5]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,767
def solve(a,b):
fdebc1fe6a8a121a21974d2ebe69144a
UNKNOWN
In this kata you will be given a sequence of the dimensions of rectangles ( sequence with width and length ) and circles ( radius - just a number ). Your task is to return a new sequence of dimensions, sorted ascending by area. For example, ```python seq = [ (4.23, 6.43), 1.23, 3.444, (1.342, 3.212) ] # [ rectangle...
["def sort_by_area(seq): \n def func(x):\n if isinstance(x, tuple):\n return x[0] * x[1]\n else:\n return 3.14 * x * x\n return sorted(seq, key=func)", "from math import pi as PI\n\ndef circle(r): return r*r*PI\ndef rect(a,b): return a*b\ndef getArea(r): ...
{"fn_name": "sort_by_area", "inputs": [[[]]], "outputs": [[[]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,062
def sort_by_area(seq):
a706e3d80e464839b24e5bfa91fff9a6
UNKNOWN
A [perfect power](https://en.wikipedia.org/wiki/Perfect_power) is a classification of positive integers: > In mathematics, a **perfect power** is a positive integer that can be expressed as an integer power of another positive integer. More formally, n is a perfect power if there exist natural numbers m > 1, and k > 1...
["from math import ceil, log, sqrt\n\ndef isPP(n):\n for b in range(2, int(sqrt(n)) + 1):\n e = int(round(log(n, b)))\n if b ** e == n:\n return [b, e]\n return None\n", "def isPP(n):\n for i in range(2, int(n**.5) + 1):\n number = n\n times = 0\n while number % i ...
{"fn_name": "isPP", "inputs": [[4], [9], [5]], "outputs": [[[2, 2]], [[3, 2]], [null]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,072
def isPP(n):
0e4bd150fe48a12703b7ad9673a0c4af
UNKNOWN
## Overview Resistors are electrical components marked with colorful stripes/bands to indicate both their resistance value in ohms and how tight a tolerance that value has. While you could always get a tattoo like Jimmie Rodgers to help you remember the resistor color codes, in the meantime, you can write a function th...
["code = {'black': 0, 'brown': 1, 'red': 2, 'orange': 3, 'yellow': 4,\n'green': 5, 'blue': 6, 'violet': 7, 'gray': 8, 'white': 9,\n'gold': 5, 'silver': 10, '': 20}\ndef decode_resistor_colors(bands):\n colors = (bands + ' ').split(' ')\n value = 10 * code[colors[0]] + code[colors[1]]\n value *= 10 ** code[colo...
{"fn_name": "decode_resistor_colors", "inputs": [["yellow violet black"], ["yellow violet red gold"], ["brown black green silver"], ["brown black black"], ["brown black brown gold"], ["red red brown"], ["orange orange brown gold"], ["yellow violet brown silver"], ["blue gray brown"], ["brown black red silver"], ["brown...
INTRODUCTORY
PYTHON3
CODEWARS
6,026
def decode_resistor_colors(bands):
034f2037805af89bfd288504a47fc7d6
UNKNOWN
Converting a normal (12-hour) time like "8:30 am" or "8:30 pm" to 24-hour time (like "0830" or "2030") sounds easy enough, right? Well, let's see if you can do it! You will have to define a function named "to24hourtime", and you will be given an hour (always in the range of 1 to 12, inclusive), a minute (always in th...
["def to24hourtime(hour, minute, period):\n return '%02d%02d' % (hour % 12 + 12 * (period == 'pm'), minute)", "from datetime import datetime\n\ndef to24hourtime(h, m, p):\n return datetime.strptime('%02d%02d%s' % (h, m, p.upper()), '%I%M%p').strftime('%H%M')", "from datetime import datetime\n\ndef to24hourtime(h,...
{"fn_name": "to24hourtime", "inputs": [[12, 0, "am"], [12, 1, "am"], [12, 2, "am"], [12, 3, "am"], [12, 4, "am"], [12, 5, "am"], [12, 6, "am"], [12, 7, "am"], [12, 8, "am"], [12, 9, "am"], [12, 10, "am"], [12, 11, "am"], [12, 12, "am"], [12, 13, "am"], [12, 14, "am"], [12, 15, "am"], [12, 16, "am"], [12, 17, "am"], [12...
INTRODUCTORY
PYTHON3
CODEWARS
3,070
def to24hourtime(hour, minute, period):
fbebbb7b8bd7aca588e7ea9600f48796
UNKNOWN
You have a grid with `$m$` rows and `$n$` columns. Return the number of unique ways that start from the top-left corner and go to the bottom-right corner. You are only allowed to move right and down. For example, in the below grid of `$2$` rows and `$3$` columns, there are `$10$` unique paths: ``` o----o----o----o | ...
["from math import factorial as f\nnumber_of_routes=lambda m,n:f(m+n)//(f(m)*f(n))", "import sys\n\nsys.setrecursionlimit(1200)\n\ncache = {}\n\ndef number_of_routes(m, n):\n if m == 0 or n == 0: return 1\n if m > n: return number_of_routes(n, m)\n result = cache.get((m,n))\n if result is None:\n cac...
{"fn_name": "number_of_routes", "inputs": [[1, 1], [5, 1], [3, 4], [5, 6], [10, 10], [100, 3], [123, 456]], "outputs": [[2], [6], [35], [462], [184756], [176851], [448843261729071620474858205566477025894357385375655014634306680560209909590802545266425906052279365647506075241055256064119806400]]}
INTRODUCTORY
PYTHON3
CODEWARS
686
def number_of_routes(m, n):
8b6c463823b6f0a62a95399051ef85cf
UNKNOWN
Complete the solution so that it returns true if it contains any duplicate argument values. Any number of arguments may be passed into the function. The array values passed in will only be strings or numbers. The only valid return values are `true` and `false`. Examples: ``` solution(1, 2, 3) --> false s...
["def solution(*args):\n return len(args) != len(set(args))", "def solution(*args):\n print (args)\n result = {}\n for x in args:\n if x in result:\n return True\n else :\n result[x] = 1\n return False\n", "def solution(*args):\n return len(args) > len(set(args))",...
{"fn_name": "solution", "inputs": [[1, 2, 3, 1, 2], [1, 1], [1, 0], ["a", "b"], ["a", "b", "a"], [1, 2, 42, 3, 4, 5, 42], ["a", "b", "c", "d"], ["a", "b", "c", "c"], ["a", "b", "c", "d", "e", "f", "f", "b"]], "outputs": [[true], [true], [false], [false], [true], [true], [false], [true], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,097
def solution(*args):
1b1d3813cbc0263b6e2b1ce70a8a3c68
UNKNOWN
The number ```89``` is the first integer with more than one digit that fulfills the property partially introduced in the title of this kata. What's the use of saying "Eureka"? Because this sum gives the same number. In effect: ```89 = 8^1 + 9^2``` The next number in having this property is ```135```. See this prop...
["def dig_pow(n):\n return sum(int(x)**y for y,x in enumerate(str(n), 1))\n\ndef sum_dig_pow(a, b): \n return [x for x in range(a,b + 1) if x == dig_pow(x)]", "def sum_dig_pow(a, b):\n return [x for x in range(a, b+1) if sum(int(d)**i for i, d in enumerate(str(x), 1)) == x]", "def sum_dig_pow(a, b): # range(a,...
{"fn_name": "sum_dig_pow", "inputs": [[1, 100], [10, 89], [10, 100], [90, 100], [90, 150], [50, 150], [10, 150], [89, 135]], "outputs": [[[1, 2, 3, 4, 5, 6, 7, 8, 9, 89]], [[89]], [[89]], [[]], [[135]], [[89, 135]], [[89, 135]], [[89, 135]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,459
def sum_dig_pow(a, b):
401bcda047952411522673f368064bd3
UNKNOWN
Your task is to create a new implementation of `modpow` so that it computes `(x^y)%n` for large `y`. The problem with the current implementation is that the output of `Math.pow` is so large on our inputs that it won't fit in a 64-bit float. You're also going to need to be efficient, because we'll be testing some prett...
["def power_mod(b, e, m):\n res, b = 1, b % m\n while e > 0:\n if e & 1: res = res * b % m\n e >>= 1\n b = b * b % m\n return res", "def power_mod(base, exponent, modulus):\n if base is 0: return 0\n if exponent is 0: return 0\n base = base % modulus\n result = 1\n while (exponent > 0):\n ...
{"fn_name": "power_mod", "inputs": [[11, 10, 300], [11, 100000, 49], [5, 100000000, 19], [2, 3, 5], [4, 12, 3], [200, 3000, 10], [8132, 21302, 5], [9, 193125, 37], [13, 81230123, 22], [29, 1013293125, 492], [31, 902938423012, 1023]], "outputs": [[1], [32], [5], [3], [1], [0], [4], [26], [19], [161], [961]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,116
def power_mod(b, e, m):
7578819889855af53b11d07a5df7a88c
UNKNOWN
In the wake of the npm's `left-pad` debacle, you decide to write a new super padding method that superceds the functionality of `left-pad`. Your version will provide the same functionality, but will additionally add right, and justified padding of string -- the `super_pad`. Your function `super_pad` should take three ...
["def super_pad(string, width, fill=\" \"):\n if fill.startswith('>'):\n return (string + width * fill[1:])[:width]\n elif fill.startswith('^'):\n pad = (width * fill[1:])[:max(0, width - len(string) + 1) // 2]\n return (pad + string + pad)[:width]\n else:\n if fill.startswith('<'):...
{"fn_name": "super_pad", "inputs": [["test", 10], ["test", 10, "x"], ["test", 10, "xO"], ["test", 10, "xO-"], ["some other test", 10, "nope"], ["some other test", 10, "> "], ["test", 7, ">nope"], ["test", 7, "^more complex"], ["test", 7, ""], ["test", 10, "< "], ["test", 3], ["test", 3, "> "], ["test", 10, ""], ["test"...
INTRODUCTORY
PYTHON3
CODEWARS
10,374
def super_pad(string, width, fill=" "):
c741c4661886657244b5e04f164f4212
UNKNOWN
We want to know the index of the vowels in a given word, for example, there are two vowels in the word super (the second and fourth letters). So given a string "super", we should return a list of [2, 4]. Some examples: Mmmm => [] Super => [2,4] Apple => [1,5] YoMama -> [1,2,4...
["def vowel_indices(word):\n return [i for i,x in enumerate(word,1) if x.lower() in 'aeiouy']", "def vowel_indices(word):\n return [i+1 for i,c in enumerate(word.lower()) if c in 'aeiouy']", "def vowel_indices(word):\n return [index for index, value in enumerate(word.lower(), 1) if value in 'aeyuio']", "VOWELS...
{"fn_name": "vowel_indices", "inputs": [["mmm"], ["apple"], ["super"], ["orange"], ["grapes"], ["supercalifragilisticexpialidocious"], ["123456"], ["crIssUm"], ["Implied"], ["rIc"], ["UNDISARMED"], ["bialy"], ["stumpknocker"], ["narboonnee"], ["carlstadt"], ["ephodee"], ["spicery"], ["oftenness"], ["bewept"], ["capsize...
INTRODUCTORY
PYTHON3
CODEWARS
17,980
def vowel_indices(word):
7b6d8d17a2d172051651e12a7a4c7814
UNKNOWN
## Enough is enough! Alice and Bob were on a holiday. Both of them took many pictures of the places they've been, and now they want to show Charlie their entire collection. However, Charlie doesn't like these sessions, since the motive usually repeats. He isn't fond of seeing the Eiffel tower 40 times. He tells them t...
["def delete_nth(order,max_e):\n ans = []\n for o in order:\n if ans.count(o) < max_e: ans.append(o)\n return ans\n", "def delete_nth(order, max_e):\n d = {}\n res = []\n for item in order:\n n = d.get(item, 0)\n if n < max_e:\n res.append(item)\n d[item] = n+1\n retu...
{"fn_name": "delete_nth", "inputs": [[[20, 37, 20, 21], 1], [[1, 1, 3, 3, 7, 2, 2, 2, 2], 3], [[1, 2, 3, 1, 1, 2, 1, 2, 3, 3, 2, 4, 5, 3, 1], 3], [[1, 1, 1, 1, 1], 5], [[], 5]], "outputs": [[[20, 37, 21]], [[1, 1, 3, 3, 7, 2, 2, 2]], [[1, 2, 3, 1, 1, 2, 2, 3, 3, 4, 5]], [[1, 1, 1, 1, 1]], [[]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,611
def delete_nth(order,max_e):
bc1a6cbca5e7769920f0fe692ea4292f
UNKNOWN
## Task Given a positive integer `n`, calculate the following sum: ``` n + n/2 + n/4 + n/8 + ... ``` All elements of the sum are the results of integer division. ## Example ``` 25 => 25 + 12 + 6 + 3 + 1 = 47 ```
["def halving_sum(n): \n s=0\n while n: \n s+=n ; n>>=1\n return s", "def halving_sum(n): \n if n == 1:\n return 1\n else:\n return n + halving_sum(n//2)", "def halving_sum(n): \n return n and n + halving_sum(n>>1)", "def halving_sum(n):\n result = n\n \n while n >= 1:\n ...
{"fn_name": "halving_sum", "inputs": [[25], [127], [38], [1], [320], [13], [15], [47], [101], [257]], "outputs": [[47], [247], [73], [1], [638], [23], [26], [89], [198], [512]]}
INTRODUCTORY
PYTHON3
CODEWARS
13,810
def halving_sum(n):
63a4307734e9b2f72c1939f8eaef3637
UNKNOWN
Two red beads are placed between every two blue beads. There are N blue beads. After looking at the arrangement below work out the number of red beads. @ @@ @ @@ @ @@ @ @@ @ @@ @ Implement count_red_beads(n) (in PHP count_red_beads($n); in Java, Javascript, TypeScript, C, C++ countRedBeads(n)) so that it returns the ...
["def count_red_beads(nb):\n return max(0, 2 * (nb - 1) )", "def count_red_beads(n_blue):\n return (n_blue - 1) * 2 if n_blue >= 2 else 0\n", "def count_red_beads(n):\n return max(0, 2 * (n-1))\n #maximum value -> two for every two beads times number of blue beads - 1\n", "def count_red_beads(n):\n return ...
{"fn_name": "count_red_beads", "inputs": [[0], [1], [3], [5]], "outputs": [[0], [0], [4], [8]]}
INTRODUCTORY
PYTHON3
CODEWARS
9,826
def count_red_beads(n):
01ee8730452d20100f7b65c458bc9a4f
UNKNOWN
Hector the hacker has stolen some information, but it is encrypted. In order to decrypt it, he needs to write a function that will generate a decryption key from the encryption key which he stole (it is in hexadecimal). To do this, he has to determine the two prime factors `P` and `Q` of the encyption key, and return t...
["def find_key(key):\n n = int(key, 16)\n return next((k - 1) * ((n // k) - 1) for k in range(2, int(n**0.5)+1) if n % k == 0)\n", "def find_key(enc):\n n = int(enc,16)\n for i in range(2,int(n**.5)+1):\n if not n%i:\n return (i-1)*(n//i-1)\n", "def prime_factors(n):\n s, a = [], 2\n ...
{"fn_name": "find_key", "inputs": [["47b"], ["2533"], ["1ba9"]], "outputs": [[1080], [9328], [6912]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,661
def find_key(key):
2dd33152b633365e46bfed5bb4a0024c
UNKNOWN
# Task John was in math class and got bored, so he decided to fold some origami from a rectangular `a × b` sheet of paper (`a > b`). His first step is to make a square piece of paper from the initial rectangular piece of paper by folding the sheet along the bisector of the right angle and cutting off the excess part. ...
["def folding(a,b):\n squares = 1\n while a != b:\n squares += 1\n b, a = sorted((a - b, b))\n return squares", "def folding(a,b):\n count = 0\n while a > 0 and b > 0:\n a, b, count = max(a-b, b), min(a-b, b), count+1\n return count", "def folding(a, b):\n return 0 if b == 0 else a // b ...
{"fn_name": "folding", "inputs": [[2, 1], [10, 7], [3, 1], [4, 1], [3, 2], [4, 2], [1000, 700], [1000, 999]], "outputs": [[2], [6], [3], [4], [3], [2], [6], [1000]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,428
def folding(a,b):
ce211889465ea60dab2940dcb39842aa
UNKNOWN
Create a function that will return true if all numbers in the sequence follow the same counting pattern. If the sequence of numbers does not follow the same pattern, the function should return false. Sequences will be presented in an array of varied length. Each array will have a minimum of 3 numbers in it. The seque...
["def validate_sequence(seq):\n return len({a - b for a, b in zip(seq, seq[1:])}) == 1", "def validate_sequence(sequence):\n return sequence == list(range(sequence[0], sequence[-1] + 1, sequence[1] - sequence[0]))\n", "def validate_sequence(s):\n return sum(s) == (s[0] + s[-1]) * len(s) /2", "def validate_sequ...
{"fn_name": "validate_sequence", "inputs": [[[1, 2, 3, 4, 5, 8, 7, 8, 9]], [[2, 8, 6, 7, 4, 3, 1, 5, 9]], [[1, 2, 3, 4, 5, 6, 7, 8, 9]], [[0, 1, 2, 3, 4, 5, 6, 7, 8]], [[1, 3, 5, 7, 9, 11, 13, 15]], [[1, 3, 5, 7, 8, 12, 14, 16]], [[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]], [[0, 2, 4, 6, 8]], [[2, 4, 6, 8, 10]], [[2, 4, 6, 8, ...
INTRODUCTORY
PYTHON3
CODEWARS
1,344
def validate_sequence(sequence):
205a08f2545d81b2650b3c605ec52aa4
UNKNOWN
# Introduction The ragbaby cipher is a substitution cipher that encodes/decodes a text using a keyed alphabet and their position in the plaintext word they are a part of. To encrypt the text `This is an example.` with the key `cipher`, first construct a keyed alphabet: ``` c i p h e r ...
["from string import ascii_lowercase as aLow\nimport re\n\ndef rotateWord(w, alpha, dct, d):\n lst = []\n for i,c in enumerate(w.lower(), 1):\n transChar = alpha[ (dct[c] + i*d) % 26 ]\n if w[i-1].isupper(): transChar = transChar.upper()\n lst.append(transChar)\n return ''.join(lst)\n\ndef...
{"fn_name": "encode", "inputs": [["cipher", "cipher"], ["cipher", "cccciiiiippphheeeeerrrrr"]], "outputs": [["ihrbfj"], ["ihrbfj"]]}
INTRODUCTORY
PYTHON3
CODEWARS
11,211
def encode(text, key):
f93243a4d1928c6a64995b36b036a77c
UNKNOWN
Your colleagues have been good enough(?) to buy you a birthday gift. Even though it is your birthday and not theirs, they have decided to play pass the parcel with it so that everyone has an even chance of winning. There are multiple presents, and you will receive one, but not all are nice... One even explodes and cove...
["_RESULTS = {\n 'goodpresent': lambda y: ''.join(chr(ord(c) + y) for c in 'goodpresent'),\n 'crap': lambda y: 'acpr',\n 'empty': lambda y: 'empty',\n 'bang': lambda y: str(sum(ord(c) - y for c in 'bang')),\n 'badpresent': lambda y: 'Take this back!',\n 'dog': lambda y: 'pass out from excitement {} ti...
{"fn_name": "present", "inputs": [["badpresent", 3], ["goodpresent", 9], ["crap", 10], ["bang", 27], ["dog", 23]], "outputs": [["Take this back!"], ["pxxmy{n|nw}"], ["acpr"], ["300"], ["pass out from excitement 23 times"]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,908
def present(x,y):
90b9611bd524209596bf50b1c02a0090
UNKNOWN
# Let's watch a parade! ## Brief You're going to watch a parade, but you only care about one of the groups marching. The parade passes through the street where your house is. Your house is at number `location` of the street. Write a function `parade_time` that will tell you the times when you need to appear to see all ...
["def parade_time(groups, location, speed, pref):\n return [c // speed for c, p in enumerate(groups, 1 + location) if p == pref]", "def parade_time(groups, location, speed, pref):\n result = []\n for i in range(1,len(groups)+1):\n if groups[i-1] == pref:\n result.append((location+i) // speed)...
{"fn_name": "parade_time", "inputs": [[["a", "b", "c", "d", "e", "f"], 3, 2, "c"], [["c", "b", "c", "d", "e", "f"], 3, 2, "c"], [["a", "b", "c", "d", "e", "f"], 3, 2, "g"], [["a", "b", "c", "c", "e", "c"], 7, 1, "c"], [["a", "b", "c", "d", "e", "f"], 1, 2, "b"], [["a", "b", "c", "d", "e", "b"], 1, 2, "b"]], "outputs": ...
INTRODUCTORY
PYTHON3
CODEWARS
1,117
def parade_time(groups, location, speed, pref):