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
cd1aac2e395f6b566972517ead16fcbd
UNKNOWN
Gray code is a form of binary encoding where transitions between consecutive numbers differ by only one bit. This is a useful encoding for reducing hardware data hazards with values that change rapidly and/or connect to slower hardware as inputs. It is also useful for generating inputs for Karnaugh maps. Here is an ex...
["def bin2gray(bits):\n bits.reverse()\n return list(reversed([x if i >= len(bits) - 1 or bits[i + 1] == 0 else 1 - x for i, x in enumerate(bits)]))\n \ndef gray2bin(bits):\n for i, x in enumerate(bits):\n if i > 0 and bits[i - 1] != 0: bits[i] = 1 - x\n return bits", "def bitlist(func):\n def wrapper(bits):...
{"fn_name": "bin2gray", "inputs": [[[1, 0, 1]], [[1, 1]], [[1]], [[0]], [[1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0]], [[1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0]]], "outputs": [[[1, 1, 1]], [[1,...
INTRODUCTORY
PYTHON3
CODEWARS
2,599
def bin2gray(bits):
40d270804cbe9b30d46c05c6c1a595d0
UNKNOWN
You are going to be given a string. Your job is to return that string in a certain order that I will explain below: Let's say you start with this: `012345` The first thing you do is reverse it:`543210` Then you will take the string from the 1st position and reverse it again:`501234` Then you will take the string ...
["def reverse_fun(n):\n for i in range(len(n)):\n n = n[:i] + n[i:][::-1]\n return n", "def reverse_fun(n):\n l = len(n)\n return ''.join(b+a for a,b in zip(list(n[:l//2])+[''], n[l//2:][::-1]))", "def reverse_fun(n):\n n = n[::-1]\n for i in range(1, len(n)):\n n = n[:i] + n[i:][::-1]\n...
{"fn_name": "reverse_fun", "inputs": [["012"], ["012345"], ["0123456789"], ["Hello"]], "outputs": [["201"], ["504132"], ["9081726354"], ["oHlel"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,515
def reverse_fun(n):
e2342073474ff5313ca1e86793c502d2
UNKNOWN
You are trying to cross a river by jumping along stones. Every time you land on a stone, you hop forwards by the value of that stone. If you skip *over* a stone then its value doesn't affect you in any way. Eg: ``` x--x-----x--> [1][2][5][1] ``` Of course, crossing from the other side might give you a different ans...
["def hop_across(lst):\n def one_side(lst):\n i = 0\n steps = 0\n while i < len(lst):\n i += lst[i]\n steps += 1\n return steps\n return one_side(lst) + one_side(lst[::-1])", "def hop_across(lst): return dist(lst)+dist(lst[::-1])\n\ndef dist(lst):\n s,i=0,0\n ...
{"fn_name": "hop_across", "inputs": [[[1]], [[2]], [[1, 1]], [[2, 1]], [[2, 1, 1]], [[1, 2, 1, 2]], [[1, 2, 5, 1]], [[2, 2, 3, 1, 1, 2, 1]]], "outputs": [[2], [2], [4], [3], [5], [5], [5], [7]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,964
def hop_across(lst):
65cf7f63d250eacfc658322bccc73c68
UNKNOWN
Check if given numbers are prime numbers. If number N is prime ```return "Probable Prime"``` else ``` return "Composite"```. HINT: Upper bount is really big so you should use an efficient algorithm. Input   1 < N ≤ 10^(100) Example   prime_or_composite(2) # should return Probable Prime   prime_or_composite(200) #...
["def prime_or_composite(n):\n if n < 4: return 'Probable Prime'\n if n % 2 == 0: return 'Composite'\n d, r = n - 1, 0\n while d % 2 == 0:\n d, r = d // 2, r + 1\n for a in [2, 31]:\n x = pow(a, d, n)\n if x in (1, n - 1):\n continue\n for _ in range(r-1):\n ...
{"fn_name": "prime_or_composite", "inputs": [[2], [3], [5], [9], [12]], "outputs": [["Probable Prime"], ["Probable Prime"], ["Probable Prime"], ["Composite"], ["Composite"]]}
INTRODUCTORY
PYTHON3
CODEWARS
6,141
def prime_or_composite(n):
9c3f8b9f19966a93f729b194493b40c9
UNKNOWN
# Task You are given an array of integers `a` and a non-negative number of operations `k`, applied to the array. Each operation consists of two parts: ``` find the maximum element value of the array; replace each element a[i] with (maximum element value - a[i]).``` How will the array look like after `k` such operation...
["def array_operations(a, n):\n li = []\n for i in range(n):\n m = max(a)\n a = [m-i for i in a] \n if a in li:\n if not n & 1 : return li[-1]\n return a\n li.append(a)\n return a", "def array_operations(a, k):\n for _ in range(2 + (k & 1)):\n m = max(a)\n ...
{"fn_name": "array_operations", "inputs": [[[-4, 0, -1, 0], 2], [[0, -1, 0, 0, -1, -1, -1, -1, 1, -1], 1], [[-1], 10000]], "outputs": [[[0, 4, 3, 4]], [[1, 2, 1, 1, 2, 2, 2, 2, 0, 2]], [[0]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,804
def array_operations(a, k):
e54f4454b0a357c21ea32c71ca37e797
UNKNOWN
Let’s get to know our hero: Agent #134 - Mr. Slayer. He was sent by his CSV agency to Ancient Rome in order to resolve some important national issues. However, something incredible has happened - the enemies have taken Julius Caesar as a prisoner!!! Caesar, not a simple man as you know, managed to send cryptic messag...
["from string import ascii_letters as az\n\n\ndef caesar_crypto_encode(text, shift):\n if not text:\n return ''\n sh = shift % 52\n return str.translate(text, str.maketrans(az, az[sh:] + az[:sh])).strip()", "from string import ascii_lowercase, ascii_uppercase\nS = ascii_lowercase+ascii_uppercase\nD = {c...
{"fn_name": "caesar_crypto_encode", "inputs": [["123,.)(!?", 10], ["", 10], [null, 10], [" ", 10], ["Hello world!", 127], ["eBIIL TLOIA!", -127], ["ksdjai8983hdk?}{", 15], ["Hello world!", 0]], "outputs": [["123,.)(!?"], [""], [""], [""], ["eBIIL TLOIA!"], ["Hello world!"], ["zHsypx8983wsz?}{"], ["Hello world!"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,703
def caesar_crypto_encode(text, shift):
667e3818c160d777ae49d989e66a00e1
UNKNOWN
Why would we want to stop to only 50 shades of grey? Let's see to how many we can go. Write a function that takes a number n as a parameter and return an array containing n shades of grey in hexadecimal code (`#aaaaaa` for example). The array should be sorted in ascending order starting with `#010101`, `#020202`, etc...
["def shades_of_grey(n):\n if n > 254:\n n = 254\n return [\"#%02x%02x%02x\" % (i,i,i) for i in range(1,n+1)]", "def shades_of_grey(n):\n return [ '#{0:02x}{0:02x}{0:02x}'.format(i+1) for i in range(min(254, n)) ]", "form = '#'+'{0:0>2}'*3\nshades_of_grey=lambda n:[form.format(hex(i)[2:])for i in range(1,min(n+...
{"fn_name": "shades_of_grey", "inputs": [[-1], [0], [1], [254], [5000]], "outputs": [[[]], [[]], [["#010101"]], [["#010101", "#020202", "#030303", "#040404", "#050505", "#060606", "#070707", "#080808", "#090909", "#0a0a0a", "#0b0b0b", "#0c0c0c", "#0d0d0d", "#0e0e0e", "#0f0f0f", "#101010", "#111111", "#121212", "#131313...
INTRODUCTORY
PYTHON3
CODEWARS
948
def shades_of_grey(n):
d005f3451fd2a2abe98f85db76728f62
UNKNOWN
# Task Consider the following operation: We take a positive integer `n` and replace it with the sum of its `prime factors` (if a prime number is presented multiple times in the factorization of `n`, then it's counted the same number of times in the sum). This operation is applied sequentially first to the given...
["def factor_sum(n):\n while True:\n i=2\n s=0\n a=n\n while i<=n:\n if n%i==0:\n s+=i\n n/=i\n if n==1:\n break\n else:\n i+=1\n \n if a!=s:\n n=s\n ...
{"fn_name": "factor_sum", "inputs": [[24], [35], [156], [4], [31]], "outputs": [[5], [7], [5], [4], [31]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,090
def factor_sum(n):
8e448693a6a8ecbdaf837766e1950314
UNKNOWN
Create your own mechanical dartboard that gives back your score based on the coordinates of your dart. Task: Use the scoring rules for a standard dartboard: Finish method: ```python def get_score(x,y): ``` The coordinates are `(x, y)` are always relative to the center of the board (0, 0). The unit is millimeters....
["from math import atan2, degrees\n\ndef get_score(x,y):\n r, a = (x*x + y*y)**0.5, degrees(atan2(y, x)) + 9\n t = str([6,13,4,18,1,20,5,12,9,14,11,8,16,7,19,3,17,2,15,10][int(a + 360 if a < 0 else a)//18])\n for l, s in [(6.35, 'DB'),(15.9,'SB'),(99,t),(107,'T'+t),(162,t),(170,'D'+t)]:\n if r <= l: ret...
{"fn_name": "get_score", "inputs": [[-133.69, -147.38], [4.06, 0.71], [2.38, -6.06], [-5.43, 117.95], [-73.905, -95.94], [55.53, -87.95], [-145.19, 86.53]], "outputs": [["X"], ["DB"], ["SB"], ["20"], ["7"], ["T2"], ["D9"]]}
INTRODUCTORY
PYTHON3
CODEWARS
6,619
def get_score(x,y):
d7f8b9b3552c9f5d76c156dd9c2673ad
UNKNOWN
Mothers arranged a dance party for the children in school. At that party, there are only mothers and their children. All are having great fun on the dance floor when suddenly all the lights went out. It's a dark night and no one can see each other. But you were flying nearby and you can see in the dark and have ability...
["def find_children(dancing_brigade):\n return ''.join(sorted(dancing_brigade,key=lambda c:(c.upper(),c.islower())))", "def find_children(s):\n return ''.join( sorted(sorted(s), key=str.lower) )", "#wow this is very long :)\ndef find_children(people) :\n string = []\n answer = []\n symbol = ''\n index = -1\n ...
{"fn_name": "find_children", "inputs": [["abBA"], ["AaaaaZazzz"], ["CbcBcbaA"], ["xXfuUuuF"], [""]], "outputs": [["AaBb"], ["AaaaaaZzzz"], ["AaBbbCcc"], ["FfUuuuXx"], [""]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,586
def find_children(dancing_brigade):
3d94a26d85f5d5cc8455f7ff5a9d4350
UNKNOWN
Create a __moreZeros__ function which will __receive a string__ for input, and __return an array__ (or null terminated string in C) containing only the characters from that string whose __binary representation of its ASCII value__ consists of _more zeros than ones_. You should __remove any duplicate characters__, kee...
["def more_zeros(s):\n results = []\n \n for letter in s:\n dec_repr = bin(ord(letter))[2:]\n if (dec_repr.count(\"0\") > dec_repr.count(\"1\")) and (letter not in results):\n results.append(letter)\n \n return results\n", "def more_zeros(s):\n L=[]\n L1=[]\n L2=[]\n ...
{"fn_name": "more_zeros", "inputs": [["abcde"], ["thequickbrownfoxjumpsoverthelazydog"], ["THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG"], ["abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_"], ["DIGEST"], ["abcdabcd"], ["Forgiveness is the fragrance that the violet sheds on the heal that has crushed it"]], "outpu...
INTRODUCTORY
PYTHON3
CODEWARS
2,526
def more_zeros(s):
45f2faabd8e8519eac42e1b8aa5a8c46
UNKNOWN
## Sum Even Fibonacci Numbers * Write a func named SumEvenFibonacci that takes a parameter of type int and returns a value of type int * Generate all of the Fibonacci numbers starting with 1 and 2 and ending on the highest number before exceeding the parameter's value #### Each new number in the Fibonacci sequence...
["def SumEvenFibonacci(limit):\n a,b,s = 1,1,0\n while a <= limit:\n if not a%2: s += a\n a,b = b, a+b\n return s", "def SumEvenFibonacci(limit):\n a, b, result = 1, 2, 0\n while b <= limit:\n if b % 2 == 0:\n result += b\n a, b = b, a + b\n return result\n", "fr...
{"fn_name": "SumEvenFibonacci", "inputs": [[1], [2], [8], [111111], [8675309], [144100000], [65140000], [7347000000], [10000000000000], [123456789000000]], "outputs": [[0], [2], [10], [60696], [4613732], [82790070], [82790070], [6293134512], [8583840088782], [154030760585064]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,069
def SumEvenFibonacci(limit):
b9a2a2b08e81112886f248d60b5ec18a
UNKNOWN
# Your task Oh no... more lemmings!! And in Lemmings Planet a huge battle is being fought between the two great rival races: the green lemmings and the blue lemmings. Everybody was now assigned to battle and they will fight until one of the races completely dissapears: the Deadly War has begun! Every single lemming ha...
["from heapq import *\n\ndef lemming_battle(battlefield, green, blue):\n hg, hb = ([-v for v in lst] for lst in (green,blue))\n heapify(hg) ; heapify(hb)\n \n while hb and hg:\n tmp_b,tmp_g = [],[]\n for _ in range(min(battlefield,len(hg),len(hb))):\n cmp = heappop(hg) - heappop(hb)...
{"fn_name": "lemming_battle", "inputs": [[5, [10], [10]], [2, [20, 10], [10, 10, 15]], [3, [50, 40, 30, 40, 50], [50, 30, 30, 20, 60]], [1, [20, 30], [15]]], "outputs": [["Green and Blue died"], ["Blue wins: 5"], ["Green wins: 10 10"], ["Green wins: 20 15"]]}
INTRODUCTORY
PYTHON3
CODEWARS
7,378
def lemming_battle(battlefield, green, blue):
8b9b8ead2f193b7fe81f17471bb8b1d0
UNKNOWN
We have a matrix of integers with m rows and n columns. We want to calculate the total sum for the matrix: As you can see, the name "alternating sum" of the title is due to the sign of the terms that changes from one term to its contiguous one and so on. Let's see an example: ``` matrix = [[1, 2, 3], [-3, -2, 1]...
["def score_matrix(matrix):\n return sum((-1) ** (i+j) * matrix[i][j] for i in range(len(matrix)) for j in range(len(matrix[i])))\n", "def score_matrix(matrix):\n return sum(\n (-1)**(i+j) * x\n for i, row in enumerate(matrix)\n for j, x in enumerate(row)\n )", "def score_matrix(matrix):\n...
{"fn_name": "score_matrix", "inputs": [[[[1, 2, 3], [-3, -2, 1], [3, -1, 2]]]], "outputs": [[8]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,419
def score_matrix(matrix):
4b680e4f0422b8b65bf7a94269e9f1b4
UNKNOWN
You are given an array of unique numbers. The numbers represent points. The higher the number the higher the points. In the array [1,3,2] 3 is the highest point value so it gets 1st place. 2 is the second highest so it gets second place. 1 is the 3rd highest so it gets 3rd place. Your task is to return an array giv...
["def rankings(arr):\n dct = {v:i for i,v in enumerate(sorted(arr, reverse=True),1)}\n return [dct[v] for v in arr]", "def rankings(a):\n s = sorted(a)[::-1]\n return [s.index(e) + 1 for e in a]", "def rankings(lst):\n std = sorted(lst, reverse=True)\n return [std.index(n) + 1 for n in lst]", "def ran...
{"fn_name": "rankings", "inputs": [[[1, 3, 2]], [[1, 2, 3, 4, 5]], [[3, 4, 1, 2, 5]], [[10, 20, 40, 50, 30]], [[1, 10]], [[22, 33, 18, 9, 110, 4, 1, 88, 6, 50]]], "outputs": [[[3, 1, 2]], [[5, 4, 3, 2, 1]], [[3, 2, 5, 4, 1]], [[5, 4, 2, 1, 3]], [[2, 1]], [[5, 4, 6, 7, 1, 9, 10, 2, 8, 3]]]}
INTRODUCTORY
PYTHON3
CODEWARS
962
def rankings(arr):
54208aadf72cba9a7c4581f4b0317b0a
UNKNOWN
# Letterss of Natac In a game I just made up that doesn’t have anything to do with any other game that you may or may not have played, you collect resources on each turn and then use those resources to build things like roads, settlements and cities. If you would like to try other kata about this game, they can be foun...
["from collections import Counter\n\ndef play_if_enough(hand, play):\n h = Counter(hand)\n p = Counter(play)\n if p&h == p:\n h.subtract(p)\n return (True, \"\".join(h.elements()))\n return (False, hand)", "from collections import Counter\n\ndef play_if_enough(hand, play):\n hand, play = Co...
{"fn_name": "play_if_enough", "inputs": [["", "bw"]], "outputs": [[[false, ""]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,713
def play_if_enough(hand, play):
24f7ce62e62336e58a021d58e109f07d
UNKNOWN
# Do names have colors? *Now they do.* Make a function that takes in a name (Any string two chars or longer really, but the name is the idea) and use the ascii values of it's substrings to produce the hex value of its color! Here is how it's going to work: * The first two hexadecimal digits are the *SUM* of the valu...
["from operator import sub, mul\nfrom functools import reduce\n\ndef string_color(string):\n if len(string) < 2:\n return None\n r = sum(map(ord, list(string))) % 256\n g = reduce(mul, list(map(ord, list(string)))) % 256\n b = abs(reduce(sub, list(map(ord, list(string))))) % 256\n return '{:02X}{:...
{"fn_name": "string_color", "inputs": [["A"], [""], ["John Doe"], ["CodeWars"]], "outputs": [[null], [null], ["C70033"], ["182892"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,677
def string_color(name):
7260fa3d1bc48946def0ceefd5f912b9
UNKNOWN
Given a string of integers, count how many times that integer repeats itself, then return a string showing the count and the integer. Example: `countMe('1123')` (`count_me` in Ruby) - Here 1 comes twice so `` will be `"21"` - then 2 comes once so `` will be `"12"` - then 3 comes once so `` will be `"13"` hence outp...
["def count_me(data):\n if not data.isdigit():\n return ''\n \n result = []\n count = 1\n last = data[0]\n \n for char in data[1:]:\n if char == last:\n count += 1\n else:\n result.append(str(count) + last)\n last = char\n count = 1\n...
{"fn_name": "count_me", "inputs": [["1123"], ["1"], ["11"], ["a"], ["a123"], ["21"], ["1211"], ["12322212223443"], [""], ["123a"]], "outputs": [["211213"], ["11"], ["21"], [""], [""], ["1211"], ["111221"], ["111213321132132413"], [""], [""]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,881
def count_me(data):
00d10dfe20884314f6592171a09dfa8a
UNKNOWN
# Task You are a lifelong fan of your local football club, and proud to say you rarely miss a game. Even though you're a superfan, you still hate boring games. Luckily, boring games often end in a draw, at which point the winner is determined by a penalty shoot-out, which brings some excitement to the viewing experienc...
["def penaltyShots(shots, score):\n return (2 if shots > 4 else 5 - shots + 1) - abs(score[0] - score[1])\n", "def penaltyShots(shots, score):\n # coding and coding..\n if score[0] == score[1] ==0 and shots==0:\n return 6\n elif shots >= 5 and score[0] == score[1] != 0:\n return 2\n elif sh...
{"fn_name": "penaltyShots", "inputs": [[2, [1, 2]], [10, [10, 10]], [5, [5, 5]], [0, [0, 0]], [1, [0, 0]], [1, [0, 1]], [1, [1, 1]], [3, [3, 3]], [3, [1, 3]], [100, [100, 100]]], "outputs": [[3], [2], [2], [6], [5], [4], [5], [3], [1], [2]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,194
def penaltyShots(shots, score):
148c4012101ee533936e649ede48bfda
UNKNOWN
The [Ones' Complement](https://en.wikipedia.org/wiki/Ones%27_complement) of a binary number is the number obtained by swapping all the 0s for 1s and all the 1s for 0s. For example: ``` onesComplement(1001) = 0110 onesComplement(1001) = 0110 ``` For any given binary number,formatted as a string, return the Ones' Compl...
["def ones_complement(n):\n return n.translate(str.maketrans(\"01\",\"10\"))", "def ones_complement(binary_number):\n return binary_number.translate(str.maketrans('01', '10'))", "def ones_complement(binary_number):\n return \"\".join([ \"1\" if binary_number[x] == \"0\" else \"0\" for x in range(0, len(binary_nu...
{"fn_name": "ones_complement", "inputs": [["0"], ["1"], ["01"], ["10"], ["1101"]], "outputs": [["1"], ["0"], ["10"], ["01"], ["0010"]]}
INTRODUCTORY
PYTHON3
CODEWARS
900
def ones_complement(binary_number):
5d1dfb94f4d0e0c9db3a237d45610faf
UNKNOWN
Mr. Khalkhoul, an amazing teacher, likes to answer questions sent by his students via e-mail, but he often doesn't have the time to answer all of them. In this kata you will help him by making a program that finds some of the answers. You are given a `question` which is a string containing the question and some `infor...
["def answer(question, information):\n score, info = max((sum(word in info.lower().split() for word in question.lower().split()), info) for info in information)\n return None if not score else info\n", "import re\n\ndef answer(question, information):\n pattern = re.compile(r'\\b({})\\b'.format('|'.join(set(que...
{"fn_name": "answer", "inputs": [["is khalkhoul dumb", ["no he is NOT", "i guess so"]]], "outputs": [["no he is NOT"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,551
def answer(question, information):
6e9674145e3ccc1d936d151149174d68
UNKNOWN
Consider the string `"adfa"` and the following rules: ```Pearl a) each character MUST be changed either to the one before or the one after in alphabet. b) "a" can only be changed to "b" and "z" to "y". ``` From our string, we get: ```Pearl "adfa" -> ["begb","beeb","bcgb","bceb"] Another example: "bd" -> ["ae","ac","...
["def solve(st):\n return all(True if ord(x) - ord(y) in [-2, 0, 2] else False for x, y in zip(st, st[::-1]))\n", "def solve(st):\n return all(abs(ord(x) - ord(y)) in {0, 2} for x, y in zip(st, st[::-1]))", "def solve(stg):\n return all(ord(x) - ord(y) in {-2, 0, 2} for x, y in zip(stg, stg[::-1]))", "solve=la...
{"fn_name": "solve", "inputs": [["abba"], ["abaazaba"], ["abccba"], ["adfa"], ["ae"], ["abzy"], ["ababbaba"], ["sq"], ["kxbkwgyydkcbtjcosgikfdyhuuprubpwthgflucpyylbofvqxkkvqthmdnywpaunfihvupbwpruwfybdmgeuocltdaidyyewmbzm"]], "outputs": [[true], [false], [true], [true], [false], [false], [true], [true], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,023
def solve(st):
8d4e212112d5db08ecf4ed060999a0e6
UNKNOWN
Flash has invited his nemesis The Turtle (He actually was a real villain! ) to play his favourite card game, SNAP. In this game a 52 card deck is dealt out so both Flash and the Turtle get 26 random cards. Each players cards will be represented by an array like below Flash’s pile: ```[ 'A', '5', 'Q', 'Q', '6', '2', ...
["def round(flash_pile, turtle_pile):\n faceup_pile = []\n while turtle_pile:\n for pile in flash_pile, turtle_pile:\n faceup_pile.append(pile.pop(0))\n if len(faceup_pile) >= 2 and faceup_pile[-1] == faceup_pile[-2]:\n flash_pile.extend(faceup_pile)\n re...
{"fn_name": "snap", "inputs": [[["3", "K", "5", "A", "5", "6", "7", "J", "7", "9", "10", "Q", "Q", "6", "8", "7", "4", "J", "8", "9", "K", "J", "10", "4", "K", "4"], ["2", "8", "9", "Q", "A", "K", "6", "3", "J", "2", "4", "3", "3", "8", "A", "2", "6", "7", "9", "10", "A", "5", "Q", "10", "2", "5"]], [["9", "5", "4", "4...
INTRODUCTORY
PYTHON3
CODEWARS
4,399
def snap(flash_pile, turtle_pile):
e75b1974a6fcb0a98084e6975ae639db
UNKNOWN
Having two standards for a keypad layout is inconvenient! Computer keypad's layout: Cell phone keypad's layout: Solve the horror of unstandartized keypads by providing a function that converts computer input to a number as if it was typed by a phone. Example: "789" -> "123" Notes: You get a string wit...
["def computer_to_phone(numbers):\n return \"\".join([str({0:0, 1:7, 2:8, 3:9, 4:4, 5:5, 6:6, 7:1, 8:2, 9:3}[int(n)]) for n in numbers])", "def computer_to_phone(numbers):\n return numbers.translate(str.maketrans('123789', '789123'))", "tbl = str.maketrans('789456123', '123456789')\n\ndef computer_to_phone(numbers)...
{"fn_name": "computer_to_phone", "inputs": [["0789456123"], ["000"], ["94561"], [""], ["919"]], "outputs": [["0123456789"], ["000"], ["34567"], [""], ["373"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,013
def computer_to_phone(numbers):
37e15d52dbcd288e400e487a8da359c1
UNKNOWN
Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number. Example: ```python create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) # => returns "(123) 456-7890" ``` ```f# createPhoneNumber [1; 2; 3; 4; 5; 6; 7; 8; 9; 0] // => returns "...
["def create_phone_number(n):\n return \"({}{}{}) {}{}{}-{}{}{}{}\".format(*n)", "def create_phone_number(n):\n n = ''.join(map(str,n))\n return '(%s) %s-%s'%(n[:3], n[3:6], n[6:])", "def create_phone_number(n):\n str1 = ''.join(str(x) for x in n[0:3])\n str2 = ''.join(str(x) for x in n[3:6])\n str3 = ''...
{"fn_name": "create_phone_number", "inputs": [[[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]], [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], [[0, 2, 3, 0, 5, 6, 0, 8, 9, 0]], [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]], "outputs": [["(123) 456-7890"], ["(111) 111-1111"], ["(023) 056-0890"], ["(000) 000-0000"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,711
def create_phone_number(n):
61d6d1b65d577fbb54f20b94f4c91eb2
UNKNOWN
The code provided is supposed replace all the dots `.` in the specified String `str` with dashes `-` But it's not working properly. # Task Fix the bug so we can all go home early. # Notes String `str` will never be null.
["def replace_dots(string):\n return string.replace('.', '-')", "import re\ndef replace_dots(str):\n return re.sub(r\"\\.\", \"-\", str)\n # literally I had to only add a \\ infront of the dot.\n # this challenge is super hard for noobs and super easy for pros. it's not fair.\n", "import re\ndef replace_dot...
{"fn_name": "replace_dots", "inputs": [[""], ["no dots"], ["one.two.three"], ["........"]], "outputs": [[""], ["no dots"], ["one-two-three"], ["--------"]]}
INTRODUCTORY
PYTHON3
CODEWARS
10,999
def replace_dots(str):
968608db49c3e10007bddc3051a2cb7a
UNKNOWN
You need count how many valleys you will pass. Start is always from zero level. Every time you go down below 0 level counts as an entry of a valley, and as you go up to 0 level from valley counts as an exit of a valley. One passed valley is equal one entry and one exit of a valley. ``` s='FUFFDDFDUDFUFUF' U=UP F=FOR...
["def counting_valleys(s): \n level = 0\n in_valley = False\n count = 0\n for c in s:\n if c =='U':\n level += 1\n elif c=='D':\n level -= 1\n if level >= 0 and in_valley:\n count += 1\n in_valley = level < 0\n return count", "def counting_...
{"fn_name": "counting_valleys", "inputs": [["UFFFD"], ["DFFFD"], ["UFFFU"], ["DFFFU"], ["UFFDDFDUDFUFU"], ["UFFDDFDUDFUFUUFFDDFDUDFUFU"], ["UFFDDFDUDFUFUUFFDDUFFDDUFFDDUDUDUDUDUDUUUUUUUUU"], ["UFFDDFDUDFUFUUFFDDFDUDFUFUUFFDDFDUDFUFUUFFDDFDUDFUFU"], ["UFFDDFDUDFUFUUFFDDFDUDFUFUUFFDDFDUDFUFUUFFDDFDUDFUFUUFFDDFDUDFUFUUFFD...
INTRODUCTORY
PYTHON3
CODEWARS
2,700
def counting_valleys(s):
4e4951084a19c419e5d56f47ef9880d1
UNKNOWN
Apparently "Put A Pillow On Your Fridge Day is celebrated on the 29th of May each year, in Europe and the U.S. The day is all about prosperity, good fortune, and having bit of fun along the way." All seems very weird to me. Nevertheless, you will be given an array of two strings (s). First find out if the first strin...
["pillow=lambda s:('n','B')in zip(*s)", "def pillow(s):\n return ('n','B') in zip(*s)", "def pillow(arr):\n s1, s2 = arr\n return bool({i for i, a in enumerate(s1) if a == 'n'} &\n {i for i, b in enumerate(s2) if b == 'B'})", "def pillow(s):\n return ('n', 'B') in zip(s[0],s[1])", "def pillow...
{"fn_name": "pillow", "inputs": [[["EvH/KNikBiyxfeyK/miCMj", "I/HwjnHlFLlahMOKNadps"]], [["\\DjQ\\[zv]SpG]Z/[Qm\\eLL", "amwZArsaGRmibriXBgTRZp"]], [["n", "B"]], [["yF[CeAAiNihWEmKxJc/NRMVn", "rMeIa\\KAfbjuLiTnAQxNw[XB"]], [["inECnBMAA/u", "ABAaIUOUx/M"]]], "outputs": [[false], [false], [true], [true], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,006
def pillow(s):
0f75c0d6cf79c86869fc48ce4bf74547
UNKNOWN
*This is the advanced version of the [Minimum and Maximum Product of k Elements](https://www.codewars.com/kata/minimum-and-maximum-product-of-k-elements/) kata.* --- Given a list of **integers** and a positive integer `k` (> 0), find the minimum and maximum possible product of `k` elements taken from the list. If y...
["from functools import reduce\n\ndef find_min_max_product(arr, k): \n if k <= len(arr):\n arr = sorted(arr, key=abs)\n lasts = arr[-k:]\n v1 = reduce(int.__mul__, lasts)\n v0 = reduce(int.__mul__, arr[:k])\n \n first_SameOrOpp = [next((v for v in lasts ...
{"fn_name": "find_min_max_product", "inputs": [[[0, 1, 2, 3, 4], 2], [[0, -1, -2, -3, -4], 2], [[0, -1, -2, -3, -4], 3], [[-1, -2, -3, -4], 2], [[-1, -2, -3, -4], 3], [[], 2], [[-4, -10, -1], 2], [[0, 6, 3, 5, 4], 4], [[5, 4, 3, 3, 6], 2]], "outputs": [[[0, 12]], [[0, 12]], [[-24, 0]], [[2, 12]], [[-24, -6]], [null], [...
INTRODUCTORY
PYTHON3
CODEWARS
16,340
def find_min_max_product(arr, k):
bdc39e63981a782bd18fcca3958caf09
UNKNOWN
Given a sequence of items and a specific item in that sequence, return the item immediately following the item specified. If the item occurs more than once in a sequence, return the item after the first occurence. This should work for a sequence of any type. When the item isn't present or nothing follows it, the funct...
["def next_item(xs, item):\n it = iter(xs)\n for x in it:\n if x == item:\n break\n return next(it, None)", "def next_item(xs, item):\n it = iter(xs)\n next(iter(x for x in it if x == item), None)\n return next(it, None)", "import itertools\ndef next_item(xs, item):\n try:\n xs =...
{"fn_name": "next_item", "inputs": [[[1, 2, 3, 4, 5, 6, 7, 8], 3], [["a", "b", "c"], "d"], [["a", "b", "c"], "c"], ["testing", "t"], ["Hello!", "o"], ["Hello!", "!"], ["Hello!", "x"]], "outputs": [[4], [null], [null], ["e"], ["!"], [null], [null]]}
INTRODUCTORY
PYTHON3
CODEWARS
21,869
def next_item(xs, item):
46d2f9bb7f798e482da25000f187b51f
UNKNOWN
Assume `"#"` is like a backspace in string. This means that string `"a#bc#d"` actually is `"bd"` Your task is to process a string with `"#"` symbols. ## Examples ``` "abc#d##c" ==> "ac" "abc##d######" ==> "" "#######" ==> "" "" ==> "" ```
["def clean_string(s):\n stk = []\n for c in s:\n if c=='#' and stk: stk.pop()\n elif c!='#': stk.append(c)\n return ''.join(stk)", "def clean_string(s):\n result = []\n for c in s:\n if c == '#':\n if result:\n result.pop()\n else:\n ...
{"fn_name": "clean_string", "inputs": [["abjd####jfk#"], ["gfh#jds###d#dsd####dasdaskhj###dhkjs####df##s##d##"], ["831####jns###s#cas/*####-5##s##6+yqw87e##hfklsd-=-28##fds##"], ["######831###dhkj####jd#dsfsdnjkf###d####dasns"], [""], ["#######"], ["####gfdsgf##hhs#dg####fjhsd###dbs########afns#######sdanfl##db#####s#a...
INTRODUCTORY
PYTHON3
CODEWARS
1,433
def clean_string(s):
41397fe1eaff2315f25eb94ab2cf995c
UNKNOWN
Decompose a number `num` into an array (tuple in Haskell, array of arrays `long[][]` in C# or Java) of the form `[[k1,k2,k3...], r]`, `([k1,k2,k3...], r)` in Haskell, `[[k1,k2,k3...], [r]]` in C# or Java) such that: 1. each kn is more than one 2. eack kn is maximized (first maximizing for 2 then 3 then 4 and so on) 3...
["from math import log\n\ndef decompose(n):\n i = 2\n result = []\n while n >= i*i:\n k = int(log(n, i))\n result.append(k)\n n -= i ** k\n i += 1\n \n return [result, n]\n", "from math import log\n\ndef decompose(num):\n i, res = 2, []\n while i**2 <= num:\n n = ...
{"fn_name": "decompose", "inputs": [[0], [4], [9], [25], [8330475], [9819938], [8331299], [8328441]], "outputs": [[[[], 0]], [[[2], 0]], [[[3], 1]], [[[4, 2], 0]], [[[22, 13, 10, 8, 7, 6, 6, 5, 5, 5, 4, 4, 4, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2], 0]], [[[23, 12, 9, 8, 6, 6, 5, 4, 4, 4, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2...
INTRODUCTORY
PYTHON3
CODEWARS
2,109
def decompose(num):
137271235d75b25cb2b727a5eb52f23a
UNKNOWN
Given a string (`str`) containing a base-10 integer between `0` and `10000`, convert the integer to its binary representation. At that point, obtain a count of the maximum amount of consecutive 0s. From there, return the count in written form with a capital letter. In the very first example, we have an argument of `"9...
["import re\nls = [\"Zero\",\"One\",\"Two\",\"Three\",\"Four\",\"Five\",\"Six\",\"Seven\",\"Eight\",\"Nine\",\"Ten\",\"Eleven\",\"Twelve\",\"Thirteen\"]\ndef max_consec_zeros(n):\n return ls[max(map(lambda x:len(x),re.findall(r'0*',bin(int(n))[2:])))]", "import re\n\ndef max_consec_zeros(n):\n return 'zero one tw...
{"fn_name": "max_consec_zeros", "inputs": [["7"], ["33"], ["77"], ["100"], ["105"], ["113"], ["160"], ["180"], ["223"], ["256"], ["777"], ["992"], ["1024"], ["1037"], ["1088"], ["2017"], ["2048"], ["3050"], ["4096"], ["6144"], ["6656"], ["7188"], ["8192"], ["9999"], ["10000"]], "outputs": [["Zero"], ["Four"], ["Two"], ...
INTRODUCTORY
PYTHON3
CODEWARS
4,457
def max_consec_zeros(n):
ac4a675ad846a96da5ca2f75c0138a83
UNKNOWN
### Task You've just moved into a perfectly straight street with exactly ```n``` identical houses on either side of the road. Naturally, you would like to find out the house number of the people on the other side of the street. The street looks something like this: -------------------- ### Street ``` 1| |6 3| |4 5...
["def over_the_road(address, n):\n '''\n Input: address (int, your house number), n (int, length of road in houses) \n Returns: int, number of the house across from your house. \n '''\n # this is as much a math problem as a coding one \n # if your house is [even/odd], the opposite house will be [odd/e...
{"fn_name": "over_the_road", "inputs": [[1, 3], [3, 3], [2, 3], [3, 5], [7, 11], [10, 22], [20, 3400], [9, 26], [20, 10]], "outputs": [[6], [4], [5], [8], [16], [35], [6781], [44], [1]]}
INTRODUCTORY
PYTHON3
CODEWARS
16,518
def over_the_road(address, n):
698bd0316665f4d935ce2eae48b29579
UNKNOWN
In this Kata you are a builder and you are assigned a job of building a wall with a specific size (God knows why...). Create a function called `build_a_wall` (or `buildAWall` in JavaScript) that takes `x` and `y` as integer arguments (which represent the number of rows of bricks for the wall and the number of bricks i...
["# -*- coding: utf-8 -*-\ndef build_a_wall(x=0, y=0):\n if type(x) != int or type(y) != int or x < 1 or y < 1: return\n if x * y > 10000: return \"Naah, too much...here's my resignation.\"\n res = [[\"\u25a0\u25a0\"]*y if i&1^x&1 else [\"\u25a0\"] + [\"\u25a0\u25a0\"]*(y-1) + [\"\u25a0\"] for i in range(x)]\n...
{"fn_name": "build_a_wall", "inputs": [[4, 5], [10, 7], ["eight", [3]], [12, -4], [0, 9], [123, 987]], "outputs": [["\u25a0|\u25a0\u25a0|\u25a0\u25a0|\u25a0\u25a0|\u25a0\u25a0|\u25a0\n\u25a0\u25a0|\u25a0\u25a0|\u25a0\u25a0|\u25a0\u25a0|\u25a0\u25a0\n\u25a0|\u25a0\u25a0|\u25a0\u25a0|\u25a0\u25a0|\u25a0\u25a0|\u25a0\n\u2...
INTRODUCTORY
PYTHON3
CODEWARS
4,621
def build_a_wall(x=0, y=0):
83e0b2a5e4269cef03853a5d85152015
UNKNOWN
# Task You're given a two-dimensional array of integers `matrix`. Your task is to determine the smallest non-negative integer that is not present in this array. # Input/Output - `[input]` 2D integer array `matrix` A non-empty rectangular matrix. `1 ≤ matrix.length ≤ 10` `1 ≤ matrix[0].length ≤ 10` - `[o...
["def smallest_integer(matrix):\n nums = set(sum(matrix, []))\n n = 0\n while n in nums: n += 1\n return n", "from itertools import filterfalse, chain, count\n\ndef smallest_integer(matrix):\n return next(filterfalse(set(chain.from_iterable(matrix)).__contains__, count()))", "def smallest_integer(matrix)...
{"fn_name": "smallest_integer", "inputs": [[[[0, 2], [5, 1]]], [[[4, 5, 3, 21, 3, 8], [2, 2, 6, 5, 10, 9], [7, 5, 6, 8, 2, 6], [1, 4, 7, 8, 9, 0], [1, 3, 6, 5, 5, 1], [2, 7, 3, 4, 4, 3]]], [[[4, 5, 3, -4, 3, 8], [2, 0, 6, 5, 4, 9], [7, 5, 6, 8, 2, 6], [1, 4, 7, 8, 9, 11], [1, 3, 10, 5, 5, 1], [12, 7, 3, 4, 4, 3]]], [[[...
INTRODUCTORY
PYTHON3
CODEWARS
1,593
def smallest_integer(matrix):
45b192df2f868307bc483affb317377a
UNKNOWN
You are given two positive integer lists with a random number of elements (1 <= n <= 100). Create a [GCD](https://en.wikipedia.org/wiki/Greatest_common_divisor) matrix and calculate the average of all values. Return a float value rounded to 3 decimal places. ## Example ``` a = [1, 2, 3] b = [4, 5, 6] # a =...
["from fractions import gcd\nfrom itertools import product, starmap\nfrom statistics import mean\n\ndef gcd_matrix(a, b):\n return round(mean(starmap(gcd, product(a, b))), 3)", "from fractions import gcd\n\ndef gcd_matrix(a, b):\n return round(sum(gcd(x, y) for x in a for y in b) / (len(a) * len(b)), 3)\n", "from...
{"fn_name": "gcd_matrix", "inputs": [[[1, 2, 3], [4, 5, 6]], [[5, 5, 5], [10, 10, 10]], [[4, 7, 2, 10, 99, 4], [55, 32, 1, 344, 35234, 3]]], "outputs": [[1.444], [5.0], [2.0]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,729
def gcd_matrix(a,b):
a7d0c2f50a1a90e563216f8332c2e436
UNKNOWN
Take debugging to a whole new level: Given a string, remove every *single* bug. This means you must remove all instances of the word 'bug' from within a given string, *unless* the word is plural ('bugs'). For example, given 'obugobugobuoobugsoo', you should return 'ooobuoobugsoo'. Another example: given 'obbugugo',...
["import re\n\ndef debug(s):\n return re.sub(r'bug(?!s)', '', s)", "import re\n\ndef debug(string):\n return re.sub(\"bug(?!s)\", \"\", string)", "def debug(s):\n s=s.replace(\"bugs\", \"^\")\n s=s.replace(\"bug\", \"\")\n s=s.replace(\"^\", \"bugs\")\n return s", "def debug(s):\n return __import__...
{"fn_name": "debug", "inputs": [["obugobugobuoobugsoo"], ["obbugugo"], ["bugs bunny"], ["bugs buggy"], ["oaiwjefbugoijoijapsbugsdoibugbugjfoijasdfbugsbug"], ["bugbugbugiahweoifuhiaasnoidfhnbugbugs"], ["bugsbugswaoeifhiauwehfoiwubugshefjnviouah"], ["bugbugbugbug"], ["bugsbugsbugsbugs"], ["buggybugs"], ["oaisjdfowjefpoib...
INTRODUCTORY
PYTHON3
CODEWARS
1,000
def debug(s):
4390adf9c5973945c63f0ba3dd8000ad
UNKNOWN
Your wizard cousin works at a Quidditch stadium and wants you to write a function that calculates the points for the Quidditch scoreboard! # Story Quidditch is a sport with two teams. The teams score goals by throwing the Quaffle through a hoop, each goal is worth **10 points**. The referee also deducts 30 points (...
["def quidditch_scoreboard(teams, actions):\n teams = {i:0 for i in teams.split(' vs ')}\n for i in actions.split(', '):\n team, action = i.split(': ')\n if 'goal' in action:\n teams[team] += 10\n elif 'foul' in action:\n teams[team] -= 30\n elif 'Snitch' in actio...
{"fn_name": "quidditch_scoreboard", "inputs": [["Appleby Arrows vs Montrose Magpies", "Montrose Magpies: Quaffle goal, Montrose Magpies: Quaffle goal, Appleby Arrows: Quaffle goal, Appleby Arrows: Quaffle goal, Montrose Magpies: Haverstacking foul, Appleby Arrows: Quaffle goal, Appleby Arrows: Quaffle goal, Appleby Arr...
INTRODUCTORY
PYTHON3
CODEWARS
5,488
def quidditch_scoreboard(teams, actions):
19cf60ca43015f16cbf6e5dfc9a8fd53
UNKNOWN
# Task Some children are playing rope skipping game. Children skip the rope at roughly the same speed: `once per second`. If the child fails during the jump, he needs to tidy up the rope and continue. This will take `3 seconds`. You are given an array `failedCount`, where each element is the jump count at the failed. ...
["def tiaosheng(a):\n j, t = 0, 0\n for j in a:\n t += 3\n if j + t > 60:\n return min(j, 60-t+3)\n return 60-t", "def tiaosheng(failed_counter):\n count = 0\n jumps = 0\n\n while count < 60:\n count += 1\n jumps += 1\n if jumps in failed_counter:\n ...
{"fn_name": "tiaosheng", "inputs": [[[]], [[12, 23, 45]], [[17]], [[10, 20, 30, 40]], [[10, 20, 30, 40, 58]], [[10, 20, 30, 40, 47, 60]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]], "outputs": [[60], [51], [57], [48], [48], [47], [30]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,642
def tiaosheng(failed_counter):
87a39ea9ae29478b935424a06bc999d3
UNKNOWN
# Task Two arrays are called similar if one can be obtained from another by swapping at most one pair of elements. Given two arrays, check whether they are similar. # Example For `A = [1, 2, 3]` and `B = [1, 2, 3]`, the output should be `true;` For `A = [1, 2, 3]` and `B = [2, 1, 3]`, the output should be `true;` ...
["def are_similar(a, b):\n return sorted(a) == sorted(b) and sum(i != j for i, j in zip(a, b)) in [0, 2]", "from collections import Counter\ndef are_similar(a, b):\n return sum(a_ == b_ for a_, b_ in zip(a, b)) >= len(a) - 2 and Counter(a) == Counter(b)", "def are_similar(a, b):\n c = [a[i] - b[i] for i in ran...
{"fn_name": "are_similar", "inputs": [[[1, 2, 3], [1, 2, 3]], [[1, 2, 3], [2, 1, 3]], [[1, 2, 2], [2, 1, 1]], [[1, 2, 3], [1, 10, 2]], [[2, 3, 1], [1, 3, 2]], [[1, 1, 2], [1, 2, 2]]], "outputs": [[true], [true], [false], [false], [true], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,423
def are_similar(a, b):
b715d9d44db70c829d360e665041f244
UNKNOWN
Sam is an avid collector of numbers. Every time he finds a new number he throws it on the top of his number-pile. Help Sam organise his collection so he can take it to the International Number Collectors Conference in Cologne. Given an array of numbers, your function should return an array of arrays, where each subar...
["group=lambda arr: [[n]*arr.count(n) for n in sorted(set(arr), key=arr.index)]", "from collections import Counter, OrderedDict\n\nclass OrderedCounter(Counter, OrderedDict): \n pass\n\ndef group(arr):\n return [[k] * v for k, v in OrderedCounter(arr).items()]", "from collections import OrderedDict\n\ndef group(a...
{"fn_name": "group", "inputs": [[[3, 2, 6, 2, 1, 3]], [[3, 2, 6, 2]], [[]], [[1, 100, 4, 2, 4]], [[-1, 1, -1]]], "outputs": [[[[3, 3], [2, 2], [6], [1]]], [[[3], [2, 2], [6]]], [[]], [[[1], [100], [4, 4], [2]]], [[[-1, -1], [1]]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,768
def group(arr):
4e8005d6a950c5966020145a58baf13a
UNKNOWN
There is no single treatment that works for every phobia, but some people cure it by being gradually exposed to the phobic situation or object. In this kata we will try curing arachnophobia by drawing primitive spiders. Our spiders will have legs, body, eyes and a mouth. Here are some examples: ``` /\((OOwOO))/\ /╲(...
["def draw_spider(leg_size, body_size, mouth, eye):\n lleg = ['', '^', '/\\\\', '/\u2572', '\u2571\u2572'][leg_size]\n rleg = ['', '^', '/\\\\', '\u2571\\\\', '\u2571\u2572'][leg_size]\n lbody = '(' * body_size\n rbody = ')' * body_size\n eye *= 2 ** (body_size - 1)\n return f'{lleg}{lbody}{eye}{mouth...
{"fn_name": "draw_spider", "inputs": [[1, 1, "W", "o"], [2, 2, "w", "O"], [3, 3, "w", "0"]], "outputs": [["^(oWo)^"], ["/\\((OOwOO))/\\"], ["/\u2572(((0000w0000)))\u2571\\"]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,597
def draw_spider(leg_size, body_size, mouth, eye):
a2b609ec6fd7e8fbe8dca2073b23628c
UNKNOWN
Given a set of numbers, return the additive inverse of each. Each positive becomes negatives, and the negatives become positives. ~~~if-not:racket ``` invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5] invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5] invert([]) == [] ``` ~~~ ```if:javascript,python,ruby,php,elixir,dart You can assume th...
["def invert(lst):\n return [-x for x in lst]", "def invert(lst):\n return list(map(lambda x: -x, lst));", "def invert(lst):\n i = 0\n inv = []\n while i < len(lst):\n inv.append(lst[i] * -1)\n i += 1\n return inv\n\n", "def invert(lst):\n return [i*-1 for i in lst]", "def invert(lst):...
{"fn_name": "invert", "inputs": [[[1, 2, 3, 4, 5]], [[1, -2, 3, -4, 5]], [[]], [[0]]], "outputs": [[[-1, -2, -3, -4, -5]], [[-1, 2, -3, 4, -5]], [[]], [[0]]]}
INTRODUCTORY
PYTHON3
CODEWARS
10,972
def invert(lst):
74977bb4c9bc4d3985bd386683c3feeb
UNKNOWN
## Task You are given three non negative integers `a`, `b` and `n`, and making an infinite sequence just like fibonacci sequence, use the following rules: - step 1: use `ab` as the initial sequence. - step 2: calculate the sum of the last two digits of the sequence, and append it to the end of sequence. - repeat step...
["def find(a,b,n):\n strng = str(a) + str(b)\n #there are 10 and 4 long loops\n if (n > 20): n = n%20+20\n while len(strng) <= n:\n next_ch = int(strng[-1]) + int(strng[-2])\n strng = strng + str(next_ch)\n return int(strng[n])", "L = [\n(\"\", \"0\"),\n(\"0\", \"1123581347\"),\n(\"0224610\...
{"fn_name": "find", "inputs": [[7, 8, 9], [0, 0, 1000000]], "outputs": [[5], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
7,591
def find(a, b, n):
50915757df457216d1ab6fb79880b8c3
UNKNOWN
# Background My TV remote control has arrow buttons and an `OK` button. I can use these to move a "cursor" on a logical screen keyboard to type "words"... The screen "keyboard" layout looks like this #tvkb { width : 300px; border: 5px solid gray; border-collapse: collapse; } #tvkb td { color : or...
["KEYBOARD = \"abcde123fghij456klmno789pqrst.@0uvwxyz_/\"\nMAP = {c: (i//8, i%8) for i,c in enumerate(KEYBOARD)}\n\ndef manhattan(*pts): return sum( abs(z2-z1) for z1,z2 in zip(*pts))\n\ndef tv_remote(word):\n return len(word) + sum( manhattan(MAP[was], MAP[curr]) for was,curr in zip('a'+word, word))", "def get...
{"fn_name": "tv_remote", "inputs": [["codewars"], ["does"], ["your"], ["solution"], ["work"], ["for"], ["these"], ["words"], ["mississippi"]], "outputs": [[36], [16], [23], [33], [20], [12], [27], [25], [35]]}
INTRODUCTORY
PYTHON3
CODEWARS
57,961
def tv_remote(word):
1a5d32181b3e2ca61a8bd42d7fff204c
UNKNOWN
In this Kata you are to implement a function that parses a string which is composed from tokens of the form 'n1-n2,n3,n4-n5:n6' where 'nX' is a positive integer. Each token represent a different range: 'n1-n2' represents the range n1 to n2 (inclusive in both ends). 'n3' represents the single integer n3. 'n4-n5:n6' rep...
["def range_parser(string):\n res = []\n for range_ in string.split(','):\n first_last, _, step = range_.partition(':')\n first, _, last = first_last.partition('-')\n res += range(int(first), int(last or first) + 1, int(step or 1))\n return res", "import re\n\ndef range_parser(s):\n ret...
{"fn_name": "range_parser", "inputs": [["1-10,14, 20-25:2"], ["5-10"], ["2"], ["1-10,3"], ["1-10:5"]], "outputs": [[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 14, 20, 22, 24]], [[5, 6, 7, 8, 9, 10]], [[2]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 3]], [[1, 6]]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,311
def range_parser(string):
201c3b4db420afcd8d687bd874913b65
UNKNOWN
# Situation You have been hired by a company making electric garage doors. Accidents with the present product line have resulted in numerous damaged cars, broken limbs and several killed pets. Your mission is to write a safer version of their controller software. # Specification We always start with a closed door. The...
["def controller(events):\n\n out, state, dir, moving = [], 0, 1, False\n \n for c in events:\n if c == 'O': dir *= -1\n elif c == 'P': moving = not moving\n if moving: state += dir\n if state in [0,5]: moving, dir = False, 1 if state == 0 else -1\n out....
{"fn_name": "controller", "inputs": [[""], [".........."], ["P.."], ["P...."], ["P......P......"], ["P.P.."], ["P.P.P...."], [".....P.P........P...."], [".....P......P.P..P...."], ["P.O...."], ["P......P.O...."], ["P..OP..P.."], ["P......P..OP..P..."], ["..P...O....."]], "outputs": [[""], ["0000000000"], ["123"], ["123...
INTRODUCTORY
PYTHON3
CODEWARS
6,280
def controller(events):
e029e11219cc377b93cf6ba2da4d76c1
UNKNOWN
Complete the solution. It should try to retrieve the value of the array at the index provided. If the index is out of the array's max bounds then it should return the default value instead. Example: ```Haskell solution [1..3] 1 1000 `shouldBe` 2 solution [1..5] (10) 1000 `shouldBe` 1000 -- negative values work as lon...
["def solution(items, index, default_value):\n try:\n return items[index]\n except IndexError:\n return default_value", "def solution(items, index, default_value):\n return items[index] if -len(items) <= index < len(items) else default_value\n", "def solution(items, index, default_value):\n tr...
{"fn_name": "solution", "inputs": [[[null, null], 0, "a"]], "outputs": [[null]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,327
def solution(items, index, default_value):
27aa6dc6e408f87580c43cc13eaec6db
UNKNOWN
Create an OR function, without use of the 'or' keyword, that takes an list of boolean values and runs OR against all of them. Assume there will be between 1 and 6 variables, and return None for an empty list.
["def alt_or(lst):\n return any(lst) if lst else None", "def alt_or(lst): return bool(sum(lst)) if lst else None", "def alt_or(a):\n return any(a) if a else None ", "def alt_or(lst):\n return eval(str(lst).replace(',', '|'))[0] if lst else None", "def alt_or(a):\n if a: return any(a)", "def alt_or(lst):\n ...
{"fn_name": "alt_or", "inputs": [[[]], [[false, false, false, false, false, false]], [[false, false, false, false, false, true]], [[false, false, false, false, true, false]], [[false, false, false, false, true, true]], [[false, false, false, true, false, false]], [[false, false, false, true, false, true]], [[false, fal...
INTRODUCTORY
PYTHON3
CODEWARS
783
def alt_or(lst):
decc8eccc6e7fd79951bbc1a4d3092e4
UNKNOWN
The Spelling Bee bees are back... # How many bees are in the beehive? * bees can be facing UP, DOWN, LEFT, RIGHT, and now also _diagonally_ up/down/left/right * bees can share parts of other bees ## Examples Ex1 ``` bee.bee .e..e.. .b..eeb ``` _Answer: 5_ Ex2 ``` beee.. eeb.e. ebee.b ``` _Answer: 7_
["def how_many_bees(h):\n if not h: return 0\n v = list(zip(*h))\n b = [None] * len(h)\n sf = (b[i:] + l + b[:i] for i,l in enumerate(h))\n sb = (b[:i] + l + b[i:] for i,l in enumerate(h))\n df = [[n for n in l if n is not None] for l in zip(*sf)]\n db = [[n for n in l if n is not None] for l in zi...
{"fn_name": "how_many_bees", "inputs": [[null]], "outputs": [[0]]}
INTRODUCTORY
PYTHON3
CODEWARS
9,021
def how_many_bees(hive):
e5f928e90f63b084f8d4411e7e98ce68
UNKNOWN
Regular Tic-Tac-Toe is boring. That's why in this Kata you will be playing Tic-Tac-Toe in **3D** using a 4 x 4 x 4 matrix! # Kata Task Play the game. Work out who wins. Return a string * `O wins after moves` * `X wins after moves` * `No winner` # Rules * Player `O` always goes first * Input `moves` is list/...
["from itertools import product\n\ndef winning_lines(size, dimension):\n if dimension == 1: return frozenset({frozenset({(n,) for n in range(size)})})\n lines = set()\n for line, idx, val in product(winning_lines(size, dimension - 1), range(dimension), range(size)):\n lines.add(frozenset({cell[:idx] + (...
{"fn_name": "play_OX_3D", "inputs": [[[]]], "outputs": [["No winner"]]}
INTRODUCTORY
PYTHON3
CODEWARS
16,484
def play_OX_3D(moves):
a8328380b8439de29fde1bbb6c3ed9de
UNKNOWN
You are given two sorted arrays that contain only integers. Your task is to find a way to merge them into a single one, sorted in **ascending order**. Complete the function `mergeArrays(arr1, arr2)`, where `arr1` and `arr2` are the original sorted arrays. You don't need to worry about validation, since `arr1` and `arr...
["def merge_arrays(arr1, arr2):\n return sorted(set(arr1+arr2))", "merge_arrays = lambda a, b: sorted(list(set(a + b)))", "merge_arrays = lambda a1, a2: sorted(set(a1+a2))", "def merge_arrays(arr1, arr2):\n for arr in (arr1, arr2):\n if arr[0] > arr[-1]:\n arr.reverse()\n res = []\n i = 0\n k = 0\n whil...
{"fn_name": "merge_arrays", "inputs": [[[1, 2, 3, 4], [5, 6, 7, 8]], [[10, 8, 6, 4, 2], [9, 7, 5, 3, 1]], [[-20, 35, 36, 37, 39, 40], [-10, -5, 0, 6, 7, 8, 9, 10, 25, 38, 50, 62]], [[5, 6, 7, 8, 9, 10], [20, 18, 15, 14, 13, 12, 11, 4, 3, 2]], [[45, 30, 20, 15, 12, 5], [9, 10, 18, 25, 35, 50]], [[-8, -3, -2, 4, 5, 6, 7,...
INTRODUCTORY
PYTHON3
CODEWARS
18,697
def merge_arrays(arr1, arr2):
07c060085458aef6b2008af26ed43778
UNKNOWN
Write a function that outputs the transpose of a matrix - a new matrix where the columns and rows of the original are swapped. For example, the transpose of: | 1 2 3 | | 4 5 6 | is | 1 4 | | 2 5 | | 3 6 | The input to your function will be an array of matrix rows. You can assume that each row...
["def transpose(matrix):\n return list(map(list, zip(*matrix)))", "def transpose(matrix):\n return [[row[i] for row in matrix] for i, col in enumerate(matrix[0])]", "import numpy as np\n\n# Take your pick\ndef transpose(matrix):\n return list(map(list, zip(*matrix)))\n return np.transpose(matrix).tolist()",...
{"fn_name": "transpose", "inputs": [[[[1]]], [[[1, 2, 3]]], [[[1, 2, 3], [4, 5, 6], [7, 8, 9]]], [[[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0]]]], "outputs": [[[[1]]], [[[1], [2], [3]]], [[[1, 4, 7], [2, 5, 8], [3, 6, 9]]], [[[1, 0, 0, 0, 1], [0, 1, 0, 1, 0], [0, 0, 1, 0, 0]]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,086
def transpose(matrix):
14e089d0326503861d1f95a3b6111666
UNKNOWN
# Task In the Land Of Chess, bishops don't really like each other. In fact, when two bishops happen to stand on the same diagonal, they immediately rush towards the opposite ends of that same diagonal. Given the initial positions (in chess notation) of two bishops, `bishop1` and `bishop2`, calculate their future pos...
["def bishop_diagonal(a, b):\n a, b = sorted([['abcdefgh'.index(f), '12345678'.index(r)] for f, r in [a, b]])\n m = int((b[1] - a[1])/(b[0] - a[0])) if abs(a[1] - b[1]) == abs(a[0] - b[0]) and abs(a[1] - b[1]) else 0\n if m:\n while all(0 < e < 7 for e in a): a = [a[0] - 1, a[1] - m]\n while all(...
{"fn_name": "bishop_diagonal", "inputs": [["d7", "f5"], ["d8", "b5"], ["a1", "h8"], ["g3", "e1"], ["b4", "e7"]], "outputs": [[["c8", "h3"]], [["b5", "d8"]], [["a1", "h8"]], [["e1", "h4"]], [["a3", "f8"]]]}
INTRODUCTORY
PYTHON3
CODEWARS
8,547
def bishop_diagonal(bishop1, bishop2):
db498f1124dff6d6b66e469838a7b79c
UNKNOWN
Write a function that takes a number or a string and gives back the number of **permutations without repetitions** that can generated using all of its element.; more on permutations [here](https://en.wikipedia.org/wiki/Permutation). For example, starting with: ``` 1 45 115 "abc" ``` You could respectively generate: `...
["from operator import mul\nfrom math import factorial\nfrom functools import reduce\nfrom collections import Counter\n\ndef perms(inp):\n return factorial(len(str(inp))) // reduce(mul, map(factorial, Counter(str(inp)).values()), 1)", "from math import factorial\ndef perms(e):\n e = str(e)\n n = factorial(len(...
{"fn_name": "perms", "inputs": [[2], [25], [342], [1397], [76853], ["a"], ["ab"], ["abc"], [737], [66666]], "outputs": [[1], [2], [6], [24], [120], [1], [2], [6], [3], [1]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,731
def perms(element):
99945aa1c18dc9d50ac6e57ec6617ada
UNKNOWN
Write ```python function combine() ``` that combines arrays by alternatingly taking elements passed to it. E.g ```python combine(['a', 'b', 'c'], [1, 2, 3]) == ['a', 1, 'b', 2, 'c', 3] combine(['a', 'b', 'c'], [1, 2, 3, 4, 5]) == ['a', 1, 'b', 2, 'c', 3, 4, 5] combine(['a', 'b', 'c'], [1, 2, 3, 4, 5], [6, 7], [8]) ...
["def combine(*args):\n out = list()\n for i in range(len(max(args, key=len))): #Sometimes you just have to love python\n for arr in args:\n if i < len(arr): out.append(arr[i])\n return out", "from itertools import chain, zip_longest\n\ndef combine(*args):\n return [x for x in chain.from_iterable(zip_long...
{"fn_name": "combine", "inputs": [[["a", "b", "c"], [1, 2, 3]], [["a", "b", "c"], [1, 2, 3, 4, 5]], [["a", "b", "c"], [1, 2, 3, 4, 5], [6, 7], [8]], [[{"a": 1}, {"b": 2}], [1, 2]], [[{"a": 2, "b": 1}, {"a": 1, "b": 2}], [1, 2, 3, 4], [5, 6], [7]]], "outputs": [[["a", 1, "b", 2, "c", 3]], [["a", 1, "b", 2, "c", 3, 4, 5]...
INTRODUCTORY
PYTHON3
CODEWARS
1,923
def combine(*args):
efc097b3f2d7400512ca08b6cb2d32ea
UNKNOWN
In this kata you need to write a function that will receive two strings (```n1``` and ```n2```), each representing an integer as a binary number. A third parameter will be provided (```o```) as a string representing one of the following operators: add, subtract, multiply. Your task is to write the calculate function s...
["def calculate(n1, n2, o):\n operators = {\n \"add\": (lambda x, y: x + y),\n \"subtract\": (lambda x, y: x - y),\n \"multiply\": (lambda x, y: x * y),\n }\n \n return \"{:b}\".format( operators[o]( int(n1, 2), int(n2, 2) ) )", "def calculate(n1, n2, o):\n def s2b(i):\n retur...
{"fn_name": "calculate", "inputs": [["1", "1", "add"], ["1", "1", "subtract"], ["1", "1", "multiply"], ["10", "10", "multiply"], ["100", "10", "subtract"]], "outputs": [["10"], ["0"], ["1"], ["100"], ["10"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,343
def calculate(n1, n2, o):
8805d057829f3abb16cb7f9b06059766
UNKNOWN
To pass the series of gates guarded by the owls, Kenneth needs to present them each with a highly realistic portrait of one. Unfortunately, he is absolutely rubbish at drawing, and needs some code to return a brand new portrait with a moment's notice. All owl heads look like this: ''0v0'' Such beautiful eyes! H...
["import re\n\ndef owl_pic(text):\n str = re.sub('[^ 8,W,T,Y,U,I,O,A,H,X,V,M]', '', text.upper())\n return str+\"''0v0''\"+str[::-1]", "def owl_pic(text):\n plumage = \"\".join(c for c in text.upper() if c in \"8WTYUIOAHXVM\")\n return f\"{plumage}''0v0''{plumage[::-1]}\"", "plumm = '8WTYUIOAHXVM'\ndef owl_...
{"fn_name": "owl_pic", "inputs": [["xwe"], ["kuawd6r8q27y87t93r76352475437"], ["t6ggggggggWw"], ["xweWXo"]], "outputs": [["XW''0v0''WX"], ["UAW8Y8T''0v0''T8Y8WAU"], ["TWW''0v0''WWT"], ["XWWXO''0v0''OXWWX"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,522
def owl_pic(text):
0d3086039f8a8695151e5228dfc44ee6
UNKNOWN
Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements. ```python move_zeros([False,1,0,1,2,0,1,3,"a"]) # returns[False,1,1,2,1,3,"a",0,0] ```
["def move_zeros(arr):\n l = [i for i in arr if isinstance(i, bool) or i!=0]\n return l+[0]*(len(arr)-len(l))", "def move_zeros(array):\n return sorted(array, key=lambda x: x==0 and type(x) is not bool)", "def move_zeros(array):\n return sorted(array, key=lambda x: x == 0 and x is not False)", "def move_zer...
{"fn_name": "move_zeros", "inputs": [[[1, 2, 0, 1, 0, 1, 0, 3, 0, 1]], [[9, 0.0, 0, 9, 1, 2, 0, 1, 0, 1, 0.0, 3, 0, 1, 9, 0, 0, 0, 0, 9]], [["a", 0, 0, "b", "c", "d", 0, 1, 0, 1, 0, 3, 0, 1, 9, 0, 0, 0, 0, 9]], [["a", 0, 0, "b", null, "c", "d", 0, 1, false, 0, 1, 0, 3, [], 0, 1, 9, 0, 0, {}, 0, 0, 9]], [[0, 1, null, 2,...
INTRODUCTORY
PYTHON3
CODEWARS
3,917
def move_zeros(array):
a93d1b64728b2fc04100425ba1b6ea73
UNKNOWN
The Mormons are trying to find new followers and in order to do that they embark on missions. Each time they go on a mission, every Mormons converts a fixed number of people (reach) into followers. This continues and every freshly converted Mormon as well as every original Mormon go on another mission and convert the ...
["def mormons(starting_number, reach, target):\n missions = 0\n while starting_number < target:\n starting_number += starting_number * reach\n missions += 1\n return missions\n\n\n# def mormons(start, reach, target, missions=0):\n# if start >= target:\n# return missions\n# return ...
{"fn_name": "mormons", "inputs": [[40, 2, 120], [40, 2, 121]], "outputs": [[1], [2]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,502
def mormons(starting_number, reach, target):
c3b7fd6f2121cd70c517caf6bea03e57
UNKNOWN
An **anagram** is the result of rearranging the letters of a word to produce a new word. **Note:** anagrams are case insensitive Complete the function to return `true` if the two arguments given are anagrams of each other; return `false` otherwise. ## Examples * `"foefet"` is an anagram of `"toffee"` * `"Buckethe...
["def is_anagram(test, original):\n return sorted(original.lower()) == sorted(test.lower()) ", "def is_anagram(test, original):\n return sorted(test.lower()) == sorted(original.lower())", "from collections import Counter\n# write the function is_anagram\ndef is_anagram(test, original):\n return Counter(test.lo...
{"fn_name": "is_anagram", "inputs": [["foefet", "toffee"], ["Buckethead", "DeathCubeK"], ["Twoo", "WooT"], ["dumble", "bumble"], ["ound", "round"], ["apple", "pale"]], "outputs": [[true], [true], [true], [false], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
28,858
def is_anagram(test, original):
c36e058d4450cfebb80d4cc4993685ea
UNKNOWN
The Ackermann function is a famous function that played a big role in computability theory as the first example of a total computable function that is not primitive recursive. Since then the function has been a bit simplified but is still of good use. Due to its definition in terms of extremely deep recursion it can b...
["from numbers import Number\ndef Ackermann(m,n):\n if isinstance(n, Number) and isinstance(m, Number):\n if m >= 0 and n >= 0:\n return Ackermann_Aux(m,n)\n \n return None\n\n \ndef Ackermann_Aux(m,n):\n \n if m == 0:\n return n + 1\n \n if m > 0:\n if n == 0...
{"fn_name": "Ackermann", "inputs": [[1, 1], [4, 0], [3, 3]], "outputs": [[3], [13], [61]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,361
def Ackermann(m,n):
ced4bac88bab63857f79321bd79d8e5f
UNKNOWN
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are: 2332 110011 54322345 For this kata, single digit numbers will not be considered numerical palindromes. For a given number ```num```, write a function to test if t...
["def palindrome(num):\n if type(num) != int or num < 0: return \"Not valid\"\n s = str(num)\n for i in range(len(s)-2):\n if s[i] == s[i+1] or s[i] == s[i+2]: return True\n return len(s) != 1 and s[-1] == s[-2]", "def palindrome(num):\n return \"Not valid\" if type(num) != int or num < 0 else boo...
{"fn_name": "palindrome", "inputs": [[868], [1321], [1215], [2], [123322367], [1551], [13598], ["ACCDDCCA"], ["1551"], [-4505], [22.22]], "outputs": [[true], [false], [true], [false], [true], [true], [false], ["Not valid"], ["Not valid"], ["Not valid"], ["Not valid"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,224
def palindrome(num):
ccd52cbcdac4c3c38b23bb725d57b237
UNKNOWN
# Task If string has more than one neighboring dashes(e.g. --) replace they with one dash(-). Dashes are considered neighbors even if there is some whitespace **between** them. # Example For `str = "we-are- - - code----warriors.-"` The result should be `"we-are- code-warriors.-"` # Input/Output - `[inpu...
["import re\ndef replace_dashes_as_one(s):\n return re.sub(r'-[ -]+-|-+',r'-',s)", "import re\ndef replace_dashes_as_one(s):\n return re.sub(\"-[- ]*-\",\"-\",s)", "from re import sub\n\ndef replace_dashes_as_one(s):\n return sub(\"-[\\s-]*-\", '-', s)", "import re\n\ndef replace_dashes_as_one(s):\n return re...
{"fn_name": "replace_dashes_as_one", "inputs": [["we-are- - - code----warriors.-"], ["a---b- - -c"], ["a------"], ["Lorem - ipsum- - - dolor sit amet, consectetur adipiscing elit. Praesent tristique lectus non erat dapibus tincidunt. Integer non nibh fermentum, cursus-diam -------pharetra, mattis--risus.-------"]], "ou...
INTRODUCTORY
PYTHON3
CODEWARS
1,275
def replace_dashes_as_one(s):
40650144e19486e4d00e20f21626dbc0
UNKNOWN
## Task Complete the function that receives an array of strings (`arr`) as an argument and returns all the valid Roman numerals. Basic Roman numerals are denoted as: ``` I: 1, V: 5, X: 10, L: 50, C: 100, D: 500, M: 1000 ``` For the purposes of this kata we will consider valid only the numbers in range 0 - 5000 (bot...
["import re\n\nPATTERN = re.compile(\"^\"\n \"M{0,4}\" # thousands\n \"(CM|CD|D?C{,3})\" # hundreds\n \"(XC|XL|L?X{,3})\" # tens\n \"(IX|IV|V?I{,3})\" # units\n \"$\")\n\ndef valid_romans(arr):\n return [e for e in arr if e and PATTERN.match(e)]", "import re\n\n\ndef valid_romans(...
{"fn_name": "valid_romans", "inputs": [[["MMMCDLXVL", "MDLXXXVI", "DCLXII", "MMMMCLL", "MMDCCCLXXXIVCD"]], [["MMMMCCCXXXII", "MMDCCCXXVCD", "MMCCCXLV", "DCCLXVIIICD", "MMMMCXII"]], [["DCCLIVI", "MDCCXXXVVI", "MDLXXVI", "MDVIL", "MCCLXIII"]], [["DV", "", "CLVIII", "MDCCCXXCD", "MDCLXVI", "MMMDCCCLXXXVI"]], [["MMCDXVIII"...
INTRODUCTORY
PYTHON3
CODEWARS
2,346
def valid_romans(arr):
1164c36e76e4ef381b68286d5ca146c9
UNKNOWN
Given a certain number, how many multiples of three could you obtain with its digits? Suposse that you have the number 362. The numbers that can be generated from it are: ``` 362 ----> 3, 6, 2, 36, 63, 62, 26, 32, 23, 236, 263, 326, 362, 623, 632 ``` But only: ```3, 6, 36, 63``` are multiple of three. We need a fun...
["from itertools import permutations\n\ndef find_mult_3(num):\n num_list = tuple(map(int, str(num)))\n \n poss = set()\n for i in range(1, len(num_list)+1):\n poss |= set(permutations(num_list, i))\n \n res = set()\n for p in poss:\n if p[0] != 0 and sum(p) % 3 == 0:\n res....
{"fn_name": "find_mult_3", "inputs": [[362], [6063], [7766553322]], "outputs": [[[4, 63]], [[25, 6630]], [[55510, 766553322]]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,663
def find_mult_3(num):
fb95f9f4e5080d0f84fc70aee6f308d1
UNKNOWN
I need to save some money to buy a gift. I think I can do something like that: First week (W0) I save nothing on Sunday, 1 on Monday, 2 on Tuesday... 6 on Saturday, second week (W1) 2 on Monday... 7 on Saturday and so on according to the table below where the days are numbered from 0 to 6. Can you tell me how much I ...
["def finance(n):\n return n * (n + 1) * (n + 2) / 2", "def finance(n):\n savings = 0\n for weeks in range(n+1):\n for days in range(weeks,n+1):\n savings += weeks + days\n return savings", "finance = lambda n: n * (n + 1) * (n + 2) / 2\n", "def finance(n):\n # For each n, there are (n ...
{"fn_name": "finance", "inputs": [[5], [6], [8], [15], [100], [365], [730], [999], [2000], [4000], [5000]], "outputs": [[105], [168], [360], [2040], [515100], [24513765], [195308580], [499999500], [4006002000], [32024004000], [62537505000]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,010
def finance(n):
ae7420c4331e7267b7ee82f9ec6bdc66
UNKNOWN
Ronald's uncle left him 3 fertile chickens in his will. When life gives you chickens, you start a business selling chicken eggs which is exactly what Ronald decided to do. A chicken lays 300 eggs in its first year. However, each chicken's egg production decreases by 20% every following year (rounded down) until when ...
["def egged(year, span): \n total = 0\n eggs_per_chicken = 300\n for i in range(min(span,year)):\n total += 3 * eggs_per_chicken\n eggs_per_chicken = int(eggs_per_chicken * 0.8)\n \n return total or \"No chickens yet!\"", "def egged(year, span, chickens = 3):\n production = [300, 2...
{"fn_name": "egged", "inputs": [[0, 5], [2, 1], [4, 8], [74, 10], [1, 15]], "outputs": [["No chickens yet!"], [900], [2655], [3984], [900]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,740
def egged(year, span):
e79ebef3bd16869716a9120663e1b413
UNKNOWN
# Task Initially a number `1` is written on a board. It is possible to do the following operations with it: ``` multiply the number by 3; increase the number by 5.``` Your task is to determine that using this two operations step by step, is it possible to obtain number `n`? # Example For `n = 1`, the result should ...
["def number_increasing(n):\n return n not in {2, 4, 7, 12, 17, 22} and n % 5 != 0\n", "from math import log\n\n\ndef number_increasing(n):\n return any(log(x,3).is_integer() for x in range(n, 0, -5))", "def number_increasing(n):\n return False if n in (2, 4, 7, 12, 17, 22) or not n % 5 else True", "def number...
{"fn_name": "number_increasing", "inputs": [[1], [2], [3], [4], [5], [6], [100], [101], [12345], [54321]], "outputs": [[true], [false], [true], [false], [false], [true], [false], [true], [false], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,500
def number_increasing(n):
104e56afa00f2500de6e3a52c373702c
UNKNOWN
#Description Everybody has probably heard of the animal heads and legs problem from the earlier years at school. It goes: ```“A farm contains chickens and cows. There are x heads and y legs. How many chickens and cows are there?” ``` Where x <= 1000 and y <=1000 #Task Assuming there are no other types of animals, ...
["def animals(heads, legs):\n chickens, cows = 2*heads-legs/2, legs/2-heads\n if chickens < 0 or cows < 0 or not chickens == int(chickens) or not cows == int(cows):\n return \"No solutions\"\n return chickens, cows", "def animals(heads, legs):\n chickens = heads * 2 - legs / 2\n cows = heads - chi...
{"fn_name": "animals", "inputs": [[72, 200], [116, 282], [12, 24], [6, 24], [344, 872], [158, 616], [25, 555], [12, 25], [54, 956], [5455, 54956], [0, 0], [-1, -1], [500, 0], [0, 500], [-45, 5], [5, -55]], "outputs": [[[44, 28]], [[91, 25]], [[12, 0]], [[0, 6]], [[252, 92]], [[8, 150]], ["No solutions"], ["No solutions...
INTRODUCTORY
PYTHON3
CODEWARS
26,978
def animals(heads, legs):
c2e8fe7483cb340555116b202a45432c
UNKNOWN
Math hasn't always been your best subject, and these programming symbols always trip you up! I mean, does `**` mean *"Times, Times"* or *"To the power of"*? Luckily, you can create the function `expression_out()` to write out the expressions for you! The operators you'll need to use are: ```python { '+': 'Plus ',...
["op = {'+': 'Plus ','-': 'Minus ','*': 'Times ', '/': 'Divided By ', '**': 'To The Power Of ', '=': 'Equals ', '!=': 'Does Not Equal '}\nnum = {'1': 'One', '2': 'Two', '3': 'Three', '4': 'Four', '5': 'Five', '6': 'Six', '7':'Seven', '8': 'Eight', '9': 'Nine', '10': 'Ten'}\n \ndef expression_out(e):\n a, b, c = e...
{"fn_name": "expression_out", "inputs": [["1 + 3"], ["2 - 10"], ["6 ** 9"], ["5 = 5"], ["7 * 4"], ["2 / 2"], ["8 != 5"]], "outputs": [["One Plus Three"], ["Two Minus Ten"], ["Six To The Power Of Nine"], ["Five Equals Five"], ["Seven Times Four"], ["Two Divided By Two"], ["Eight Does Not Equal Five"]]}
INTRODUCTORY
PYTHON3
CODEWARS
424
def expression_out(exp):
c63ed0085028fe485d96b7cc82d5e342
UNKNOWN
##Task: You have to write a function `add` which takes two binary numbers as strings and returns their sum as a string. ##Note: * You are `not allowed to convert binary to decimal & vice versa`. * The sum should contain `No leading zeroes`. ##Examples: ``` add('111','10'); => '1001' add('1101','101'); => '10010' add(...
["def binary_string_to_int(string):\n return sum((d == '1') * 2**i for i, d in enumerate(string[::-1]))\n\ndef add(a, b):\n return '{:b}'.format(binary_string_to_int(a) + binary_string_to_int(b))", "from itertools import zip_longest\n\nADDER = {\n ('0', '0', '0'): ('0', '0'),\n ('0', '0', '1'): ('1', '0'),\...
{"fn_name": "add", "inputs": [["111", "10"], ["1101", "101"], ["1101", "10111"], ["10111", "001010101"], ["00", "0"]], "outputs": [["1001"], ["10010"], ["100100"], ["1101100"], ["0"]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,598
def add(a,b):
68e7c8410cb7eaac1dad1f72d9020d60
UNKNOWN
You are the judge at a competitive eating competition and you need to choose a winner! There are three foods at the competition and each type of food is worth a different amount of points. Points are as follows: - Chickenwings: 5 points - Hamburgers: 3 points - Hotdogs: 2 points Write a function that helps yo...
["def scoreboard(who_ate_what):\n scores = {'chickenwings': 5, 'hamburgers': 3, 'hotdogs': 2}\n return sorted((\n {'name': person.pop('name'),\n 'score': sum(scores.get(k, 0) * v for k, v in list(person.items()))}\n for person in who_ate_what), key=lambda a: (-a['score'], a['name']))\n", "PT...
{"fn_name": "scoreboard", "inputs": [[[{"name": "Billy The Beast", "chickenwings": 17, "hamburgers": 7, "hotdogs": 8}, {"name": "Habanero Hillary", "chickenwings": 5, "hamburgers": 17, "hotdogs": 11}, {"name": "Joey Jaws", "chickenwings": 8, "hamburgers": 8, "hotdogs": 15}, {"name": "Big Bob", "chickenwings": 20, "hamb...
INTRODUCTORY
PYTHON3
CODEWARS
3,700
def scoreboard(who_ate_what):
9fc49794c0b465def99525d5eff062dc
UNKNOWN
Our AAA company is in need of some software to help with logistics: you will be given the width and height of a map, a list of x coordinates and a list of y coordinates of the supply points, starting to count from the top left corner of the map as 0. Your goal is to return a two dimensional array/list with every item ...
["def logistic_map(width,height,xs,ys):\n return [ [ min([abs(x-x2)+abs(y-ys[i]) for (i,x2) in enumerate(xs)]) if len(xs) else None for x in range(width) ] for y in range(height) ]", "def logistic_map(w, h, xs, ys):\n md = lambda i, j: min((abs(x - i) + abs(y - j) for x, y in zip(xs, ys)), default=None)\n retu...
{"fn_name": "logistic_map", "inputs": [[3, 3, [0], [0]], [3, 3, [2], [2]], [1, 1, [0], [0]], [5, 2, [0, 4], [0, 0]], [2, 2, [], []]], "outputs": [[[[0, 1, 2], [1, 2, 3], [2, 3, 4]]], [[[4, 3, 2], [3, 2, 1], [2, 1, 0]]], [[[0]]], [[[0, 1, 2, 1, 0], [1, 2, 3, 2, 1]]], [[[null, null], [null, null]]]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,243
def logistic_map(width,height,xs,ys):
42bb279f5e209e0c697258f1c06f73d9
UNKNOWN
The goal of this Kata is to reduce the passed integer to a single digit (if not already) by converting the number to binary, taking the sum of the binary digits, and if that sum is not a single digit then repeat the process. - n will be an integer such that 0 < n < 10^20 - If the passed integer is already a single dig...
["def single_digit(n):\n while n > 9:\n n = bin(n).count(\"1\")\n return n", "def single_digit(n):\n while n > 9:\n n = int(bin(n).count('1'))\n return n", "def single_digit(n):\n return n if n<10 else single_digit(bin(n).count(\"1\"))", "def single_digit(n):\n if len(str(n)) == 1:\n ...
{"fn_name": "single_digit", "inputs": [[5], [999], [1234444123], [443566], [565656565], [9889345778311094737448], [4868872], [234234235], [567448], [10000000000]], "outputs": [[5], [8], [1], [2], [3], [2], [8], [2], [7], [3]]}
INTRODUCTORY
PYTHON3
CODEWARS
978
def single_digit(n):
1be7a423a4dcb476a21a64966bd2a494
UNKNOWN
Complete the function that takes a non-negative integer `n` as input, and returns a list of all the powers of 2 with the exponent ranging from 0 to `n` (inclusive). ## Examples ```python n = 0 ==> [1] # [2^0] n = 1 ==> [1, 2] # [2^0, 2^1] n = 2 ==> [1, 2, 4] # [2^0, 2^1, 2^2] ```
["def powers_of_two(n):\n return [2**x for x in range(n+1)]", "def powers_of_two(n):\n return [1<<x for x in range(n + 1)]", "def powers_of_two(n): return [ 2 ** i for i in range(n+1) ]", "def powers_of_two(n):\n a = []\n for i in range(0, n + 1):\n a.append(2 ** i) \n return a", "from itertool...
{"fn_name": "powers_of_two", "inputs": [[0], [1], [4]], "outputs": [[[1]], [[1, 2]], [[1, 2, 4, 8, 16]]]}
INTRODUCTORY
PYTHON3
CODEWARS
12,192
def powers_of_two(n):
a21b8d8815543e385c30bfa580c615a5
UNKNOWN
# Task Two players - `"black"` and `"white"` are playing a game. The game consists of several rounds. If a player wins in a round, he is to move again during the next round. If a player loses a round, it's the other player who moves on the next round. Given whose turn it was on the previous round and whether he won, de...
["def whoseMove(lastPlayer, win):\n return lastPlayer if win else 'white' if lastPlayer == 'black' else 'black'", "def whoseMove(lastPlayer, win):\n players = ['white', 'black']\n return lastPlayer if win else players[players.index(lastPlayer) - 1]", "def whoseMove(lastPlayer, win):\n return [\"white\", \"b...
{"fn_name": "whoseMove", "inputs": [["black", false], ["white", false], ["black", true], ["white", true]], "outputs": [["white"], ["black"], ["black"], ["white"]]}
INTRODUCTORY
PYTHON3
CODEWARS
16,798
def whoseMove(lastPlayer, win):
80ee8d866757b2ae112610af9d5d376d
UNKNOWN
Take an input string and return a string that is made up of the number of occurences of each english letter in the input followed by that letter, sorted alphabetically. The output string shouldn't contain chars missing from input (chars with 0 occurence); leave them out. An empty string, or one with no letters, should...
["from collections import Counter\n\ndef string_letter_count(s):\n cnt = Counter(c for c in s.lower() if c.isalpha())\n return ''.join(str(n)+c for c,n in sorted(cnt.items()))", "def string_letter_count(s):\n s = s.lower()\n m = ''\n for i in sorted(list(set(s))):\n if i.islower():\n m ...
{"fn_name": "string_letter_count", "inputs": [["The quick brown fox jumps over the lazy dog."], ["The time you enjoy wasting is not wasted time."], ["./4592#{}()"], ["This%Sentence\"is$$being^tested."], ["abccdefgdhijklmno_pqrsTuvwxYz"], [""], ["."], ["y"]], "outputs": [["1a1b1c1d3e1f1g2h1i1j1k1l1m1n4o1p1q2r1s2t2u1v1w1...
INTRODUCTORY
PYTHON3
CODEWARS
2,388
def string_letter_count(s):
207de0b785141c1243d1b9c2e842dacd
UNKNOWN
--- # Story The Pied Piper has been enlisted to play his magical tune and coax all the rats out of town. But some of the rats are deaf and are going the wrong way! # Kata Task How many deaf rats are there? # Legend * ```P``` = The Pied Piper * ```O~``` = Rat going left * ```~O``` = Rat going right # Example * ...
["def count_deaf_rats(town):\n return town.replace(' ', '')[::2].count('O')", "import re\ndef count_deaf_rats(town):\n return re.findall(r\"O~|~O\",town.split(\"P\")[0]).count(\"O~\") + re.findall(r\"O~|~O\",town.split(\"P\")[1]).count(\"~O\")", "import re\n\ndef count_deaf_rats(town):\n town = re.sub(\"(~O|O~...
{"fn_name": "count_deaf_rats", "inputs": [["~O~O~O~O P"], ["P O~ O~ ~O O~"], ["~O~O~O~OP~O~OO~"], ["O~~OO~~OO~~OO~P~OO~~OO~~OO~~O"], ["~OP"], ["PO~"], ["O~P"], ["P~O"], [" P"], ["P "], [" P "], ["P"]], "outputs": [[0], [1], [2], [8], [0], [0], [1], [1], [0], [0], [0], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,843
def count_deaf_rats(town):
2d5cf320e55385410e9e3116a4d2b9ee
UNKNOWN
Your job is to build a function which determines whether or not there are double characters in a string (including whitespace characters). For example ```aa```, ``!!`` or ``` ```. You want the function to return true if the string contains double characters and false if not. The test should not be case sensitive; ...
["import re\n\ndef double_check(str):\n return bool(re.search(r\"(.)\\1\", str.lower()))", "def double_check(str):\n str = str.lower()\n c1 = ''\n for c in str:\n if c == c1:\n return True\n c1 = c\n return False", "from itertools import groupby\n\n\ndef double_check(s):\n return any(...
{"fn_name": "double_check", "inputs": [["abca"], ["aabc"], ["a 11 c d"], ["AabBcC"], ["a b c"], ["a b c d e f g h i h k"], ["2020"], ["a!@\u20ac\u00a3#$%^&*()_-+=}]{[|':;?/>.<,~"]], "outputs": [[false], [true], [true], [true], [true], [false], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,465
def double_check(strng):
8780d8d0d32a89c2e0e9a825def41b92
UNKNOWN
Make the 2D list by the sequential integers started by the ```head``` number. See the example test cases for the expected output. ``` Note: -10**20 < the head number <10**20 1 <= the number of rows <= 1000 0 <= the number of columms <= 1000 ```
["def make_2d_list(head,row,col):\n return [[head + c + r*col for c in range(col)] for r in range(row)]", "import numpy as np\n\ndef make_2d_list(head,row,col):\n return np.array(list(range(head, head + row*col))).reshape(row, col).tolist()\n", "make_2d_list=lambda Q,R,C:[[Q + C * r + c for c in range(C)] for r i...
{"fn_name": "make_2d_list", "inputs": [[1, 2, 3], [2, 3, 4], [5, 6, 1], [7, 1, 1], [0, 1, 0], [-20, 2, 2], [10000000000, 2, 2]], "outputs": [[[[1, 2, 3], [4, 5, 6]]], [[[2, 3, 4, 5], [6, 7, 8, 9], [10, 11, 12, 13]]], [[[5], [6], [7], [8], [9], [10]]], [[[7]]], [[[]]], [[[-20, -19], [-18, -17]]], [[[10000000000, 1000000...
INTRODUCTORY
PYTHON3
CODEWARS
1,426
def make_2d_list(head,row,col):
e07ff439066e42c93ba9b679d992b346
UNKNOWN
In this task you have to code process planner. You will be given initial thing, target thing and a set of processes to turn one thing into another (in the form of _[process\_name, start\_thing, end\_thing]_). You must return names of shortest sequence of processes to turn initial thing into target thing, or empty seq...
["def processes(start, end, processes):\n '''Dijkstra's shortest path algorithm'''\n q = [(start,[])]\n visited = set()\n \n while q:\n s, path = q.pop(0)\n if s == end: return path\n visited.add(s)\n for p in [x for x in processes if x[1] == s]:\n if not p[2] in visited:\n ...
{"fn_name": "processes", "inputs": [["a", "c", [["1", "a", "c"], ["2", "a", "b"], ["3", "b", "c"]]], ["a", "d", [["1", "a", "b"], ["2", "b", "c"], ["3", "c", "b"]]], ["a", "d", [["1", "a", "b"], ["2", "b", "c"], ["3", "c", "b"], ["4", "c", "d"]]]], "outputs": [[["1"]], [[]], [["1", "2", "4"]]]}
INTRODUCTORY
PYTHON3
CODEWARS
5,247
def processes(start, end, processes):
663900077183cc0f0734a969b030cd84
UNKNOWN
You're hanging out with your friends in a bar, when suddenly one of them is so drunk, that he can't speak, and when he wants to say something, he writes it down on a paper. However, none of the words he writes make sense to you. He wants to help you, so he points at a beer and writes "yvvi". You start to understand wha...
["def parse_character(char):\n if 65 <= ord(char) <= 90:\n return chr(155 - ord(char))\n elif 97 <= ord(char) <= 122:\n return chr(219 - ord(char))\n else:\n return char\n\ndef decode(string_):\n if not isinstance(string_, str):\n return \"Input is not a string\"\n return \"\"...
{"fn_name": "decode", "inputs": [["yvvi"], ["Blf zoivzwb szw 10 yvvih"], ["Ovg'h hdrn rm gsv ulfmgzrm!"], [{"brand": "Starobrno"}], ["Tl slnv, blf'iv wifmp"], ["Hfiv r xzm wzmxv lm xlk'h xzi, slow nb yvvi"], [true], ["Hvv? R'n mlg gszg wifmp, r xzm hgroo gzpv nb xolgsvh luu"], [123], [["Beer"]]], "outputs": [["beer"], ...
INTRODUCTORY
PYTHON3
CODEWARS
4,576
def decode(string_):
0677f24c12a0f8f3f9af5ab85134df6d
UNKNOWN
Simply find the closest value to zero from the list. Notice that there are negatives in the list. List is always not empty and contains only integers. Return ```None``` if it is not possible to define only one of such values. And of course, we are expecting 0 as closest value to zero. Examples: ```code [2, 4, -1, -3]...
["def closest(lst):\n m = min(lst, key=abs)\n return m if m == 0 or -m not in lst else None", "def closest(lst):\n result = min(lst, key=abs)\n return result if not result or -result not in lst else None\n", "def closest(lst):\n m = min(lst, key=lambda x: abs(x))\n if not m or -m not in lst: return m"...
{"fn_name": "closest", "inputs": [[[10, 3, 9, 1]], [[2, 4, -1, -3]], [[5, 2, -2]], [[5, 2, 2]], [[13, 0, -6]], [[1]], [[5, 1, -1, 2, -10]], [[5, -5, -2, 5, -3]], [[27, 37, 48, -18, 42, 16, 5, 34, 35, 26, -34, 3, -43, 35, 0, -45, -7, 45, 34, -18, 44, 12, 6, -45, 33, 27, -2, 28, 12, 9]], [[11, -30, -18, 4, -13, 43, 12, -...
INTRODUCTORY
PYTHON3
CODEWARS
1,347
def closest(lst):
df690d92c38dd701130a4482eda0cd12
UNKNOWN
## Objective Given a number `n` we will define it's sXORe to be `0 XOR 1 XOR 2 ... XOR n` where `XOR` is the [bitwise XOR operator](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). Write a function that takes `n` and returns it's sXORe. ## Examples | n | sXORe n |---------|-------- | 0 | 0 ...
["def sxore(n):\n return [n, 1, n + 1, 0][n % 4]", "def sxore(n):\n return (n,1,n+1,0)[n%4]", "def sxore(n):\n res = {0: n, 1: 1, 2: n + 1, 3: 0}\n return res[n % 4]", "sxore=lambda n:{n%4==0:n,n%4==1:1,n%4==2:n+1}.get(True,0)", "sxore=lambda n:(n,1,n+1,0)[n%4]", "def sxore(n):\n return (n >> 1) & 1 ^ ( ...
{"fn_name": "sxore", "inputs": [[0], [1], [2], [50], [1000000], [1000001], [9999999999999999999999999]], "outputs": [[0], [1], [3], [51], [1000000], [1], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
748
def sxore(n):
8999d4b236145894cfe3021675f38ac0
UNKNOWN
You have been speeding on a motorway and a police car had to stop you. The policeman is a funny guy that likes to play games. Before issuing penalty charge notice he gives you a choice to change your penalty. Your penalty charge is a combination of numbers like: speed of your car, speed limit in the area, speed of th...
["def penalty(lst):\n lst, maxLen = list(map(str, lst)), max(map(len, lst))\n return ''.join(sorted(lst, key=lambda s: s.ljust(maxLen, s[-1])))", "#return str of the smallest value of the combined numbers in a_list\ndef penalty(a_list):\n return ''.join(sorted(a_list, key = lambda n: n + n[:1]))", "penalty=lambd...
{"fn_name": "penalty", "inputs": [[["45", "30", "50", "1"]], [["100", "10", "1"]], [["32", "3"]], [["70", "46", "4", "19"]], [["71", "82", "42", "34", "90"]], [["31", "97", "6", "78"]], [["72", "7", "7", "78", "79", "709", "94"]]], "outputs": [["1304550"], ["100101"], ["323"], ["1944670"], ["3442718290"], ["3167897"], ...
INTRODUCTORY
PYTHON3
CODEWARS
2,153
def penalty(a_list):
a622285082e3585b951d04c38bfb11e7
UNKNOWN
# Task Smartphones software security has become a growing concern related to mobile telephony. It is particularly important as it relates to the security of available personal information. For this reason, Ahmed decided to encrypt phone numbers of contacts in such a way that nobody can decrypt them. At first he tri...
["def decrypt(s):\n return next((str(b // 11) for b in (int(str(a) + s) for a in range(1, 11)) if b % 11 == 0), 'impossible')", "def decrypt(s):\n for i in range(1,11):\n n = int(str(i)+s)\n if n//11*11==n : return str(n//11)\n return 'impossible'", "def decrypt(s):\n x, l = int(s), 10**len(s)\n ...
{"fn_name": "decrypt", "inputs": [["353"], ["444"], ["123456"], ["147"], ["4334"]], "outputs": [["123"], ["404"], ["738496"], ["377"], ["impossible"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,831
def decrypt(s):
23e073aaaf86e340c1850da1cc49f124
UNKNOWN
There are two lists of different length. The first one consists of keys, the second one consists of values. Write a function ```createDict(keys, values)``` that returns a dictionary created from keys and values. If there are not enough values, the rest of keys should have a ```None``` value. If there not enough keys, j...
["def createDict(keys, values):\n while len(keys) > len(values):\n values.append(None)\n \n dictionary = dict(list(zip(keys, values))) \n return dictionary\n", "def createDict(keys, values):\n return dict(zip(keys, values + [None]*(len(keys) - len(values))))", "def createDict(keys, values):\n r...
{"fn_name": "createDict", "inputs": [[[], []], [[], [1]], [["a"], []], [["a", "b", "c"], [1, 2, 3]], [["a", "b", "c", "d", "e"], [1, 2]], [["a", "b"], [1, 2, 3, 4]]], "outputs": [[{}], [{}], [{"a": null}], [{"a": 1, "b": 2, "c": 3}], [{"a": 1, "b": 2, "c": null, "d": null, "e": null}], [{"a": 1, "b": 2}]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,284
def createDict(keys, values):
6dc4e6d2abe81b3ed18060a162b406a1
UNKNOWN
Fans of The Wire will appreciate this one. For those that haven't seen the show, the Barksdale Organization has a simple method for encoding telephone numbers exchanged via pagers: "Jump to the other side of the 5 on the keypad, and swap 5's and 0's." Here's a keypad for visualization. ``` ┌───┬───┬───┐ │ 1 │ 2 │ 3 │...
["def decode(s):\n return s.translate(str.maketrans(\"1234567890\", \"9876043215\"))", "def decode(string):\n return \"\".join([\"5987604321\"[int(char)] for char in string])", "def decode(string):\n return string.translate(str.maketrans(\"1234567890\",\"9876043215\"))", "def decode(string):\n key = {\n ...
{"fn_name": "decode", "inputs": [["4103432323"], ["4103438970"], ["4104305768"], ["4102204351"], ["4107056043"]], "outputs": [["6957678787"], ["6957672135"], ["6956750342"], ["6958856709"], ["6953504567"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,660
def decode(string):
520e3f37e9d6a29c759e191f21262023
UNKNOWN
You have to create a function that converts integer given as string into ASCII uppercase letters. All ASCII characters have their numerical order in table. For example, ``` from ASCII table, character of number 65 is "A". ``` Numbers will be next to each other, So you have to split given number to two digit long i...
["def convert(number):\n return ''.join(chr(int(number[a:a + 2])) for a in range(0, len(number), 2))\n", "def convert(number):\n return \"\".join(chr(int(number[i:i + 2])) for i in range(0, len(number), 2))\n pass", "def convert(number):\n return \"\".join([chr(int(x)) for x in map(''.join, zip(*[iter(num...
{"fn_name": "convert", "inputs": [["65"], ["656667"], ["676584"], ["73327673756932858080698267658369"], ["32327332327679866932328380656769833232"], ["84726982693273833278793270857832737832657889327984726982326765836983"]], "outputs": [["A"], ["ABC"], ["CAT"], ["I LIKE UPPERCASE"], [" I LOVE SPACES "], ["THERE IS NO...
INTRODUCTORY
PYTHON3
CODEWARS
986
def convert(number):
db0607b7c9219ba8455801b561504910
UNKNOWN
# Task Pac-Man got lucky today! Due to minor performance issue all his enemies have frozen. Too bad Pac-Man is not brave enough to face them right now, so he doesn't want any enemy to see him. Given a gamefield of size `N` x `N`, Pac-Man's position(`PM`) and his enemies' positions(`enemies`), your task is to count...
["def pac_man(size, pacman, enemies):\n px, py = pacman\n mx, my, Mx, My = -1, -1, size, size\n for x, y in enemies:\n if x < px and x > mx: mx = x\n if y < py and y > my: my = y\n if x > px and x < Mx: Mx = x\n if y > py and y < My: My = y\n return (Mx - mx - 1) * (My - my - 1) ...
{"fn_name": "pac_man", "inputs": [[1, [0, 0], []], [2, [0, 0], []], [3, [0, 0], []], [3, [1, 1], []], [2, [0, 0], [[1, 1]]], [3, [2, 0], [[1, 1]]], [3, [2, 0], [[0, 2]]], [10, [4, 6], [[0, 2], [5, 2], [5, 5]]], [8, [1, 1], [[5, 4]]], [8, [1, 5], [[5, 4]]], [8, [6, 1], [[5, 4]]]], "outputs": [[0], [3], [8], [8], [0], [0...
INTRODUCTORY
PYTHON3
CODEWARS
7,098
def pac_man(N, PM, enemies):
60ad80cd1f990a8a5f9af0cfc75460ef
UNKNOWN
# YOUR MISSION An [octahedron](https://en.wikipedia.org/wiki/Octahedron) is an 8-sided polyhedron whose faces are triangles. Create a method that outputs a 3-dimensional array of an octahedron in which the height, width, and depth are equal to the provided integer `size`, which is equal to the length from one vertex...
["def create_octahedron(size):\n if size <= 1 or size % 2 == 0:\n return []\n m = size // 2\n return [[[int(abs(x - m) + abs(y - m) + abs(z - m) <= m)\n for z in range(size)]\n for y in range(size)]\n for x in range(size)]", "def face(size, m, n):\n return [\n [abs(r-m) + ...
{"fn_name": "create_octahedron", "inputs": [[7], [0], [-7]], "outputs": [[[[[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]], [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1,...
INTRODUCTORY
PYTHON3
CODEWARS
2,861
def create_octahedron(size):
fe644cc009e761614c4ac399484e0dc3
UNKNOWN
--- # Hint This Kata is an extension of the earlier ones in this series. Completing those first will make this task easier. # Background My TV remote control has arrow buttons and an `OK` button. I can use these to move a "cursor" on a logical screen keyboard to type words... # Keyboard The screen "keyboard" la...
["H, W = 6, 8\nKEYBOARD = [ \"abcde123fghij456klmno789pqrst.@0uvwxyz_/\\u000e \",\n \"ABCDE123FGHIJ456KLMNO789PQRST.@0UVWXYZ_/\\u000e \",\n \"^~?!'\\\"()-:;+&%*=<>\u20ac\u00a3$\u00a5\u00a4\\\\[]{},.@\u00a7#\u00bf\u00a1\\u000e\\u000e\\u000e_/\\u000e \"]\nMAP = [ {c: (i//W, i%W) for i,c i...
{"fn_name": "tv_remote", "inputs": [["Too Easy?"], ["does"], ["your"], ["solution"], ["work"], ["for"], ["these"], ["words"], ["DOES"], ["YOUR"], ["SOLUTION"], ["WORK"], ["FOR"], ["THESE"], ["WORDS"], ["^does^"], ["$your$"], ["#solution#"], ["\u00bfwork\u00bf"], ["{for}"], ["\u00a3these\u00a3"], ["?symbols?"], ["a"], [...
INTRODUCTORY
PYTHON3
CODEWARS
16,951
def tv_remote(words):
e3c35711b51d0f834419fc74ae78c2d6
UNKNOWN
Mary wrote a recipe book and is about to publish it, but because of a new European law, she needs to update and include all measures in grams. Given all the measures in tablespoon (`tbsp`) and in teaspoon (`tsp`), considering `1 tbsp = 15g` and `1 tsp = 5g`, append to the end of the measurement the biggest equivalent ...
["import re, math\n\ndef convert_recipe(recipe):\n \n def repl(m):\n ratio = 15 if m.group(2) == \"tbsp\" else 5\n return m.group(0) + \" (%sg)\" % math.ceil(eval(m.group(1)) * ratio)\n \n return re.sub(\"([0-9/]+) (tb?sp)\", repl, recipe)", "import re\nimport math\ndef convert_recipe(recipe):...
{"fn_name": "convert_recipe", "inputs": [["2 tbsp of butter"], ["Add to the mixing bowl and coat well with 1 tbsp of olive oil & 1/2 tbsp of dried dill"], ["1/2 tsp of baking powder"], ["In another bowl, add 2 tsp of vanilla extract, 3 tsp of baking soda and 1/2 tsp of salt"], ["10 tbsp of cocoa powder"], ["1/8 tbsp of...
INTRODUCTORY
PYTHON3
CODEWARS
3,555
def convert_recipe(recipe):
f190d041ff7b4261960416ab4b3bfb40
UNKNOWN
## Your story You've always loved both Fizz Buzz katas and cuckoo clocks, and when you walked by a garage sale and saw an ornate cuckoo clock with a missing pendulum, and a "Beyond-Ultimate Raspberry Pi Starter Kit" filled with all sorts of sensors and motors and other components, it's like you were suddenly hit by a b...
["def fizz_buzz_cuckoo_clock(t):\n h, m = list(map(int, t.split(':')))\n h = h-12 if h > 12 else h+12 if h == 0 else h\n \n if m == 0:\n return ' '.join('Cuckoo' for i in range(h))\n if m == 30:\n return 'Cuckoo'\n if m%3 == 0 and m%5 == 0:\n return 'Fizz Buzz'\n if m%3 == 0:\n...
{"fn_name": "fizz_buzz_cuckoo_clock", "inputs": [["13:34"], ["21:00"], ["11:15"], ["03:03"], ["14:30"], ["08:55"], ["00:00"], ["12:00"]], "outputs": [["tick"], ["Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo"], ["Fizz Buzz"], ["Fizz"], ["Cuckoo"], ["Buzz"], ["Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo Cuckoo C...
INTRODUCTORY
PYTHON3
CODEWARS
4,023
def fizz_buzz_cuckoo_clock(time):
c2f27dd3e3a482c8c0497abe5e6be990
UNKNOWN
Complete the function `power_of_two`/`powerOfTwo` (or equivalent, depending on your language) that determines if a given non-negative integer is a [power of two](https://en.wikipedia.org/wiki/Power_of_two). From the corresponding Wikipedia entry: > *a power of two is a number of the form 2^(n) where **n** is an integ...
["def power_of_two(x):\n return x != 0 and ((x & (x - 1)) == 0)", "def power_of_two(num):\n return bin(num).count('1') == 1\n", "def power_of_two(x):\n return x and (not(x&(x-1)))", "def power_of_two(x):\n # your code here\n return x > 0 and (x & (x-1)) == 0", "def power_of_two(x):\n # your code here\n ret...
{"fn_name": "power_of_two", "inputs": [[0], [1], [536870912]], "outputs": [[false], [true], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
13,390
def power_of_two(x):
17351885390e9df2c715ddd3f31b51d9
UNKNOWN
Write a function that accepts two arguments: an array/list of integers and another integer (`n`). Determine the number of times where two integers in the array have a difference of `n`. For example: ``` [1, 1, 5, 6, 9, 16, 27], n=4 --> 3 # (1,5), (1,5), (5,9) [1, 1, 3, 3], n=2 --> 4 # (1,3), (1,3), ...
["def int_diff(arr, n):\n num=0\n for i in range(len(arr)):\n for j in range(i+1,len(arr)):\n if abs(arr[i]-arr[j])==n:\n num+=1\n return num", "int_diff=lambda l,n:sum(n==abs(a-b)for i,a in enumerate(l)for b in l[:i])", "import itertools\n\ndef int_diff(arr, n):\n return su...
{"fn_name": "int_diff", "inputs": [[[1, 1, 5, 6, 9, 16, 27], 4], [[1, 1, 3, 3], 2], [[4, 8, 12, 12, 3, 6, 2], 6], [[1, 2, 3, 4, 5, 6, 7], 7], [[1, 6, 2, 3, 7, 8, 7], 0], [[1, 2, 3, 4], 0], [[1, 1, 1, 1], 0], [[], 3]], "outputs": [[3], [4], [3], [0], [1], [0], [6], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,671
def int_diff(arr, n):
af87d95b9eb678ecad032109f805266c
UNKNOWN
Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements. For example: ```python unique_in_order('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B'] unique_in_order('...
["def unique_in_order(iterable):\n result = []\n prev = None\n for char in iterable[0:]:\n if char != prev:\n result.append(char)\n prev = char\n return result", "from itertools import groupby\n\ndef unique_in_order(iterable):\n return [k for (k, _) in groupby(iterable)]", "d...
{"fn_name": "unique_in_order", "inputs": [[""], ["A"], ["AA"], ["AAAABBBCCDAABBB"], ["AADD"], ["AAD"], ["ADD"], ["ABBCcAD"], [[1, 2, 3, 3]], [["a", "b", "b"]]], "outputs": [[[]], [["A"]], [["A"]], [["A", "B", "C", "D", "A", "B"]], [["A", "D"]], [["A", "D"]], [["A", "D"]], [["A", "B", "C", "c", "A", "D"]], [[1, 2, 3]], ...
INTRODUCTORY
PYTHON3
CODEWARS
1,422
def unique_in_order(iterable):
346e11b41d039dc5e4acff2bd6071a29
UNKNOWN
It's a Pokemon battle! Your task is to calculate the damage that a particular move would do using the following formula (not the actual one from the game): Where: * attack = your attack power * defense = the opponent's defense * effectiveness = the effectiveness of the attack based on the matchup (see explanation bel...
["import math\n\neffectiveness = {\n \"electric\":{\n \"electric\": 0.5,\n \"fire\": 1,\n \"grass\": 1,\n \"water\": 2\n },\n \"fire\":{\n \"electric\": 1,\n \"fire\": 0.5,\n \"grass\": 2,\n \"water\": 0.5\n },\n \"grass\":{\n \"electric\": 1,\n \"fir...
{"fn_name": "calculate_damage", "inputs": [["fire", "water", 100, 100], ["grass", "water", 100, 100], ["electric", "fire", 100, 100], ["grass", "electric", 57, 19], ["grass", "water", 40, 40], ["grass", "fire", 35, 5], ["fire", "electric", 10, 2]], "outputs": [[25], [100], [50], [150], [100], [175], [250]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,556
def calculate_damage(your_type, opponent_type, attack, defense):