problem_id
int64
2.36k
5k
question
stringlengths
52
14k
solutions
stringlengths
79
675k
input_output
stringlengths
37
505k
difficulty
stringclasses
1 value
url
stringlengths
36
94
starter_code
stringlengths
0
952
3,464
In this kata you should simply determine, whether a given year is a leap year or not. In case you don't know the rules, here they are: * years divisible by 4 are leap years * but years divisible by 100 are **not** leap years * but years divisible by 400 are leap years Additional Notes: * Only valid years (positive i...
["def isLeapYear(year):\n return (year % 100 != 0 and year % 4 == 0) or year % 400 == 0", "from calendar import isleap as isLeapYear", "def isLeapYear(year):\n return year % 4 == 0 and year % 100 != 0 or year % 400 == 0", "def isLeapYear(year):\n return year % 4 is 0 and year % 100 is not 0 or year % 400 == 0"...
{"fn_name": "isLeapYear", "inputs": [[1984], [2000], [2004], [8], [0], [1234], [1100], [1194]], "outputs": [[true], [true], [true], [true], [true], [false], [false], [false]]}
introductory
https://www.codewars.com/kata/526c7363236867513f0005ca
def isLeapYear(year):
3,465
# Description Write a function that checks whether a credit card number is correct or not, using the Luhn algorithm. The algorithm is as follows: * From the rightmost digit, which is the check digit, moving left, double the value of every second digit; if the product of this doubling operation is greater than 9 (e.g....
["def valid_card(card):\n s = list(map(int, str(card.replace(' ', ''))))\n s[0::2] = [d * 2 - 9 if d * 2 > 9 else d * 2 for d in s[0::2]]\n return sum(s) % 10 == 0", "def valid_card(card_number):\n total = 0\n for i, a in enumerate(reversed(card_number.replace(' ', ''))):\n if i % 2:\n ...
{"fn_name": "valid_card", "inputs": [["5457 6238 9823 4311"], ["8895 6238 9323 4311"], ["5457 6238 5568 4311"], ["5457 6238 9323 4311"], ["2222 2222 2222 2224"], ["5457 1125 9323 4311"], ["1252 6238 9323 4311"], ["9999 9999 9999 9995"], ["0000 0300 0000 0000"], ["4444 4444 4444 4448"], ["5457 6238 9323 1252"], ["5457 6...
introductory
https://www.codewars.com/kata/56d55dcdc87df58c81000605
def valid_card(card):
3,466
Create a function that will return ```true``` if the input is in the following date time format ```01-09-2016 01:20``` and ```false``` if it is not. This Kata has been inspired by the Regular Expressions chapter from the book Eloquent JavaScript.
["from re import match\n\n\ndef date_checker(date):\n return bool(match(r'\\d{2}-\\d{2}-\\d{4}\\s\\d{2}:\\d{2}', date))\n", "import re\n\ndef date_checker(date):\n return bool(re.fullmatch(\"\\d\\d-\\d\\d-\\d\\d\\d\\d \\d\\d:\\d\\d\", date))", "# Really, nothing to check if days and motnhs and zeroes or too high?...
{"fn_name": "date_checker", "inputs": [["01-09-2016 01:20"], ["01-09-2016 01;20"], ["01_09_2016 01:20"], ["14-10-1066 12:00"], ["Tenth of January"], ["20 Sep 1988"], ["19-12-2050 13:34"], ["Tue Sep 06 2016 01:46:38 GMT+0100"], ["01-09-2016 00:00"], ["01-09-2016 2:00"]], "outputs": [[true], [false], [false], [true], [fa...
introductory
https://www.codewars.com/kata/57ce0c634001a5f3c7000006
def date_checker(date):
3,467
Create a function that finds the [integral](https://en.wikipedia.org/wiki/Integral) of the expression passed. In order to find the integral all you need to do is add one to the `exponent` (the second argument), and divide the `coefficient` (the first argument) by that new number. For example for `3x^2`, the integral ...
["def integrate(coef, exp):\n exp = exp + 1\n coef = coef / exp if coef % exp else coef // exp\n return f\"{coef}x^{exp}\"", "def integrate(coefficient, exponent):\n return (str(coefficient // (exponent + 1)) + 'x^' + str(exponent + 1)) ", "def integrate(coefficient, exponent):\n return f'{coefficient /...
{"fn_name": "integrate", "inputs": [[3, 2], [12, 5], [20, 1], [40, 3], [90, 2]], "outputs": [["1x^3"], ["2x^6"], ["10x^2"], ["10x^4"], ["30x^3"]]}
introductory
https://www.codewars.com/kata/59811fd8a070625d4c000013
def integrate(coefficient, exponent):
3,468
Complete the function `scramble(str1, str2)` that returns `true` if a portion of ```str1``` characters can be rearranged to match ```str2```, otherwise returns ```false```. **Notes:** * Only lower case letters will be used (a-z). No punctuation or digits will be included. * Performance needs to be considered ## Exam...
["def scramble(s1,s2):\n for c in set(s2):\n if s1.count(c) < s2.count(c):\n return False\n return True", "from collections import Counter\ndef scramble(s1,s2):\n # Counter basically creates a dictionary of counts and letters\n # Using set subtraction, we know that if anything is left over...
{"fn_name": "scramble", "inputs": [["rkqodlw", "world"], ["cedewaraaossoqqyt", "codewars"], ["katas", "steak"], ["scriptjavx", "javascript"], ["scriptingjava", "javascript"], ["scriptsjava", "javascripts"], ["javscripts", "javascript"], ["aabbcamaomsccdd", "commas"], ["commas", "commas"], ["sammoc", "commas"]], "output...
introductory
https://www.codewars.com/kata/55c04b4cc56a697bb0000048
def scramble(s1, s2):
3,469
Complete the function that counts the number of unique consonants in a string (made up of printable ascii characters). Consonants are letters used in English other than `"a", "e", "i", "o", "u"`. We will count `"y"` as a consonant. Remember, your function needs to return the number of unique consonants - disregarding...
["CONSONANTS = set('bcdfghjklmnpqrstvwxyz')\n\ndef count_consonants(text):\n return len(CONSONANTS.intersection(text.lower()))", "def count_consonants(text):\n return len(set(filter(str.isalpha,text.lower())) - set(\"aeiou\"))", "def count_consonants(s):\n return len({c for c in s.lower() if c in 'bcdfghjklmnp...
{"fn_name": "count_consonants", "inputs": [["sillystring"], ["aeiou"], ["abcdefghijklmnopqrstuvwxyz"], ["Count my unique consonants!!"]], "outputs": [[7], [0], [21], [7]]}
introductory
https://www.codewars.com/kata/5a19226646d843de9000007d
def count_consonants(text):
3,470
The goal is to write a pair of functions the first of which will take a string of binary along with a specification of bits, which will return a numeric, signed complement in two's complement format. The second will do the reverse. It will take in an integer along with a number of bits, and return a binary string. ht...
["def to_twos_complement(binary, bits):\n return int(binary.replace(' ', ''), 2) - 2 ** bits * int(binary[0])\n\ndef from_twos_complement(n, bits):\n return '{:0{}b}'.format(n & 2 ** bits - 1, bits)", "def to_twos_complement(b, bits):\n b = b.replace(\" \",\"\")\n return int(b,2) if int(b,2) < 2**(bits-1) e...
{"fn_name": "to_twos_complement", "inputs": [["00000001", 8], ["00000010", 8], ["01111110", 8], ["01111111", 8], ["11111111", 8], ["11111110", 8], ["10000010", 8], ["1000 0000", 8], ["1010 1010 0010 0010 1110 1010 0010 1110", 32], ["1000 0000 1110 1111 0011 0100 1100 1010", 32], ["10110001000100000101100011111000", 32]...
introductory
https://www.codewars.com/kata/58d4785a2285e7795c00013b
def to_twos_complement(binary, bits):
3,471
# MOD 256 without the MOD operator The MOD-operator % (aka mod/modulus/remainder): ``` Returns the remainder of a division operation. The sign of the result is the same as the sign of the first operand. (Different behavior in Python!) ``` The short unbelievable mad story for this kata: I wrote a program and needed th...
["def mod256_without_mod(number):\n return number & 255 ", "def mod256_without_mod(number):\n return number-number//256*256", "def mod256_without_mod(number):\n return number.__mod__(256)\n", "def mod256_without_mod(number):\n return divmod(number, 256)[1]\n", "def mod256_without_mod(num):\n return num & 255"...
{"fn_name": "mod256_without_mod", "inputs": [[254], [256], [258], [-254], [-256], [-258]], "outputs": [[254], [0], [2], [2], [0], [254]]}
introductory
https://www.codewars.com/kata/581e1d083a4820eb4f00004f
def mod256_without_mod(number):
3,472
# Task You have set an alarm for some of the week days. Days of the week are encoded in binary representation like this: ``` 0000001 - Sunday 0000010 - Monday 0000100 - Tuesday 0001000 - Wednesday 0010000 - Thursday 0100000 - Friday 1000000 - Saturday``` For example, if your alarm is set only for Sunday and Friday...
["def next_day_of_week(current_day, available_week_days):\n x = 2 ** current_day\n while not x & available_week_days:\n x = max(1, (x * 2) % 2 ** 7)\n return x.bit_length()", "def next_day_of_week(c, a):\n return next((weekday - 1) % 7 + 1 for weekday in range(c+1, c+8) if (1 << ((weekday-1) % 7)) & ...
{"fn_name": "next_day_of_week", "inputs": [[4, 42], [6, 42], [7, 42]], "outputs": [[6], [2], [2]]}
introductory
https://www.codewars.com/kata/58aa9662c55ffbdceb000101
def next_day_of_week(current_day, available_week_days):
3,473
In this Kata, you will write a function `doubles` that will remove double string characters that are adjacent to each other. For example: `doubles('abbcccdddda') = 'aca'`, because, from left to right: ```Haskell a) There is only one 'a' on the left hand side, so it stays. b) The 2 b's disappear because we are removin...
["def doubles(s):\n cs = []\n for c in s:\n if cs and cs[-1] == c:\n cs.pop()\n else:\n cs.append(c)\n return ''.join(cs)", "def doubles(s):\n for i in s:\n if i*2 in s:\n \n s = s.replace(i*2, '')\n return s", "import re\n\ndef doubles(s):...
{"fn_name": "doubles", "inputs": [["abbbzz"], ["zzzzykkkd"], ["abbcccdddda"], ["vvvvvoiiiiin"], ["rrrmooomqqqqj"], ["xxbnnnnnyaaaaam"], ["qqqqqqnpppgooooonpppppqmmmmmc"], ["qqqqqwwwx"], ["jjjfzzzzzzsddgrrrrru"], ["jjjjjfuuuutgggggqppdaaas"], ["iiiiibllllllyqqqqqbiiiiiituuf"], ["mmmmmmuzzqllllmqqqp"]], "outputs": [["ab"...
introductory
https://www.codewars.com/kata/5a145ab08ba9148dd6000094
def doubles(s):
3,474
## Task Using `n` as a parameter in the function `pattern`, where `n>0`, complete the codes to get the pattern (take the help of examples): **Note:** There is no newline in the end (after the pattern ends) ### Examples `pattern(3)` should return `"1\n1*2\n1**3"`, e.g. the following: ``` 1 1*2 1**3 ``` `pattern(10...
["def pattern(n):\n return '\\n'.join(['1'] + ['1' + '*' * (i-1) + str(i) for i in range(2, n+1)])\n", "def pattern(n):\n s = ''\n for i in range(n):\n if i == 0:\n s += '1\\n'\n else:\n s += '1{}{}\\n'.format('*' * i, i + 1)\n \n return s.rstrip('\\n')\n", "def patter...
{"fn_name": "pattern", "inputs": [[3], [7], [20]], "outputs": [["1\n1*2\n1**3"], ["1\n1*2\n1**3\n1***4\n1****5\n1*****6\n1******7"], ["1\n1*2\n1**3\n1***4\n1****5\n1*****6\n1******7\n1*******8\n1********9\n1*********10\n1**********11\n1***********12\n1************13\n1*************14\n1**************15\n1**************...
introductory
https://www.codewars.com/kata/5631213916d70a0979000066
def pattern(n):
3,475
Implement a function/class, which should return an integer if the input string is in one of the formats specified below, or `null/nil/None` otherwise. Format: * Optional `-` or `+` * Base prefix `0b` (binary), `0x` (hexadecimal), `0o` (octal), or in case of no prefix decimal. * Digits depending on base Any extra char...
["import re\n\ndef to_integer(s):\n if re.match(\"\\A[+-]?(\\d+|0b[01]+|0o[0-7]+|0x[0-9a-fA-F]+)\\Z\", s):\n return int(s, 10 if s[1:].isdigit() else 0)", "from re import compile, match\n\nREGEX = compile(r'[+-]?(0(?P<base>[bxo]))?[\\d\\w]+\\Z')\n\n\ndef to_integer(strng):\n try:\n return int(strng,...
{"fn_name": "to_integer", "inputs": [["123"], ["0x123"], ["0o123"], ["0123"], ["123 "], [" 123"], ["0b1010"], ["+123"], ["-123"], ["0B1010"], ["0b12"], ["-0x123"], ["-0o123"], ["-0123"], ["123\n"], ["\n123"], ["-0b1010"], ["0xDEADbeef"], ["0X123"], ["0O123"], ["0o18"]], "outputs": [[123], [291], [83], [123], [null], [n...
introductory
https://www.codewars.com/kata/5682e1082cc7862db5000039
def to_integer(string):
3,476
# Task The number is considered to be `unlucky` if it does not have digits `4` and `7` and is divisible by `13`. Please count all unlucky numbers not greater than `n`. # Example For `n = 20`, the result should be `2` (numbers `0 and 13`). For `n = 100`, the result should be `7` (numbers `0, 13, 26, 39, 52, 65, a...
["def unlucky_number(n):\n return sum(not ('4' in s or '7' in s) for s in map(str, range(0, n+1, 13)))", "def unlucky_number(n):\n return sum(1 for k in range(0, n+1, 13) if not set(str(k)) & {\"4\", \"7\"})\n", "def unlucky_number(n):\n return sum(x % 13 == 0 and '4' not in str(x) and '7' not in str(x) for x in...
{"fn_name": "unlucky_number", "inputs": [[20], [100], [1000], [1000000]], "outputs": [[2], [7], [40], [20182]]}
introductory
https://www.codewars.com/kata/58b65c5e8b98b2e4fa000034
def unlucky_number(n):
3,477
Define a method that accepts 2 strings as parameters. The method returns the first string sorted by the second. ```python sort_string("foos", "of") == "oofs" sort_string("string", "gnirts") == "gnirts" sort_string("banana", "abn") == "aaabnn" ``` To elaborate, the second string defines the ordering. It is po...
["def sort_string(s, ordering):\n answer = ''\n for o in ordering:\n answer += o * s.count(o)\n s = s.replace(o,'')\n return answer + s ", "def sort_string(s, ordering):\n dct = {c:-i for i,c in enumerate(reversed(ordering))}\n return ''.join(sorted(s,key=lambda c:dct.get(c,1)))", "sort_str...
{"fn_name": "sort_string", "inputs": [["banana", "abn"], ["banana", "xyz"], ["banana", "an"], ["foos", "of"], ["string", "gnirts"], ["banana", "a"], ["bungholio", "aacbuoldiiaoh"], ["fumyarhncujlj", "nsejcwn"]], "outputs": [["aaabnn"], ["banana"], ["aaannb"], ["oofs"], ["gnirts"], ["aaabnn"], ["buoolihng"], ["njjcfumya...
introductory
https://www.codewars.com/kata/536c6b8749aa8b3c2600029a
def sort_string(s, ordering):
3,478
Magic The Gathering is a collectible card game that features wizards battling against each other with spells and creature summons. The game itself can be quite complicated to learn. In this series of katas, we'll be solving some of the situations that arise during gameplay. You won't need any prior knowledge of the gam...
["from itertools import zip_longest\n\ndef battle(player1, player2):\n result = {'player1': [], 'player2': []}\n for (p1, t1), (p2, t2) in zip_longest(player1, player2, fillvalue=[0,0]):\n if t1 > p2:\n result['player1'].append([p1,t1])\n if t2 > p1:\n result['player2'].append(...
{"fn_name": "battle", "inputs": [[[[2, 3], [1, 4]], [[3, 3], [4, 1]]], [[], []], [[[1, 1]], [[1, 1]]], [[[2, 1]], [[2, 1]]], [[[1, 2]], [[1, 2]]], [[[2, 3]], [[3, 2]]], [[[2, 7]], [[3, 5]]], [[[2, 5]], [[6, 6]]], [[[6, 6]], [[2, 5]]], [[], [[1, 1], [2, 2]]], [[[1, 1], [2, 2]], []], [[[1, 3], [3, 5], [4, 6], [5, 2]], [[...
introductory
https://www.codewars.com/kata/567af2c8b46252f78400004d
def battle(player1, player2):
3,479
We need a function (for commercial purposes) that may perform integer partitions with some constraints. The function should select how many elements each partition should have. The function should discard some "forbidden" values in each partition. So, create ```part_const()```, that receives three arguments. ```part_co...
["def p(t,k,n,l=1):\n if t<l: pass\n elif k==1 and t!=n: yield [t]\n else: yield from ([m]+s for m in range(l,t-l+1) for s in p(t-m,k-1,n,m) if m!=n)\n\ndef part_const(t,k,n): return sum(1 for _ in p(t,k,n))", "def part_const(n, k, num):\n return part(n, k) - part(n-(num or n), k-1)\n\ndef part(n, k):\n ...
{"fn_name": "part_const", "inputs": [[10, 3, 2], [10, 3, 0], [10, 4, 1], [10, 5, 3], [15, 5, 3], [15, 5, 4], [15, 3, 3]], "outputs": [[4], [8], [2], [4], [15], [19], [13]]}
introductory
https://www.codewars.com/kata/55fbb7063097cf0b6b000032
def part_const(n, k, num):
3,480
As the title suggests, this is the hard-core version of another neat kata. The task is simple to explain: simply sum all the numbers from the first parameter being the beginning to the second parameter being the upper limit (possibly included), going in steps expressed by the third parameter: ```python sequence_sum(...
["# from math import copysign\ndef sequence_sum(a, b, step):\n n = (b-a)//step\n return 0 if n<0 else (n+1)*(n*step+a+a)//2", "def sequence_sum(b, e, s):\n q, r = divmod(e - b, s)\n return (b + e - r) * max(q + 1, 0) // 2", "def sequence_sum(start, stop, step):\n n = (stop - start) // step\n last = st...
{"fn_name": "sequence_sum", "inputs": [[2, 6, 2], [1, 5, 1], [1, 5, 3], [-1, -5, -3], [16, 15, 3], [-24, -2, 22], [-2, 4, 658], [780, 6851543, 5], [9383, 71418, 2], [20, 673388797, 5]], "outputs": [[12], [15], [5], [-5], [0], [-26], [-2], [4694363402480], [1253127200], [45345247259849570]]}
introductory
https://www.codewars.com/kata/587a88a208236efe8500008b
def sequence_sum(b, e, s):
3,481
Write a method that takes a string as an argument and groups the number of time each character appears in the string as a hash sorted by the highest number of occurrences. The characters should be sorted alphabetically e.g: ```python get_char_count("cba") == {1: ["a", "b", "c"]} ``` You should ignore spaces, special...
["def get_char_count(s):\n counts = {}\n for c in (c.lower() for c in s if c.isalnum()):\n counts[c] = counts[c] + 1 if c in counts else 1\n m = {}\n for k, v in counts.items():\n m[v] = sorted(m[v] + [k]) if v in m else [k]\n return m", "from collections import Counter, defaultdict\nfrom b...
{"fn_name": "get_char_count", "inputs": [["Get me the bacon!"], ["Codewars is bacon"], ["France is also bacon"], ["AaAAaAAabB!B!B3b23jdc"], [""], ["!!!@@@"], ["Mississippi"], ["Hello. Hello? HELLO!"], ["aaa...bb...c!"], ["abc123"], ["aaabbbccc"]], "outputs": [[{"3": ["e"], "2": ["t"], "1": ["a", "b", "c", "g", "h", "m"...
introductory
https://www.codewars.com/kata/543e8390386034b63b001f31
def get_char_count(s):
3,482
# Definition **_Extra perfect number_** *is the number that* **_first_** and **_last_** *bits* are **_set bits_**. ____ # Task **_Given_** *a positive integer* `N` , **_Return_** the **_extra perfect numbers_** *in range from* `1` to `N` . ____ # Warm-up (Highly recommended) # [Playing With Numbers Series]...
["def extra_perfect(n):\n return list(range(1,n+1,2))", "def extra_perfect(n):\n return list(range(1, n + 1, 2))\n", "def extra_perfect(n):\n return [i for i in range(n+1) if i % 2 != 0] ", "def extra_perfect(n):\n return [i for i in range(1,n+1) if bin(i)[2]=='1' and bin(i)[-1]=='1']", "def extra_perfect(n...
{"fn_name": "extra_perfect", "inputs": [[3], [5], [7], [28], [39]], "outputs": [[[1, 3]], [[1, 3, 5]], [[1, 3, 5, 7]], [[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27]], [[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39]]]}
introductory
https://www.codewars.com/kata/5a662a02e626c54e87000123
def extra_perfect(n):
3,483
Create a program that will take in a string as input and, if there are duplicates of more than two alphabetical characters in the string, returns the string with all the extra characters in a bracket. For example, the input "aaaabbcdefffffffg" should return "aa[aa]bbcdeff[fffff]g" Please also ensure that the input ...
["import re\ndef string_parse(string):\n return re.sub(r'(.)\\1(\\1+)', r'\\1\\1[\\2]', string) if isinstance(string, str) else 'Please enter a valid string'", "import re\ndef string_parse(s):\n if not isinstance(s, str): return \"Please enter a valid string\"\n for l in set(s):\n s = re.sub(r\"(%s%s)(%...
{"fn_name": "string_parse", "inputs": [["aaaabbcdefffffffg"], [3], ["boopdedoop"], ["helloookat"], [true], [""], ["aAAabbcdeffFfFffg"], ["aAAabbcdeFFFffffg"], [{}], [[5.3]]], "outputs": [["aa[aa]bbcdeff[fffff]g"], ["Please enter a valid string"], ["boopdedoop"], ["helloo[o]kat"], ["Please enter a valid string"], [""], ...
introductory
https://www.codewars.com/kata/5411c4205f3a7fd3f90009ea
def string_parse(string):
3,484
This kata requires you to convert minutes (`int`) to hours and minutes in the format `hh:mm` (`string`). If the input is `0` or negative value, then you should return `"00:00"` **Hint:** use the modulo operation to solve this challenge. The modulo operation simply returns the remainder after a division. For example t...
["def time_convert(num):\n return \"{:02d}:{:02d}\".format(*divmod(max(num, 0), 60))", "def time_convert(num):\n if num <= 0:\n return '00:00'\n return f'{num//60:02}:{num%60:02}'", "def time_convert(num):\n a=num//60\n b=num%60\n if num<=0:\n return '00:00'\n elif 0<num<10:\n ...
{"fn_name": "time_convert", "inputs": [[0], [-6], [8], [32], [75], [63], [134], [180], [970], [565757]], "outputs": [["00:00"], ["00:00"], ["00:08"], ["00:32"], ["01:15"], ["01:03"], ["02:14"], ["03:00"], ["16:10"], ["9429:17"]]}
introductory
https://www.codewars.com/kata/5a084a098ba9146690000969
def time_convert(num):
3,485
Don't Drink the Water Given a two-dimensional array representation of a glass of mixed liquids, sort the array such that the liquids appear in the glass based on their density. (Lower density floats to the top) The width of the glass will not change from top to bottom. ``` ====================== | Density Chart ...
["DENSITY = {'H': 1.36, 'W': 1, 'A': 0.87, 'O': 0.8}\n\n\ndef separate_liquids(glass):\n if not glass:\n return []\n column = len(glass[0])\n liquids = sorted((b for a in glass for b in a), key=lambda c: DENSITY[c])\n return [liquids[d:d + column] for d in range(0, len(liquids), column)]\n", "def sep...
{"fn_name": "separate_liquids", "inputs": [[[["H", "H", "W", "O"], ["W", "W", "O", "W"], ["H", "H", "O", "O"]]], [[["A", "A", "O", "H"], ["A", "H", "W", "O"], ["W", "W", "A", "W"], ["H", "H", "O", "O"]]], [[["A", "H", "W", "O"]]], [[["A"], ["H"], ["W"], ["O"]]], [[]]], "outputs": [[[["O", "O", "O", "O"], ["W", "W", "W"...
introductory
https://www.codewars.com/kata/562e6df5cf2d3908ad00019e
def separate_liquids(glass):
3,486
# Task The game starts with `n` people standing in a circle. The presenter counts `m` people starting with the first one, and gives `1` coin to each of them. The rest of the players receive `2` coins each. After that, the last person who received `1` coin leaves the circle, giving everything he had to the next partici...
["def find_last(n, m):\n li, start = [[0, i + 1] for i in range(n)], 0 # form list of circle with numbers\n while len(li) != 1:\n prev, l_ = li[start][1], len(li) # starting point and length of circle\n for k in range(m): # adding 1 to first m players i...
{"fn_name": "find_last", "inputs": [[5, 1], [8, 3], [75, 34], [82, 49], [73, 38], [86, 71], [61, 17], [42, 38], [29, 5], [64, 49], [61, 20], [88, 52]], "outputs": [[[5, 24]], [[7, 51]], [[35, 4238]], [[48, 5091]], [[61, 3996]], [[10, 6275]], [[26, 3000]], [[12, 1578]], [[28, 740]], [[43, 3327]], [[32, 2922]], [[59, 585...
introductory
https://www.codewars.com/kata/5bb5e174528b2908930005b5
def find_last(n, m):
3,487
Let's pretend your company just hired your friend from college and paid you a referral bonus. Awesome! To celebrate, you're taking your team out to the terrible dive bar next door and using the referral bonus to buy, and build, the largest three-dimensional beer can pyramid you can. And then probably drink those beers,...
["def beeramid(bonus, price):\n beers = bonus // price\n levels = 0\n \n while beers >= (levels + 1) ** 2:\n levels += 1\n beers -= levels ** 2\n \n return levels", "from itertools import count\n\ndef beeramid(bonus, price):\n bonus = max(bonus,0)\n n = bonus//price\n return n...
{"fn_name": "beeramid", "inputs": [[9, 2], [10, 2], [11, 2], [21, 1.5], [454, 5], [455, 5], [4, 4], [3, 4], [0, 4], [-1, 4]], "outputs": [[1], [2], [2], [3], [5], [6], [1], [0], [0], [0]]}
introductory
https://www.codewars.com/kata/51e04f6b544cf3f6550000c1
def beeramid(bonus, price):
3,488
Switch/Case - Bug Fixing #6 Oh no! Timmy's evalObject function doesn't work. He uses Switch/Cases to evaluate the given properties of an object, can you fix timmy's function?
["def eval_object(v):\n return {\"+\": v['a']+v['b'],\n \"-\": v['a']-v['b'],\n \"/\": v['a']/v['b'],\n \"*\": v['a']*v['b'],\n \"%\": v['a']%v['b'],\n \"**\": v['a']**v['b'], }.get(v['operation'])", "def eval_object(v):\n return eval(\"{a}{operation}{b}\".for...
{"fn_name": "eval_object", "inputs": [[{"a": 1, "b": 1, "operation": "+"}], [{"a": 1, "b": 1, "operation": "-"}], [{"a": 1, "b": 1, "operation": "/"}], [{"a": 1, "b": 1, "operation": "*"}], [{"a": 1, "b": 1, "operation": "%"}], [{"a": 1, "b": 1, "operation": "**"}]], "outputs": [[2], [0], [1], [1], [0], [1]]}
introductory
https://www.codewars.com/kata/55c933c115a8c426ac000082
def eval_object(v):
3,489
Your task is to determine how many files of the copy queue you will be able to save into your Hard Disk Drive. The files must be saved in the order they appear in the queue. ### Input: * Array of file sizes `(0 <= s <= 100)` * Capacity of the HD `(0 <= c <= 500)` ### Output: * Number of files that can be fully sav...
["def save(sizes, hd): \n for i,s in enumerate(sizes):\n if hd < s: return i\n hd -= s\n return len(sizes)", "def save(sizes, hd): \n return save(sizes[:-1], hd) if sum(sizes) > hd else len(sizes)", "from bisect import bisect\nfrom itertools import accumulate\n\n\ndef save(sizes, hd): \n retur...
{"fn_name": "save", "inputs": [[[4, 4, 4, 3, 3], 12], [[4, 4, 4, 3, 3], 11], [[4, 8, 15, 16, 23, 42], 108], [[13], 13], [[1, 2, 3, 4], 250], [[100], 500], [[11, 13, 15, 17, 19], 8], [[45], 12]], "outputs": [[3], [2], [6], [1], [4], [1], [0], [0]]}
introductory
https://www.codewars.com/kata/5d49c93d089c6e000ff8428c
def save(sizes, hd):
3,490
Given an array of positive integers, replace every element with the least greater element to its right. If there is no greater element to its right, replace it with -1. For instance, given the array `[8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28]`, the desired output is `[18, 63, 80, 25, 32, 43,...
["def array_manip(array):\n return [min([a for a in array[i+1:] if a > array[i]], default=-1) for i in range(len(array))]", "def array_manip(array):\n return [min((r for r in array[i:] if r > n), default=-1) for i, n in enumerate(array, 1)]\n", "# This is O(n\u00b2), it's a bad solution\n# You can do it in O(n*lo...
{"fn_name": "array_manip", "inputs": [[[8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28]], [[2, 4, 18, 16, 7, 3, 9, 13, 18, 10]]], "outputs": [[[18, 63, 80, 25, 32, 43, 80, 93, 80, 25, 93, -1, 28, -1, -1]], [[3, 7, -1, 18, 9, 9, 10, 18, -1, -1]]]}
introductory
https://www.codewars.com/kata/58d5e6c114286c8594000027
def array_manip(array):
3,491
Find the longest substring within a string that contains at most 2 unique characters. ``` substring("a") => "a" substring("aaa") => "aaa" substring("abacd") => "aba" substring("abacddcd") => "cddcd" substring("cefageaacceaccacca") => "accacca" ``` This function will take alphanumeric characters as input. In cases wh...
["def substring(s):\n r, rm = [], []\n for i, x in enumerate(s):\n if x in r or len(set(r)) < 2:\n r += x;\n else:\n if len(r) > len(rm): rm = r[:]\n r = [y for y in r[-1::-1] if y == r[-1]] + [x]\n if len(r) > len(rm): rm = r[:]\n return ''.join(rm)", "def sub...
{"fn_name": "substring", "inputs": [[""], ["a"], ["aa"], ["aaa"], ["ab"], ["aba"], ["abc"], ["abcba"], ["bbacc"], ["ccddeeff"], ["bbacddddcdd"], ["abcddeejabbedsajaajjaajjajajajjajjaaacedajajaj"], ["aaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbccccccccccccccccccccddddddddddddddddddddeeeeeeeeeeeeeeeeeeeeffffffffffffffffffffg...
introductory
https://www.codewars.com/kata/55bc0c54147a98798f00003e
def substring(s):
3,492
There are 32 letters in the Polish alphabet: 9 vowels and 23 consonants. Your task is to change the letters with diacritics: ``` ą -> a, ć -> c, ę -> e, ł -> l, ń -> n, ó -> o, ś -> s, ź -> z, ż -> z ``` and print out the string without the use of the Polish letters. For example: ``` "Jędrzej Błądziński" --> "J...
["def correct_polish_letters(s):\n return s.translate(str.maketrans(\"\u0105\u0107\u0119\u0142\u0144\u00f3\u015b\u017a\u017c\", \"acelnoszz\"))", "def correct_polish_letters(st):\n l = \"\u0105\u0107\u0119\u0142\u0144\u00f3\u015b\u017a\u017c\"\n lt = \"acelnoszz\"\n for i in range(len(l)):\n st = st....
{"fn_name": "correct_polish_letters", "inputs": [["J\u0119drzej B\u0142\u0105dzi\u0144ski"], ["Lech Wa\u0142\u0119sa"], ["Maria Sk\u0142odowska-Curie"], ["W\u0142adys\u0142aw Reymont"], ["Miko\u0142aj Kopernik"], ["J\u00f3zef Pi\u0142sudski"], ["Czes\u0142aw Mi\u0142osz"], ["Agnieszka Radwa\u0144ska"], ["Wojciech Szcz\...
introductory
https://www.codewars.com/kata/57ab2d6072292dbf7c000039
def correct_polish_letters(st):
3,493
You've been collecting change all day, and it's starting to pile up in your pocket, but you're too lazy to see how much you've found. Good thing you can code! Create ```change_count()``` to return a dollar amount of how much change you have! Valid types of change include: ``` penny: 0.01 nickel: 0.05 dime: 0.10 quar...
["#Remember you have a CHANGE dictionary to work with ;)\n\ndef change_count(change):\n money = {'penny' : 0.01, 'nickel' : 0.05, 'dime' : 0.10, 'quarter' : 0.25, 'dollar' : 1.00}\n count = 0\n for coin in change.split():\n count += money[coin]\n result = \"%.2f\" % count\n return '$' + result\n ...
{"fn_name": "change_count", "inputs": [["dime penny dollar"], ["dime penny nickel"], ["quarter quarter"], ["dollar penny dollar"], ["dollar dollar dollar dollar dollar dollar dollar dollar dollar dollar penny"]], "outputs": [["$1.11"], ["$0.16"], ["$0.50"], ["$2.01"], ["$10.01"]]}
introductory
https://www.codewars.com/kata/57e1857d333d8e0f76002169
def change_count(change):
3,494
Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks untouched. ## Examples ```python pig_it('Pig latin is cool') # igPay atinlay siay oolcay pig_it('Hello world !') # elloHay orldway ! ``` ```C++ pig_it("Pig latin is cool"); // igPay atinlay siay oo...
["def pig_it(text):\n lst = text.split()\n return ' '.join( [word[1:] + word[:1] + 'ay' if word.isalpha() else word for word in lst])\n", "def pig_it(text):\n return \" \".join(x[1:] + x[0] + \"ay\" if x.isalnum() else x for x in text.split())", "def pig_it(text):\n res = []\n \n for i in text.split()...
{"fn_name": "pig_it", "inputs": [["Pig latin is cool"], ["This is my string"]], "outputs": [["igPay atinlay siay oolcay"], ["hisTay siay ymay tringsay"]]}
introductory
https://www.codewars.com/kata/520b9d2ad5c005041100000f
def pig_it(text):
3,495
In this Kata, we are going to see how a Hash (or Map or dict) can be used to keep track of characters in a string. Consider two strings `"aabcdefg"` and `"fbd"`. How many characters do we have to remove from the first string to get the second string? Although not the only way to solve this, we could create a Hash of...
["from collections import Counter\n\ndef solve(a,b):\n return 0 if Counter(b) - Counter(a) else len(a) - len(b)", "def solve(a,b):\n for x in set(b):\n if a.count(x) >= b.count(x):\n continue\n else:\n return 0\n return len(a)-len(b)", "def solve(a,b):\n print((a,b))\n ...
{"fn_name": "solve", "inputs": [["xyz", "yxz"], ["abcxyz", "ayxz"], ["abcdexyz", "yxz"], ["xyz", "yxxz"], ["abdegfg", "ffdb"], ["aabcdefg", "fbd"]], "outputs": [[0], [2], [5], [0], [0], [5]]}
introductory
https://www.codewars.com/kata/59fab1f0c9fc0e7cd4000072
def solve(a,b):
3,496
In this kata you will be given a sequence of the dimensions of rectangles ( sequence with width and length ) and circles ( radius - just a number ). Your task is to return a new sequence of dimensions, sorted ascending by area. For example, ```python seq = [ (4.23, 6.43), 1.23, 3.444, (1.342, 3.212) ] # [ rectangle...
["def sort_by_area(seq): \n def func(x):\n if isinstance(x, tuple):\n return x[0] * x[1]\n else:\n return 3.14 * x * x\n return sorted(seq, key=func)", "from math import pi as PI\n\ndef circle(r): return r*r*PI\ndef rect(a,b): return a*b\ndef getArea(r): ...
{"fn_name": "sort_by_area", "inputs": [[[]]], "outputs": [[[]]]}
introductory
https://www.codewars.com/kata/5a1ebc2480171f29cf0000e5
def sort_by_area(seq):
3,497
A [perfect power](https://en.wikipedia.org/wiki/Perfect_power) is a classification of positive integers: > In mathematics, a **perfect power** is a positive integer that can be expressed as an integer power of another positive integer. More formally, n is a perfect power if there exist natural numbers m > 1, and k > 1...
["from math import ceil, log, sqrt\n\ndef isPP(n):\n for b in range(2, int(sqrt(n)) + 1):\n e = int(round(log(n, b)))\n if b ** e == n:\n return [b, e]\n return None\n", "def isPP(n):\n for i in range(2, int(n**.5) + 1):\n number = n\n times = 0\n while number % i ...
{"fn_name": "isPP", "inputs": [[4], [9], [5]], "outputs": [[[2, 2]], [[3, 2]], [null]]}
introductory
https://www.codewars.com/kata/54d4c8b08776e4ad92000835
def isPP(n):
3,498
## Overview Resistors are electrical components marked with colorful stripes/bands to indicate both their resistance value in ohms and how tight a tolerance that value has. While you could always get a tattoo like Jimmie Rodgers to help you remember the resistor color codes, in the meantime, you can write a function th...
["code = {'black': 0, 'brown': 1, 'red': 2, 'orange': 3, 'yellow': 4,\n'green': 5, 'blue': 6, 'violet': 7, 'gray': 8, 'white': 9,\n'gold': 5, 'silver': 10, '': 20}\ndef decode_resistor_colors(bands):\n colors = (bands + ' ').split(' ')\n value = 10 * code[colors[0]] + code[colors[1]]\n value *= 10 ** code[colo...
{"fn_name": "decode_resistor_colors", "inputs": [["yellow violet black"], ["yellow violet red gold"], ["brown black green silver"], ["brown black black"], ["brown black brown gold"], ["red red brown"], ["orange orange brown gold"], ["yellow violet brown silver"], ["blue gray brown"], ["brown black red silver"], ["brown...
introductory
https://www.codewars.com/kata/57cf3dad05c186ba22000348
def decode_resistor_colors(bands):
3,499
Converting a normal (12-hour) time like "8:30 am" or "8:30 pm" to 24-hour time (like "0830" or "2030") sounds easy enough, right? Well, let's see if you can do it! You will have to define a function named "to24hourtime", and you will be given an hour (always in the range of 1 to 12, inclusive), a minute (always in th...
["def to24hourtime(hour, minute, period):\n return '%02d%02d' % (hour % 12 + 12 * (period == 'pm'), minute)", "from datetime import datetime\n\ndef to24hourtime(h, m, p):\n return datetime.strptime('%02d%02d%s' % (h, m, p.upper()), '%I%M%p').strftime('%H%M')", "from datetime import datetime\n\ndef to24hourtime(h,...
{"fn_name": "to24hourtime", "inputs": [[12, 0, "am"], [12, 1, "am"], [12, 2, "am"], [12, 3, "am"], [12, 4, "am"], [12, 5, "am"], [12, 6, "am"], [12, 7, "am"], [12, 8, "am"], [12, 9, "am"], [12, 10, "am"], [12, 11, "am"], [12, 12, "am"], [12, 13, "am"], [12, 14, "am"], [12, 15, "am"], [12, 16, "am"], [12, 17, "am"], [12...
introductory
https://www.codewars.com/kata/59b0a6da44a4b7080300008a
def to24hourtime(hour, minute, period):
3,500
Write function RemoveExclamationMarks which removes all exclamation marks from a given string.
["def remove_exclamation_marks(s):\n return s.replace('!', '')", "def remove_exclamation_marks(s):\n \"\"\"Removes exclamation marks from given input.\n \"\"\"\n return s.replace('!', '')", "remove_exclamation_marks=lambda s: s.replace(\"!\",\"\")", "def remove_exclamation_marks(s):\n x = s.replace(\"!\"...
{"fn_name": "remove_exclamation_marks", "inputs": [["Hello World!"], ["Hello World!!!"], ["Hi! Hello!"], [""], ["Oh, no!!!"]], "outputs": [["Hello World"], ["Hello World"], ["Hi Hello"], [""], ["Oh, no"]]}
introductory
https://www.codewars.com/kata/57a0885cbb9944e24c00008e
def remove_exclamation_marks(s):
3,501
You have a grid with `$m$` rows and `$n$` columns. Return the number of unique ways that start from the top-left corner and go to the bottom-right corner. You are only allowed to move right and down. For example, in the below grid of `$2$` rows and `$3$` columns, there are `$10$` unique paths: ``` o----o----o----o | ...
["from math import factorial as f\nnumber_of_routes=lambda m,n:f(m+n)//(f(m)*f(n))", "import sys\n\nsys.setrecursionlimit(1200)\n\ncache = {}\n\ndef number_of_routes(m, n):\n if m == 0 or n == 0: return 1\n if m > n: return number_of_routes(n, m)\n result = cache.get((m,n))\n if result is None:\n cac...
{"fn_name": "number_of_routes", "inputs": [[1, 1], [5, 1], [3, 4], [5, 6], [10, 10], [100, 3], [123, 456]], "outputs": [[2], [6], [35], [462], [184756], [176851], [448843261729071620474858205566477025894357385375655014634306680560209909590802545266425906052279365647506075241055256064119806400]]}
introductory
https://www.codewars.com/kata/56a127b14d9687bba200004d
def number_of_routes(m, n):
3,502
Complete the solution so that it returns true if it contains any duplicate argument values. Any number of arguments may be passed into the function. The array values passed in will only be strings or numbers. The only valid return values are `true` and `false`. Examples: ``` solution(1, 2, 3) --> false s...
["def solution(*args):\n return len(args) != len(set(args))", "def solution(*args):\n print (args)\n result = {}\n for x in args:\n if x in result:\n return True\n else :\n result[x] = 1\n return False\n", "def solution(*args):\n return len(args) > len(set(args))",...
{"fn_name": "solution", "inputs": [[1, 2, 3, 1, 2], [1, 1], [1, 0], ["a", "b"], ["a", "b", "a"], [1, 2, 42, 3, 4, 5, 42], ["a", "b", "c", "d"], ["a", "b", "c", "c"], ["a", "b", "c", "d", "e", "f", "f", "b"]], "outputs": [[true], [true], [false], [false], [true], [true], [false], [true], [true]]}
introductory
https://www.codewars.com/kata/520d9c27e9940532eb00018e
def solution(*args):
3,503
The number ```89``` is the first integer with more than one digit that fulfills the property partially introduced in the title of this kata. What's the use of saying "Eureka"? Because this sum gives the same number. In effect: ```89 = 8^1 + 9^2``` The next number in having this property is ```135```. See this prop...
["def dig_pow(n):\n return sum(int(x)**y for y,x in enumerate(str(n), 1))\n\ndef sum_dig_pow(a, b): \n return [x for x in range(a,b + 1) if x == dig_pow(x)]", "def sum_dig_pow(a, b):\n return [x for x in range(a, b+1) if sum(int(d)**i for i, d in enumerate(str(x), 1)) == x]", "def sum_dig_pow(a, b): # range(a,...
{"fn_name": "sum_dig_pow", "inputs": [[1, 100], [10, 89], [10, 100], [90, 100], [90, 150], [50, 150], [10, 150], [89, 135]], "outputs": [[[1, 2, 3, 4, 5, 6, 7, 8, 9, 89]], [[89]], [[89]], [[]], [[135]], [[89, 135]], [[89, 135]], [[89, 135]]]}
introductory
https://www.codewars.com/kata/5626b561280a42ecc50000d1
def sum_dig_pow(a, b):
3,504
Your task is to create a new implementation of `modpow` so that it computes `(x^y)%n` for large `y`. The problem with the current implementation is that the output of `Math.pow` is so large on our inputs that it won't fit in a 64-bit float. You're also going to need to be efficient, because we'll be testing some prett...
["def power_mod(b, e, m):\n res, b = 1, b % m\n while e > 0:\n if e & 1: res = res * b % m\n e >>= 1\n b = b * b % m\n return res", "def power_mod(base, exponent, modulus):\n if base is 0: return 0\n if exponent is 0: return 0\n base = base % modulus\n result = 1\n while (exponent > 0):\n ...
{"fn_name": "power_mod", "inputs": [[11, 10, 300], [11, 100000, 49], [5, 100000000, 19], [2, 3, 5], [4, 12, 3], [200, 3000, 10], [8132, 21302, 5], [9, 193125, 37], [13, 81230123, 22], [29, 1013293125, 492], [31, 902938423012, 1023]], "outputs": [[1], [32], [5], [3], [1], [0], [4], [26], [19], [161], [961]]}
introductory
https://www.codewars.com/kata/52fe629e48970ad2bd0007e6
def power_mod(b, e, m):
3,505
In the wake of the npm's `left-pad` debacle, you decide to write a new super padding method that superceds the functionality of `left-pad`. Your version will provide the same functionality, but will additionally add right, and justified padding of string -- the `super_pad`. Your function `super_pad` should take three ...
["def super_pad(string, width, fill=\" \"):\n if fill.startswith('>'):\n return (string + width * fill[1:])[:width]\n elif fill.startswith('^'):\n pad = (width * fill[1:])[:max(0, width - len(string) + 1) // 2]\n return (pad + string + pad)[:width]\n else:\n if fill.startswith('<'):...
{"fn_name": "super_pad", "inputs": [["test", 10], ["test", 10, "x"], ["test", 10, "xO"], ["test", 10, "xO-"], ["some other test", 10, "nope"], ["some other test", 10, "> "], ["test", 7, ">nope"], ["test", 7, "^more complex"], ["test", 7, ""], ["test", 10, "< "], ["test", 3], ["test", 3, "> "], ["test", 10, ""], ["test"...
introductory
https://www.codewars.com/kata/56f3ca069821793533000a3a
def super_pad(string, width, fill=" "):
3,506
We want to know the index of the vowels in a given word, for example, there are two vowels in the word super (the second and fourth letters). So given a string "super", we should return a list of [2, 4]. Some examples: Mmmm => [] Super => [2,4] Apple => [1,5] YoMama -> [1,2,4...
["def vowel_indices(word):\n return [i for i,x in enumerate(word,1) if x.lower() in 'aeiouy']", "def vowel_indices(word):\n return [i+1 for i,c in enumerate(word.lower()) if c in 'aeiouy']", "def vowel_indices(word):\n return [index for index, value in enumerate(word.lower(), 1) if value in 'aeyuio']", "VOWELS...
{"fn_name": "vowel_indices", "inputs": [["mmm"], ["apple"], ["super"], ["orange"], ["grapes"], ["supercalifragilisticexpialidocious"], ["123456"], ["crIssUm"], ["Implied"], ["rIc"], ["UNDISARMED"], ["bialy"], ["stumpknocker"], ["narboonnee"], ["carlstadt"], ["ephodee"], ["spicery"], ["oftenness"], ["bewept"], ["capsize...
introductory
https://www.codewars.com/kata/5680781b6b7c2be860000036
def vowel_indices(word):
3,507
## Enough is enough! Alice and Bob were on a holiday. Both of them took many pictures of the places they've been, and now they want to show Charlie their entire collection. However, Charlie doesn't like these sessions, since the motive usually repeats. He isn't fond of seeing the Eiffel tower 40 times. He tells them t...
["def delete_nth(order,max_e):\n ans = []\n for o in order:\n if ans.count(o) < max_e: ans.append(o)\n return ans\n", "def delete_nth(order, max_e):\n d = {}\n res = []\n for item in order:\n n = d.get(item, 0)\n if n < max_e:\n res.append(item)\n d[item] = n+1\n retu...
{"fn_name": "delete_nth", "inputs": [[[20, 37, 20, 21], 1], [[1, 1, 3, 3, 7, 2, 2, 2, 2], 3], [[1, 2, 3, 1, 1, 2, 1, 2, 3, 3, 2, 4, 5, 3, 1], 3], [[1, 1, 1, 1, 1], 5], [[], 5]], "outputs": [[[20, 37, 21]], [[1, 1, 3, 3, 7, 2, 2, 2]], [[1, 2, 3, 1, 1, 2, 2, 3, 3, 4, 5]], [[1, 1, 1, 1, 1]], [[]]]}
introductory
https://www.codewars.com/kata/554ca54ffa7d91b236000023
def delete_nth(order,max_e):
3,508
## Task Given a positive integer `n`, calculate the following sum: ``` n + n/2 + n/4 + n/8 + ... ``` All elements of the sum are the results of integer division. ## Example ``` 25 => 25 + 12 + 6 + 3 + 1 = 47 ```
["def halving_sum(n): \n s=0\n while n: \n s+=n ; n>>=1\n return s", "def halving_sum(n): \n if n == 1:\n return 1\n else:\n return n + halving_sum(n//2)", "def halving_sum(n): \n return n and n + halving_sum(n>>1)", "def halving_sum(n):\n result = n\n \n while n >= 1:\n ...
{"fn_name": "halving_sum", "inputs": [[25], [127], [38], [1], [320], [13], [15], [47], [101], [257]], "outputs": [[47], [247], [73], [1], [638], [23], [26], [89], [198], [512]]}
introductory
https://www.codewars.com/kata/5a58d46cfd56cb4e8600009d
def halving_sum(n):
3,509
Scientists working internationally use metric units almost exclusively. Unless that is, they wish to crash multimillion dollars worth of equipment on Mars. Your task is to write a simple function that takes a number of meters, and outputs it using metric prefixes. In practice, meters are only measured in "mm" (thousa...
["def meters(x):\n #your code here\n arr = ['','k','M','G','T','P','E','Z','Y']\n count=0\n while x>=1000 :\n x /=1000.00 \n count+=1\n if int(x)==x:\n x=int(x) \n return str(x)+arr[count]+'m'\n", "PREFIXES = (\n (10 ** 24, 'Y'),\n (10 ** 21, 'Z'),\n ...
{"fn_name": "meters", "inputs": [[1], [999], [123456], [12300000], [9000000000.0], [9000000000000.0], [9000000000000000.0], [9e+18], [9e+21], [9e+24]], "outputs": [["1m"], ["999m"], ["123.456km"], ["12.3Mm"], ["9Gm"], ["9Tm"], ["9Pm"], ["9Em"], ["9Zm"], ["9Ym"]]}
introductory
https://www.codewars.com/kata/5264f5685fda8ed370000265
def meters(x):
3,510
Two red beads are placed between every two blue beads. There are N blue beads. After looking at the arrangement below work out the number of red beads. @ @@ @ @@ @ @@ @ @@ @ @@ @ Implement count_red_beads(n) (in PHP count_red_beads($n); in Java, Javascript, TypeScript, C, C++ countRedBeads(n)) so that it returns the ...
["def count_red_beads(nb):\n return max(0, 2 * (nb - 1) )", "def count_red_beads(n_blue):\n return (n_blue - 1) * 2 if n_blue >= 2 else 0\n", "def count_red_beads(n):\n return max(0, 2 * (n-1))\n #maximum value -> two for every two beads times number of blue beads - 1\n", "def count_red_beads(n):\n return ...
{"fn_name": "count_red_beads", "inputs": [[0], [1], [3], [5]], "outputs": [[0], [0], [4], [8]]}
introductory
https://www.codewars.com/kata/58712dfa5c538b6fc7000569
def count_red_beads(n):
3,511
Hector the hacker has stolen some information, but it is encrypted. In order to decrypt it, he needs to write a function that will generate a decryption key from the encryption key which he stole (it is in hexadecimal). To do this, he has to determine the two prime factors `P` and `Q` of the encyption key, and return t...
["def find_key(key):\n n = int(key, 16)\n return next((k - 1) * ((n // k) - 1) for k in range(2, int(n**0.5)+1) if n % k == 0)\n", "def find_key(enc):\n n = int(enc,16)\n for i in range(2,int(n**.5)+1):\n if not n%i:\n return (i-1)*(n//i-1)\n", "def prime_factors(n):\n s, a = [], 2\n ...
{"fn_name": "find_key", "inputs": [["47b"], ["2533"], ["1ba9"]], "outputs": [[1080], [9328], [6912]]}
introductory
https://www.codewars.com/kata/5962ddfc2f9addd52200001d
def find_key(key):
3,512
Just like in the ["father" kata](http://www.codewars.com/kata/find-fibonacci-last-digit/), you will have to return the last digit of the nth element in the Fibonacci sequence (starting with 1,1, to be extra clear, not with 0,1 or other numbers). You will just get much bigger numbers, so good luck bruteforcing your way...
["def last_fib_digit(n):\n return [0,1,1,2,3,5,8,3,1,4,5,9,4,3,7,0,7,7,4,1,5,6,1,7,8,5,3,8,1,9,0,9,9,8,7,5,2,7,9,6,5,1,6,7,3,0,3,3,6,9,5,4,9,3,2,5,7,2,9,1][n%60]", "def last_fib_digit(n):\n \"\"\" well, it is periodic on 60 \"\"\"\n a = 0\n b = 1\n for _ in range(n%60):\n a, b = b, (a+b)%10\n r...
{"fn_name": "last_fib_digit", "inputs": [[1], [21], [302], [4003], [50004], [600005], [7000006], [80000007], [900000008], [1000000009]], "outputs": [[1], [6], [1], [7], [8], [5], [3], [8], [1], [9]]}
introductory
https://www.codewars.com/kata/56b7771481290cc283000f28
def last_fib_digit(n):
3,513
# Task John was in math class and got bored, so he decided to fold some origami from a rectangular `a × b` sheet of paper (`a > b`). His first step is to make a square piece of paper from the initial rectangular piece of paper by folding the sheet along the bisector of the right angle and cutting off the excess part. ...
["def folding(a,b):\n squares = 1\n while a != b:\n squares += 1\n b, a = sorted((a - b, b))\n return squares", "def folding(a,b):\n count = 0\n while a > 0 and b > 0:\n a, b, count = max(a-b, b), min(a-b, b), count+1\n return count", "def folding(a, b):\n return 0 if b == 0 else a // b ...
{"fn_name": "folding", "inputs": [[2, 1], [10, 7], [3, 1], [4, 1], [3, 2], [4, 2], [1000, 700], [1000, 999]], "outputs": [[2], [6], [3], [4], [3], [2], [6], [1000]]}
introductory
https://www.codewars.com/kata/58bfa1ea43fadb41840000b4
def folding(a,b):
3,514
Create a function that will return true if all numbers in the sequence follow the same counting pattern. If the sequence of numbers does not follow the same pattern, the function should return false. Sequences will be presented in an array of varied length. Each array will have a minimum of 3 numbers in it. The seque...
["def validate_sequence(seq):\n return len({a - b for a, b in zip(seq, seq[1:])}) == 1", "def validate_sequence(sequence):\n return sequence == list(range(sequence[0], sequence[-1] + 1, sequence[1] - sequence[0]))\n", "def validate_sequence(s):\n return sum(s) == (s[0] + s[-1]) * len(s) /2", "def validate_sequ...
{"fn_name": "validate_sequence", "inputs": [[[1, 2, 3, 4, 5, 8, 7, 8, 9]], [[2, 8, 6, 7, 4, 3, 1, 5, 9]], [[1, 2, 3, 4, 5, 6, 7, 8, 9]], [[0, 1, 2, 3, 4, 5, 6, 7, 8]], [[1, 3, 5, 7, 9, 11, 13, 15]], [[1, 3, 5, 7, 8, 12, 14, 16]], [[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]], [[0, 2, 4, 6, 8]], [[2, 4, 6, 8, 10]], [[2, 4, 6, 8, ...
introductory
https://www.codewars.com/kata/553f01db29490a69ff000049
def validate_sequence(sequence):
3,515
# Introduction The ragbaby cipher is a substitution cipher that encodes/decodes a text using a keyed alphabet and their position in the plaintext word they are a part of. To encrypt the text `This is an example.` with the key `cipher`, first construct a keyed alphabet: ``` c i p h e r ...
["from string import ascii_lowercase as aLow\nimport re\n\ndef rotateWord(w, alpha, dct, d):\n lst = []\n for i,c in enumerate(w.lower(), 1):\n transChar = alpha[ (dct[c] + i*d) % 26 ]\n if w[i-1].isupper(): transChar = transChar.upper()\n lst.append(transChar)\n return ''.join(lst)\n\ndef...
{"fn_name": "encode", "inputs": [["cipher", "cipher"], ["cipher", "cccciiiiippphheeeeerrrrr"]], "outputs": [["ihrbfj"], ["ihrbfj"]]}
introductory
https://www.codewars.com/kata/5a2166f355519e161a000019
def encode(text, key):
3,516
Your colleagues have been good enough(?) to buy you a birthday gift. Even though it is your birthday and not theirs, they have decided to play pass the parcel with it so that everyone has an even chance of winning. There are multiple presents, and you will receive one, but not all are nice... One even explodes and cove...
["_RESULTS = {\n 'goodpresent': lambda y: ''.join(chr(ord(c) + y) for c in 'goodpresent'),\n 'crap': lambda y: 'acpr',\n 'empty': lambda y: 'empty',\n 'bang': lambda y: str(sum(ord(c) - y for c in 'bang')),\n 'badpresent': lambda y: 'Take this back!',\n 'dog': lambda y: 'pass out from excitement {} ti...
{"fn_name": "present", "inputs": [["badpresent", 3], ["goodpresent", 9], ["crap", 10], ["bang", 27], ["dog", 23]], "outputs": [["Take this back!"], ["pxxmy{n|nw}"], ["acpr"], ["300"], ["pass out from excitement 23 times"]]}
introductory
https://www.codewars.com/kata/5805f0663f1f9c49be00011f
def present(x,y):
3,517
# Let's watch a parade! ## Brief You're going to watch a parade, but you only care about one of the groups marching. The parade passes through the street where your house is. Your house is at number `location` of the street. Write a function `parade_time` that will tell you the times when you need to appear to see all ...
["def parade_time(groups, location, speed, pref):\n return [c // speed for c, p in enumerate(groups, 1 + location) if p == pref]", "def parade_time(groups, location, speed, pref):\n result = []\n for i in range(1,len(groups)+1):\n if groups[i-1] == pref:\n result.append((location+i) // speed)...
{"fn_name": "parade_time", "inputs": [[["a", "b", "c", "d", "e", "f"], 3, 2, "c"], [["c", "b", "c", "d", "e", "f"], 3, 2, "c"], [["a", "b", "c", "d", "e", "f"], 3, 2, "g"], [["a", "b", "c", "c", "e", "c"], 7, 1, "c"], [["a", "b", "c", "d", "e", "f"], 1, 2, "b"], [["a", "b", "c", "d", "e", "b"], 1, 2, "b"]], "outputs": ...
introductory
https://www.codewars.com/kata/560d41fd7e0b946ac700011c
def parade_time(groups, location, speed, pref):
3,518
On Unix system type files can be identified with the ls -l command which displays the type of the file in the first alphabetic letter of the file system permissions field. You can find more information about file type on Unix system on the [wikipedia page](https://en.wikipedia.org/wiki/Unix_file_types). - '-' A regula...
["dict = {'-':\"file\",'d':\"directory\",'l':\"symlink\",'c':\"character_file\",'b':\"block_file\",'p':\"pipe\",'s':\"socket\",'D':\"door\"}\ndef linux_type(file_attribute):\n return dict[file_attribute[0]]", "def linux_type(s):\n return {x: y for x, y in zip(\"-dlcbpsD\", \"file directory symlink character_file ...
{"fn_name": "linux_type", "inputs": [["-rwxrwxrwx"], ["Drwxr-xr-x"], ["lrwxrw-rw-"], ["srwxrwxrwx"]], "outputs": [["file"], ["door"], ["symlink"], ["socket"]]}
introductory
https://www.codewars.com/kata/5822b65bb81f702016000026
def linux_type(file_attribute):
3,519
Given two arrays of integers `m` and `n`, test if they contain *at least* one identical element. Return `true` if they do; `false` if not. Your code must handle any value within the range of a 32-bit integer, and must be capable of handling either array being empty (which is a `false` result, as there are no duplicate...
["def duplicate_elements(m, n):\n return not set(m).isdisjoint(n)", "def duplicate_elements(m, n):\n return any(x in n for x in m)", "def duplicate_elements(m, n):\n return bool(set(m) & set(n))", "def duplicate_elements(m, n):\n return bool(set(m).intersection(n))", "def duplicate_elements(m, n):\n retu...
{"fn_name": "duplicate_elements", "inputs": [[[1, 2, 3, 4, 5], [1, 6, 7, 8, 9]], [[9, 8, 7], [8, 1, 3]], [[2398632, 9172846, 4728162], [2398632, 9235623, 8235492]], [[-2, -4, -6, -8], [-2, -3, -5, -7]], [[-9, -8, -7], [-8, -1, -3]], [[-2398632, -9172846, -4728162], [-2398632, -9235623, -8235492]], [[1, 3, 5, 7, 9], [2,...
introductory
https://www.codewars.com/kata/583ebb9328a0c034490001ba
def duplicate_elements(m, n):
3,520
The prime numbers are not regularly spaced. For example from `2` to `3` the step is `1`. From `3` to `5` the step is `2`. From `7` to `11` it is `4`. Between 2 and 50 we have the following pairs of 2-steps primes: `3, 5 - 5, 7, - 11, 13, - 17, 19, - 29, 31, - 41, 43` We will write a function `step` with parameters: ...
["import math\ndef isPrime(n):\n if n <= 1:\n return False\n for i in range(2,int(math.sqrt(n)+1)):\n if n % i == 0:\n return False\n return True\n\ndef step(g,m,n):\n if m >= n:\n return []\n else:\n for i in range(m,n+1-g):\n if isPrime(i) and isPrime(i...
{"fn_name": "step", "inputs": [[2, 100, 110], [4, 100, 110], [6, 100, 110], [8, 300, 400], [10, 300, 400], [4, 30000, 100000], [6, 30000, 100000], [8, 30000, 100000], [11, 30000, 100000], [16, 5, 20], [2, 10000000, 11000000], [52, 1300, 15000], [10, 4900, 5000], [30, 4900, 5000], [2, 4900, 5000], [2, 104000, 105000], [...
introductory
https://www.codewars.com/kata/5613d06cee1e7da6d5000055
def step(g, m, n):
3,521
Given some points (cartesian coordinates), return true if all of them lie on a line. Treat both an empty set and a single point as a line. ```python on_line(((1,2), (7,4), (22,9)) == True on_line(((1,2), (-3,-14), (22,9))) == False ```
["def on_line(points):\n points = list(set(points))\n cross_product = lambda a, b, c: a[0]*(b[1]-c[1]) + b[0]*(c[1]-a[1]) + c[0]*(a[1]-b[1])\n return all(cross_product(p, *points[:2]) == 0 for p in points[2:])", "from functools import partial\n\ndef collinear(p1, p2, p3):\n return (p3[1] - p2[1])*(p2[0] - p...
{"fn_name": "on_line", "inputs": [[[]], [[1, 1]]], "outputs": [[true], [true]]}
introductory
https://www.codewars.com/kata/53b7bc844db8fde50800020a
def on_line(points):
3,522
# Introduction and Warm-up (Highly recommended) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) ___ # Task **_Given_** an *array/list [] of integers* , **_Find_** **_The maximum difference_** *between the successive elements in its sorted form*. ___ # Note...
["def max_gap(numbers):\n lst = sorted(numbers)\n return max(b-a for a,b in zip(lst, lst[1:]))", "import numpy\n\ndef max_gap(numbers):\n return max(numpy.diff(sorted(numbers)))", "def max_gap(numbers):\n A = sorted(numbers)\n return max([abs(A[i] - A[i+1]) for i in range(len(A)-1)])", "def max_gap(n):\n...
{"fn_name": "max_gap", "inputs": [[[13, 10, 2, 9, 5]], [[13, 3, 5]], [[24, 299, 131, 14, 26, 25]], [[-3, -27, -4, -2]], [[-7, -42, -809, -14, -12]], [[12, -5, -7, 0, 290]], [[-54, 37, 0, 64, -15, 640, 0]], [[130, 30, 50]], [[1, 1, 1]], [[-1, -1, -1]]], "outputs": [[4], [8], [168], [23], [767], [278], [576], [80], [0], ...
introductory
https://www.codewars.com/kata/5a7893ef0025e9eb50000013
def max_gap(numbers):
3,523
## Description Your job is to create a simple password validation function, as seen on many websites. The rules for a valid password are as follows: - There needs to be at least 1 uppercase letter. - There needs to be at least 1 lowercase letter. - There needs to be at least 1 number. - The password needs to be at le...
["CRITERIA = (str.islower, str.isupper, str.isdigit)\n\ndef password(s):\n return len(s)>7 and all( any(map(f,s)) for f in CRITERIA)", "import re\n\ndef password(s):\n return bool(re.match(r'(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).{8}', s))", "import re \n\ndef password(string):\n patterns = (r'[A-Z]', r'[a-z]', r'[0-...
{"fn_name": "password", "inputs": [["Abcd1234"], ["Abcd123"], ["abcd1234"], ["AbcdefGhijKlmnopQRsTuvwxyZ1234567890"], ["ABCD1234"], ["Ab1!@#$%^&*()-_+={}[]|\\:;?/>.<,"], ["!@#$%^&*()-_+={}[]|\\:;?/>.<,"], [""], [" aA1----"], ["4aA1----"]], "outputs": [[true], [false], [false], [true], [false], [true], [false], [false],...
introductory
https://www.codewars.com/kata/56a921fa8c5167d8e7000053
def password(string):
3,524
Deoxyribonucleic acid, DNA is the primary information storage molecule in biological systems. It is composed of four nucleic acid bases Guanine ('G'), Cytosine ('C'), Adenine ('A'), and Thymine ('T'). Ribonucleic acid, RNA, is the primary messenger molecule in cells. RNA differs slightly from DNA its chemical structu...
["def dna_to_rna(dna):\n return dna.replace(\"T\", \"U\")", "dna_to_rna = lambda s: s.replace('T', 'U')", "def dna_to_rna(dna):\n rna = []\n for x in dna:\n if x == 'T':\n rna.append('U')\n else:\n rna.append(x)\n return ''.join(rna)\n", "dna_to_rna = lambda dna:dna.trans...
{"fn_name": "dna_to_rna", "inputs": [["TTTT"], ["GCAT"], ["GACCGCCGCC"], ["GATTCCACCGACTTCCCAAGTACCGGAAGCGCGACCAACTCGCACAGC"], ["CACGACATACGGAGCAGCGCACGGTTAGTACAGCTGTCGGTGAACTCCATGACA"], ["AACCCTGTCCACCAGTAACGTAGGCCGACGGGAAAAATAAACGATCTGTCAATG"], ["GAAGCTTATCCGTTCCTGAAGGCTGTGGCATCCTCTAAATCAGACTTGGCTACGCCGTTAGCCGAGGGCTT...
introductory
https://www.codewars.com/kata/5556282156230d0e5e000089
def dna_to_rna(dna):
3,525
Iahub got bored, so he invented a game to be played on paper.  He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n) and flips all values ak for which their positions are in range [i, j] (that is i ≤ k ≤ j)....
["def flipping_game(num):\n current = 0\n biggest = 0\n for i in num:\n current = max(0, current - ( i or -1 ) )\n biggest = max(biggest, current)\n \n return sum(num) + (biggest or -1)", "def flipping_game(num):\n return max([sum(num) + num[i: j + 1].count(0) - num[i: j + 1].count(1...
{"fn_name": "flipping_game", "inputs": [[[1, 0, 0, 1, 0, 0]], [[1, 0, 0, 1]], [[1]], [[0]], [[1, 0, 0, 0, 1, 0, 0, 0]], [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], [[0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1...
introductory
https://www.codewars.com/kata/59841e5084533834d6000025
def flipping_game(num):
3,526
Check your arrows You have a quiver of arrows, but some have been damaged. The quiver contains arrows with an optional range information (different types of targets are positioned at different ranges), so each item is an arrow. You need to verify that you have some good ones left, in order to prepare for battle: ```py...
["def any_arrows(arrows):\n return any(not i.get(\"damaged\", False) for i in arrows)\n", "def any_arrows(arrows):\n return any(not arrow.get('damaged', False) for arrow in arrows)\n", "def any_arrows(arrows):\n return any([True for a in arrows if 'damaged' not in a or a['damaged'] == False])", "def any_arrows...
{"fn_name": "any_arrows", "inputs": [[[]], [[{"range": 5, "damaged": false}]], [[{"range": 5, "damaged": false}, {"range": 15, "damaged": true}]], [[{"range": 5}, {"range": 10, "damaged": true}, {"damaged": true}]], [[{"range": 10, "damaged": true}, {"damaged": true}]]], "outputs": [[false], [true], [true], [true], [fa...
introductory
https://www.codewars.com/kata/559f860f8c0d6c7784000119
def any_arrows(arrows):
3,527
This function should take two string parameters: a person's name (`name`) and a quote of theirs (`quote`), and return a string attributing the quote to the person in the following format: ```python '[name] said: "[quote]"' ``` For example, if `name` is `'Grae'` and `'quote'` is `'Practice makes perfect'` then your fu...
["def quotable(name, quote):\n return '{} said: \"{}\"'.format(name, quote)", "def quotable(name, quote):\n return f'{name} said: \"{quote}\"'", "def quotable(name, quote):\n return name + ' said: ' + '\"' + quote + '\"'", "quotable = '{} said: \"{}\"'.format\n", "def quotable(name, quote):\n said = \" said...
{"fn_name": "quotable", "inputs": [["Grae", "Practice makes perfect"], ["Dan", "Get back to work, Grae"], ["Alex", "Python is great fun"], ["Bethany", "Yes, way more fun than R"], ["Darrell", "What the heck is this thing?"]], "outputs": [["Grae said: \"Practice makes perfect\""], ["Dan said: \"Get back to work, Grae\""...
introductory
https://www.codewars.com/kata/5859c82bd41fc6207900007a
def quotable(name, quote):
3,528
You have to create a method "compoundArray" which should take as input two int arrays of different length and return one int array with numbers of both arrays shuffled one by one. ```Example: Input - {1,2,3,4,5,6} and {9,8,7,6} Output - {1,9,2,8,3,7,4,6,5,6} ```
["def compound_array(a, b):\n x = []\n while a or b:\n if a: x.append(a.pop(0))\n if b: x.append(b.pop(0))\n return x", "def compound_array(a, b):\n x = min(map(len,(a,b)))\n return sum(map(list,zip(a,b)),[]) + a[x:] + b[x:]", "def compound_array(a, b):\n\n res = []\n \n for i in range(max(l...
{"fn_name": "compound_array", "inputs": [[[1, 2, 3, 4, 5, 6], [9, 8, 7, 6]], [[0, 1, 2], [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]], [[11, 12], [21, 22, 23, 24]], [[2147483647, 2147483646, 2147483645, 2147483644, 2147483643], [9]], [[214, 215, 216, 217, 218], []], [[], [214, 215, 219, 217, 218]], [[], []]], "outputs": [[[1, 9, 2,...
introductory
https://www.codewars.com/kata/56044de2aa75e28875000017
def compound_array(a, b):
3,529
## The Problem James is a DJ at a local radio station. As it's getting to the top of the hour, he needs to find a song to play that will be short enough to fit in before the news block. He's got a database of songs that he'd like you to help him filter in order to do that. ## What To Do Create `longestPossible`(`lon...
["songs = [{'artist': 'Marillion', 'title': 'Keyleigh', 'playback': '03:36'}, {'artist': 'Pink Floyd', 'title': 'Time', 'playback': '06:48'}, {'artist': 'Rush', 'title': 'YYZ', 'playback': '04:27'}, {'artist': 'Bonobo', 'title': 'Days To Come', 'playback': '03:50'}, {'artist': 'Coldplay', 'title': 'Yellow', 'playback':...
{"fn_name": "longest_possible", "inputs": [[215], [270], [13], [300]], "outputs": [["For Reasons Unknown"], ["YYZ"], [false], ["Surfing With The Alien"]]}
introductory
https://www.codewars.com/kata/561bbcb0fbbfb0f5010000ee
songs = [{'artist': 'Marillion', 'title': 'Keyleigh', 'playback': '03:36'}, {'artist': 'Pink Floyd', 'title': 'Time', 'playback': '06:48'}, {'artist': 'Rush', 'title': 'YYZ', 'playback': '04:27'}, {'artist': 'Bonobo', 'title': 'Days To Come', 'playback': '03:50'}, {'artist': 'Coldplay', 'title': 'Yellow', 'playback': ...
3,530
# Task You are given a function that should insert an asterisk (`*`) between every pair of **even digits** in the given input, and return it as a string. If the input is a sequence, concat the elements first as a string. ## Input The input can be an integer, a string of digits or a sequence containing integers onl...
["import re\n\ndef asterisc_it(s):\n if isinstance(s,int): s=str(s)\n elif isinstance(s,list): s=''.join(map(str,s))\n return re.sub(r'(?<=[02468])(?=[02468])', '*', s)", "def asterisc_it(n): \n if type(n) == list: n = \"\".join(str(i) for i in n)\n if type(n) == int : n = str(n)\n return \"\".join...
{"fn_name": "asterisc_it", "inputs": [[5312708], [9682135], [2222], [1111], [9999], ["0000"], [8], [2], [0], [[1, 4, 64, 68, 67, 23, 1]]], "outputs": [["531270*8"], ["96*8*2135"], ["2*2*2*2"], ["1111"], ["9999"], ["0*0*0*0"], ["8"], ["2"], ["0"], ["14*6*4*6*8*67231"]]}
introductory
https://www.codewars.com/kata/5888cba35194f7f5a800008b
def asterisc_it(n):
3,531
A [Mersenne prime](https://en.wikipedia.org/wiki/Mersenne_prime) is a prime number that can be represented as: Mn = 2^(n) - 1. Therefore, every Mersenne prime is one less than a power of two. Write a function that will return whether the given integer `n` will produce a Mersenne prime or not. The tests will check ra...
["def valid_mersenne(n):\n return n in {2,3,5,7,13,17,19,31,61,89,107,127,521,607,1279}", "def valid_mersenne(n):\n '''Currently using the Lucas-Lehmer test.'''\n \n if n < 2:\n return False\n \n if n == 2:\n return True\n \n mersenne = 2**n - 1\n \n residue = 4\n for _ in...
{"fn_name": "valid_mersenne", "inputs": [[2], [3], [5], [7], [11], [13], [17], [19], [21], [23], [31], [49], [61], [89], [107], [127], [221], [521], [607], [1279]], "outputs": [[true], [true], [true], [true], [false], [true], [true], [true], [false], [false], [true], [false], [true], [true], [true], [true], [false], [t...
introductory
https://www.codewars.com/kata/56af6e4198909ab73200013f
def valid_mersenne(n):
3,532
As a treat, I'll let you read part of the script from a classic 'I'm Alan Partridge episode: ``` Lynn: Alan, there’s that teacher chap. Alan: Michael, if he hits me, will you hit him first? Michael: No, he’s a customer. I cannot hit customers. I’ve been told. I’ll go and get some stock. Alan: Yeah, chicken stock. Phil:...
["def apple(x):\n return \"It's hotter than the sun!!\" if int(x) ** 2 > 1000 else \"Help yourself to a honeycomb Yorkie for the glovebox.\"", "def apple(x):\n if int(x)**2 > 1000:\n return \"It's hotter than the sun!!\"\n else:\n return \"Help yourself to a honeycomb Yorkie for the glovebox.\"", ...
{"fn_name": "apple", "inputs": [["50"], [4], ["12"], [60]], "outputs": [["It's hotter than the sun!!"], ["Help yourself to a honeycomb Yorkie for the glovebox."], ["Help yourself to a honeycomb Yorkie for the glovebox."], ["It's hotter than the sun!!"]]}
introductory
https://www.codewars.com/kata/580a094553bd9ec5d800007d
def apple(x):
3,533
# Task Write a function `deNico`/`de_nico()` that accepts two parameters: - `key`/`$key` - string consists of unique letters and digits - `message`/`$message` - string with encoded message and decodes the `message` using the `key`. First create a numeric key basing on the provided `key` by assigning each letter p...
["def de_nico(key, msg):\n ll, order, s = len(key), [sorted(key).index(c) for c in key], ''\n while msg:\n s, msg = s + ''.join(msg[i] for i in order if i < len(msg)), msg[ll:]\n return s.strip()", "def de_nico(key,msg):\n \n decoder = []\n \n # assign key letters numbers according to alphab...
{"fn_name": "de_nico", "inputs": [["crazy", "cseerntiofarmit on "], ["crazy", "cseerntiofarmit on"], ["abc", "abcd"], ["ba", "2143658709"], ["a", "message"], ["key", "eky"]], "outputs": [["secretinformation"], ["secretinformation"], ["abcd"], ["1234567890"], ["message"], ["key"]]}
introductory
https://www.codewars.com/kata/596f610441372ee0de00006e
def de_nico(key,msg):
3,534
Bit Vectors/Bitmaps A bitmap is one way of efficiently representing sets of unique integers using single bits. To see how this works, we can represent a set of unique integers between `0` and `< 20` using a vector/array of 20 bits: ``` var set = [3, 14, 2, 11, 16, 4, 6];``` ``` var bitmap = [0, 0, 1, 1, 1, 0, 1, 0, 0, ...
["def to_bits(s):\n lst = [0] * 5000\n for i in map(int,s.split()): lst[i] = 1\n return lst", "def to_bits(s):\n return [1 if i in set(map(int, s.split(\"\\n\"))) else 0 for i in range(5000)]", "def to_bits(string):\n bitmap = [0] * 5000\n for x in map(int, string.split()):\n bitmap[x] = 1\n ...
{"fn_name": "to_bits", "inputs": [["4814\n3815\n54\n2747\n1449\n1880\n1109\n4942\n1646\n1750\n2933\n963\n1757\n137\n4100\n2188\n2487\n3027\n1771\n1223\n4458\n2755\n247\n3975\n2125\n1071\n3967\n3557\n2741\n3052\n2013\n4741\n4501\n975\n1194\n2352\n3548\n3436\n462\n2990\n1072\n53\n920\n3028\n3648\n2928\n4186\n2057\n3238\n...
introductory
https://www.codewars.com/kata/59f8dd1132b8b9af150001ea
def to_bits(string):
3,535
Some new cashiers started to work at your restaurant. They are good at taking orders, but they don't know how to capitalize words, or use a space bar! All the orders they create look something like this: `"milkshakepizzachickenfriescokeburgerpizzasandwichmilkshakepizza"` The kitchen staff are threatening to quit,...
["def get_order(order):\n menu = ['burger', 'fries', 'chicken', 'pizza', 'sandwich', 'onionrings', 'milkshake', 'coke']\n clean_order = ''\n for i in menu:\n clean_order += (i.capitalize() + ' ') * order.count(i)\n return clean_order[:-1]", "MENU = [\"Burger\", \"Fries\", \"Chicken\", \"Pizza\", \"Sa...
{"fn_name": "get_order", "inputs": [["burgerfriesfriesfriesfriesfriespizzasandwichcokefriesburger"]], "outputs": [["Burger Burger Fries Fries Fries Fries Fries Fries Pizza Sandwich Coke"]]}
introductory
https://www.codewars.com/kata/5d23d89906f92a00267bb83d
def get_order(order):
3,536
# Kata Task You are given a list of cogs in a gear train Each element represents the number of teeth of that cog e.g. `[100, 50, 25]` means * 1st cog has 100 teeth * 2nd cog has 50 teeth * 3rd cog has 25 teeth If the ``nth`` cog rotates clockwise at 1 RPM what is the RPM of the cogs at each end of the gear train?...
["def cog_RPM(cogs, n):\n return [\n cogs[n] / cogs[0] * (-1 if n % 2 else 1),\n cogs[n] / cogs[-1] * (1 if (len(cogs) - n) % 2 else -1),\n ]", "def cog_RPM(cogs, n):\n sign1 = -1 if n % 2 else 1\n sign2 = 1 if (len(cogs) - n) % 2 else -1\n return [sign1 * cogs[n] / cogs[0], sign2 * cogs[n...
{"fn_name": "cog_RPM", "inputs": [[[100], 0], [[100, 100, 100, 100], 0], [[100, 100, 100, 100], 1], [[100, 100, 100, 100], 2], [[100, 100, 100, 100], 3]], "outputs": [[[1, 1]], [[1, -1]], [[-1, 1]], [[1, -1]], [[-1, 1]]]}
introductory
https://www.codewars.com/kata/59e72bdcfc3c4974190000d9
def cog_RPM(cogs, n):
3,537
In this Kata we are passing a number (n) into a function. Your code will determine if the number passed is even (or not). The function needs to return either a true or false. Numbers may be positive or negative, integers or floats. Floats are considered UNeven for this kata.
["def is_even(n): \n return n%2 == 0", "def is_even(n):\n\n#a modulos will return the whole number remainder of a division\n\n#using the modulos sign with 2 and another number will only return 0 and 1 \n\n#if the remainder of n and 2 is equal to 1 the number will be odd\n \n if (n % 2) == 1:\n return False...
{"fn_name": "is_even", "inputs": [[0], [0.5], [1], [2], [-4], [15], [20], [220], [222222221], [500000000]], "outputs": [[true], [false], [false], [true], [true], [false], [true], [true], [false], [true]]}
introductory
https://www.codewars.com/kata/555a67db74814aa4ee0001b5
def is_even(n):
3,538
## Story > "You have serious coding skillz? You wannabe a [scener](https://en.wikipedia.org/wiki/Demoscene)? Complete this mission and u can get in teh crew!" You have read a similar message on your favourite [diskmag](https://en.wikipedia.org/wiki/Disk_magazine) back in the early 90s, and got really excited. You con...
["from math import pi, sin\n\ndef scroller(text, amp, period):\n return '\\n'.join(' ' * (amp + int(round(sin(i * 2 * pi / period) * amp))) + c for i, c in enumerate(text))\n", "import math\ndef scroller(text, amp, period):\n l = lambda i, c: ' '*(amp+i) + c + \"\\n\"\n return (''.join([l(round(amp * math.sin(...
{"fn_name": "scroller", "inputs": [["Hello World!", 3, 10], ["I'm a Codewars warrior lately...", 5, 18]], "outputs": [[" H\n e\n l\n l\n o\n \n W\no\nr\n l\n d\n !"], [" I\n '\n m\n \n a\n \n C\n o\n d\n e\n w\n a\n r\...
introductory
https://www.codewars.com/kata/59cabf6baeb28482b8000017
def scroller(text, amp, period):
3,539
Implement a function that normalizes out of range sequence indexes (converts them to 'in range' indexes) by making them repeatedly 'loop' around the array. The function should then return the value at that index. Indexes that are not out of range should be handled normally and indexes to empty sequences should return u...
["def norm_index_test(a, n):\n if a: return a[n % len(a)]", "def norm_index_test(seq, ind):\n if seq:\n return seq[ind%len(seq)]\n return None", "def norm_index_test(seq, ind): \n try:\n return seq[ind%len(seq)]\n except:\n pass", "def norm_index_test(seq, ind): \n if seq==[]:\n ...
{"fn_name": "norm_index_test", "inputs": [[[], 10]], "outputs": [[null]]}
introductory
https://www.codewars.com/kata/5285bf61f8fc1b181700024c
def norm_index_test(seq, ind):
3,540
According to ISO 8601, the first calendar week (1) starts with the week containing the first thursday in january. Every year contains of 52 (53 for leap years) calendar weeks. **Your task is** to calculate the calendar week (1-53) from a given date. For example, the calendar week for the date `2019-01-01` (string) sho...
["from datetime import datetime\n\n\ndef get_calendar_week(date_string):\n return datetime.strptime(date_string, \"%Y-%m-%d\").isocalendar()[1] ", "from datetime import date\n\ndef get_calendar_week(s):\n return date(*map(int, s.split(\"-\"))).isocalendar()[1]", "import datetime\nget_calendar_week=lambda d:dat...
{"fn_name": "get_calendar_week", "inputs": [["2017-01-01"], ["2018-12-24"], ["2018-12-31"], ["2019-01-01"], ["2016-02-29"], ["2015-12-29"], ["2024-12-31"], ["2025-01-05"], ["2025-01-06"], ["1995-12-31"], ["1996-01-01"], ["1999-12-31"], ["2000-01-02"], ["2000-01-03"], ["2016-12-25"], ["2016-12-26"], ["2017-01-02"], ["20...
introductory
https://www.codewars.com/kata/5c2bedd7eb9aa95abe14d0ed
def get_calendar_week(date_string):
3,541
You're given an ancient book that unfortunately has a few pages in the wrong position, fortunately your computer has a list of every page number in order from ``1`` to ``n``. You're supplied with an array of numbers, and should return an array with each page number that is out of place. Incorrect page numbers will not...
["def find_page_number(pages):\n n, miss = 1, []\n for i in pages:\n if i!=n: miss.append(i)\n else: n+=1\n return miss", "def find_page_number(pages):\n n = [1]\n return [i for i in pages if n[-1] != i or n.append(n[-1]+1)]", "def find_page_number(p):\n r, i = [], 0\n\n while i < ...
{"fn_name": "find_page_number", "inputs": [[[1, 2, 10, 3, 4, 5, 8, 6, 7]], [[1, 2, 3, 4, 50, 5, 6, 7, 51, 8, 40, 9]], [[1, 2, 3000, 3, 4, 5, 8, 6, 7, 8, 100, 9, 40, 10, 11, 13]], [[1, 2, 3, 4, 50, 5, 6, 7, 51, 8, 9]], [[4, 1, 2, 3, 3, 4, 26, 5, 6, 2, 7]]], "outputs": [[[10, 8]], [[50, 51, 40]], [[3000, 8, 100, 40, 13]]...
introductory
https://www.codewars.com/kata/5aa20a964a6b34417c00008d
def find_page_number(pages):
3,542
This is related to my other Kata about cats and dogs. # Kata Task I have a cat and a dog which I got as kitten / puppy. I forget when that was, but I do know their current ages as `catYears` and `dogYears`. Find how long I have owned each of my pets and return as a list [`ownedCat`, `ownedDog`] NOTES: * Results ar...
["def owned_cat_and_dog(cy, dy):\n cat = 0 if cy < 15 else 1 if cy < 24 else 2 + (cy - 24) // 4\n dog = 0 if dy < 15 else 1 if dy < 24 else 2 + (dy - 24) // 5\n return [cat, dog]", "def owned_cat_and_dog(cat_years, dog_years):\n i = cat_years\n k = dog_years\n if i < 24:\n cat_years = 1\n if k...
{"fn_name": "owned_cat_and_dog", "inputs": [[9, 7], [15, 15], [18, 21], [19, 17], [24, 24], [25, 25], [26, 26], [27, 27], [56, 64]], "outputs": [[[0, 0]], [[1, 1]], [[1, 1]], [[1, 1]], [[2, 2]], [[2, 2]], [[2, 2]], [[2, 2]], [[10, 10]]]}
introductory
https://www.codewars.com/kata/5a6d3bd238f80014a2000187
def owned_cat_and_dog(cat_years, dog_years):
3,543
Your job is to write a function which increments a string, to create a new string. - If the string already ends with a number, the number should be incremented by 1. - If the string does not end with a number. the number 1 should be appended to the new string. Examples: `foo -> foo1` `foobar23 -> foobar24` `foo004...
["def increment_string(strng):\n head = strng.rstrip('0123456789')\n tail = strng[len(head):]\n if tail == \"\": return strng+\"1\"\n return head + str(int(tail) + 1).zfill(len(tail))", "def increment_string(strng):\n \n # strip the decimals from the right\n stripped = strng.rstrip('1234567890')\n ...
{"fn_name": "increment_string", "inputs": [["foo"], ["foobar001"], ["foobar1"], ["foobar00"], ["foobar99"], [""], ["foobar000"], ["foobar999"], ["foobar00999"], ["1"], ["009"]], "outputs": [["foo1"], ["foobar002"], ["foobar2"], ["foobar01"], ["foobar100"], ["1"], ["foobar001"], ["foobar1000"], ["foobar01000"], ["2"], [...
introductory
https://www.codewars.com/kata/54a91a4883a7de5d7800009c
def increment_string(strng):
3,544
The Earth has been invaded by aliens. They demand our beer and threaten to destroy the Earth if we do not supply the exact number of beers demanded. Unfortunately, the aliens only speak Morse code. Write a program to convert morse code into numbers using the following convention: 1 .---- 2 ..--- 3 ...-- 4 ....- 5 ......
["MORSE_TO_NUM = {\n \".----\" : \"1\",\n \"..---\" : \"2\",\n \"...--\" : \"3\",\n \"....-\" : \"4\",\n \".....\" : \"5\",\n \"-....\" : \"6\",\n \"--...\" : \"7\",\n \"---..\" : \"8\",\n \"----.\" : \"9\",\n \"-----\" : \"0\",\n}\n\ndef morse_converter(s):\n return int(\"\".join(MORSE...
{"fn_name": "morse_converter", "inputs": [[".----.----.----.----.----"], ["..----------...-....----------"], ["---------------"], ["..---.--------....--"], [".----..---...--....-.....-....--...---..----.-----"]], "outputs": [[11111], [207600], [0], [2193], [1234567890]]}
introductory
https://www.codewars.com/kata/56dc4f570a10feaf0a000850
def morse_converter(s):
3,545
For every good kata idea there seem to be quite a few bad ones! In this kata you need to check the provided 2 dimensional array (x) for good ideas 'good' and bad ideas 'bad'. If there are one or two good ideas, return 'Publish!', if there are more than 2 return 'I smell a series!'. If there are no good ideas, as is of...
["from itertools import chain\n\ndef well(arr):\n c = sum(isinstance(x, str) and x.lower() == 'good' for x in chain.from_iterable(arr))\n return (\n 'I smell a series!' if c > 2 else\n 'Publish!' if c > 0 else\n 'Fail!'\n )", "def well(arr):\n good_ideas = str(arr).lower().count('good')...
{"fn_name": "well", "inputs": [[[["bad", "bAd", "bad"], ["bad", "bAd", "bad"], ["bad", "bAd", "bad"]]], [[["gOOd", "bad", "BAD", "bad", "bad"], ["bad", "bAd", "bad"], ["GOOD", "bad", "bad", "bAd"]]], [[["gOOd", "bAd", "BAD", "bad", "bad", "GOOD"], ["bad"], ["gOOd", "BAD"]]]], "outputs": [["Fail!"], ["Publish!"], ["I sm...
introductory
https://www.codewars.com/kata/57f22b0f1b5432ff09001cab
def well(arr):
3,546
A lot of goods have an International Article Number (formerly known as "European Article Number") abbreviated "EAN". EAN is a 13-digits barcode consisting of 12-digits data followed by a single-digit checksum (EAN-8 is not considered in this kata). The single-digit checksum is calculated as followed (based upon the ...
["validate_ean = lambda code: (sum(map(int, code[0::2])) + sum(map(int, code[1::2])) * 3) % 10 == 0", "def validate_ean(code):\n data, last = code[:12], int(code[12])\n checksum = -sum(int(d) * 3**(i % 2) for i, d in enumerate(data)) % 10\n return last == checksum ", "def validate_ean(code):\n checksum = ...
{"fn_name": "validate_ean", "inputs": [["9783815820865"], ["9783815820864"], ["9783827317100"]], "outputs": [[true], [false], [true]]}
introductory
https://www.codewars.com/kata/55563df50dda59adf900004d
def validate_ean(code):
3,547
The town sheriff dislikes odd numbers and wants all odd numbered families out of town! In town crowds can form and individuals are often mixed with other people and families. However you can distinguish the family they belong to by the number on the shirts they wear. As the sheriff's assistant it's your job to find all...
["def odd_ones_out(numbers):\n return [i for i in numbers if numbers.count(i) % 2 == 0]", "from collections import Counter\n\ndef odd_ones_out(numbers):\n cnt = Counter(numbers)\n return [v for v in numbers if not cnt[v]&1 ]", "def odd_ones_out(numbers):\n temp = []\n count = 0\n for i in range(len(nu...
{"fn_name": "odd_ones_out", "inputs": [[[1, 2, 3, 1, 3, 3]], [[75, 68, 75, 47, 68]], [[42, 72, 32, 4, 94, 82, 67, 67]], [[100, 100, 5, 5, 100, 50, 68, 50, 68, 50, 68, 5, 100]], [[82, 86, 71, 58, 44, 79, 50, 44, 79, 67, 82, 82, 55, 50]]], "outputs": [[[1, 1]], [[75, 68, 75, 68]], [[67, 67]], [[100, 100, 100, 100]], [[44...
introductory
https://www.codewars.com/kata/5d376cdc9bcee7001fcb84c0
def odd_ones_out(numbers):
3,548
# Task Given an array of roots of a polynomial equation, you should reconstruct this equation. ___ ## Output details: * If the power equals `1`, omit it: `x = 0` instead of `x^1 = 0` * If the power equals `0`, omit the `x`: `x - 2 = 0` instead of `x - 2x^0 = 0` * There should be no 2 signs in a row: `x - 1 = 0` ins...
["import re\n\ndef polynomialize(roots):\n \n def deploy(roots):\n r = -roots[0]\n if len(roots) == 1: return [r, 1]\n \n sub = deploy(roots[1:]) + [0]\n return [c*r + sub[i-1] for i,c in enumerate(sub)]\n \n coefs = deploy(roots)\n poly = ' + '.join([\"{}x^{}\".format...
{"fn_name": "polynomialize", "inputs": [[[0]], [[0, 0]], [[-1]], [[1]], [[1, -1]], [[0, -2, -3]], [[0, 2, 3]], [[1, 2, 3, 4, 5]]], "outputs": [["x = 0"], ["x^2 = 0"], ["x + 1 = 0"], ["x - 1 = 0"], ["x^2 - 1 = 0"], ["x^3 + 5x^2 + 6x = 0"], ["x^3 - 5x^2 + 6x = 0"], ["x^5 - 15x^4 + 85x^3 - 225x^2 + 274x - 120 = 0"]]}
introductory
https://www.codewars.com/kata/5b2d5be2dddf0be5b00000c4
def polynomialize(roots):
3,549
Write a function that takes a list of at least four elements as an argument and returns a list of the middle two or three elements in reverse order.
["def reverse_middle(lst):\n l = len(lst)//2 - 1\n return lst[l:-l][::-1]", "def reverse_middle(a):\n l=len(a)//2\n return a[-l:l-2:-1]", "def reverse_middle(lst):\n return lst[(len(lst)+1)//2:len(lst)//2-2:-1]", "def reverse_middle(lst):\n l = len(lst)\n return lst[(l+1)//2:(l//2)-2:-1] ", "def re...
{"fn_name": "reverse_middle", "inputs": [[[4, 3, 100, 1]], [[1, false, "string", {}, 7.43]]], "outputs": [[[100, 3]], [[{}, "string", false]]]}
introductory
https://www.codewars.com/kata/5a043724ffe75fbab000009f
def reverse_middle(lst):
3,550
In this Kata, you're to complete the function `sum_square_even_root_odd`. You will be given a list of numbers, `nums`, as the only argument to the function. Take each number in the list and *square* it if it is even, or *square root* the number if it is odd. Take this new list and find the *sum*, rounding to two decim...
["def sum_square_even_root_odd(nums):\n return round(sum(n ** 2 if n % 2 == 0 else n ** 0.5 for n in nums), 2)", "def sum_square_even_root_odd(nums):\n return round(sum(n**(0.5 if n % 2 else 2) for n in nums), 2)", "sum_square_even_root_odd=lambda l:round(sum(x**[2,.5][x&1]for x in l),2)\n", "def sum_square_even_...
{"fn_name": "sum_square_even_root_odd", "inputs": [[[4, 5, 7, 8, 1, 2, 3, 0]], [[1, 14, 9, 8, 17, 21]]], "outputs": [[91.61], [272.71]]}
introductory
https://www.codewars.com/kata/5a4b16435f08299c7000274f
def sum_square_even_root_odd(nums):
3,551
# Task Given array of integers, for each position i, search among the previous positions for the last (from the left) position that contains a smaller value. Store this value at position i in the answer. If no such value can be found, store `-1` instead. # Example For `items = [3, 5, 2, 4, 5]`, the output should be...
["def array_previous_less(arr):\n return [next((y for y in arr[:i][::-1] if y < x),-1) for i,x in enumerate(arr)]", "def array_previous_less(arr):\n out = []\n \n for i, n in enumerate(arr):\n x = -1\n for m in arr[:i][::-1]:\n if m < n:\n x = m\n break\n...
{"fn_name": "array_previous_less", "inputs": [[[3, 5, 2, 4, 5]], [[2, 2, 1, 3, 4, 5, 5, 3]], [[3, 2, 1]]], "outputs": [[[-1, 3, -1, 2, 4]], [[-1, -1, -1, 1, 3, 4, 4, 1]], [[-1, -1, -1]]]}
introductory
https://www.codewars.com/kata/588856a82ffea640c80000cc
def array_previous_less(arr):
3,552
You are playing euchre and you want to know the new score after finishing a hand. There are two teams and each hand consists of 5 tricks. The team who wins the majority of the tricks will win points but the number of points varies. To determine the number of points, you must know which team called trump, how many trick...
["def update_score(score, trump, alone, tricks):\n done = tricks.count(trump)\n mul = 2 if done == 5 and alone else 1\n add = 1 if done in (3, 4) else 2\n winner = trump if done > 2 else (3 - trump)\n return [pts + (add * mul if team == winner else 0) for team, pts in enumerate(score, 1)]", "def update_s...
{"fn_name": "update_score", "inputs": [[[4, 0], 1, false, [2, 2, 2, 2, 2]], [[4, 2], 1, true, [2, 2, 2, 2, 2]], [[4, 4], 2, false, [2, 2, 2, 2, 2]], [[4, 6], 2, true, [2, 2, 2, 2, 2]], [[7, 2], 1, false, [1, 2, 2, 2, 2]], [[7, 4], 1, true, [1, 2, 2, 2, 2]], [[7, 6], 2, false, [1, 2, 2, 2, 2]], [[7, 7], 2, true, [1, 2, ...
introductory
https://www.codewars.com/kata/586eca3b35396db82e000481
def update_score(current_score, called_trump, alone, tricks):
3,553
There's a new security company in Paris, and they decided to give their employees an algorithm to make first name recognition faster. In the blink of an eye, they can now detect if a string is a first name, no matter if it is a one-word name or an hyphenated name. They're given this documentation with the algorithm: ...
["import re\n\n\ndef show_me(name):\n return bool(re.match(r'(-[A-Z][a-z]+)+$', '-' + name))", "def show_me(name):\n return all(word.isalpha() and word.capitalize() == word for word in name.split('-'))", "from re import match, compile\ndef show_me(name):\n return match(compile(r'^[A-Z][a-z]+(?:-[A-Z][a-z]+)*$'),...
{"fn_name": "show_me", "inputs": [["Francis"], ["Jean-Eluard"], ["Le Mec"], ["Bernard-Henry-Levy"], ["Meme Gertrude"], ["A-a-a-a----a-a"], ["Z-------------"], ["Jean-luc"], ["Jean--Luc"], ["JeanLucPicard"], ["-Jean-Luc"], ["Jean-Luc-Picard-"]], "outputs": [[true], [true], [false], [true], [false], [false], [false], [fa...
introductory
https://www.codewars.com/kata/574c51aa3e4ea6de22001363
def show_me(name):
3,554
Zonk is addictive dice game. In each round player rolls 6 dice. Then (s)he composes combinations from them. Each combination gives certain points. Then player can take one or more dice combinations to his hand and re-roll remaining dice or save his score. Dice in player's hand won't be taken into account in subsequen...
["def get_score(dice):\n if all(i in dice for i in range(1, 7)):\n return 1000\n if len(dice) == 6 and all(dice.count(d) == 2 for d in set(dice)):\n return 750\n score = 0\n score += sum((dice.count(d)==n) * d * (n-2) * (1000 if d==1 else 100) for d in set(dice) for n in range(3, 7))\n scor...
{"fn_name": "get_score", "inputs": [[[1]], [[5]], [[1, 1]], [[5, 5]], [[5, 1]], [[5, 6]], [[1, 1, 1]], [[2, 2, 2]], [[3, 3, 3]], [[4, 4, 4]], [[5, 5, 5]], [[6, 6, 6]], [[1, 2, 1]], [[1, 1, 5]], [[5, 5, 6]], [[1, 5, 5]], [[1, 1, 1, 1]], [[2, 2, 2, 2]], [[3, 3, 3, 3]], [[4, 4, 4, 4]], [[5, 5, 5, 5]], [[6, 6, 6, 6]], [[1,...
introductory
https://www.codewars.com/kata/53837b8c94c170e55f000811
def get_score(dice):
3,555
Given the number n, return a string which shows the minimum number of moves to complete the tower of Hanoi consisting of n layers. Tower of Hanoi : https://en.wikipedia.org/wiki/Tower_of_Hanoi Example - 2 layered Tower of Hanoi Input: n=2 Start [[2, 1], [], []] Goal [[], [], [2, 1]] Expected Output : '[[2, 1], []...
["def hanoiArray(n):\n A, B, C = list(range(n, 0, -1)), [], []\n res = [str([A, C, B])]\n def rec(n, X, Y, Z):\n if not n: return\n rec(n-1, X, Z, Y)\n Y.append(X.pop())\n res.append(str([A, C, B]))\n rec(n-1, Z, Y, X) \n rec(n, A, B, C)\n return '\\n'.join(res)"...
{"fn_name": "hanoiArray", "inputs": [[2], [3]], "outputs": [["[[2, 1], [], []]\n[[2], [1], []]\n[[], [1], [2]]\n[[], [], [2, 1]]"], ["[[3, 2, 1], [], []]\n[[3, 2], [], [1]]\n[[3], [2], [1]]\n[[3], [2, 1], []]\n[[], [2, 1], [3]]\n[[1], [2], [3]]\n[[1], [], [3, 2]]\n[[], [], [3, 2, 1]]"]]}
introductory
https://www.codewars.com/kata/5a02a758ffe75f8da5000030
def hanoiArray(n):
3,556
Base on the fairy tale [Diamonds and Toads](https://en.wikipedia.org/wiki/Diamonds_and_Toads) from Charles Perrault. In this kata you will have to complete a function that take 2 arguments: - A string, that correspond to what the daugther says. - A string, that tell you wich fairy the girl have met, this one can be `...
["from collections import Counter\n\ndef diamonds_and_toads(sentence, fairy):\n c = Counter(sentence)\n d = {'good':['ruby', 'crystal'], 'evil':['python', 'squirrel']}\n\n return {s:c[s[0]] + 2*c[s[0].upper()] for s in d[fairy]}", "def diamonds_and_toads(sentence,fairy):\n items = {\"ruby\":0, \"crystal\":0...
{"fn_name": "diamonds_and_toads", "inputs": [["Ruby and Crystal", "good"], ["This string contain some Ruby and some Crystal in it", "good"], ["Python and Squirrel", "evil"], ["This string contain some Python and some Squirrel in it", "evil"]], "outputs": [[{"ruby": 3, "crystal": 2}], [{"ruby": 4, "crystal": 3}], [{"pyt...
introductory
https://www.codewars.com/kata/57fa537f8b0760c7da000407
def diamonds_and_toads(sentence,fairy):
3,557
Given a number **n**, return the number of positive odd numbers below **n**, EASY! Expect large Inputs!
["def odd_count(n):\n return len(range(1, n, 2))", "def odd_count(n):\n if n < 1:\n return 0\n\n return int(n / 2)\n \n", "def odd_count(n):\n #Return number of positive odd numbers below N\n #Find numbers below N -> Add +1 to count \n #More of a math problem\n #Try to find a way besides ...
{"fn_name": "odd_count", "inputs": [[15], [15023]], "outputs": [[7], [7511]]}
introductory
https://www.codewars.com/kata/59342039eb450e39970000a6
def odd_count(n):
3,558
Your coworker was supposed to write a simple helper function to capitalize a string (that contains a single word) before they went on vacation. Unfortunately, they have now left and the code they gave you doesn't work. Fix the helper function they wrote so that it works as intended (i.e. make the first character in th...
["def capitalize_word(word):\n return word.capitalize()\n\n # .capitilize() for the first word in the string\n # .title() for each word in the string\n", "def capitalize_word(word):\n return word.capitalize()", "def capitalize_word(word):\n\n return \"\".join(char.capitalize() for char in word.split())",...
{"fn_name": "capitalize_word", "inputs": [["word"], ["i"], ["glasswear"]], "outputs": [["Word"], ["I"], ["Glasswear"]]}
introductory
https://www.codewars.com/kata/595970246c9b8fa0a8000086
def capitalize_word(word):
3,559
The male gametes or sperm cells in humans and other mammals are heterogametic and contain one of two types of sex chromosomes. They are either X or Y. The female gametes or eggs however, contain only the X sex chromosome and are homogametic. The sperm cell determines the sex of an individual in this case. If a sperm c...
["def chromosome_check(sperm):\n return 'Congratulations! You\\'re going to have a {}.'.format('son' if 'Y' in sperm else 'daughter')", "def chromosome_check(sperm):\n gender = {\"XY\" : \"son\", \"XX\" : \"daughter\"}\n \n return \"Congratulations! You're going to have a {}.\".format(gender[sperm])", "def ...
{"fn_name": "chromosome_check", "inputs": [["XY"], ["XX"]], "outputs": [["Congratulations! You're going to have a son."], ["Congratulations! You're going to have a daughter."]]}
introductory
https://www.codewars.com/kata/56530b444e831334c0000020
def chromosome_check(sperm):
3,560
You are a skier (marked below by the `X`). You have made it to the Olympics! Well done. ``` \_\_\_X\_ \*\*\*\*\*\ \*\*\*\*\*\*\ \*\*\*\*\*\*\*\ \*\*\*\*\*\*\*\*\ \*\*\*\*\*\*\*\*\*\\.\_\_\_\_/ ``` Your job in this kata is to calculate the maximum speed you will achieve during your downhill run. The speed is dictated ...
["def ski_jump(mountain):\n height = len(mountain)\n speed = height * 1.5\n jump_length = height * speed * 9 / 10\n return (\n f\"{jump_length:.2f} metres: He's crap!\" if jump_length < 10 else\n f\"{jump_length:.2f} metres: He's ok!\" if jump_length < 25 else\n f\"{jump_length:.2f} me...
{"fn_name": "ski_jump", "inputs": [[["*"]], [["*", "**", "***"]], [["*", "**", "***", "****", "*****", "******"]], [["*", "**", "***", "****", "*****", "******", "*******", "********"]]], "outputs": [["1.35 metres: He's crap!"], ["12.15 metres: He's ok!"], ["48.60 metres: He's flying!"], ["86.40 metres: Gold!!"]]}
introductory
https://www.codewars.com/kata/57ed7214f670e99f7a000c73
def ski_jump(mountain):
3,561
Another Fibonacci... yes but with other kinds of result. The function is named `aroundFib` or `around_fib`, depending of the language. Its parameter is `n` (positive integer). First you have to calculate `f` the value of `fibonacci(n)` with `fibonacci(0) --> 0` and `fibonacci(1) --> 1` (see: ) - 1) Find the count of ...
["from collections import Counter\nfib = [0, 1]\n\ndef around_fib(n):\n while len(fib) <= n: fib.append(fib[-1] + fib[-2])\n f = str(fib[n])\n val = max((v, -int(k)) for k,v in Counter(f).items())\n last = f[-(len(f)%25 or 25):]\n return f\"Last chunk {last}; Max is {val[0]} for digit {-val[1]}\"", "def ...
{"fn_name": "around_fib", "inputs": [[666], [934], [617], [576], [982], [628], [901], [957], [916], [823], [988], [703], [873], [664], [749], [581], [986], [904], [716], [673], [12965], [17001], [16381], [18035], [10611], [13959], [17962], [13505], [15366], [13883], [10210], [16797], [15923], [18108], [12314], [15708],...
introductory
https://www.codewars.com/kata/59bf943cafcda28e31000130
def around_fib(n):
3,562
In computer science and discrete mathematics, an [inversion](https://en.wikipedia.org/wiki/Inversion_%28discrete_mathematics%29) is a pair of places in a sequence where the elements in these places are out of their natural order. So, if we use ascending order for a group of numbers, then an inversion is when larger num...
["def count_inversion(nums):\n return sum(a > b for i, a in enumerate(nums) for b in nums[i + 1:])\n", "def count_inversion(s):\n return sum(s[i] > s[j]\n for i in range(len(s) - 1)\n for j in range(i + 1, len(s)))", "def count_inversion(sequence):\n def rec(arr):\n if len(ar...
{"fn_name": "count_inversion", "inputs": [[[1, 2, 3]], [[-3, -2, -1]], [[-20, 0, 20]], [[-13, 4, 8]], [[1, 3, 2]], [[-2, -3, -1]], [[-20, 20, 0]], [[-13, 9, 8]], [[3, 6, 2]], [[3, 6, 2, 7, 3]], [[26, 32, -21, 45, 21]], [[14, 12, 17, 124, 1, -12, 21, -24]], [[]], [[25, 12, 7, 4, 2, -7, -12, -22]], [[324, 123, 36, 4, -1,...
introductory
https://www.codewars.com/kata/5728a1bc0838ffea270018b2
def count_inversion(sequence):
3,563
Final kata of the series (highly recommended to compute [layers](https://www.codewars.com/kata/progressive-spiral-number-position/) and [branch](https://www.codewars.com/kata/progressive-spiral-number-branch/) first to get a good idea), this is a blatant ripoff of [the one offered on AoC](http://adventofcode.com/2017/d...
["def distance(n):\n if n == 1: return 0\n r = 0 - (1 - n ** .5) // 2\n d, m = divmod(n - (2*r - 1) ** 2 - 1, 2*r)\n z = (r * (1 + 1j) - m - 1) * 1j ** d\n return abs(z.real) + abs(z.imag)", "from itertools import count\n\ndef pos(n):\n for i in count(1, 2):\n if i*i >= n:\n break\n ...
{"fn_name": "distance", "inputs": [[1], [5], [25], [30], [96], [50], [66], [306], [307], [308]], "outputs": [[0], [2], [4], [5], [5], [7], [7], [17], [18], [17]]}
introductory
https://www.codewars.com/kata/5a27e3438882f334a10000e3
def distance(n):