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
d6e57c16bed95ade1c1b5c3b95fb5264
UNKNOWN
You should write a simple function that takes string as input and checks if it is a valid Russian postal code, returning `true` or `false`. A valid postcode should be 6 digits with no white spaces, letters or other symbols. Empty string should also return false. Please also keep in mind that a valid post code **cann...
["def zipvalidate(postcode):\n return len(postcode) == 6 and postcode.isdigit() and postcode[0] not in \"05789\"", "import re\n\ndef zipvalidate(postcode):\n return bool(re.fullmatch(r\"[12346]\\d{5}\", postcode))", "def zipvalidate(p):\n return p.isdigit() and 100000 < int(p) < 699999 and p[0] != \"5\"\n \...
{"fn_name": "zipvalidate", "inputs": [["142784"], ["642784"], ["111"], ["1111111"], ["AA5590"], [""], ["\n245980"], ["245980\n"], ["245980a"], ["24598a"], [" 310587 "], ["555555"], ["775255"], ["875555"], ["012345"], ["968345"], ["@68345"]], "outputs": [[true], [true], [false], [false], [false], [false], [false], [fals...
INTRODUCTORY
PYTHON3
CODEWARS
2,254
def zipvalidate(postcode):
94e66b43300e33be5fa38d68814dba59
UNKNOWN
Take a string and return a hash with all the ascii values of the characters in the string. Returns nil if the string is empty. The key is the character, and the value is the ascii value of the character. Repeated characters are to be ignored and non-alphebetic characters as well.
["def char_to_ascii(string):\n return {c: ord(c) for c in set(string) if c.isalpha()} if len(string) else None", "def char_to_ascii(s):\n if s: return {c: ord(c) for c in set(s) if c.isalpha()}\n", "def char_to_ascii(s):\n if s: return {c: ord(c) for c in set(s) if c.isalpha()}", "char_to_ascii = lambda s: {e:...
{"fn_name": "char_to_ascii", "inputs": [[""], ["a"], ["aaa"], ["hello world"], ["ABaa ^"]], "outputs": [[null], [{"a": 97}], [{"a": 97}], [{"h": 104, "e": 101, "l": 108, "o": 111, "w": 119, "r": 114, "d": 100}], [{"A": 65, "B": 66, "a": 97}]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,083
def char_to_ascii(string):
512d2d959fd36eccf9f45d241cd987ac
UNKNOWN
> If you've finished this kata, you can try the [more difficult version](https://www.codewars.com/kata/5b256145a454c8a6990000b5). ## Taking a walk A promenade is a way of uniquely representing a fraction by a succession of “left or right” choices. For example, the promenade `"LRLL"` represents the fraction `4/7`. ...
["def promenade(choices):\n \n def compute(): return l+r,m+s\n \n l,m, r,s = 1,0, 0,1\n for c in choices:\n if c=='L': l,m = compute()\n else: r,s = compute()\n \n return compute()", "def promenade(choices):\n l, m = (1, 0)\n r, s = (0, 1)\n for choice in choices:\n ...
{"fn_name": "promenade", "inputs": [[""], ["L"], ["R"], ["LRLL"], ["LLRLR"], ["RRRLRRR"], ["LLLLRLLLL"], ["LLLLLLLLLL"], ["RLRLRLRRLRLL"], ["LLRRLRRLRLLL"], ["LRRLLRLLRLRR"], ["LRRLRLLLLRLL"], ["LLLRRRLLLRLL"], ["RRLRRRLLRLRR"], ["RRRRLLRLLRLR"], ["LLRLRLLRLLRL"], ["LRLLRRRRLLRR"], ["RLRRLRRRRRRR"]], "outputs": [[[1, 1...
INTRODUCTORY
PYTHON3
CODEWARS
3,114
def promenade(choices):
f8ffd31df121c01f20f49cf7206c7fa3
UNKNOWN
*This is my first Kata in the Ciphers series. This series is meant to test our coding knowledge.* ## Ciphers #1 - The 01 Cipher This cipher doesn't exist, I just created it by myself. It can't actually be used, as there isn't a way to decode it. It's a hash. Multiple sentences may also have the same result. ## How th...
["def encode(s):\n return ''.join( str(1 - ord(c)%2) if c.isalpha() else c for c in s )", "encode = lambda s: \"\".join((x, str(~ord(x)%2))[x.isalpha()] for x in s)", "import re\n\ndef encode(s):\n return re.sub(r\"[a-zA-Z]\", lambda m: str((ord(m.group())+1)%2), s)", "def encode(s):\n return \"\".join(['1', '...
{"fn_name": "encode", "inputs": [["Hello World!"]], "outputs": [["10110 00111!"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,385
def encode(s):
5a2feb5146291dd9b0b3607969be2a5e
UNKNOWN
This kata is the second part of a series: [Neighbourhood kata collection](https://www.codewars.com/collections/5b2f4db591c746349d0000ce). If this one is to easy you can try out the harder Katas.;) ___ The neighbourhood of a cell (in a matrix) are cells that are near to it. There are two popular types: - The [Moore nei...
["def get_neighbourhood(typ, arr, coordinates):\n \n def isInside(x,y): return 0 <= x < len(arr) and 0 <= y < len(arr[0])\n \n x,y = coordinates\n if not isInside(x,y): return []\n \n neigh = ( [(dx, dy) for dx in range(-1,2) for dy in range(-1,2) if (dx,dy) != (0,0)]\n if typ == '...
{"fn_name": "get_neighbourhood", "inputs": [["moore", [[]], [0, 0]], ["von_neumann", [[]], [0, 0]], ["moore", [[], [], []], [0, 0]], ["von_neumann", [[], [], []], [0, 0]]], "outputs": [[[]], [[]], [[]], [[]]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,456
def get_neighbourhood(n_type, mat, coordinates):
8e4cfe5202b45486587484ffd3a3a4f9
UNKNOWN
Your website is divided vertically in sections, and each can be of different size (height). You need to establish the section index (starting at `0`) you are at, given the `scrollY` and `sizes` of all sections. Sections start with `0`, so if first section is `200` high, it takes `0-199` "pixels" and second starts a...
["def get_section_id(scroll, sizes):\n c = 0\n for idx, s in enumerate(sizes):\n c += s\n if scroll < c: return idx\n return -1", "from itertools import accumulate\n\n# Once again, thanks itertools\ndef get_section_id(scroll, sizes):\n return next((i for i,x in enumerate(accumulate(sizes)) if ...
{"fn_name": "get_section_id", "inputs": [[1, [300, 200, 400, 600, 100]], [299, [300, 200, 400, 600, 100]], [300, [300, 200, 400, 600, 100]], [1599, [300, 200, 400, 600, 100]], [1600, [300, 200, 400, 600, 100]]], "outputs": [[0], [0], [1], [4], [-1]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,688
def get_section_id(scroll, sizes):
fc05f0d3143834342fc8a59a4f2fbea1
UNKNOWN
Write a function that accepts a string, and returns true if it is in the form of a phone number. Assume that any integer from 0-9 in any of the spots will produce a valid phone number. Only worry about the following format: (123) 456-7890 (don't forget the space after the close parentheses) Examples: ``` validPho...
["def validPhoneNumber(phoneNumber):\n import re\n return bool(re.match(r\"^(\\([0-9]+\\))? [0-9]+-[0-9]+$\", phoneNumber))", "# This is actually quite a bit more complicated in real life\n# I'd use https://github.com/googlei18n/libphonenumber\nimport re\n\nprog = re.compile('^\\(\\d{3}\\) \\d{3}-\\d{4}$')\n\ndef...
{"fn_name": "validPhoneNumber", "inputs": [["(123) 456-7890"], ["(1111)555 2345"], ["(098) 123 4567"], ["(123)456-7890"], ["abc(123)456-7890"], ["(123)456-7890abc"], ["abc(123)456-7890abc"], ["abc(123) 456-7890"], ["(123) 456-7890abc"], ["abc(123) 456-7890abc"]], "outputs": [[true], [false], [false], [false], [false], ...
INTRODUCTORY
PYTHON3
CODEWARS
2,262
def validPhoneNumber(phoneNumber):
3f0ad9bee1be558d0e67b69fac97e416
UNKNOWN
Here your task is to Create a (nice) Christmas Tree. You don't have to check errors or incorrect input values, every thing is ok without bad tricks, only one int parameter as input and a string to return;-)... So what to do?First three easy examples: ```` Input: 3 and Output: * *** ***** ### Input 9 and Output:...
["def christmas_tree(h):\n return \"\" if h<3 else \"\\r\\n\".join([\"\\r\\n\".join([\" \"*(((5-y)//2)+(h//3)-i-1)+\"*\"*(y+i*2) for y in [1,3,5]]) for i in range(h//3)])+\"\\r\\n\"+\" \"*(h//3)+\"###\"", "def christmas_tree(height):\n height, tree = height // 3, []\n for floor in range(height):\n for bra...
{"fn_name": "christmas_tree", "inputs": [[5], [10], [8], [2]], "outputs": [[" *\r\n ***\r\n*****\r\n ###"], [" *\r\n ***\r\n *****\r\n ***\r\n *****\r\n *******\r\n *****\r\n *******\r\n*********\r\n ###"], [" *\r\n ***\r\n *****\r\n ***\r\n *****\r\n*******\r\n ###"], [""]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,905
def christmas_tree(height):
19e71731c9c9c5d3ae60181f82637952
UNKNOWN
Given a number `n` we will define its scORe to be `0 | 1 | 2 | 3 | ... | n`, where `|` is the [bitwise OR operator](https://en.wikipedia.org/wiki/Bitwise_operation#OR). Write a function that takes `n` and finds its scORe. --------------------- | n | scORe n | |---------|-------- | | 0 | 0 | | 1 ...
["score=lambda n:2**n.bit_length()-1", "score=lambda n:(1<<n.bit_length())-1", "def score(n):\n # Good Luck!\n return 2**n.bit_length()-1", "def score(n):\n res = n\n while n:\n res, n = res | n, n >> 1\n return res", "def score(n):\n return 0 if n == 0 else n | int(n.bit_length() * '1', 2)", "...
{"fn_name": "score", "inputs": [[0], [1], [49], [1000000], [10000000], [1000000000000000000]], "outputs": [[0], [1], [63], [1048575], [16777215], [1152921504606846975]]}
INTRODUCTORY
PYTHON3
CODEWARS
744
def score(n):
8efdb5d8d8cf4e01e53f92ce495e2810
UNKNOWN
In this kata you will have to change every letter in a given string to the next letter in the alphabet. You will write a function `nextLetter` to do this. The function will take a single parameter `s` (string). Examples: ``` "Hello" --> "Ifmmp" "What is your name?" --> "Xibu jt zpvs obnf?" "zoo" --> "app" "zzZAaa"...
["def next_letter(string):\n return \"\".join(chr(ord(c)+(-25 if c in 'zZ' else 1)) if c.isalpha() else c for c in string)", "def next_letter(s):\n return s.translate(str.maketrans('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', \n 'bcdefghijklmnopqrstuvwxyzaBCDEFGHIJKLMNOPQRSTUVWXYZA'))", "from string...
{"fn_name": "next_letter", "inputs": [["Hello"], ["What is your name?"], ["zOo"]], "outputs": [["Ifmmp"], ["Xibu jt zpvs obnf?"], ["aPp"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,405
def next_letter(s):
de324fd9f4b62ed0dbafde592603d242
UNKNOWN
You have recently discovered that horses travel in a unique pattern - they're either running (at top speed) or resting (standing still). Here's an example of how one particular horse might travel: ``` The horse Blaze can run at 14 metres/second for 60 seconds, but must then rest for 45 seconds. After 500 seconds Bla...
["def travel(total_time, run_time, rest_time, speed):\n q, r = divmod(total_time, run_time + rest_time)\n return (q * run_time + min(r, run_time)) * speed\n", "def travel(total_time, run_time, rest_time, speed):\n d, m = divmod(total_time, run_time + rest_time)\n return (d * run_time + min(m, run_time)) * s...
{"fn_name": "travel", "inputs": [[1000, 10, 127, 14], [1000, 10, 0, 10], [25, 50, 120, 18], [35869784, 90, 100, 5], [1234567, 4, 3, 11], [100000000, 21, 5, 14], [0, 100, 10, 14], [250, 0, 5, 14], [100, 10, 0, 14], [500, 100, 10, 0]], "outputs": [[1120], [10000], [450], [84954920], [7760148], [1130769276], [0], [0], [14...
INTRODUCTORY
PYTHON3
CODEWARS
2,435
def travel(total_time, run_time, rest_time, speed):
a01c2007686c95aa47883032a64309db
UNKNOWN
Sort array by last character Complete the function to sort a given array or list by last character of elements. ```if-not:haskell Element can be an integer or a string. ``` ### Example: ``` ['acvd', 'bcc'] --> ['bcc', 'acvd'] ``` The last characters of the strings are `d` and `c`. As `c` comes before `d`, sortin...
["def sort_me(arr):\n return sorted(arr, key=lambda elem: str(elem)[-1])", "def sort_me(arr):\n # Good Luck!\n return sorted(arr, key=lambda x:str(x)[-1])", "def sort_me(xs):\n return sorted(xs, key=lambda x: str(x)[-1])", "def sort_me(a):\n return sorted(a, key=lambda x: str(x)[-1])", "def sort_me(arr):...
{"fn_name": "sort_me", "inputs": [[["acvd", "bcc"]], [["14", "13"]], [["asdf", "asdf", "14", "13"]], [["bsde", "asdf", 14, "13"]], [["asdf", 14, "13", "asdf"]]], "outputs": [[["bcc", "acvd"]], [["13", "14"]], [["13", "14", "asdf", "asdf"]], [["13", 14, "bsde", "asdf"]], [["13", 14, "asdf", "asdf"]]]}
INTRODUCTORY
PYTHON3
CODEWARS
944
def sort_me(arr):
90a920847668e5eeb47bf59a710d07ed
UNKNOWN
# Task Christmas is coming. In the [previous kata](https://www.codewars.com/kata/5a405ba4e1ce0e1d7800012e), we build a custom Christmas tree with the specified characters and the specified height. Now, we are interested in the center of the Christmas tree. Please imagine that we build a Christmas tree with `chars =...
["def center_of(chars):\n if not chars:\n return \"\"\n total=0\n res=[]\n for i in range(1,len(chars)*2+1): \n if i%2==1:\n res.append((i+1)//2+total)\n res[-1]=chars[(res[-1]-1)%len(chars)]\n total+=i\n res=\"\".join(res)\n for i in range(len(res)//2+...
{"fn_name": "center_of", "inputs": [[""], ["a"], ["ab"], ["abc"], ["abab"], ["abcde"], ["aaaaaaaaaaaaaa"], ["abaabaaab"], ["dbdbebedbddbedededeeddbbdeddbeddeebdeddeebbbb"], ["vttussvutvuvvtustsvsvtvu"]], "outputs": [[""], ["a"], ["a"], ["aba"], ["a"], ["aecea"], ["a"], ["aba"], ["deededebddeebeddeddeddbddeddeddebeeddbe...
INTRODUCTORY
PYTHON3
CODEWARS
5,700
def center_of(chars):
765595b31004073fcdedb6d3e5d17526
UNKNOWN
You will be given an array of positive integers. The array should be sorted by the amount of distinct perfect squares and reversed, that can be generated from each number permuting its digits. E.g.: ```arr = [715, 112, 136, 169, 144]``` ``` Number Perfect Squares w/ its Digits Amount 715 - ...
["from collections import defaultdict\nSQUARES = [x**2 for x in range(1, 3163)]\nDIGITS = defaultdict(int)\nfor sqr in SQUARES:\n DIGITS[''.join(sorted(str(sqr)))] += 1\n\ndef sort_by_perfsq(arr):\n return sorted(arr, key=lambda n: (-DIGITS[''.join(sorted(str(n)))], n))", "from itertools import permutations\n\nd...
{"fn_name": "sort_by_perfsq", "inputs": [[[715, 112, 136, 169, 144]], [[234, 61, 16, 441, 144, 728]]], "outputs": [[[169, 144, 112, 136, 715]], [[144, 441, 16, 61, 234, 728]]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,149
def sort_by_perfsq(arr):
54288728a4cbde6bb48d00379319cedb
UNKNOWN
# Task An IP address contains four numbers(0-255) and separated by dots. It can be converted to a number by this way: Given a string `s` represents a number or an IP address. Your task is to convert it to another representation(`number to IP address` or `IP address to number`). You can assume that all inputs are va...
["from ipaddress import IPv4Address\n\ndef numberAndIPaddress(s):\n return str(int(IPv4Address(s))) if '.' in s else str(IPv4Address(int(s)))", "from ipaddress import IPv4Address\n\ndef numberAndIPaddress(string):\n if '.' in string:\n return str(int(IPv4Address(string)))\n return str(IPv4Address(int(st...
{"fn_name": "numberAndIPaddress", "inputs": [["10.0.3.193"], ["167969729"]], "outputs": [["167773121"], ["10.3.3.193"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,374
def numberAndIPaddress(s):
18ef6e03eb8fd5ec0ea743d434720165
UNKNOWN
As a strict big brother, I do limit my young brother Vasya on time he spends on computer games. I define a prime-time as a time period till which Vasya have a permission to play computer games. I specify start hour and end hour as pair of integers. I need a function which will take three numbers - a present moment (cu...
["def can_i_play(now_hour, start_hour, end_hour):\n return 0<=(now_hour-start_hour)%24<(end_hour-start_hour)%24\n", "def can_i_play(now_hour, start_hour, end_hour):\n if start_hour < end_hour:\n return start_hour <= now_hour < end_hour\n return start_hour <= now_hour or now_hour < end_hour\n", "def ca...
{"fn_name": "can_i_play", "inputs": [[9, 10, 11], [12, 12, 13], [13, 10, 15], [14, 9, 14], [15, 8, 12], [20, 21, 1], [21, 21, 6], [17, 15, 3], [0, 22, 1], [1, 22, 1], [3, 23, 2], [20, 0, 23], [14, 2, 9], [9, 20, 11], [23, 23, 0], [11, 2, 9], [0, 20, 23], [4, 0, 3], [6, 2, 10]], "outputs": [[false], [true], [true], [fal...
INTRODUCTORY
PYTHON3
CODEWARS
1,889
def can_i_play(now_hour, start_hour, end_hour):
0e9449ca9de6067d91e8d3718614959a
UNKNOWN
###Task: You have to write a function **pattern** which returns the following Pattern(See Examples) upto n rows, where n is parameter. ####Rules/Note: * If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string. * The length of each line = (2n-1). * Range of n is (-∞,100] ###Examples: pa...
["def pattern(n):\n nums = '1234567890'\n str_nums = nums*(n//10) + nums[:n%10]\n return '\\n'.join(' '*(n - i - 1) + str_nums + ' '*i for i in range(n))\n", "def pattern(n):\n return \"\\n\".join([(n-1 - i) * \" \" + \"\".join(str(j % 10) for j in range(1, n+1)) + (i * \" \") for i in range(n)])", "def pat...
{"fn_name": "pattern", "inputs": [[3], [5], [8], [-3], [-11], [-25], [0]], "outputs": [[" 123\n 123 \n123 "], [" 12345\n 12345 \n 12345 \n 12345 \n12345 "], [" 12345678\n 12345678 \n 12345678 \n 12345678 \n 12345678 \n 12345678 \n 12345678 \n12345678 "], [""], [""...
INTRODUCTORY
PYTHON3
CODEWARS
1,466
def pattern(n):
bbb3dcd5f6dc49b42b0cec88f025e669
UNKNOWN
Consider an array that has no prime numbers, and none of its elements has any prime digit. It would start with: `[1,4,6,8,9,10,14,16,18,..]`. `12` and `15` are not in the list because `2` and `5` are primes. You will be given an integer `n` and your task will be return the number at that index in the array. For exa...
["n,forbid = 100000, set(\"2357\")\nsieve, notPrimes = [0]*(n+1), [1]\nfor i in range(2, n+1):\n if sieve[i]:\n if not (forbid & set(str(i))): notPrimes.append(i)\n else:\n for j in range(i**2, n+1, i): sieve[j] = 1\n\ndef solve(n): return notPrimes[n]", "solve=lambda n: [1,4,6,8,9,10,14,16,18,40,4...
{"fn_name": "solve", "inputs": [[10], [50], [100], [150], [200], [300], [400], [500], [1000], [2000], [3000]], "outputs": [[44], [169], [644], [896], [1060], [1668], [4084], [4681], [9110], [18118], [46166]]}
INTRODUCTORY
PYTHON3
CODEWARS
43,423
def solve(n):
e024c2292ce03547403ea28659831741
UNKNOWN
Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result. Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0). If the input string is empty, return an empty string. The words in the input String will onl...
["def order(sentence):\n return \" \".join(sorted(sentence.split(), key=lambda x: int(\"\".join(filter(str.isdigit, x)))))\n", "def order(words):\n return ' '.join(sorted(words.split(), key=lambda w:sorted(w)))", "def order(sentence):\n if not sentence:\n return \"\"\n result = [] #the list that wil...
{"fn_name": "order", "inputs": [["is2 Thi1s T4est 3a"], ["4of Fo1r pe6ople g3ood th5e the2"], ["d4o dru7nken sh2all w5ith s8ailor wha1t 3we a6"], [""], ["3 6 4 2 8 7 5 1 9"]], "outputs": [["Thi1s is2 3a T4est"], ["Fo1r the2 g3ood 4of th5e pe6ople"], ["wha1t sh2all 3we d4o w5ith a6 dru7nken s8ailor"], [""], ["1 2 3 4 5 ...
INTRODUCTORY
PYTHON3
CODEWARS
2,664
def order(sentence):
c5b0e52dd84b39ea6db077d9b2716382
UNKNOWN
Lucy loves to travel. Luckily she is a renowned computer scientist and gets to travel to international conferences using her department's budget. Each year, Society for Exciting Computer Science Research (SECSR) organizes several conferences around the world. Lucy always picks one conference from that list that is hos...
["def conference_picker(cities_visited, cities_offered):\n for city in cities_offered:\n if city not in cities_visited:\n return city\n return 'No worthwhile conferences this year!'", "def conference_picker(visited, offered):\n visited = set(visited)\n return next((city for city in offered...
{"fn_name": "conference_picker", "inputs": [[[], ["Philadelphia", "Osaka", "Tokyo", "Melbourne"]], [[], ["Brussels", "Madrid", "London"]], [[], ["Sydney", "Tokyo"]], [["London", "Berlin", "Mexico City", "Melbourne", "Buenos Aires", "Hong Kong", "Madrid", "Paris"], ["Berlin", "Melbourne"]], [["Beijing", "Johannesburg", ...
INTRODUCTORY
PYTHON3
CODEWARS
4,382
def conference_picker(cities_visited, cities_offered):
318b9c7f1401c1075078c21c40a75d0e
UNKNOWN
Because my other two parts of the serie were pretty well received I decided to do another part. Puzzle Tiles You will get two Integer n (width) and m (height) and your task is to draw following pattern. Each line is seperated with '\n'. Both integers are equal or greater than 1. No need to check for invalid paramet...
["def puzzle_tiles(width, height):\n def f():\n yield ' ' + ' _( )__' * width\n for i in range(height):\n if i % 2 == 0:\n yield ' _|' + ' _|' * width\n yield '(_' + ' _ (_' * width\n yield ' |' + '__( )_|' * width\n else: ...
{"fn_name": "puzzle_tiles", "inputs": [[1, 1], [3, 2]], "outputs": [[" _( )__\n _| _|\n(_ _ (_\n |__( )_|"], [" _( )__ _( )__ _( )__\n _| _| _| _|\n(_ _ (_ _ (_ _ (_\n |__( )_|__( )_|__( )_|\n |_ |_ |_ |_\n _) _ _) _ _) _ _)\n |__( )_|__( )_|__( )_|"]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,881
def puzzle_tiles(width, height):
03c7fe804da5a4c32e8439531bae56a9
UNKNOWN
I'm new to coding and now I want to get the sum of two arrays...actually the sum of all their elements. I'll appreciate for your help. P.S. Each array includes only integer numbers. Output is a number too.
["def array_plus_array(arr1,arr2):\n return sum(arr1+arr2)\n", "def array_plus_array(arr1,arr2):\n return sum(arr1) + sum(arr2)", "def array_plus_array(*args):\n return sum(map(sum, args))\n", "def array_plus_array(a, b):\n return sum(a+b)", "def array_plus_array(arr1,arr2):\n counter = 0\n for i in a...
{"fn_name": "array_plus_array", "inputs": [[[1, 2, 3], [4, 5, 6]], [[-1, -2, -3], [-4, -5, -6]], [[0, 0, 0], [4, 5, 6]], [[100, 200, 300], [400, 500, 600]]], "outputs": [[21], [-21], [15], [2100]]}
INTRODUCTORY
PYTHON3
CODEWARS
14,039
def array_plus_array(arr1,arr2):
2b465f2265587e11a83ec25d3f02f9de
UNKNOWN
# Story Well, here I am stuck in another traffic jam. *Damn all those courteous people!* Cars are trying to enter the main road from side-streets somewhere ahead of me and people keep letting them cut in. Each time somebody is let in the effect ripples back down the road, so pretty soon I am not moving at all. (S...
["def traffic_jam(road, sides):\n X = road.index(\"X\")\n main = list(road[:X+1])\n \n for i in reversed(range( min(X,len(sides)) )):\n tmp = []\n for j in range(1, min(len(main)-i-1, len(sides[i]))+1 ):\n tmp.append(sides[i][-j])\n tmp.append(main[i+j])\n main[...
{"fn_name": "traffic_jam", "inputs": [["abcdeXghi", ["", "", "CCCCC", "", "EEEEEEEEEE", "FFFFFF", "", "", "IIIIII"]], ["abcdefX", []], ["abcXdef", []], ["Xabcdef", []], ["abcdefghijklmX", ["", "", "", "BBBBBB", "", "", "", "", "CCCCC"]], ["abcdefghijkX", ["", "AAAAAAAAAA", "", "BBBBBBBB", "", "CCCC"]], ["abcdefghijkX",...
INTRODUCTORY
PYTHON3
CODEWARS
3,598
def traffic_jam(main_road, side_streets):
94cecca389dfdfbb32957a672fccaf6e
UNKNOWN
# Task A masked number is a string that consists of digits and one asterisk (`*`) that should be replaced by exactly one digit. Given a masked number `s`, find all the possible options to replace the asterisk with a digit to produce an integer divisible by 6. # Input/Output `[input]` string `s` A masked number. `1...
["def is_divisible_by_6(s):\n all_numbers = [ int(s.replace('*', str(n))) for n in range(10) ]\n return [ str(n) for n in all_numbers if n % 6 == 0 ]", "def is_divisible_by_6(s):\n return [str(n) for n in [int(s.replace('*', str(i))) for i in range(10)] if n % 6 == 0]", "def is_divisible_by_6(stg):\n result =...
{"fn_name": "is_divisible_by_6", "inputs": [["1*0"], ["*"], ["*1"], ["*2"], ["81234567890*"], ["41*"], ["*6"], ["2345*345729"], ["34234*2"], ["1234567890123456789012345678*0"]], "outputs": [[["120", "150", "180"]], [["0", "6"]], [[]], [["12", "42", "72"]], [["812345678904"]], [["414"]], [["6", "36", "66", "96"]], [[]],...
INTRODUCTORY
PYTHON3
CODEWARS
3,005
def is_divisible_by_6(s):
d50b19d2e50461c87fc4558871b3a0d5
UNKNOWN
Born a misinterpretation of [this kata](https://www.codewars.com/kata/simple-fun-number-334-two-beggars-and-gold/), your task here is pretty simple: given an array of values and an amount of beggars, you are supposed to return an array with the sum of what each beggar brings home, assuming they all take regular turns, ...
["def beggars(values, n):\n return [sum(values[i::n]) for i in range(n)]", "def beggars(a, n): \n return [sum(a[i::n]) for i in range(n)]", "def beggars(values, n):\n if n == 0:\n return []\n i=0\n take=[]\n for x in range(n):\n take.append(0)\n for val in values:\n take[i%n...
{"fn_name": "beggars", "inputs": [[[1, 2, 3, 4, 5], 1], [[1, 2, 3, 4, 5], 2], [[1, 2, 3, 4, 5], 3], [[1, 2, 3, 4, 5], 6], [[1, 2, 3, 4, 5], 0]], "outputs": [[[15]], [[9, 6]], [[5, 7, 3]], [[1, 2, 3, 4, 5, 0]], [[]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,342
def beggars(values, n):
052515368ed4e48ed078cdf25ba75d6d
UNKNOWN
In graph theory, a graph is a collection of nodes with connections between them. Any node can be connected to any other node exactly once, and can be connected to no nodes, to some nodes, or to every other node. Nodes cannot be connected to themselves A path through a graph is a sequence of nodes, with every node conne...
["def isTree(matrix):\n visited_nodes = set([0])\n crossed_edges = set()\n agenda = [0]\n\n while agenda:\n node = agenda.pop()\n for i in matrix[node]:\n if (node, i) in crossed_edges: continue \n if i in visited_nodes: return False\n agenda.append(i)\n ...
{"fn_name": "isTree", "inputs": [[[[], []]], [[[1], [0]]], [[[1, 2], [0, 2], [0, 1]]], [[[1, 2, 3], [0, 2], [1, 2], [0]]], [[[1, 2, 3], [0], [0], [0, 4], [3]]], [[[1, 2, 3], [0], [0], [0, 4], [3], []]], [[[1], [0, 2], [1, 3, 5], [2, 4], [3, 5], [4, 2]]], [[[1], [0, 2, 3, 4], [1], [1], [1]]], [[[1], [0, 2, 3], [1], [1],...
INTRODUCTORY
PYTHON3
CODEWARS
4,235
def isTree(matrix):
09e352621407309636189b2ee427e42f
UNKNOWN
In this Kata, you will create a function that converts a string with letters and numbers to the inverse of that string (with regards to Alpha and Numeric characters). So, e.g. the letter `a` will become `1` and number `1` will become `a`; `z` will become `26` and `26` will become `z`. Example: `"a25bz"` would become `...
["import re\ndef AlphaNum_NumAlpha(string):\n return re.sub( r'[0-9]{1,2}|[a-z]', lambda x:str(ord(x.group() )-96) if x.group().isalpha() else chr(int(x.group())+96) , string)\n \n #\\w\n", "import re\nfrom string import ascii_lowercase\n\ndef repl(m):\n x = m.group()\n if x.isdigit():\n return a...
{"fn_name": "AlphaNum_NumAlpha", "inputs": [["25abcd26"], ["18zyz14"], ["a1b2c3d4"], ["5a8p17"], ["w6aa4ct24m5"], ["17dh"], ["25gj8sk6r17"], ["18zzz14"], ["y17kg5et11"], ["abcdefghijklmnopqrstuvwxyz"], ["1a2b3c4d5e6f7g8h9i10j11k12l13m14n15o16p17q18r19s20t21u22v23w24x25y26z"], ["h15q4pc6yw23nmx19y"], ["p16k11o25x7m6m20c...
INTRODUCTORY
PYTHON3
CODEWARS
853
def AlphaNum_NumAlpha(string):
41e3cd5fe671b115b2971762f3e82f5a
UNKNOWN
Convert a hash into an array. Nothing more, Nothing less. ``` {name: 'Jeremy', age: 24, role: 'Software Engineer'} ``` should be converted into ``` [["name", "Jeremy"], ["age", 24], ["role", "Software Engineer"]] ``` ```if:python,javascript,crystal **Note**: The output array should be sorted alphabetically. ``` Goo...
["def convert_hash_to_array(hash):\n return sorted(map(list, hash.items()))", "def convert_hash_to_array(hash):\n return [[k, hash[k]] for k in sorted(hash)]", "def convert_hash_to_array(d):\n return [ [k,v] for k,v in sorted(d.items()) ] ", "def convert_hash_to_array(dct):\n return sorted(list(item) for it...
{"fn_name": "convert_hash_to_array", "inputs": [[{"name": "Jeremy"}], [{"name": "Jeremy", "age": 24}], [{"name": "Jeremy", "age": 24, "role": "Software Engineer"}], [{"product": "CodeWars", "power_level_over": 9000}], [{}]], "outputs": [[[["name", "Jeremy"]]], [[["age", 24], ["name", "Jeremy"]]], [[["age", 24], ["name"...
INTRODUCTORY
PYTHON3
CODEWARS
1,220
def convert_hash_to_array(hash):
88bc4e7b2df87f17821c588198806714
UNKNOWN
To participate in a prize draw each one gives his/her firstname. Each letter of a firstname has a value which is its rank in the English alphabet. `A` and `a` have rank `1`, `B` and `b` rank `2` and so on. The *length* of the firstname is added to the *sum* of these ranks hence a number `som`. An array of random ...
["def rank(st, we, n):\n if not st:\n return \"No participants\"\n \n if n>len(we):\n return \"Not enough participants\"\n\n name_score = lambda name,w: w*(len(name)+sum([ord(c.lower())-96for c in name]))\n \n scores= [name_score(s,we[i]) for i,s in enumerate(st.split(','))]\n \n s...
{"fn_name": "rank", "inputs": [["Addison,Jayden,Sofia,Michael,Andrew,Lily,Benjamin", [4, 2, 1, 4, 3, 1, 2], 4], ["Elijah,Chloe,Elizabeth,Matthew,Natalie,Jayden", [1, 3, 5, 5, 3, 6], 2], ["Aubrey,Olivai,Abigail,Chloe,Andrew,Elizabeth", [3, 1, 4, 4, 3, 2], 4], ["Lagon,Lily", [1, 5], 2], ["Elijah,Michael,Avery,Sophia,Sama...
INTRODUCTORY
PYTHON3
CODEWARS
5,124
def rank(st, we, n):
35f7c9a2a23e91af2f12ed127a6b620d
UNKNOWN
Write a function named setAlarm which receives two parameters. The first parameter, employed, is true whenever you are employed and the second parameter, vacation is true whenever you are on vacation. The function should return true if you are employed and not on vacation (because these are the circumstances under whic...
["def set_alarm(employed, vacation):\n return employed and not vacation", "def set_alarm(employed, vacation):\n # Your code here\n if employed:\n if vacation:\n return False\n return True\n return False", "def set_alarm(employed, vacation):\n return employed==True and vacation==F...
{"fn_name": "set_alarm", "inputs": [[true, true], [false, true], [false, false], [true, false]], "outputs": [[false], [false], [false], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
16,736
def set_alarm(employed, vacation):
b90bd24cf5f87ede00b3262e27583b9e
UNKNOWN
Calculus class...is awesome! But you are a programmer with no time for mindless repetition. Your teacher spent a whole day covering differentiation of polynomials, and by the time the bell rang, you had already conjured up a program to automate the process. You realize that a polynomial of degree n anx^(n) + an-1x^(n...
["def diff(poly):\n return [poly[i] * (len(poly)-1-i) for i in range(len(poly)-1)]", "def diff(poly):\n return [d*c for d,c in enumerate(poly[::-1]) if d][::-1]", "diff=lambda s:[i*j for i,j in enumerate(s[:-1][::-1],1)][::-1]", "def diff(poly):\n return [i * n for i, n in enumerate(poly[-2::-1], 1)][::-1]", "de...
{"fn_name": "diff", "inputs": [[[]]], "outputs": [[[]]]}
INTRODUCTORY
PYTHON3
CODEWARS
857
def diff(poly):
02b79ea6f50a198ee1242ee576673fa2
UNKNOWN
Given is a md5 hash of a five digits long PIN. It is given as string. Md5 is a function to hash your password: "password123" ===> "482c811da5d5b4bc6d497ffa98491e38" Why is this useful? Hash functions like md5 can create a hash from string in a short time and it is impossible to find out the password, if you only got t...
["import hashlib\ndef crack(hash):\n for i in range(100000):\n if hashlib.md5(str(i).zfill(5).encode()).hexdigest() == hash:\n return str(i).zfill(5)", "from hashlib import md5\nfrom itertools import product\n\ndef crack(hash):\n for bs in map(bytes, product(b'0123456789', repeat=5)):\n i...
{"fn_name": "crack", "inputs": [["827ccb0eea8a706c4c34a16891f84e7b"], ["86aa400b65433b608a9db30070ec60cd"]], "outputs": [["12345"], ["00078"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,194
def crack(hash):
6eb8e5652df43734433de1e369bf3f75
UNKNOWN
# Task After a long night (work, play, study) you find yourself sleeping on a bench in a park. As you wake up and try to figure out what happened you start counting trees. You notice there are different tree sizes but there's always one size which is unbalanced. For example there are 2 size 2, 2 size 1 and 1 size 3. (...
["def find_the_missing_tree(trees):\n return sorted(trees, key=trees.count)[0]", "from collections import Counter\ndef find_the_missing_tree(trees):\n return Counter(trees).most_common()[-1][0] ", "def find_the_missing_tree(trees):\n return min(trees, key = lambda n: trees.count(n))", "def find_the_missing_tr...
{"fn_name": "find_the_missing_tree", "inputs": [[[1, 2, 2, 3, 3]], [[11, 2, 3, 3, 3, 11, 2, 2]], [[234, 76, 45, 99, 99, 99, 99, 45, 234, 234, 45, 45, 76, 234, 76]], [[1, 1, 1, 1, 1, 1, 1, 22, 22, 22, 22, 22, 22, 22, 3, 3, 3, 3, 3, 3]], [[10, 205, 3000, 3000, 10]], [[50, 408, 50, 50, 50, 50, 408, 408, 408, 680, 408, 680...
INTRODUCTORY
PYTHON3
CODEWARS
1,588
def find_the_missing_tree(trees):
0ee8b92fbc14be07b942a04ff69773d7
UNKNOWN
You probably know the 42 number as "The answer to life, the universe and everything" according to Douglas Adams' "The Hitchhiker's Guide to the Galaxy". For Freud, the answer was quite different. In the society he lived in, people-women in particular- had to repress their sexual needs and desires. This was simply how ...
["def to_freud(sentence):\n return ' '.join('sex' for _ in sentence.split())\n", "def to_freud(s):\n return (len(s.split()) * \"sex \").strip()", "def to_freud(sentence):\n words = sentence.split()\n wordcount = len(words)\n print(wordcount)\n s = \"\"\n while wordcount > 0:\n s = s + \"sex ...
{"fn_name": "to_freud", "inputs": [["test"], ["sexy sex"], ["This is a test"], ["This is a longer test"], ["You're becoming a true freudian expert"]], "outputs": [["sex"], ["sex sex"], ["sex sex sex sex"], ["sex sex sex sex sex"], ["sex sex sex sex sex sex"]]}
INTRODUCTORY
PYTHON3
CODEWARS
12,322
def to_freud(sentence):
b86d0ea1fd830496eccb0246f2aae817
UNKNOWN
# Making Change Complete the method that will determine the minimum number of coins needed to make change for a given amount in American currency. Coins used will be half-dollars, quarters, dimes, nickels, and pennies, worth 50¢, 25¢, 10¢, 5¢ and 1¢, respectively. They'll be represented by the symbols `H`, `Q`, `D`, ...
["BASE = {\"H\": 50, \"Q\": 25, \"D\": 10, \"N\": 5, \"P\": 1}\n\ndef make_change(n):\n r = {}\n for x, y in BASE.items():\n if n >= y:\n r[x], n = divmod(n, y)\n return r", "def make_change(amount):\n H = 50\n Q = 25\n D = 10\n N = 5\n P = 1\n change = {}\n while amount ...
{"fn_name": "make_change", "inputs": [[0], [1], [5], [43], [91], [101], [239]], "outputs": [[{}], [{"P": 1}], [{"N": 1}], [{"Q": 1, "D": 1, "N": 1, "P": 3}], [{"H": 1, "Q": 1, "D": 1, "N": 1, "P": 1}], [{"H": 2, "P": 1}], [{"H": 4, "Q": 1, "D": 1, "P": 4}]]}
INTRODUCTORY
PYTHON3
CODEWARS
5,219
def make_change(amount):
f87dd37035b325be28dd1292fadbfab1
UNKNOWN
A very easy task for you! You have to create a method, that corrects a given date string. There was a problem in addition, so many of the date strings are broken. Date-Format is european. That means "DD.MM.YYYY". Some examples: "30.02.2016" -> "01.03.2016" "40.06.2015" -> "10.07.2015" "11.13.2014" -> "11.01.2015" "...
["import re\nfrom datetime import date, timedelta\n\ndef date_correct(text):\n if not text:\n return text\n try:\n d, m, y = map(int, re.match(r'^(\\d{2})\\.(\\d{2})\\.(\\d{4})$', text).groups())\n mo, m = divmod(m - 1, 12)\n return (date(y + mo, m + 1, 1) + timedelta(days=d - 1)).strf...
{"fn_name": "date_correct", "inputs": [[null], [""], ["01112016"], ["01,11,2016"], ["0a.1c.2016"], ["03.12.2016"], ["30.02.2016"], ["40.06.2015"], ["11.13.2014"], ["33.13.2014"], ["99.11.2010"]], "outputs": [[null], [""], [null], [null], [null], ["03.12.2016"], ["01.03.2016"], ["10.07.2015"], ["11.01.2015"], ["02.02.20...
INTRODUCTORY
PYTHON3
CODEWARS
4,645
def date_correct(date):
c65447e73b79fb2f06a2202b41320460
UNKNOWN
An array is said to be `hollow` if it contains `3` or more `0`s in the middle that are preceded and followed by the same number of non-zero elements. Furthermore, all the zeroes in the array must be in the middle of the array. Write a function named `isHollow`/`is_hollow`/`IsHollow` that accepts an integer array and ...
["def is_hollow(x):\n while x and x[0] != 0 and x[-1] != 0: x = x[1:-1]\n return len(x) > 2 and set(x) == {0}", "from itertools import groupby\nfrom operator import not_\n\ndef is_hollow(a):\n b = [(x, [*y]) for x, y in groupby(a, key=not_)]\n return len(b) == 1 and b[0][0] and len(b[0][1]) > 2 or len(b) ==...
{"fn_name": "is_hollow", "inputs": [[[-1, 0, 0, 0, 3]], [[1, 0, 0, 0, 0]]], "outputs": [[true], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,975
def is_hollow(x):
81cb4dc9847b27e0e5174eb42d43dbcc
UNKNOWN
A number is self-descriptive when the n'th digit describes the amount n appears in the number. E.g. 21200: There are two 0's in the number, so the first digit is 2. There is one 1 in the number, so the second digit is 1. There are two 2's in the number, so the third digit is 2. There are no 3's in the number, so t...
["from collections import Counter\n\n\ndef self_descriptive(num):\n s = [int(a) for a in str(num)]\n cnt = Counter(s)\n return all(cnt[i] == b for i, b in enumerate(s))\n", "def self_descriptive(num):\n numList = list(str(num))\n for i, s in enumerate(numList):\n if int(s) != numList.count(str(i))...
{"fn_name": "self_descriptive", "inputs": [[21200], [3211000], [42101000], [21230], [11200], [1210], [51120111], [2020], [11201], [6210001000]], "outputs": [[true], [true], [true], [false], [false], [true], [false], [true], [false], [true]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,362
def self_descriptive(num):
c7722fe38b31364d4709fcace8c8e3df
UNKNOWN
The aim of the kata is to decompose `n!` (factorial n) into its prime factors. Examples: ``` n = 12; decomp(12) -> "2^10 * 3^5 * 5^2 * 7 * 11" since 12! is divisible by 2 ten times, by 3 five times, by 5 two times and by 7 and 11 only once. n = 22; decomp(22) -> "2^19 * 3^9 * 5^4 * 7^3 * 11^2 * 13 * 17 * 19" n = 25;...
["from collections import defaultdict\n\ndef dec(n):\n decomp = defaultdict(lambda:0)\n i = 2\n while n > 1:\n while n % i == 0:\n n /= i\n decomp[i] += 1\n i += 1\n return decomp\n \n\ndef decomp(n):\n ans = defaultdict(lambda:0)\n for i in range(2, n + ...
{"fn_name": "decomp", "inputs": [[5], [14], [17], [22], [25], [79], [98], [3988], [3989], [3990]], "outputs": [["2^3 * 3 * 5"], ["2^11 * 3^5 * 5^2 * 7^2 * 11 * 13"], ["2^15 * 3^6 * 5^3 * 7^2 * 11 * 13 * 17"], ["2^19 * 3^9 * 5^4 * 7^3 * 11^2 * 13 * 17 * 19"], ["2^22 * 3^10 * 5^6 * 7^3 * 11^2 * 13 * 17 * 19 * 23"], ["2^7...
INTRODUCTORY
PYTHON3
CODEWARS
12,355
def decomp(n):
cf2641a55c770fc890ac76108645c638
UNKNOWN
# Write Number in Expanded Form - Part 2 This is version 2 of my ['Write Number in Exanded Form' Kata](https://www.codewars.com/kata/write-number-in-expanded-form). You will be given a number and you will need to return it as a string in [Expanded Form](https://www.mathplacementreview.com/arithmetic/decimals.php#writ...
["def expanded_form(num):\n integer_part, fractional_part = str(num).split('.')\n\n result = [str(int(num) * (10 ** i)) for i, num in enumerate(integer_part[::-1]) if num != '0'][::-1]\n result += [str(num) + '/' + str(10 ** (i + 1)) for i, num in enumerate(fractional_part) if num != '0']\n\n return ' + '.j...
{"fn_name": "expanded_form", "inputs": [[1.24], [7.304], [0.04], [1.04], [7.3004], [0.004], [693.230459]], "outputs": [["1 + 2/10 + 4/100"], ["7 + 3/10 + 4/1000"], ["4/100"], ["1 + 4/100"], ["7 + 3/10 + 4/10000"], ["4/1000"], ["600 + 90 + 3 + 2/10 + 3/100 + 4/10000 + 5/100000 + 9/1000000"]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,580
def expanded_form(num):
9bf8e8448476784c638ab90dfc4ec95f
UNKNOWN
A wildlife study involving ducks is taking place in North America. Researchers are visiting some wetlands in a certain area taking a survey of what they see. The researchers will submit reports that need to be processed by your function. ## Input The input for your function will be an array with a list of common duc...
["def create_report(names):\n result = {}\n \n for name in names:\n if name.startswith(\"Labrador Duck\"):\n return [\"Disqualified data\"]\n \n name = name.upper().replace(\"-\", \" \").split()\n count = int(name.pop())\n \n if len(name) == 1: code = nam...
{"fn_name": "create_report", "inputs": [[["Redhead 5", "Labrador Duck 9", "Blue-Winged Teal 25", "Steller's Eider 200"]], [["Canvasback 10", "Mallard 150", "American Wigeon 45", "Baikal Teal 3", "Barrow's Goldeneye 6", "Surf Scoter 12"]], [["Redhead 3", "Gadwall 1", "Smew 4", "Greater Scaup 10", "Redhead 3", "Ga...
INTRODUCTORY
PYTHON3
CODEWARS
6,176
def create_report(names):
9c819e5cf740b33f560ba0aaf9bde1ee
UNKNOWN
`This kata is the first of the ADFGX Ciphers, the harder version can be found `here. The ADFGX Cipher is a pretty well-known Cryptographic tool, and is essentially a modified Polybius Square. Rather than having numbers as coordinates on the table, it has the letters: `A, D, F, G, X` Also, because this is the first...
["from itertools import product\nimport re\n\nKEY = [ a+b for a, b in product(\"ADFGX\", repeat=2) ]\n \n\ndef adfgx_encrypt(plaintext, square):\n d = dict(zip(square, KEY))\n oddity = d['i'] if 'i' in d else d['j']\n return ''.join(d.get(c, oddity) for c in plaintext)\n \n \ndef adfgx_decrypt(cip...
{"fn_name": "adfgx_encrypt", "inputs": [["helloworld", "bchigklnmoqprstuvwxyzadef"]], "outputs": [["AFXGDDDDDXGFDXFFDDXF"]]}
INTRODUCTORY
PYTHON3
CODEWARS
5,803
def adfgx_encrypt(plaintext, square):
fe76011f2ad0049130bae28ffc6d3277
UNKNOWN
In this Kata, you will be given a string and your task will be to return a list of ints detailing the count of uppercase letters, lowercase, numbers and special characters, as follows. ```Haskell Solve("*'&ABCDabcde12345") = [4,5,5,3]. --the order is: uppercase letters, lowercase, numbers and special characters. ``` ...
["def solve(s):\n uc, lc, num, sp = 0, 0, 0, 0\n for ch in s:\n if ch.isupper(): uc += 1\n elif ch.islower(): lc += 1\n elif ch.isdigit(): num += 1\n else: sp += 1\n return [uc, lc, num, sp]", "import re\ndef solve(s):\n return [len(re.findall(i,s)) for i in ('[A-Z]','[a-z]','\\d','[^a-zA-Z0-9]')]\n",...
{"fn_name": "solve", "inputs": [["Codewars@codewars123.com"], ["bgA5<1d-tOwUZTS8yQ"], ["P*K4%>mQUDaG$h=cx2?.Czt7!Zn16p@5H"], ["RYT'>s&gO-.CM9AKeH?,5317tWGpS<*x2ukXZD"], ["$Cnl)Sr<7bBW-&qLHI!mY41ODe"], ["@mw>0=QD-iAx!rp9TaG?o&M%l$34L.nbft"]], "outputs": [[[1, 18, 3, 2]], [[7, 6, 3, 2]], [[9, 9, 6, 9]], [[15, 8, 6, 9]], ...
INTRODUCTORY
PYTHON3
CODEWARS
2,184
def solve(s):
cdcf0215176e1b83a0ea9f1c6acc42c1
UNKNOWN
You're a buyer/seller and your buisness is at stake... You ___need___ to make profit... Or at least, you need to lose the least amount of money! Knowing a list of prices for buy/sell operations, you need to pick two of them. Buy/sell market is evolving across time and the list represent this evolution. First, you nee...
["def max_profit(prices):\n m = best = float('-inf')\n for v in reversed(prices):\n m, best = max(m, best-v), max(best,v)\n return m", "def max_profit(prices):\n out = prices[1] - prices[0]\n min_price = prices[0]\n \n for i in prices[1:]:\n if i - min_price > out:\n out = ...
{"fn_name": "max_profit", "inputs": [[[10, 7, 5, 8, 11, 9]], [[3, 4]], [[9, 9]], [[10, 7, 5, 4, 1]]], "outputs": [[6], [1], [0], [-1]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,910
def max_profit(prices):
8993f675e939d615ac93a82f25a7ee27
UNKNOWN
Every Turkish citizen has an identity number whose validity can be checked by these set of rules: - It is an 11 digit number - First digit can't be zero - Take the sum of 1st, 3rd, 5th, 7th and 9th digit and multiply it by 7. Then subtract the sum of 2nd, 4th, 6th and 8th digits from this value. Modulus 10 of the resu...
["def check_valid_tr_number(n):\n return type(n) == int and len(str(n)) == 11 and \\\n 8*sum(map(int, str(n)[:-1:2])) % 10 == sum(map(int, str(n)[:-1])) % 10 == n % 10", "import re\n\ndef check_valid_tr_number(n):\n lst = list(map(int,str(n) if isinstance(n,int) else '0'))\n return (isinstance(n,int)\n ...
{"fn_name": "check_valid_tr_number", "inputs": [[6923522112], [692352217312], ["x5810a78432"], [36637640050], [12762438338], ["03868894286"], [10000000146], [19415235426], [16691067984], [72097107542], [57040492705]], "outputs": [[false], [false], [false], [true], [false], [false], [true], [true], [false], [true], [fal...
INTRODUCTORY
PYTHON3
CODEWARS
2,153
def check_valid_tr_number(number):
d360bfeffb30229759fd30c9d2cb9f0b
UNKNOWN
# Task: Write a function that accepts an integer `n` and returns **the sum of the factorials of the first **`n`** Fibonacci numbers** ## Examples: ```python sum_fib(2) = 2 # 0! + 1! = 2 sum_fib(3) = 3 # 0! + 1! + 1! = 3 sum_fib(4) = 5 # 0! + 1! + 1! + 2! = 5 sum_fib(10) = 295232799039604140898709551821456...
["from math import factorial\n\nfib = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]\n\ndef sum_fib(n):\n return sum( factorial(x) for x in fib[:n] )", "from math import factorial\n\ndef sum_fib(n):\n a, b, s = 0, 1, 0\n while n:\n s += factorial(a)\n a...
{"fn_name": "sum_fib", "inputs": [[2], [3]], "outputs": [[2], [3]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,609
def sum_fib(n):
c76e61f91d81e11118f07a80cc462829
UNKNOWN
# Feynman's squares Richard Phillips Feynman was a well-known American physicist and a recipient of the Nobel Prize in Physics. He worked in theoretical physics and pioneered the field of quantum computing. Recently, an old farmer found some papers and notes that are believed to have belonged to Feynman. Among notes a...
["def count_squares(n):\n return sum([i * i for i in range(n + 1 ) ] )", "def count_squares(n):\n return n*(n+1)*(2*n+1)/6", "def count_squares(n): \n \"\"\" Function that uses recursion to calculate the number of square units in an n X n square\"\"\"\n if n == 1:\n return 1\n else:\n retu...
{"fn_name": "count_squares", "inputs": [[1], [2], [3], [5], [8], [15]], "outputs": [[1], [5], [14], [55], [204], [1240]]}
INTRODUCTORY
PYTHON3
CODEWARS
752
def count_squares(n):
3d8de1ed4e00bf955d684820809c02b1
UNKNOWN
# Task John loves encryption. He can encrypt any string by the following algorithm: ``` take the first and the last letters of the word; replace the letters between them with their number; replace this number with the sum of it digits until a single digit is obtained.``` Given two strings(`s1` and `s2`), re...
["def same_encryption(s1, s2):\n return (s1[0], s1[-1], len(s1) % 9) == (s2[0], s2[-1], len(s2) % 9)", "def same_encryption(s1, s2):\n encrypt = lambda s: f\"{s[0]}{len(s[1:-1]) % 9}{s[-1]}\"\n return encrypt(s1) == encrypt(s2)", "def same_encryption(s1, s2):\n return ( s1[0] == s2[0]\n and s1[-...
{"fn_name": "same_encryption", "inputs": [["abc", "abc"], ["abc", "abd"], ["fKhjuytrdfcdc", "flJc"], ["OKhjuytrdfcdc", "OijK"]], "outputs": [[true], [false], [true], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,899
def same_encryption(s1, s2):
4ee5a6cb1c79f851ba84eb3fe900eff1
UNKNOWN
Given three arrays of integers, return the sum of elements that are common in all three arrays. For example: ``` common([1,2,3],[5,3,2],[7,3,2]) = 5 because 2 & 3 are common in all 3 arrays common([1,2,2,3],[5,3,2,2],[7,3,2,2]) = 7 because 2,2 & 3 are common in the 3 arrays ``` More examples in the test cases. Go...
["from collections import Counter\ndef common(a,b,c):\n return sum((Counter(a) & Counter(b) & Counter(c)).elements())", "from functools import reduce\nfrom operator import and_\nfrom collections import Counter\n\ndef common(a,b,c):\n return sum(reduce(and_,map(Counter, (a,b,c))).elements())", "from collections im...
{"fn_name": "common", "inputs": [[[1, 2, 3], [5, 3, 2], [7, 3, 2]], [[1, 2, 2, 3], [5, 3, 2, 2], [7, 3, 2, 2]], [[1], [1], [1]], [[1], [1], [2]]], "outputs": [[5], [7], [1], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,028
def common(a,b,c):
66f7a8d20980ddc314614df819d84579
UNKNOWN
Write a function with the signature shown below: ```python def is_int_array(arr): return True ``` * returns `true / True` if every element in an array is an integer or a float with no decimals. * returns `true / True` if array is empty. * returns `false / False` for every other input.
["def is_int_array(a):\n return isinstance(a, list) and all(isinstance(x, (int, float)) and x == int(x) for x in a)", "def is_int_array(arr):\n if arr == []:\n return True\n if arr in [None, \"\"]:\n return False\n for i in arr:\n if type(i) in [int, float]:\n if int(i) != i:...
{"fn_name": "is_int_array", "inputs": [[[]], [[1, 2, 3, 4]], [[-11, -12, -13, -14]], [[1.0, 2.0, 3.0]], [[1, 2, null]], [null], [""], [[null]], [[1.0, 2.0, 3.0001]], [["-1"]]], "outputs": [[true], [true], [true], [true], [false], [false], [false], [false], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,156
def is_int_array(arr):
475483bd7ba82580299ebb4d9756214d
UNKNOWN
Imagine two rings with numbers on them. The inner ring spins clockwise (decreasing by 1 each spin) and the outer ring spins counter clockwise (increasing by 1 each spin). We start with both rings aligned on 0 at the top, and on each move we spin each ring one increment. How many moves will it take before both rings sho...
["from itertools import count\n\ndef spinning_rings(inner_max, outer_max):\n return next(i for i in count(1) if i % (outer_max + 1) == -i % (inner_max + 1))", "def spinning_rings(inner_max, outer_max):\n a,b,res = inner_max,1,1\n while a != b:\n a = (a + inner_max) % (inner_max+1)\n b = (b + 1) %...
{"fn_name": "spinning_rings", "inputs": [[2, 3], [3, 2], [1, 1], [2, 2], [3, 3]], "outputs": [[5], [2], [1], [3], [2]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,336
def spinning_rings(inner_max, outer_max):
51b2c5f6bd620094dacd27b80da70b15
UNKNOWN
In this Kata, you will be given a multi-dimensional array containing `2 or more` sub-arrays of integers. Your task is to find the maximum product that can be formed by taking any one element from each sub-array. ``` Examples: solve( [[1, 2],[3, 4]] ) = 8. The max product is given by 2 * 4 solve( [[10,-15],[-1,-3]] ) =...
["def solve(arr):\n \n p, q = 1, 1\n \n for k in arr:\n \n x, y = max(k), min(k)\n \n a = p * x\n b = q * x\n c = p * y\n d = q * y\n \n p = max(a, b, c, d)\n q = min(a, b, c, d)\n \n return max(p, q)", "def solve(arr):\n ...
{"fn_name": "solve", "inputs": [[[[1, 2], [3, 4]]], [[[10, -15], [-1, -3]]], [[[-1, 2, -3, 4], [1, -2, 3, -4]]], [[[-11, -6], [-20, -20], [18, -4], [-20, 1]]], [[[14, 2], [0, -16], [-12, -16]]], [[[-3, -4], [1, 2, -3]]], [[[-2, -15, -12, -8, -16], [-4, -15, -7], [-10, -5]]]], "outputs": [[8], [45], [12], [17600], [3584...
INTRODUCTORY
PYTHON3
CODEWARS
1,768
def solve(arr):
70ff649a0f00dace2a0059912ed5c350
UNKNOWN
Mr Leicester's cheese factory is the pride of the East Midlands, but he's feeling a little blue. It's the time of the year when **the taxman is coming round to take a slice of his cheddar** - and the final thing he has to work out is how much money he's spending on his staff. Poor Mr Leicester can barely sleep he's so ...
["from math import ceil\ndef pay_cheese(arr):\n return f'L{ceil(sum(arr) / 100) * 35}'", "from math import ceil\n\ndef pay_cheese(lst):\n return f\"L{35 * ceil(sum(lst) / 100)}\"", "from math import ceil\ndef pay_cheese(a): \n return f\"L{round(ceil(((sum(a)*6.)/10.)/60.)*35)}\"", "pay_cheese=lambda l:f\"L{...
{"fn_name": "pay_cheese", "inputs": [[[750, 750, 750, 750, 600]], [[700, 750, 700, 750, 600]], [[574, 574, 574, 574, 574]], [[1, 1, 1, 1, 1]], [[0, 0, 0, 0, 0]]], "outputs": [["L1260"], ["L1225"], ["L1015"], ["L35"], ["L0"]]}
INTRODUCTORY
PYTHON3
CODEWARS
895
def pay_cheese(arr):
aa4b58ebdb31f0680783d890604b1c82
UNKNOWN
# Task Given an integer `product`, find the smallest positive integer the product of whose digits is equal to product. If there is no such integer, return -1 instead. # Example For `product = 1`, the output should be `11`; `1 x 1 = 1` (1 is not a valid result, because it has only 1 digit) For `product = 12`, ...
["def digits_product(product):\n if product < 10:\n return 10 + product\n n = ''\n for d in range(9, 1, -1):\n while not product % d:\n n += str(d)\n product //= d\n return int(n[::-1]) if product == 1 else -1", "from functools import reduce\nfrom operator import mul\n\nd...
{"fn_name": "digits_product", "inputs": [[12], [19], [450], [0], [13], [1], [5], [10]], "outputs": [[26], [-1], [2559], [10], [-1], [11], [15], [25]]}
INTRODUCTORY
PYTHON3
CODEWARS
5,935
def digits_product(product):
858664bfa5b1082820bfedabea02bc51
UNKNOWN
The medians of a triangle are the segments that unit the vertices with the midpoint of their opposite sides. The three medians of a triangle intersect at the same point, called the barycenter or the centroid. Given a triangle, defined by the cartesian coordinates of its vertices we need to localize its barycenter or ce...
["def bar_triang(a, b, c):\n return [round(sum(x)/3.0, 4) for x in zip(a, b, c)]", "def bar_triang(pointA, pointB, pointC): \n a = (pointA[0] + pointB[0] + pointC[0]) / 3.0\n b = (pointA[1] + pointB[1] + pointC[1]) / 3.0\n return [round(a, 4), round(b, 4)]", "def bar_triang(pointA, pointB, pointC): # points...
{"fn_name": "bar_triang", "inputs": [[[4, 6], [12, 4], [10, 10]], [[4, 2], [12, 2], [6, 10]], [[4, 8], [8, 2], [16, 6]]], "outputs": [[[8.6667, 6.6667]], [[7.3333, 4.6667]], [[9.3333, 5.3333]]]}
INTRODUCTORY
PYTHON3
CODEWARS
18,341
def bar_triang(pointA, pointB, pointC):
42f3644c14a23b12ff6ba50c6c558efb
UNKNOWN
In this kata you must take an input string, reverse the order of the words, and reverse the order of the letters within the words. But, as a bonus, every test input will end with a punctuation mark (! ? .) and the output should be returned with the mark at the end. A few examples should help clarify: ```python esrev...
["def esrever(s):\n return s[:-1][::-1] + s[-1] if s else ''", "def esrever(string):\n return string and string[-2::-1] + string[-1]", "def esrever(string):\n return string[:-1][::-1] + string[-1:]", "def esrever(string):\n return string[-2::-1] + string[-1:]", "esrever = lambda s: s[-2::-1] + s[:-2:-1]", "...
{"fn_name": "esrever", "inputs": [["an Easy one?"], ["a small lOan OF 1,000,000 $!"], ["<?> &!.\"."], ["b3tTer p4ss thIS 0ne."], [""]], "outputs": [["eno ysaE na?"], ["$ 000,000,1 FO naOl llams a!"], ["\".!& >?<."], ["en0 SIht ss4p reTt3b."], [""]]}
INTRODUCTORY
PYTHON3
CODEWARS
745
def esrever(string):
5878b38edbf145b52ce56bd19d1fe7cf
UNKNOWN
# Task You are given a decimal number `n` as a **string**. Transform it into an array of numbers (given as **strings** again), such that each number has only one nonzero digit and their sum equals n. Each number in the output array should be written without any leading and trailing zeros. # Input/Output - `[inpu...
["def split_exp(n):\n dot = n.find('.')\n if dot == -1: dot = len(n)\n return [d+\"0\"*(dot-i-1) if i<dot else \".{}{}\".format(\"0\"*(i-dot-1), d)\n for i,d in enumerate(n) if i != dot and d != '0']", "def split_exp(n):\n j = n.find('.') + 1 or len(n) + 1\n return [f\"{c}{'0'*(j-i-2)}\" if i ...
{"fn_name": "split_exp", "inputs": [["7970521.5544"], ["7496314"], ["0"], ["6"], ["1.0000000000"], ["0000000000.1"], ["1010101"], ["1234567890.1234567890"]], "outputs": [[["7000000", "900000", "70000", "500", "20", "1", ".5", ".05", ".004", ".0004"]], [["7000000", "400000", "90000", "6000", "300", "10", "4"]], [[]], [[...
INTRODUCTORY
PYTHON3
CODEWARS
2,375
def split_exp(n):
328f50c7924201420a9613765f335dcf
UNKNOWN
In this kata, your task is to write a function `to_bytes(n)` (or `toBytes(n)` depending on language) that produces a list of bytes that represent a given non-negative integer `n`. Each byte in the list is represented by a string of `'0'` and `'1'` of length 8. The most significant byte is first in the list. The example...
["def to_bytes(n):\n if not n:\n return ['00000000']\n \n res = []\n while n:\n res.append('{:08b}'.format(n % 256))\n n //= 256\n \n return res[::-1]", "import re\nfrom math import ceil\ndef to_bytes(n):\n return re.findall('.{8}', '{:0{}b}'.format(n, int(8 * ceil(n.bit_length...
{"fn_name": "to_bytes", "inputs": [[0], [1]], "outputs": [[["00000000"]], [["00000001"]]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,343
def to_bytes(n):
ba9a143370f0509d3c619418aa94cffa
UNKNOWN
Consider a sequence, which is formed by the following rule: next term is taken as the smallest possible non-negative integer, which is not yet in the sequence, so that `no 3` terms of sequence form an arithmetic progression. ## Example `f(0) = 0` -- smallest non-negative `f(1) = 1` -- smallest non-negative, which i...
["sequence=lambda n:int(format(n,'b'),3)", "def sequence(n):\n return int(format(n, 'b'), 3)", "sequence=lambda n:int(bin(n)[2:],3)", "# A005836\ndef sequence(n):\n return n and 3*sequence(n>>1) + (n&1)", "from math import log2\n\ndef sequence(i):\n if i == 0:\n return 0\n e = int(log2(i))\n retur...
{"fn_name": "sequence", "inputs": [[0], [1], [2], [3], [4], [5], [334], [123], [546], [1634], [14514]], "outputs": [[0], [1], [3], [4], [9], [10], [7329], [1084], [19929], [79707], [2305425]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,876
def sequence(n):
73f0b9313500ef7017843b1d0ab7120b
UNKNOWN
In some countries of former Soviet Union there was a belief about lucky tickets. A transport ticket of any sort was believed to posess luck if sum of digits on the left half of its number was equal to the sum of digits on the right half. Here are examples of such numbers: ``` 003111 # 3 = 1 + 1 + 1 81337...
["def luck_check(string):\n e0, b1 = len(string) // 2, (len(string) + 1) // 2\n return sum(map(int, string[:e0])) == sum(map(int, string[b1:]))", "def luck_check(s):\n if not s or not all(c in '0123456789' for c in s):\n raise ValueError('Invalid ticket number')\n e0, b1 = len(s) // 2, (len(s) + 1) /...
{"fn_name": "luck_check", "inputs": [["5555"], ["003111"], ["543970707"], ["439924"], ["943294329932"], ["000000"], ["454319"], ["1233499943"], ["935336"]], "outputs": [[true], [true], [false], [false], [false], [true], [true], [false], [false]]}
INTRODUCTORY
PYTHON3
CODEWARS
838
def luck_check(string):
bd144843df2fac53f95b915179669e04
UNKNOWN
Lucas numbers are numbers in a sequence defined like this: ``` L(0) = 2 L(1) = 1 L(n) = L(n-1) + L(n-2) ``` Your mission is to complete the function that returns the `n`th term of this sequence. **Note:** It should work for negative numbers as well; how you do this is you flip the equation around, so for negative num...
["def lucasnum(n):\n a = 2\n b = 1\n\n flip = n < 0 and n % 2 != 0\n\n for _ in range(abs(n)):\n a, b = b, a + b\n \n return -a if flip else a", "SEQUENCE = [2, 1]\n\ndef lucasnum(n):\n try:\n return SEQUENCE[abs(n)] * (1, -1)[n < 0 and n % 2]\n except IndexError:\n while l...
{"fn_name": "lucasnum", "inputs": [[-10], [-1]], "outputs": [[123], [-1]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,477
def lucasnum(n):
a0b637079f18996c4d041d796f2fcd6b
UNKNOWN
`late_clock` function receive an array with 4 digits and should return the latest time that can be built with those digits. The time should be in `HH:MM` format. Examples: ``` [1, 9, 8, 3] => 19:38 [9, 1, 2, 5] => 21:59 ``` You can suppose the input is correct and you can build from it a correct 24-hour time.
["from itertools import permutations\n\ndef late_clock(digits):\n for p in permutations(sorted(digits, reverse=True)):\n if p[0] > 2 or (p[0] == 2 and p[1] > 3) or p[2] > 5: continue\n return '{}{}:{}{}'.format(*p)", "def late_clock(digits):\n res, digits = [], digits[:]\n def rec(i):\n if i == 3:\n...
{"fn_name": "late_clock", "inputs": [[[9, 1, 2, 5]], [[1, 9, 8, 3]], [[0, 2, 2, 2]], [[3, 5, 0, 2]], [[9, 0, 1, 1]], [[2, 3, 2, 4]], [[1, 2, 8, 9]]], "outputs": [["21:59"], ["19:38"], ["22:20"], ["23:50"], ["19:10"], ["23:42"], ["19:28"]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,222
def late_clock(digits):
32ea8a9c04d6ea6d8e7497c191afc248
UNKNOWN
## Task Write a method `remainder` which takes two integer arguments, `dividend` and `divisor`, and returns the remainder when dividend is divided by divisor. Do NOT use the modulus operator (%) to calculate the remainder! #### Assumption Dividend will always be `greater than or equal to` divisor. #### Notes Make ...
["def remainder(dividend,divisor):\n while divisor <= dividend:\n dividend = dividend - divisor\n return dividend", "# Take your pick\nfrom operator import mod as remainder\nremainder = int.__mod__", "def remainder(d1,d2):\n return d1%d2", "def remainder(dividend,divisor):\n return dividend - (dividend...
{"fn_name": "remainder", "inputs": [[3, 2], [19, 2], [10, 2], [34, 7], [27, 5]], "outputs": [[1], [1], [0], [6], [2]]}
INTRODUCTORY
PYTHON3
CODEWARS
827
def remainder(dividend, divisor):
ef8acc86ed95efd868e955663860c4e2
UNKNOWN
## Task Given a string, add the fewest number of characters possible from the front or back to make it a palindrome. ## Example For the input `cdcab`, the output should be `bacdcab` ## Input/Output Input is a string consisting of lowercase latin letters with length 3 <= str.length <= 10 The output is a palindrome...
["def build_palindrome(s):\n for n in range(len(s), -1, -1):\n if s[:n] == s[:n][::-1]:\n return s[n:][::-1] + s\n if s[-n:] == s[-n:][::-1]:\n return s + s[:-n][::-1]", "def build_palindrome(s):\n a = s[1:][::-1] + s\n temp = s\n for i in range(len(s)+1):\n temp =...
{"fn_name": "build_palindrome", "inputs": [["abcdc"], ["ababa"]], "outputs": [["abcdcba"], ["ababa"]]}
INTRODUCTORY
PYTHON3
CODEWARS
5,535
def build_palindrome(s):
80a7db2dfb786bc2c4345cd6f2a7a5e9
UNKNOWN
# Task In the field, two beggars A and B found some gold at the same time. They all wanted the gold, and they decided to use simple rules to distribute gold: ``` They divided gold into n piles and be in line. The amount of each pile and the order of piles all are randomly. They took turns to take away a pile of gold...
["def distribution_of(golds):\n g = golds[:]\n turn, total = 0, [0, 0]\n while g:\n total[turn % 2] += g.pop(-(g[0] < g[-1]))\n turn += 1\n return total\n", "from collections import deque\ndef distribution_of(golds):\n g = deque(golds)\n s = [0, 0]\n t = 0\n while g:\n s[t] ...
{"fn_name": "distribution_of", "inputs": [[[4, 7, 2, 9, 5, 2]], [[10, 1000, 2, 1]]], "outputs": [[[11, 18]], [[12, 1001]]]}
INTRODUCTORY
PYTHON3
CODEWARS
5,628
def distribution_of(golds):
7886628ca2cd4e9e24a22a25637db480
UNKNOWN
## Task: You have to write a function **pattern** which returns the following Pattern(See Examples) upto (2n-1) rows, where n is parameter. ### Rules/Note: * If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string. * All the lines in the pattern have same length i.e equal to the number o...
["def pattern(n):\n lines = []\n for i in range(1, n + 1):\n line = ' ' * (n - i)\n line += ''.join(str(j % 10) for j in range(1, i + 1))\n line += line[::-1][1:]\n lines.append(line)\n return '\\n'.join(lines + lines[::-1][1:])\n", "def pattern(n):\n lines = []\n for c in ran...
{"fn_name": "pattern", "inputs": [[1], [3], [7], [0], [-25]], "outputs": [["1"], [" 1 \n 121 \n12321\n 121 \n 1 "], [" 1 \n 121 \n 12321 \n 1234321 \n 123454321 \n 12345654321 \n1234567654321\n 12345654321 \n 123454321 \n 1234321 \n 12321 \n 121 \n 1 "], [...
INTRODUCTORY
PYTHON3
CODEWARS
2,170
def pattern(n):
2da31240b92087c9cdc2ce5c351ee809
UNKNOWN
Write a function ```x(n)``` that takes in a number ```n``` and returns an ```nxn``` array with an ```X``` in the middle. The ```X``` will be represented by ```1's``` and the rest will be ```0's```. E.g. ```python x(5) == [[1, 0, 0, 0, 1], [0, 1, 0, 1, 0], [0, 0, 1, 0, 0], [0, 1, 0, 1, 0]...
["def x(n): \n d = [[0] * n for i in range (n)]\n for i in range(n):\n d[i][i] = 1\n d[i][-i-1] = 1\n return d", "def fill(i, j, n):\n if i == j or i + j == n - 1:\n return 1\n else:\n return 0\n\ndef x(n):\n return [[fill(i, j, n) for j in range(n)] for i in range(n)]", "...
{"fn_name": "x", "inputs": [[1], [2], [3], [4], [5], [6]], "outputs": [[[[1]]], [[[1, 1], [1, 1]]], [[[1, 0, 1], [0, 1, 0], [1, 0, 1]]], [[[1, 0, 0, 1], [0, 1, 1, 0], [0, 1, 1, 0], [1, 0, 0, 1]]], [[[1, 0, 0, 0, 1], [0, 1, 0, 1, 0], [0, 0, 1, 0, 0], [0, 1, 0, 1, 0], [1, 0, 0, 0, 1]]], [[[1, 0, 0, 0, 0, 1], [0, 1, 0, 0,...
INTRODUCTORY
PYTHON3
CODEWARS
1,103
def x(n):
bd2a16f6a8aba2b6e7ce2f44fcaa3c4d
UNKNOWN
You are given an array of integers. Your task is to sort odd numbers within the array in ascending order, and even numbers in descending order. Note that zero is an even number. If you have an empty array, you need to return it. For example: ``` [5, 3, 2, 8, 1, 4] --> [1, 3, 8, 4, 5, 2] odd numbers ascending: [...
["def sort_array(xs):\n es = sorted(x for x in xs if x % 2 == 0)\n os = sorted((x for x in xs if x % 2 != 0), reverse=True)\n return [(es if x % 2 == 0 else os).pop() for x in xs]", "def sort_array(a):\n odds = []; evens = []; newArray = []\n for i in a:\n if i % 2 == 0:\n evens.append(...
{"fn_name": "sort_array", "inputs": [[[5, 3, 2, 8, 1, 4, 11]], [[2, 22, 37, 11, 4, 1, 5, 0]], [[1, 111, 11, 11, 2, 1, 5, 0]], [[]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]], [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]], [[0, 1, 2, 3, 4, 9, 8, 7, 6, 5]]], "outputs": [[[1, 3, 8, 4, 5, 2, 11]], [[22, 4, 1, 5, 2, 11, 37, 0]], [[1, 1, 5, 11, 2...
INTRODUCTORY
PYTHON3
CODEWARS
3,873
def sort_array(a):
9d18609bf3f93300166ff5fb893cc55d
UNKNOWN
In this kata, we will check is an array is (hyper)rectangular. A rectangular array is an N-dimensional array with fixed sized within one dimension. Its sizes can be repsented like A1xA2xA3...xAN. That means a N-dimensional array has N sizes. The 'As' are the hyperrectangular properties of an array. You should implem...
["from itertools import chain\n\ndef hyperrectangularity_properties(arr):\n hr, arr = [], [arr]\n while 1:\n check = sum(isinstance(v, int) for v in arr) # Check homogeneity\n if check or not arr: # some int are present or empty array (edge case)\n if...
{"fn_name": "hyperrectangularity_properties", "inputs": [[[]]], "outputs": [[[0]]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,567
def hyperrectangularity_properties(arr):
a6e358c8e1b17ec8fa2d2ee6b98710fa
UNKNOWN
# Challenge : Write a function that takes a single argument `n` that is a string representation of a simple mathematical expression and evaluates it as a floating point value. # Commands : - positive or negative decimal numbers - `+, -, *, /, ( / ).` --- Expressions use [infix notation](https://en.wikipedia.org/...
["def e(s):return f([*s,'+'])\ndef f(s,r=0,o=0,x='',c=0):\n while s and')'!=c:\n c=s.pop(0);i='+-*/)('.find(c)\n if c=='-'>x or i<0:x+=c\n elif c=='(':x=str(f(s))\n elif i>-1:a=float(x);r=[r+a,r-a,r*a,r/a][o];o=i;x=''\n return r", "def e(s,t=[],x=0,o='+',m=')*+-/'):\n if s:t+=list(s.replace(' ','')+')')\n while o!=...
{"fn_name": "e", "inputs": [["2*3*4*5+99"]], "outputs": [[219]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,233
def e(s):
6880094ea8867cbe5ed85594a5b5af1e
UNKNOWN
DropCaps means that the first letter of the starting word of the paragraph should be in caps and the remaining lowercase, just like you see in the newspaper. But for a change, let's do that for each and every word of the given String. Your task is to capitalize every word that has length greater than 2, leaving small...
["def drop_cap(str_):\n return ' '.join( w.capitalize() if len(w) > 2 else w for w in str_.split(' ') )\n", "import re\n\ndef drop_cap(s):\n return re.sub(r'\\w{3,}', lambda m: m[0].title(), s)", "def drop_cap(str_):\n return \" \".join([i[0].upper() + i[1::].lower() if len(i) > 2 else i for i in str_.split(\"...
{"fn_name": "drop_cap", "inputs": [["Apple Banana"], ["Apple"], [""], ["of"], ["Revelation of the contents outraged American public opinion, and helped generate"], ["more than one space between words"], [" leading spaces"], ["trailing spaces "], ["ALL CAPS CRAZINESS"], ["rAnDoM CaPs CrAzInEsS"]], "outputs": [["A...
INTRODUCTORY
PYTHON3
CODEWARS
1,012
def drop_cap(str_):
e3e97f03f19f5646466fbe77469b7f2a
UNKNOWN
Given a string `s` of uppercase letters, your task is to determine how many strings `t` (also uppercase) with length equal to that of `s` satisfy the followng conditions: * `t` is lexicographical larger than `s`, and * when you write both `s` and `t` in reverse order, `t` is still lexicographical larger than `s`. ``...
["def solve(s):\n r, l = 0, 0\n for c in s:\n m = ord('Z') - ord(c)\n r, l = r + m + l * m, m + l * 26\n return r % 1000000007", "def solve(s, z=ord('Z')):\n a = r = 0\n for i in (z - ord(c) for c in s):\n r += (a + 1) * i\n a = a * 26 + i\n r %= 1000000007\n a %...
{"fn_name": "solve", "inputs": [["XYZ"], ["ABC"], ["ABCD"], ["ZAZ"], ["XYZA"]], "outputs": [[5], [16174], [402230], [25], [34480]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,216
def solve(s):
b168f71f4781d8d9fde6989cb824ea65
UNKNOWN
**This Kata is intended as a small challenge for my students** Create a function, called ``removeVowels`` (or ``remove_vowels``), that takes a string argument and returns that same string with all vowels removed (vowels are "a", "e", "i", "o", "u").
["REMOVE_VOWS = str.maketrans('','','aeiou')\n\ndef remove_vowels(s):\n return s.translate(REMOVE_VOWS)", "def remove_vowels(strng):\n return ''.join([i for i in strng if i not in 'aeiou'])", "def remove_vowels(stg):\n return \"\".join(c for c in stg if c not in \"aeiou\")", "def remove_vowels(s):\n return ...
{"fn_name": "remove_vowels", "inputs": [["drake"], ["scholarstem"], ["codewars"], ["high fives!"], [""], ["i"], ["b"]], "outputs": [["drk"], ["schlrstm"], ["cdwrs"], ["hgh fvs!"], [""], [""], ["b"]]}
INTRODUCTORY
PYTHON3
CODEWARS
987
def remove_vowels(s):
af6e8b85df7c38530435afe6ab0e5c2c
UNKNOWN
Complete the function so that it takes an array of keys and a default value and returns a hash (Ruby) / dictionary (Python) with all keys set to the default value. ## Example ```python ["draft", "completed"], 0 # should return {"draft": 0, "completed: 0} ```
["def populate_dict(keys, default):\n return {key: default for key in keys}", "populate_dict = dict.fromkeys", "def populate_dict(keys, default):\n return dict.fromkeys(keys, default)", "def populate_dict(keys, default):\n return {k:default for k in keys}", "from itertools import repeat\ndef populate_dict(keys...
{"fn_name": "populate_dict", "inputs": [[["draft", "completed"], 0], [["a", "b", "c"], null], [[1, 2, 3, 4], "OK"]], "outputs": [[{"completed": 0, "draft": 0}], [{"c": null, "b": null, "a": null}], [{"1": "OK", "2": "OK", "3": "OK", "4": "OK"}]]}
INTRODUCTORY
PYTHON3
CODEWARS
902
def populate_dict(keys, default):
4e3ba7c0a47fbf9633be60d1cb5fc493
UNKNOWN
If we write out the digits of "60" as English words we get "sixzero"; the number of letters in "sixzero" is seven. The number of letters in "seven" is five. The number of letters in "five" is four. The number of letters in "four" is four: we have reached a stable equilibrium. Note: for integers larger than 9, write ou...
["digits = 'zero one two three four five six seven eight nine'.split()\n\ndef f(n):\n return ''.join(map(digits.__getitem__, map(int, str(n))))\n\ndef numbers_of_letters(n):\n result = [f(n)]\n print(n, result)\n while result[-1] != 'four':\n result.append(f(len(result[-1])))\n return result", "wo...
{"fn_name": "numbers_of_letters", "inputs": [[1], [2], [3], [4], [12], [37], [311], [999]], "outputs": [[["one", "three", "five", "four"]], [["two", "three", "five", "four"]], [["three", "five", "four"]], [["four"]], [["onetwo", "six", "three", "five", "four"]], [["threeseven", "onezero", "seven", "five", "four"]], [["...
INTRODUCTORY
PYTHON3
CODEWARS
3,512
def numbers_of_letters(n):
9ef2a401bdf6fab957363a6a93a610ad
UNKNOWN
We need a function ```prime_bef_aft()``` that gives the largest prime below a certain given value ```n```, ```befPrime or bef_prime``` (depending on the language), and the smallest prime larger than this value, ```aftPrime/aft_prime``` (depending on the language). The result should be output in a list like the f...
["def prime(a):\n if a < 2: return False\n if a == 2 or a == 3: return True \n if a % 2 == 0 or a % 3 == 0: return False\n maxDivisor = a**0.5\n d, i = 5, 2\n while d <= maxDivisor:\n if a % d == 0: return False\n d += i \n i = 6 - i\n \n return True\n\ndef prime_bef_aft(num)...
{"fn_name": "prime_bef_aft", "inputs": [[3], [4], [100], [97], [101], [120], [130]], "outputs": [[[2, 5]], [[3, 5]], [[97, 101]], [[89, 101]], [[97, 103]], [[113, 127]], [[127, 131]]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,727
def prime_bef_aft(num):
a5d54d951286db0151264aa824f6220a
UNKNOWN
It is 2050 and romance has long gone, relationships exist solely for practicality. MatchMyHusband is a website that matches busy working women with perfect house husbands. You have been employed by MatchMyHusband to write a function that determines who matches!! The rules are... a match occurs providing the husband's...
["def match(usefulness, months):\n return \"Match!\" if sum(usefulness) >= 0.85**months * 100 else \"No match!\"", "def match(usefulness, months):\n return 'Match!' if sum(usefulness) >= 100*0.85**months else 'No match!'", "def current(usefulness):\n return sum(usefulness)\n\ndef needed(months):\n if months...
{"fn_name": "match", "inputs": [[[15, 24, 12], 4], [[26, 23, 19], 3], [[11, 25, 36], 1], [[22, 9, 24], 5], [[8, 11, 4], 10], [[17, 31, 21], 2], [[34, 25, 36], 1], [[35, 35, 29], 0], [[35, 35, 30], 0], [[35, 35, 31], 0]], "outputs": [["No match!"], ["Match!"], ["No match!"], ["Match!"], ["Match!"], ["No match!"], ["Matc...
INTRODUCTORY
PYTHON3
CODEWARS
1,306
def match(usefulness, months):
54786c8184b80a60409adee5f9f21d03
UNKNOWN
Your job is to figure out the index of which vowel is missing from a given string: * `A` has an index of 0, * `E` has an index of 1, * `I` has an index of 2, * `O` has an index of 3, * `U` has an index of 4. **Notes:** There is no need for string validation and every sentence given will contain all vowles but one. ...
["def absent_vowel(x): \n return ['aeiou'.index(i) for i in 'aeiou' if i not in x][0]", "def absent_vowel(x): \n return 'aeiou'.index((set('aeiou') - set(x.lower())).pop())", "def absent_vowel(stg): \n return next(i for i, v in enumerate(\"aeiou\") if v not in stg)", "def absent_vowel(x): \n strings = ['a',...
{"fn_name": "absent_vowel", "inputs": [["John Doe hs seven red pples under his bsket"], ["Bb Smith sent us six neatly arranged range bicycles"]], "outputs": [[0], [3]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,425
def absent_vowel(x):
1c702f91283a5bc5e6eb33074fefd60e
UNKNOWN
Quantum mechanics tells us that a molecule is only allowed to have specific, discrete amounts of internal energy. The 'rigid rotor model', a model for describing rotations, tells us that the amount of rotational energy a molecule can have is given by: `E = B * J * (J + 1)`, where J is the state the molecule is in...
["def rot_energies(B, Jmin, Jmax):\n return [B * J * (J + 1) for J in range(Jmin, Jmax + 1)] if B > 0 else []", "def rot_energies(rot, energy_min, energy_max):\n # We're programmers, not scientists or mathematicians, we can use legible variable names.\n if rot <= 0:\n return []\n else:\n retur...
{"fn_name": "rot_energies", "inputs": [[1, 1, 2], [2, 0, 3], [423, 100, 150], [1, 2, 0], [1, 2, 2], [-1.0, 2, 2]], "outputs": [[[2, 6]], [[0, 4, 12, 24]], [[4272300, 4357746, 4444038, 4531176, 4619160, 4707990, 4797666, 4888188, 4979556, 5071770, 5164830, 5258736, 5353488, 5449086, 5545530, 5642820, 5740956, 5839938, 5...
INTRODUCTORY
PYTHON3
CODEWARS
1,459
def rot_energies(B, Jmin, Jmax):
04bc629632449a16c772089d4a196393
UNKNOWN
It's bonus time in the big city! The fatcats are rubbing their paws in anticipation... but who is going to make the most money? Build a function that takes in two arguments (salary, bonus). Salary will be an integer, and bonus a boolean. If bonus is true, the salary should be multiplied by 10. If bonus is false, the...
["def bonus_time(salary, bonus):\n return \"${}\".format(salary * (10 if bonus else 1))", "def bonus_time(salary, bonus):\n #your code here\n if bonus :\n return \"$\" + str(salary * 10)\n else:\n return \"$\" + str(salary)", "def bonus_time(salary, bonus):\n return '$' + str(salary * [1,10...
{"fn_name": "bonus_time", "inputs": [[10000, true], [25000, true], [10000, false], [60000, false], [2, true], [78, false], [67890, true]], "outputs": [["$100000"], ["$250000"], ["$10000"], ["$60000"], ["$20"], ["$78"], ["$678900"]]}
INTRODUCTORY
PYTHON3
CODEWARS
12,221
def bonus_time(salary, bonus):
b49bbb9232af0d69a62144eab10606d4
UNKNOWN
#### Task: Your job here is to write a function (`keepOrder` in JS/CoffeeScript, `keep_order` in Ruby/Crystal/Python, `keeporder` in Julia), which takes a sorted array `ary` and a value `val`, and returns the lowest index where you could insert `val` to maintain the sorted-ness of the array. The input array will alway...
["from bisect import bisect_left as keep_order", "from bisect import bisect_left\n\ndef keep_order(arr, val):\n return bisect_left(arr, val)", "def keep_order(ary, val):\n for i, x in enumerate(ary):\n if x >= val:\n return i\n return len(ary)", "def keep_order(arr, val):\n for i in range(...
{"fn_name": "keep_order", "inputs": [[[1, 2, 3, 4, 7], 5], [[1, 2, 3, 4, 7], 0], [[1, 1, 2, 2, 2], 2], [[1, 2, 3, 4], 5], [[1, 2, 3, 4], -1], [[1, 2, 3, 4], 2], [[1, 2, 3, 4], 0], [[1, 2, 3, 4], 1], [[1, 2, 3, 4], 3], [[], 1], [[], 0], [[1, 1, 1, 1], 2], [[1, 1, 1, 1], 1], [[1, 1, 1, 1], 0], [[1, 3, 5, 6], 0], [[1, 3, ...
INTRODUCTORY
PYTHON3
CODEWARS
2,397
def keep_order(ary, val):
bbde7397b3b381c5aaf44946816daaff
UNKNOWN
How many bees are in the beehive? * bees can be facing UP, DOWN, LEFT, or RIGHT * bees can share parts of other bees Examples Ex1 ``` bee.bee .e..e.. .b..eeb ``` *Answer: 5* Ex2 ``` bee.bee e.e.e.e eeb.eeb ``` *Answer: 8* # Notes * The hive may be empty or null/None/nil/... * Python: the hive is passe...
["from itertools import chain\ndef how_many_bees(hive):\n return bool(hive) and sum(s.count('bee') + s.count('eeb') for s in map(''.join, chain(hive, zip(*hive))))", "def count(it):\n return sum(''.join(x).count('bee') + ''.join(x).count('eeb') for x in it)\n\ndef how_many_bees(hive):\n return count(hive) ...
{"fn_name": "how_many_bees", "inputs": [[null]], "outputs": [[0]]}
INTRODUCTORY
PYTHON3
CODEWARS
8,103
def how_many_bees(hive):
73420a4efa0b7355365305592932229e
UNKNOWN
```if:python,php In this kata you will have to write a function that takes `litres` and `price_per_litre` as arguments. Purchases of 2 or more litres get a discount of 5 cents per litre, purchases of 4 or more litres get a discount of 10 cents per litre, and so on every two litres, up to a maximum discount of 25 cents ...
["def fuel_price(litres, price_per_liter):\n discount = int(min(litres, 10)/2) * 5 / 100\n return round((price_per_liter - discount) * litres, 2)", "fuel_price = lambda l,p: round(l*(p-min(0.05*(l//2), 0.25)), 2)", "from bisect import bisect\n\n\ndef fuel_price(litres, price_per_liter):\n discount = (0, 5, 10,...
{"fn_name": "fuel_price", "inputs": [[10, 21.5], [40, 10], [15, 5.83]], "outputs": [[212.5], [390], [83.7]]}
INTRODUCTORY
PYTHON3
CODEWARS
31,507
def fuel_price(litres, price_per_liter):
c9bd8772b5dacbeb3795c87ee560998b
UNKNOWN
## The Riddle The King of a small country invites 1000 senators to his annual party. As a tradition, each senator brings the King a bottle of wine. Soon after, the Queen discovers that one of the senators is trying to assassinate the King by giving him a bottle of poisoned wine. Unfortunately, they do not know which s...
["def find(r):\n return sum(2**i for i in r)", "def find(rats):\n \"\"\"\n The rule the king should use is the following:\n 1) Label all bottle from 1 to 1000\n 2) Label all rats from 0 to 9\n 3) For each rat r, make it drink the bottle b if the binary representation of b has it's rth bit\...
{"fn_name": "find", "inputs": [[[0]], [[1]], [[2]], [[3]], [[4]], [[5]], [[6]], [[7]], [[8]], [[9]], [[3, 5, 6, 7, 8, 9]], [[0, 3, 5, 4, 9, 8]], [[0, 1, 9, 3, 5]], [[0, 1, 2, 3, 4, 6]], [[0, 1, 3, 4]]], "outputs": [[1], [2], [4], [8], [16], [32], [64], [128], [256], [512], [1000], [825], [555], [95], [27]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,164
def find(r):
d709b40f6e5688ed65baf7af6e683a04
UNKNOWN
We have the numbers with different colours with the sequence: ['red', 'yellow', 'blue']. That sequence colours the numbers in the following way: 1 2 3 4 5 6 7 8 9 10 11 12 13 ..... We have got the following recursive function: ``` f(1) = 1 f(n) = f(n - 1) + n ``` Some terms of this seque...
["D, R = {}, [[], [], []]\nfor i in range(10000):\n D[i] = D.get(i - 1, 0) + i\n R[D[i]%3].append(D[i])\n \ndef same_col_seq(val, k, col):\n r = ['blue', 'red', 'yellow'].index(col)\n return [e for e in R[r] if e > val][:k] ", "def same_col_seq(val, k, col):\n colDct = {'red': 1, 'blue': 0}\n\n ...
{"fn_name": "same_col_seq", "inputs": [[3, 3, "blue"], [100, 4, "red"], [250, 6, "yellow"], [1000, 7, "red"]], "outputs": [[[6, 15, 21]], [[136, 190, 253, 325]], [[]], [[1081, 1225, 1378, 1540, 1711, 1891, 2080]]]}
INTRODUCTORY
PYTHON3
CODEWARS
4,260
def same_col_seq(val, k, col):
314e371073285374085dc3db0fe774d9
UNKNOWN
Given the triangle of consecutive odd numbers: ``` 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 ... ``` Calculate the row sums of this triangle from the row index (starting at index 1) e.g.: ```python row_sum_odd_numbers(1); # 1 row_sum_odd_numbers(2); # 3 ...
["def row_sum_odd_numbers(n):\n #your code here\n return n ** 3", "def row_sum_odd_numbers(n):\n if type(n)==int and n>0:\n return n**3\n else:\n return \"Input a positive integer\"", "def row_sum_odd_numbers(n):\n return n*n*n", "def row_sum_odd_numbers(n):\n return pow(n, 3)", "def row...
{"fn_name": "row_sum_odd_numbers", "inputs": [[1], [2], [13], [19], [41], [42], [74], [86], [93], [101]], "outputs": [[1], [8], [2197], [6859], [68921], [74088], [405224], [636056], [804357], [1030301]]}
INTRODUCTORY
PYTHON3
CODEWARS
18,706
def row_sum_odd_numbers(n):
4e925e398fcaf2b8adf12902360ab22c
UNKNOWN
Given a standard english sentence passed in as a string, write a method that will return a sentence made up of the same words, but sorted by their first letter. However, the method of sorting has a twist to it: * All words that begin with a lower case letter should be at the beginning of the sorted sentence, and sorted...
["from string import punctuation\n\nt = str.maketrans(\"\", \"\", punctuation)\n\ndef pseudo_sort(s):\n a = s.translate(t).split()\n b = sorted(x for x in a if x[0].islower())\n c = sorted((x for x in a if x[0].isupper()), reverse=True)\n return \" \".join(b + c)", "from string import punctuation\ndef pseud...
{"fn_name": "pseudo_sort", "inputs": [["I, habitan of the Alleghanies, treating of him as he is in himself in his own rights"], ["take up the task eternal, and the burden and the lesson"], ["Land of the eastern Chesapeake"], ["And I send these words to Paris with my love"], ["O Liberty! O mate for me!"], ["With Egypt, ...
INTRODUCTORY
PYTHON3
CODEWARS
2,993
def pseudo_sort(st):
f736a18fba283bb26a91a8449ac9f89e
UNKNOWN
You are given array of integers, your task will be to count all pairs in that array and return their count. **Notes:** * Array can be empty or contain only one value; in this case return `0` * If there are more pairs of a certain number, count each pair only once. E.g.: for `[0, 0, 0, 0]` the return value is `2` ...
["def duplicates(arr):\n return sum(arr.count(i)//2 for i in set(arr))", "from collections import Counter\n\ndef duplicates(arr):\n return sum(v//2 for v in list(Counter(arr).values()))\n", "def duplicates(arr):\n return sum((arr.count(n) // 2 for n in set(arr))) ", "from collections import Counter\n\ndef d...
{"fn_name": "duplicates", "inputs": [[[1, 2, 2, 20, 6, 20, 2, 6, 2]], [[1000, 1000]], [[]], [[54]]], "outputs": [[4], [1], [0], [0]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,176
def duplicates(arr):
95f1a2262e86d0480f826889ee48287a
UNKNOWN
## Task In your favorite game, you must shoot a target with a water-gun to gain points. Each target can be worth a different amount of points. You are guaranteed to hit every target that you try to hit. You cannot hit consecutive targets though because targets are only visible for one second (one at a time) and it...
["def target_game(values):\n a = b = 0\n for n in values:\n a, b = b, max(a + n, b)\n return max(a, b)", "def target_game(values):\n max_can_shoot, max_can_not_shoot = 0, 0\n for val in values:\n new = max_can_shoot + val\n max_can_shoot = max(max_can_not_shoot, new)\n max_can...
{"fn_name": "target_game", "inputs": [[[1, 2, 3, 4]], [[1, 3, 1]], [[5, 5, 5, 5, 5]], [[36, 42, 93, 29, 0, 33, 15, 84, 14, 24, 81, 11]], [[73, 80, 40, 86, 14, 96, 10, 56, 61, 84, 82, 36, 85]], [[11, 82, 47, 48, 80, 35, 73, 99, 86, 32, 32]], [[26, 54, 36, 35, 63, 58, 31, 80, 59, 61, 34, 54, 62, 73, 89, 7, 98, 91, 78]], ...
INTRODUCTORY
PYTHON3
CODEWARS
3,303
def target_game(values):
e444872ef5aa38d1227eefdf946a93fe
UNKNOWN
My friend wants a new band name for her band. She like bands that use the formula: "The" + a noun with the first letter capitalized, for example: `"dolphin" -> "The Dolphin"` However, when a noun STARTS and ENDS with the same letter, she likes to repeat the noun twice and connect them together with the first and last...
["def band_name_generator(name):\n return name.capitalize()+name[1:] if name[0]==name[-1] else 'The '+ name.capitalize()", "def band_name_generator(name):\n if name[0] == name[-1]:\n return name.title()+name[1:]\n return (\"the \"+name).title()", "def band_name_generator(name):\n if name[0] != name[-...
{"fn_name": "band_name_generator", "inputs": [["knife"], ["tart"], ["sandles"], ["bed"], ["qq"]], "outputs": [["The Knife"], ["Tartart"], ["Sandlesandles"], ["The Bed"], ["Qqq"]]}
INTRODUCTORY
PYTHON3
CODEWARS
1,394
def band_name_generator(name):
96d22d08e10991eb65acb00e71c430fd
UNKNOWN
Ever since you started work at the grocer, you have been faithfully logging down each item and its category that passes through. One day, your boss walks in and asks, "Why are we just randomly placing the items everywhere? It's too difficult to find anything in this place!" Now's your chance to improve the system, impr...
["def group_groceries(groceries):\n categories = {\"fruit\": [], \"meat\": [], \"other\": [], \"vegetable\": []}\n for entry in groceries.split(\",\"):\n category, item = entry.split(\"_\")\n categories[category if category in categories else \"other\"].append(item)\n return \"\\n\".join([f\"{cat...
{"fn_name": "group_groceries", "inputs": [["fruit_banana,vegetable_carrot,meat_chicken,drink_juice"], ["fruit_banana,vegetable_carrot,fruit_apple,canned_sardines,drink_juice,fruit_orange"], ["vegetable_celery,meat_chicken,meat_beef,fruit_banana,vegetable_carrot,canned_sardines,drink_juice,frozen_fries,fruit_lemon"], ["...
INTRODUCTORY
PYTHON3
CODEWARS
4,152
def group_groceries(groceries):
daf1ba5725f2938127eeaf1b9838d6aa
UNKNOWN
# How much is the fish! (- Scooter ) The ocean is full of colorful fishes. We as programmers want to know the hexadecimal value of these fishes. ## Task Take all hexadecimal valid characters (a,b,c,d,e,f) of the given name and XOR them. Return the result as an integer. ## Input The input is always a string, which can...
["from functools import reduce\nVALID = frozenset('abcdefABCDEF')\n\n\ndef fisHex(s):\n return reduce(lambda b, c: b ^ c, (int(a, 16) for a in s if a in VALID), 0)\n", "def fisHex(name):\n # fish is 15\n hexdict={'A':10,'B':11,'C':12,'D':13,'E':14,'F':15}\n res=0\n for c in name.upper():\n if c in...
{"fn_name": "fisHex", "inputs": [["pufferfish"], ["puffers"], ["balloonfish"], ["blowfish"], ["bubblefish"], ["globefish"], ["swellfish"], ["toadfish"], ["toadies"], ["honey toads"], ["sugar toads"], ["sea squab"], [""], ["Aeneus corydoras"], ["African glass catfish"], ["African lungfish"], ["Aholehole"], ["Airbreathin...
INTRODUCTORY
PYTHON3
CODEWARS
2,993
def fisHex(name):
bdd00a98ebcb1cbb4705b81bfe94e139
UNKNOWN
```if-not:racket Write a function called `repeat_str` which repeats the given string `src` exactly `count` times. ``` ```if:racket Write a function called `repeat-string` which repeats the given string `str` exactly `count` times. ```
["def repeat_str(repeat, string):\n return repeat * string", "def repeat_str(a,b):\n '''crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a crazy\ni am a cr...
{"fn_name": "repeat_str", "inputs": [[4, "a"], [3, "hello "], [2, "abc"]], "outputs": [["aaaa"], ["hello hello hello "], ["abcabc"]]}
INTRODUCTORY
PYTHON3
CODEWARS
55,567
def repeat_str(repeat, string):
5f125bdb7acb72dbd92d20103eee21ef
UNKNOWN
This is a follow up from my kata Insert Dashes. Write a function ```insertDashII(num)``` that will insert dashes ('-') between each two odd numbers and asterisk ('\*') between each even numbers in ```num``` For example: ```insertDashII(454793)``` --> 4547-9-3 ```insertDashII(1012356895)``` --> 10123-56*89-5 Zero...
["def insert_dash2(num):\n \n prev = 0\n out = ''\n\n for dig in str(num):\n if int(dig) % 2 == int(prev) % 2 and int(prev) and int(dig):\n out += '*-'[int(prev) % 2]\n out += dig\n prev = dig\n return out", "import re\n\ndef insert_dash2(num):\n s = str(num)\n s = r...
{"fn_name": "insert_dash2", "inputs": [[454793], [123456], [40546793], [1012356895], [0]], "outputs": [["4547-9-3"], ["123456"], ["4054*67-9-3"], ["10123-56*89-5"], ["0"]]}
INTRODUCTORY
PYTHON3
CODEWARS
2,277
def insert_dash2(num):
861edbfb2f25379b34e0a3b4bd26e50f
UNKNOWN
Uh oh, Someone at the office has dropped all these sequences on the floor and forgotten to label them with their correct bases. We have to fix this before the boss gets back or we're all going to be fired! This is what your years of coding have been leading up to, now is your time to shine! ## Task You will have t...
["def base_finder(seq):\n return len(set(''.join(seq)))", "def base_finder(a):\n return int(max(x[-1] for x in a)) + 1", "def base_finder(seq):\n base = 0\n for i in range(10): #as the sequence will always be 10 numbers long\n number = seq[i] # converting each list element to a string\n for i ...
{"fn_name": "base_finder", "inputs": [[["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]], [["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]], [["1", "2", "3", "4", "5", "6", "10", "11", "12", "13"]], [["301", "302", "303", "304", "305", "310", "311", "312", "313", "314"]], [["50", "51", "61", "53", "54", "60", "52...
INTRODUCTORY
PYTHON3
CODEWARS
1,382
def base_finder(seq):
cdb7ae643d22bf3daa088962d647f8e8
UNKNOWN
Write a function that flattens an `Array` of `Array` objects into a flat `Array`. Your function must only do one level of flattening. ```python flatten [1,2,3] # => [1,2,3] flatten [[1,2,3],["a","b","c"],[1,2,3]] # => [1,2,3,"a","b","c",1,2,3] flatten [[[1,2,3]]] # => [[1,2,3]] ```
["def flatten(lst):\n r = []\n for x in lst:\n if type(x) is list:\n r.extend(x)\n else:\n r.append(x)\n return r ", "def flatten(lst):\n return sum(([i] if not isinstance(i, list) else i for i in lst), [])", "from itertools import chain\ndef flatten(lst):\n try:\n re...
{"fn_name": "flatten", "inputs": [[[[[3], [4], [5]], [9], [9, 9], [8], [[1, 2, 3]]]], [[[[3], [4], [5]], [9], [9, 9], [8], [[1, 2, 3], [77777]]]], [[[[3], [4], [5]], [9], [9, 9], [8], [[1, 2, 3], [77777]], "a"]], [[[[3], [4], [5]], [9], [9, 9], [8], [[1, 2, 3], [77777]], [["a"]]]]], "outputs": [[[[3], [4], [5], 9, 9, 9...
INTRODUCTORY
PYTHON3
CODEWARS
1,291
def flatten(lst):
1d481edb02d7c719fa20dc49df5f7919
UNKNOWN
Similar to the [previous kata](https://www.codewars.com/kata/string-subpattern-recognition-ii/), but this time you need to operate with shuffled strings to identify if they are composed repeating a subpattern Since there is no deterministic way to tell which pattern was really the original one among all the possible p...
["from collections import Counter\nfrom functools import reduce\nfrom fractions import gcd\n\ndef has_subpattern(s):\n c = Counter(s)\n m = reduce(gcd, c.values())\n return ''.join(sorted(k*(v//m) for k,v in c.items()))", "from collections import Counter\nfrom functools import reduce\nfrom math import gcd\n\n\...
{"fn_name": "has_subpattern", "inputs": [["a"], ["aaaa"], ["abcd"], ["babababababababa"], ["bbabbaaabbaaaabb"], ["123a123a123a"], ["123A123a123a"], ["12aa13a21233"], ["12aa13a21233A"], ["abcdabcaccd"]], "outputs": [["a"], ["a"], ["abcd"], ["ab"], ["ab"], ["123a"], ["111222333Aaa"], ["123a"], ["111222333Aaaa"], ["aaabbc...
INTRODUCTORY
PYTHON3
CODEWARS
2,650
def has_subpattern(string):
6711a94afdb19b18ba5e3c9b583ac350
UNKNOWN
Write a function, `gooseFilter` / `goose-filter` / `goose_filter` /` GooseFilter`, that takes an array of strings as an argument and returns a filtered array containing the same elements but with the 'geese' removed. The geese are any strings in the following array, which is pre-populated in your solution: ```python ...
["geese = {\"African\", \"Roman Tufted\", \"Toulouse\", \"Pilgrim\", \"Steinbacher\"}\n\ndef goose_filter(birds):\n return [bird for bird in birds if bird not in geese]", "geese = [\"African\", \"Roman Tufted\", \"Toulouse\", \"Pilgrim\", \"Steinbacher\"]\ndef goose_filter(birds):\n return list(filter(lambda x: x...
{"fn_name": "goose_filter", "inputs": [[["Mallard", "Hook Bill", "African", "Crested", "Pilgrim", "Toulouse", "Blue Swedish"]], [["Mallard", "Barbary", "Hook Bill", "Blue Swedish", "Crested"]], [["African", "Roman Tufted", "Toulouse", "Pilgrim", "Steinbacher"]]], "outputs": [[["Mallard", "Hook Bill", "Crested", "Blue S...
INTRODUCTORY
PYTHON3
CODEWARS
22,112
def goose_filter(birds):
4ed74ab92fcab85cf5a69f9ce07952cd
UNKNOWN
Hi! Welcome to my first kata. In this kata the task is to take a list of integers (positive and negative) and split them according to a simple rule; those ints greater than or equal to the key, and those ints less than the key (the itself key will always be positive). However, in this kata the goal is to sort the num...
["from itertools import groupby\n\n\ndef group_ints(lst, key=0):\n return [list(g) for _, g in groupby(lst, lambda a: a < key)]\n\n\n# PEP8: function name should use snake_case\ngroupInts = group_ints", "from itertools import groupby\n\ndef group_ints(lst, key=0):\n return [list(g) for _, g in groupby(lst, key.__...
{"fn_name": "group_ints", "inputs": [[[], 0], [[1], 1], [[1, 2, 3], 0], [[1, 2, 3], 3], [[1, 1, 1, 0, 0, 6, 10, 5, 10], 6]], "outputs": [[[]], [[[1]]], [[[1, 2, 3]]], [[[1, 2], [3]]], [[[1, 1, 1, 0, 0], [6, 10], [5], [10]]]]}
INTRODUCTORY
PYTHON3
CODEWARS
3,404
def group_ints(lst, key=0):
fe2779c7fbca7fb1f8ae6e1fa58faed5
UNKNOWN
Every non-negative integer N has a binary representation.  For example, 5 can be represented as "101" in binary, 11 as "1011" in binary, and so on.  Note that except for N = 0, there are no leading zeroes in any binary representation. The complement of a binary representation is the number in binary you get when changi...
["class Solution:\n def bitwiseComplement(self, N: int) -> int:\n return (1 << len(bin(N))-2) - N - 1", "class Solution:\n def bitwiseComplement(self, N: int) -> int:\n \n if N==0:\n return 1\n \n dummy_num=N\n \n n=0\n while(dummy_num):\n ...
{"fn_name": "bitwiseComplement", "inputs": [[5]], "outputs": [2]}
INTRODUCTORY
PYTHON3
LEETCODE
810
class Solution: def bitwiseComplement(self, N: int) -> int: