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
2,962
Complete the function which takes two arguments and returns all numbers which are divisible by the given divisor. First argument is an array of `numbers` and the second is the `divisor`. ## Example ```python divisible_by([1, 2, 3, 4, 5, 6], 2) == [2, 4, 6] ```
["def divisible_by(numbers, divisor):\n return [x for x in numbers if x%divisor == 0]", "def divisible_by(numbers, divisor):\n return [i for i in numbers if i%divisor == 0]", "def divisible_by(numbers, divisor):\n return [n for n in numbers if n%divisor==0]", "def divisible_by(numbers, divisor):\n div_by = ...
{"fn_name": "divisible_by", "inputs": [[[1, 2, 3, 4, 5, 6], 2], [[1, 2, 3, 4, 5, 6], 3], [[0, 1, 2, 3, 4, 5, 6], 4], [[0], 4], [[1, 3, 5], 2], [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 1]], "outputs": [[[2, 4, 6]], [[3, 6]], [[0, 4]], [[0]], [[]], [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]]}
introductory
https://www.codewars.com/kata/55edaba99da3a9c84000003b
def divisible_by(numbers, divisor):
2,963
Given a string, swap the case for each of the letters. e.g. CodEwArs --> cODeWaRS ### Examples ``` "" -> "" "CodeWars" -> "cODEwARS" "abc" -> "ABC" "ABC" -> "abc" "123235" -> "123235" ```
["def swap(string_):\n return string_.swapcase()", "swap = str.swapcase", "swap = lambda s: \"\".join([c.lower() if c.isupper() else c.upper() for c in s])", "swap = lambda s : s.swapcase() ", "def swap(s):\n '''\nSalvador Dali - The Persistence of Memory\n ;!>,!!!>\n <! ;!!!`\n !! `!!!.\n !!`...
{"fn_name": "swap", "inputs": [["HelloWorld"], ["CodeWars"], ["ThIs iS A l0NG sENTence witH nUMbERs in IT 123 456"], [""], [" "], [" "], [" 1a1 "], ["H_E_l-l_0 WO|||Rld"], ["TeSt"], ["EeEEeeEEEeee"]], "outputs": [["hELLOwORLD"], ["cODEwARS"], ["tHiS Is a L0ng SentENCE WITh NumBerS IN it 123 456"], [""], [" "], [" "],...
introductory
https://www.codewars.com/kata/5590961e6620c0825000008f
def swap(string_):
2,964
Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 positive integers. No floats or non-positive integers will be passed. For example, when an array is passed like `[19, 5, 42, 2, 77]`, the output should be `7`. `[10, 343445353, 3453445, 3453545353453]` should return ...
["def sum_two_smallest_numbers(numbers):\n return sum(sorted(numbers)[:2])", "def sum_two_smallest_numbers(num_list):\n num_list.sort()\n return num_list[0] + num_list[1]", "def sum_two_smallest_numbers(numbers):\n smallest1 = None\n smallest2 = None \n for n in numbers: \n if not smallest1 or ...
{"fn_name": "sum_two_smallest_numbers", "inputs": [[[5, 8, 12, 18, 22]], [[7, 15, 12, 18, 22]], [[25, 42, 12, 18, 22]], [[1, 8, 12, 18, 5]], [[13, 12, 5, 61, 22]]], "outputs": [[13], [19], [30], [6], [17]]}
introductory
https://www.codewars.com/kata/558fc85d8fd1938afb000014
def sum_two_smallest_numbers(numbers):
2,965
We have 3 equations with 3 unknowns x, y, and z and we are to solve for these unknowns. Equations 4x -3y +z = -10, 2x +y +3z = 0, and -x +2y -5z = 17 will be passed in as an array of [[4, -3, 1, -10], [2, 1, 3, 0], [-1, 2, -5, 17]] and the result should be returned as an array like [1, 4, -2] (i.e. [x, y, z]). Note: I...
["import numpy as np\n\ndef solve_eq(eq):\n a = np.array([arr[:3] for arr in eq])\n b = np.array([arr[-1] for arr in eq])\n return [round(x) for x in np.linalg.solve(a,b)]", "import numpy as np\n\ndef solve_eq(eq):\n m = np.array(eq)\n return np.linalg.solve(m[:,:3], m[:,3]).round().astype(int).tolist()"...
{"fn_name": "solve_eq", "inputs": [[[[4, -3, 1, -10], [2, 1, 3, 0], [-1, 2, -5, 17]]], [[[2, 1, 3, 10], [-3, -2, 7, 5], [3, 3, -4, 7]]], [[[3, 2, 0, 7], [-4, 0, 3, -6], [0, -2, -6, -10]]], [[[4, 2, -5, -21], [2, -2, 1, 7], [4, 3, -1, -1]]]], "outputs": [[[1, 4, -2]], [[-1, 6, 2]], [[3, -1, 2]], [[1, 0, 5]]]}
introductory
https://www.codewars.com/kata/59280c056d6c5a74ca000149
def solve_eq(eq):
2,966
Given a string of words and numbers. Extract the expression including: 1. the operator: either addition or subtraction 2. the two numbers that we are operating on Return the result of the calculation. Example: "Panda has 48 apples and loses 4" returns 44 "Jerry has 34 apples and gains 6" returns 40 "loses" and "g...
["def calculate(s):\n x=[int(i) for i in s.split() if i.isdigit()]\n return sum(x) if 'gains' in s.split() else x[0]-x[1]", "import re\ndef calculate(string):\n x,y=re.findall('\\d+',string)\n if re.search('loses', string): s= int(x)-int(y)\n if re.search('gains', string): s= int(x)+int(y)\n return s"...
{"fn_name": "calculate", "inputs": [["Panda has 48 apples and loses 4"], ["Jerry has 34 apples and gains 6"], ["Tom has 20 apples and gains 15"], ["Fred has 110 bananas and loses 50"], ["Pippi has 20 tunas and gains 0"]], "outputs": [[44], [40], [35], [60], [20]]}
introductory
https://www.codewars.com/kata/57b9fc5b8f5813384a000aa3
def calculate(string):
2,967
Define two functions: `hex_to_bin` and `bin_to_hex` (or `hexToBin` and `binToHex`) # hex_to_bin Takes a hexadecimal string as an argument . **Note:** This string can contain upper or lower case characters and start with any amount of zeros. Returns the binary representation (without leading zeros) of the numerical...
["bin2hex = {\"0000\": \"0\", \"0001\": \"1\", \"0010\": \"2\", \"0011\": \"3\", \n \"0100\": \"4\", \"0101\": \"5\", \"0110\": \"6\", \"0111\": \"7\", \n \"1000\": \"8\", \"1001\": \"9\", \"1010\": \"a\", \"1011\": \"b\", \n \"1100\": \"c\", \"1101\": \"d\", \"1110\": \"e\", \"1111\": \"f...
{"fn_name": "bin_to_hex", "inputs": [["000101"], ["001111"], ["000"], ["10011010010"]], "outputs": [["5"], ["f"], ["0"], ["4d2"]]}
introductory
https://www.codewars.com/kata/55d1b0782aa1152115000037
def bin_to_hex(binary_string):
2,968
You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters. #Examples: ~~~if-not:bf ``` Kata.getMiddle("test") should return "es" Kata.getMiddle("testing") should retur...
["def get_middle(s):\n return s[(len(s)-1)//2:len(s)//2+1]\n", "def get_middle(s):\n index, odd = divmod(len(s), 2)\n return s[index] if odd else s[index - 1:index + 1]\n", "import math\ndef get_middle(s):\n #your code here\n x = len(s)\n y = int(x/2)\n if x%2==0:\n return s[y-1:y+1]\n els...
{"fn_name": "get_middle", "inputs": [["test"], ["testing"], ["middle"], ["A"], ["of"]], "outputs": [["es"], ["t"], ["dd"], ["A"], ["of"]]}
introductory
https://www.codewars.com/kata/56747fd5cb988479af000028
def get_middle(s):
2,969
Laura Bassi was the first female professor at a European university. Despite her immense intellect, she was not always allowed to lecture publicly. One day a professor with very strong beliefs against women in academia sent some `agents` to find Bassi and end her career. Help her escape by telling her the safest pl...
["def advice(agents, n):\n frontier = { (x,y) for x,y in agents if 0<=x<n and 0<=y<n }\n bag = { (x,y) for x in range(n) for y in range(n)}\n if frontier==bag: return []\n while frontier and bag>frontier:\n bag -= frontier\n frontier = {pos for x,y in frontier for pos in ((x+1,y),(x-1,y),(x,y+...
{"fn_name": "advice", "inputs": [[[[1, 1]], 2], [[[1, 1]], 0], [[[9, 9]], 1], [[[0, 0]], 10]], "outputs": [[[[0, 0]]], [[]], [[[0, 0]]], [[[9, 9]]]]}
introductory
https://www.codewars.com/kata/5dd82b7cd3d6c100109cb4ed
def advice(agents, n):
2,970
Given a natural number n, we want to know in how many ways we may express these numbers as product of other numbers. For example the number ```python 18 = 2 x 9 = 3 x 6 = 2 x 3 x 3 # (we do not consider the product 18 x 1), (3 ways) ``` See this example a bit more complicated, ```python 60 = 2 x 30 = 3 x 20 = 4 x ...
["def prod_int_part(n, min_=2):\n total, fac = 0, []\n for d in range(min_, int(n ** .5) + 1):\n if not n % d:\n count, sub = prod_int_part(n // d, d)\n total += count + 1\n if not count: sub = [n // d]\n if not fac: fac = [d] + sub\n return [total, fac]", "de...
{"fn_name": "prod_int_part", "inputs": [[18], [60], [54], [37], [61]], "outputs": [[[3, [2, 3, 3]]], [[10, [2, 2, 3, 5]]], [[6, [2, 3, 3, 3]]], [[0, []]], [[0, []]]]}
introductory
https://www.codewars.com/kata/56135a61f8b29814340000cd
def prod_int_part(n):
2,971
You have to build a pyramid. This pyramid should be built from characters from a given string. You have to create the code for these four methods: ```python watch_pyramid_from_the_side(characters): watch_pyramid_from_above(characters): count_visible_characters_of_the_pyramid(characters): count_all_characters_of_th...
["def watch_pyramid_from_the_side(characters):\n if not characters : return characters\n baseLen = len(characters)*2-1\n return '\\n'.join( ' '*(i) + characters[i]*(baseLen-2*i) + ' '*(i) for i in range(len(characters)-1,-1,-1) )\n\n\ndef watch_pyramid_from_above(characters):\n if not characters : return ch...
{"fn_name": "watch_pyramid_from_the_side", "inputs": [[null], [""]], "outputs": [[null], [""]]}
introductory
https://www.codewars.com/kata/5797d1a9c38ec2de1f00017b
def watch_pyramid_from_the_side(characters):
2,972
Your task is to write function which takes string and list of delimiters as an input and returns list of strings/characters after splitting given string. Example: ```python multiple_split('Hi, how are you?', [' ']) => ['Hi,', 'how', 'are', 'you?'] multiple_split('1+2-3', ['+', '-']) => ['1', '2', '3'] ``` List of del...
["def multiple_split(string, delimiters=[]):\n for d in delimiters:\n string = string.replace(d, '###')\n return [s for s in string.split('###') if s]", "def multiple_split(s, d=[]):\n for i in d:\n s = s.replace(i, '___')\n return [x for x in s.split('___') if x]", "def multiple_split(s, deli...
{"fn_name": "multiple_split", "inputs": [["Hi everybody!", [" ", "!"]], ["(1+2)*6-3^9", ["+", "-", "(", ")", "^", "*"]], ["Solve_this|kata-very\\quickly!", ["!", "|", "\\", "_", "-"]], ["", []], [""], ["some strange string"], ["1_2_3_huhuh_hahaha", ["_"]], ["((1+2))*(6-3)^9", ["+", "-", "(", ")", "^", "*"]], ["(((1+2)-...
introductory
https://www.codewars.com/kata/575690ee34a34efb37001796
def multiple_split(string, delimiters=[]):
2,973
# Task Given an array of 2^(k) integers (for some integer `k`), perform the following operations until the array contains only one element: ``` On the 1st, 3rd, 5th, etc. iterations (1-based) replace each pair of consecutive elements with their sum; On the 2nd, 4th, 6th, etc. iterations replace each pair of consecut...
["def array_conversion(arr):\n sign = 0\n while len(arr) > 1:\n sign = 1^sign\n arr = list(map(lambda x, y: x+y, arr[0::2],arr[1::2]) if sign else map(lambda x, y: x*y, arr[0::2],arr[1::2]))\n return arr[0]", "array_conversion=c=lambda a,p=0:a[1:]and c([[x+y,x*y][p]for x,y in zip(*[iter(a)]*2)],1...
{"fn_name": "array_conversion", "inputs": [[[1, 2, 3, 4, 5, 6, 7, 8]], [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], [[3, 3, 5, 5]]], "outputs": [[186], [64], [60]]}
introductory
https://www.codewars.com/kata/588854201361435f5e0000bd
def array_conversion(arr):
2,974
Write a function that calculates the original product price, without VAT. ## Example If a product price is `200.00` and VAT is `15%`, then the final product price (with VAT) is: `200.00 + 15% = 230.00` Thus, if your function receives `230.00` as input, it should return `200.00` **Notes:** * VAT is *always* `15%` f...
["def excluding_vat_price(price):\n try:\n return round(price / 1.15, 2)\n except TypeError:\n return -1", "def excluding_vat_price(price):\n return round(price / 1.15, 2) if price else -1", "excluding_vat_price = lambda p: round(p/115*100, 2) if p else -1", "def excluding_vat_price(price, vat=15...
{"fn_name": "excluding_vat_price", "inputs": [[230.0], [123], [777], [460.0], [null]], "outputs": [[200.0], [106.96], [675.65], [400.0], [-1]]}
introductory
https://www.codewars.com/kata/5890d8bc9f0f422cf200006b
def excluding_vat_price(price):
2,975
Polycarpus works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let's assume that a song consists of some number of words (that don't contain WUB). To make the dubstep remix of this so...
["def song_decoder(song):\n return \" \".join(song.replace('WUB', ' ').split())", "def song_decoder(song):\n return \" \".join(song.replace('WUB', ' ').split()).strip()\n", "def song_decoder(song):\n import re\n return re.sub('(WUB)+', ' ', song).strip()\n", "def song_decoder(song):\n return ' '.join([a ...
{"fn_name": "song_decoder", "inputs": [["AWUBBWUBC"], ["AWUBWUBWUBBWUBWUBWUBC"], ["WUBAWUBBWUBCWUB"], ["RWUBWUBWUBLWUB"], ["WUBJKDWUBWUBWBIRAQKFWUBWUBYEWUBWUBWUBWVWUBWUB"], ["WUBKSDHEMIXUJWUBWUBRWUBWUBWUBSWUBWUBWUBHWUBWUBWUB"], ["QWUBQQWUBWUBWUBIWUBWUBWWWUBWUBWUBJOPJPBRH"], ["WUBWUBOWUBWUBWUBIPVCQAFWYWUBWUBWUBQWUBWUBWU...
introductory
https://www.codewars.com/kata/551dc350bf4e526099000ae5
def song_decoder(song):
2,976
This time no story, no theory. The examples below show you how to write function `accum`: **Examples:** ``` accum("abcd") -> "A-Bb-Ccc-Dddd" accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy" accum("cwAt") -> "C-Ww-Aaa-Tttt" ``` The parameter of accum is a string which includes only letters from `a..z` and `A.....
["def accum(s):\n return '-'.join(c.upper() + c.lower() * i for i, c in enumerate(s))", "def accum(s):\n return '-'.join((a * i).title() for i, a in enumerate(s, 1))\n", "def accum(s):\n output = \"\"\n for i in range(len(s)):\n output+=(s[i]*(i+1))+\"-\"\n return output.title()[:-1]", "def accum(...
{"fn_name": "accum", "inputs": [["ZpglnRxqenU"], ["NyffsGeyylB"], ["MjtkuBovqrU"], ["EvidjUnokmM"], ["HbideVbxncC"], ["VwhvtHtrxfE"], ["KurgiKmkphY"], ["NctlfBlnmfH"], ["WegunHvbdmV"], ["VoywwSpqidE"], ["VbaixFpxdcO"], ["OlyqvYwkuzF"], ["JrhfdMtchiH"], ["JiwpcSwslvW"], ["EagpiEvmabJ"], ["RznlcEmuxxP"], ["OrggaExarzP"],...
introductory
https://www.codewars.com/kata/5667e8f4e3f572a8f2000039
def accum(s):
2,978
We need a function ```count_sel()``` that receives an array or list of integers (positive and negative) and may give us the following information in the order and structure presented bellow: ```[(1), (2), (3), [[(4)], 5]]``` (1) - Total amount of received integers. (2) - Total amount of different values the array h...
["from collections import defaultdict, Counter\n\n\ndef count_sel(nums):\n cnt = Counter(nums)\n d = defaultdict(list)\n total = 0\n unique = 0\n for k, v in cnt.items():\n d[v].append(k)\n total += v\n unique += 1\n maximum = max(d)\n return [total, unique, len(d[1]), [sorted(...
{"fn_name": "count_sel", "inputs": [[[-3, -2, -1, 3, 4, -5, -5, 5, -1, -5]], [[5, -1, 1, -1, -2, 5, 0, -2, -5, 3]], [[-2, 4, 4, -2, -2, -1, 3, 5, -5, 5]], [[4, -5, 1, -5, 2, 4, -1, 4, -1, 1]], [[4, 4, 2, -3, 1, 4, 3, 2, 0, -5, 2, -2, -2, -5]]], "outputs": [[[10, 7, 5, [[-5], 3]]], [[10, 7, 4, [[-2, -1, 5], 2]]], [[10, ...
introductory
https://www.codewars.com/kata/55f95dbb350b7b1239000030
def count_sel(lst):
2,979
Ask a small girl - "How old are you?". She always says strange things... Lets help her! For correct answer program should return int from 0 to 9. Assume test input string always valid and may look like "1 year old" or "5 years old", etc.. The first char is number only.
["def get_age(age):\n return int(age[0])", "import re\n\ndef get_age(age):\n return int(re.search(r\"\\d+\", age).group())", "def get_age(age):\n for x in age:\n if x.isdigit():\n return int(x) \n", "def get_age(age):\n return int(age.split()[0])", "def get_age(age):\n #your code here\n...
{"fn_name": "get_age", "inputs": [["1 year old"], ["2 years old"], ["3 years old"], ["4 years old"], ["5 years old"], ["6 years old"], ["7 years old"], ["8 years old"], ["9 years old"]], "outputs": [[1], [2], [3], [4], [5], [6], [7], [8], [9]]}
introductory
https://www.codewars.com/kata/557cd6882bfa3c8a9f0000c1
def get_age(age):
2,980
The number ```12``` is the first number in having six divisors, they are: ```1, 2, 3, 4, 6 and 12.``` Your challenge for this kata is to find the minimum number that has a certain number of divisors. For this purpose we have to create the function ```find_min_num() or findMinNum() or similar in the other languages```...
["def find_min_num(d, n=1):\n while div_num(n) != d:\n n += 1\n return n\n\ndef div_num(n):\n s = n**0.5\n return sum(2 for k in range(1, int(s)+1) if n % k == 0) - (s % 1 == 0)", "from collections import Counter\n\ndef number_of_div(n):\n i = 2\n factors = []\n while i * i <= n:\n if...
{"fn_name": "find_min_num", "inputs": [[6], [10], [12], [13]], "outputs": [[12], [48], [60], [4096]]}
introductory
https://www.codewars.com/kata/5612ab201830eb000f0000c0
def find_min_num(d, n=1):
2,981
Your job is to write function last_digits(n,d) which return the last `d` digits of an integer `n` as a list. `n` will be from 0 to 10^10 Examples: `last_digits(1,1) --> [1]` `last_digits(1234,2) --> [3,4]` `last_digits(637547,6) --> [6,3,7,5,4,7]` Special cases: If `d` > the number of digits, just return th...
["def solution(n, d):\n return [int(c) for c in str(n)[-d:]] if d > 0 else []", "def solution(n,d):\n s = str(n)\n return list(map(int,s))[-d if d>0 else len(s):]", "def solution(n,d):\n if d <= 0:\n return []\n else:\n return ([int(i) for i in str(n)][-d:])", "def solution(n,d):\n retur...
{"fn_name": "solution", "inputs": [[1, 1], [123767, 4], [0, 1], [34625647867585, 10], [1234, 0], [24134, -4], [1343, 5]], "outputs": [[[1]], [[3, 7, 6, 7]], [[0]], [[5, 6, 4, 7, 8, 6, 7, 5, 8, 5]], [[]], [[]], [[1, 3, 4, 3]]]}
introductory
https://www.codewars.com/kata/5cd5ba1ce4471a00256930c0
def solution(n,d):
2,982
Here you will create the classic [Pascal's triangle](https://en.wikipedia.org/wiki/Pascal%27s_triangle). Your function will be passed the depth of the triangle and you code has to return the corresponding pascal triangle up to that depth. The triangle should be returned as a nested array. for example: ```python pasca...
["def pascal(p):\n triangle = [[1]]\n for _ in range(p - 1):\n to_sum = list(zip([0] + triangle[-1], triangle[-1] + [0]))\n triangle.append(list(map(sum, to_sum)))\n return triangle\n", "def pascal(p):\n def create_row(n):\n row = [1]\n for k in range(n):\n row.append(...
{"fn_name": "pascal", "inputs": [[1], [5], [10]], "outputs": [[[[1]]], [[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]], [[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1], [1, 6, 15, 20, 15, 6, 1], [1, 7, 21, 35, 35, 21, 7, 1], [1, 8, 28, 56, 70, 56, 28, 8, 1], [1, 9, 36, 84, 126, 1...
introductory
https://www.codewars.com/kata/52945ce49bb38560fe0001d9
def pascal(p):
2,983
A `bouncy number` is a positive integer whose digits neither increase nor decrease. For example, 1235 is an increasing number, 5321 is a decreasing number, and 2351 is a bouncy number. By definition, all numbers under 100 are non-bouncy, and 101 is the first bouncy number. Determining if a number is bouncy is easy, bu...
["def bouncy_count(m):\n num = den = 1\n for i in range(1, 11):\n num *= m + i + i * (i == 10)\n den *= i\n return 10 ** m - num // den + 10 * m + 1", "def bouncy_count(n):\n k = m = 1\n for i in range(1, 11):\n k *= n + i*(1+(i == 10))\n m *= i\n return 10*(10**(n-1)+n)- k...
{"fn_name": "bouncy_count", "inputs": [[0], [1], [2], [3], [4], [5], [6], [10], [20], [50]], "outputs": [[0], [0], [0], [525], [8325], [95046], [987048], [9999722967], [99999999999959940181], [99999999999999999999999999999999999999912040301674]]}
introductory
https://www.codewars.com/kata/5769ac186f2dea6304000172
def bouncy_count(n):
2,984
In this kata, the number 0 is infected. You are given a list. Every turn, any item in the list that is adjacent to a 0 becomes infected and transforms into a 0. How many turns will it take for the whole list to become infected? ``` [0,1,1,0] ==> [0,0,0,0] All infected in 1 turn. [1,1,0,1,1] --> [1,0,0,0,1] --> [0,0,...
["def infected_zeroes(s):\n m=0; l=0\n for i,n in enumerate(s):\n if n==0: m=i if l==0 else max(m, (i-l+1)//2); l=i+1\n return max(m,len(s)-l)", "def infected_zeroes(lst):\n left, *enclosed, right = \"\".join(str(digit) for digit in lst).split(\"0\")\n return max(len(left), len(right), *((len(ones...
{"fn_name": "infected_zeroes", "inputs": [[[0]], [[0, 1, 1, 0]], [[0, 1, 1, 1, 0]], [[1, 1, 0, 1, 1]], [[0, 1, 1, 1]], [[1, 1, 1, 0]]], "outputs": [[0], [1], [2], [2], [3], [3]]}
introductory
https://www.codewars.com/kata/5a511db1b3bfa8f45b000098
def infected_zeroes(lst):
2,985
## **Task** Four mirrors are placed in a way that they form a rectangle with corners at coordinates `(0, 0)`, `(max_x, 0)`, `(0, max_y)`, and `(max_x, max_y)`. A light ray enters this rectangle through a hole at the position `(0, 0)` and moves at an angle of 45 degrees relative to the axes. Each time it hits one of th...
["def reflections(n, m):\n x = y = 0\n dx = dy = 1\n while 1:\n x += dx\n y += dy\n if x == y == 0 or x == n and y == m: return 1\n if 0 in (x, y) and (x == n or y == m): return 0\n if x in (0, n): dx *= -1\n if y in (0, m): dy *= -1", "from math import gcd\n\ndef refl...
{"fn_name": "reflections", "inputs": [[10, 10], [10, 20], [12, 23], [5, 25]], "outputs": [[true], [false], [false], [true]]}
introductory
https://www.codewars.com/kata/5eaf88f92b679f001423cc66
def reflections(max_x, max_y):
2,986
You are given a set of `n` segments on the axis `Ox`, each segment has integer endpoints between `0` and `m` inclusive.  Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers li and ri — coordinates of the left and of the right endpoints.  Consider all integer ...
["def segments(m, arr):\n return [i for i in range(m+1) if not any(a<=i<=b for a,b in arr)]", "def segments(m, a):\n vals = set(range(m+1))\n for st, en in a:\n vals -= set(range(st, en+1))\n return sorted(vals)\n", "def segments(m, a):\n return [p for p in range(m+1) if all(not x[0]<=p<=x[1] for ...
{"fn_name": "segments", "inputs": [[7, [[0, 7]]], [2, []], [0, []], [0, [[0, 0]]]], "outputs": [[[]], [[0, 1, 2]], [[0]], [[]]]}
introductory
https://www.codewars.com/kata/5baa25f3246d071df90002b7
def segments(m, a):
2,987
Your task is to create function```isDivideBy``` (or ```is_divide_by```) to check if an integer number is divisible by each out of two arguments. A few cases: ``` (-12, 2, -6) -> true (-12, 2, -5) -> false (45, 1, 6) -> false (45, 5, 15) -> true (4, 1, 4) -> true (15, -5, 3) -> true ```
["def is_divide_by(number, a, b):\n return number % a == 0 and number % b == 0", "def is_divide_by(n, a, b):\n return n%a == 0 == n%b", "def is_divide_by(number, a, b):\n return not (number%a or number%b)", "def is_divide_by(number, a, b):\n return number % a == 0 == number % b ", "def is_divide_by(number, a...
{"fn_name": "is_divide_by", "inputs": [[8, 2, 4], [12, -3, 4], [8, 3, 4], [48, 2, -5], [-100, -25, 10], [10000, 5, -3], [4, 4, 2], [5, 2, 3], [-96, 25, 17], [33, 1, 33]], "outputs": [[true], [true], [false], [false], [true], [false], [true], [false], [false], [true]]}
introductory
https://www.codewars.com/kata/5a2b703dc5e2845c0900005a
def is_divide_by(number, a, b):
2,988
Your task is to ___Reverse and Combine Words___. It's not too difficult, but there are some things you have to consider... ### So what to do? Input: String containing different "words" separated by spaces ``` 1. More than one word? Reverse each word and combine first with second, third with fourth and so on... (...
["from itertools import zip_longest\n\ndef reverse_and_combine_text(text):\n words = text.split(' ')\n while len(words) > 1:\n it = map(lambda w: w[::-1], words)\n words = [a + b for a, b in zip_longest(it, it, fillvalue='')]\n return words[0]", "def reverse_and_combine_text(s):\n while ' ' in...
{"fn_name": "reverse_and_combine_text", "inputs": [["abc def"], ["abc def ghi jkl"], ["dfghrtcbafed"], ["234hh54 53455 sdfqwzrt rtteetrt hjhjh lllll12 44"], ["sdfsdf wee sdffg 342234 ftt"]], "outputs": [["cbafed"], ["defabcjklghi"], ["dfghrtcbafed"], ["trzwqfdstrteettr45hh4325543544hjhjh21lllll"], ["gffds432243fdsfdse...
introductory
https://www.codewars.com/kata/56b861671d36bb0aa8000819
def reverse_and_combine_text(text):
2,989
The odd and even numbers are fighting against each other! You are given a list of positive integers. The odd numbers from the list will fight using their `1` bits from their binary representation, while the even numbers will fight using their `0` bits. If present in the list, number `0` will be neutral, hence not figh...
["def bits_battle(nums):\n binary = '{:b}'.format\n evens = odds = 0\n for num in nums:\n if num % 2:\n odds += binary(num).count('1')\n else:\n evens += binary(num).count('0')\n if odds == evens:\n return 'tie'\n return '{} win'.format('odds' if odds > evens el...
{"fn_name": "bits_battle", "inputs": [[[5, 3, 14]], [[3, 8, 22, 15, 78]], [[]], [[1, 13, 16]]], "outputs": [["odds win"], ["evens win"], ["tie"], ["tie"]]}
introductory
https://www.codewars.com/kata/58856a06760b85c4e6000055
def bits_battle(numbers):
2,990
The Monty Hall problem is a probability puzzle base on the American TV show "Let's Make A Deal". In this show, you would be presented with 3 doors: One with a prize behind it, and two without (represented with goats). After choosing a door, the host would open one of the other two doors which didn't include a prize, ...
["def monty_hall(door, guesses):\n return round(100.0 * (len(guesses)-guesses.count(door))/len(guesses))", "def monty_hall(c, p):\n print((c, p))\n return round((1 - (p.count(c) / len(p))) * 100)\n # Your code here!\n", "def monty_hall(correct, guesses):\n return round(sum([correct != x for x in guesses]...
{"fn_name": "monty_hall", "inputs": [[1, [1, 2, 2, 2, 3, 2, 1, 3, 1, 3]], [2, [2, 1, 2, 1, 2, 3, 1, 1, 2, 2, 3]], [3, [1, 1, 1, 2, 2, 3, 2, 2, 1, 3, 3, 2, 3, 1, 1, 2]]], "outputs": [[70], [55], [75]]}
introductory
https://www.codewars.com/kata/54f9cba3c417224c63000872
def monty_hall(correct_door_number, participant_guesses):
2,991
# Task You are a magician. You're going to perform a trick. You have `b` black marbles and `w` white marbles in your magic hat, and an infinite supply of black and white marbles that you can pull out of nowhere. You ask your audience to repeatedly remove a pair of marbles from your hat and, for each pair removed...
["def not_so_random(b,w):\n return ['White', 'Black'][b % 2]", "def not_so_random(b,w):\n return ('White', 'Black')[b % 2]", "def not_so_random(b,w):\n if b % 2 == 0 and w % 2 == 0:\n return \"White\"\n elif b % 2 == 1 and w % 2 == 0:\n return \"Black\"\n elif b % 2 == 1 and w % 2 == 1:\n ...
{"fn_name": "not_so_random", "inputs": [[1, 1], [2, 1], [1, 2], [2, 2], [6, 9], [10000, 10000], [11111, 22222]], "outputs": [["Black"], ["White"], ["Black"], ["White"], ["White"], ["White"], ["Black"]]}
introductory
https://www.codewars.com/kata/58ad2e9c0e3c08126000003f
def not_so_random(b,w):
2,992
Given a string made up of letters a, b, and/or c, switch the position of letters a and b (change a to b and vice versa). Leave any incidence of c untouched. Example: 'acb' --> 'bca' 'aabacbaa' --> 'bbabcabb'
["def switcheroo(s):\n return s.translate(str.maketrans('ab','ba'))", "def switcheroo(string):\n return string.translate(str.maketrans('ab','ba'))", "def switcheroo(string):\n return ((string.replace('a','x')).replace('b','a')).replace('x','b')", "def switcheroo(string):\n #your code here\n result = ''\n...
{"fn_name": "switcheroo", "inputs": [["abc"], ["aaabcccbaaa"], ["ccccc"], ["abababababababab"], ["aaaaa"]], "outputs": [["bac"], ["bbbacccabbb"], ["ccccc"], ["babababababababa"], ["bbbbb"]]}
introductory
https://www.codewars.com/kata/57f759bb664021a30300007d
def switcheroo(string):
2,993
## Nova polynomial add This kata is from a series on polynomial handling. ( [#1](http://www.codewars.com/kata/nova-polynomial-1-add-1) [#2](http://www.codewars.com/kata/570eb07e127ad107270005fe) [#3](http://www.codewars.com/kata/5714041e8807940ff3001140 ) [#4](http://www.codewars.com/kata/571a2e2df24bdfd4e20001f5) ) ...
["# return the sum of the two polynomials p1 and p2. \ndef poly_add(p1,p2):\n if p1 == []:\n return p2\n if p2 == []:\n return p1\n return [p1[0] + p2[0]] + poly_add(p1[1:], p2[1:])\n", "from itertools import zip_longest\ndef poly_add(p1, p2):\n return [x+y for x, y in zip_longest(p1, p2, fil...
{"fn_name": "poly_add", "inputs": [[[1], [1]], [[1, 2], [1]], [[1, 2, 3, 4], [4, 3, 2, 1]], [[], []], [[1, 2, 3, 4, 5, 6], []], [[], [1, 2, 3, 4, 5, 6]]], "outputs": [[[2]], [[2, 2]], [[5, 5, 5, 5]], [[]], [[1, 2, 3, 4, 5, 6]], [[1, 2, 3, 4, 5, 6]]]}
introductory
https://www.codewars.com/kata/570ac43a1618ef634000087f
def poly_add(p1, p2):
2,994
Complete the function that takes two numbers as input, ```num``` and ```nth``` and return the `nth` digit of `num` (counting from right to left). ## Note - If ```num``` is negative, ignore its sign and treat it as a positive value - If ```nth``` is not positive, return `-1` - Keep in mind that `42 = 00042`. This means...
["def find_digit(num, nth):\n if nth <= 0:\n return -1\n try:\n return int(str(num).lstrip('-')[-nth])\n except IndexError:\n return 0", "def find_digit(num, nth):\n num = str(num)\n if nth<=0: return -1\n elif nth> len(num): return 0\n else:\n num = num[::-1]\n r...
{"fn_name": "find_digit", "inputs": [[5673, 4], [129, 2], [-2825, 3], [0, 20], [65, 0], [24, -8], [-456, 5], [-1234, 2], [-5540, 1], [678998, 0], [-67854, -57], [0, -3]], "outputs": [[5], [2], [8], [0], [-1], [-1], [0], [3], [0], [-1], [-1], [-1]]}
introductory
https://www.codewars.com/kata/577b9960df78c19bca00007e
def find_digit(num, nth):
2,995
## Your Job Find the sum of all multiples of `n` below `m` ## Keep in Mind * `n` and `m` are natural numbers (positive integers) * `m` is **excluded** from the multiples ## Examples
["def sum_mul(n, m):\n if m>0 and n>0:\n return sum(range(n, m, n))\n else:\n return 'INVALID'", "def sum_mul(n, m):\n return sum(x for x in range(n, m, n)) if m > 0 and n > 0 else 'INVALID'", "xrange = range\n\ndef sum_mul(n, m):\n if m <= 0 or n <= 0:\n return \"INVALID\"\n k = (m ...
{"fn_name": "sum_mul", "inputs": [[4, 123], [123, 4567], [2, 10], [2, 2], [7, 7], [7, 2], [21, 3], [0, 2], [2, 0], [4, -7], [-7, 4]], "outputs": [[1860], [86469], [20], [0], [0], [0], [0], ["INVALID"], ["INVALID"], ["INVALID"], ["INVALID"]]}
introductory
https://www.codewars.com/kata/57241e0f440cd279b5000829
def sum_mul(n, m):
2,996
Everybody know that you passed to much time awake during night time... Your task here is to define how much coffee you need to stay awake after your night. You will have to complete a function that take an array of events in arguments, according to this list you will return the number of coffee you need to stay awake...
["cs={'cw':1,'CW':2,'cat':1,'CAT':2,'dog':1,'DOG':2,'movie':1,'MOVIE':2}\n\ndef how_much_coffee(events):\n c=sum(cs.get(e,0) for e in events)\n return 'You need extra sleep' if c>3 else c", "def how_much_coffee(events):\n activities = [\"cw\", \"cat\", \"dog\", \"movie\"]\n coffee = 0\n for e in events:\...
{"fn_name": "how_much_coffee", "inputs": [[[]], [["cw"]], [["CW"]], [["cw", "CAT"]], [["cw", "CAT", "DOG"]], [["cw", "CAT", "cw=others"]]], "outputs": [[0], [1], [2], [3], ["You need extra sleep"], [3]]}
introductory
https://www.codewars.com/kata/57de78848a8b8df8f10005b1
def how_much_coffee(events):
2,997
The rgb function is incomplete. Complete it so that passing in RGB decimal values will result in a hexadecimal representation being returned. Valid decimal values for RGB are 0 - 255. Any values that fall out of that range must be rounded to the closest valid value. Note: Your answer should always be 6 characters long...
["def rgb(r, g, b):\n round = lambda x: min(255, max(x, 0))\n return (\"{:02X}\" * 3).format(round(r), round(g), round(b))", "def limit(num):\n if num < 0:\n return 0\n if num > 255:\n return 255\n return num\n\n\ndef rgb(r, g, b):\n return \"{:02X}{:02X}{:02X}\".format(limit(r), limit(g...
{"fn_name": "rgb", "inputs": [[0, 0, 0], [1, 2, 3], [255, 255, 255], [254, 253, 252], [-20, 275, 125]], "outputs": [["000000"], ["010203"], ["FFFFFF"], ["FEFDFC"], ["00FF7D"]]}
introductory
https://www.codewars.com/kata/513e08acc600c94f01000001
def rgb(r, g, b):
2,998
You are a *khm*mad*khm* scientist and you decided to play with electron distribution among atom's shells. You know that basic idea of electron distribution is that electrons should fill a shell untill it's holding the maximum number of electrons. --- Rules: - Maximum number of electrons in a shell is distribute...
["def atomic_number(electrons):\n result = []\n i = 1\n while electrons > 0:\n result.append(min(2 * (i ** 2), electrons))\n electrons -= result[-1]\n i += 1\n return result", "def atomic_number(electrons):\n level, shells = 1, []\n while electrons:\n shells.append(min(2 * ...
{"fn_name": "atomic_number", "inputs": [[1], [10], [11], [22], [23], [47], [50], [52], [60], [61]], "outputs": [[[1]], [[2, 8]], [[2, 8, 1]], [[2, 8, 12]], [[2, 8, 13]], [[2, 8, 18, 19]], [[2, 8, 18, 22]], [[2, 8, 18, 24]], [[2, 8, 18, 32]], [[2, 8, 18, 32, 1]]]}
introductory
https://www.codewars.com/kata/59175441e76dc9f9bc00000f
def atomic_number(electrons):
2,999
### Description As hex values can include letters `A` through to `F`, certain English words can be spelled out, such as `CAFE`, `BEEF`, or `FACADE`. This vocabulary can be extended by using numbers to represent other letters, such as `5EAF00D`, or `DEC0DE5`. Given a string, your task is to return the decimal sum of al...
["def hex_word_sum(s):\n return sum(int(w, 16) for w in s.translate(str.maketrans('OS', '05')).split() if set(w) <= set('0123456789ABCDEF'))", "def hex_word_sum(string):\n sum = 0\n for word in string.upper().replace('S', '5').replace('O', '0').split(' '):\n try:\n sum += int(word.strip(), 16...
{"fn_name": "hex_word_sum", "inputs": [["DEFACE"], ["SAFE"], ["CODE"], ["BUGS"], [""], ["DO YOU SEE THAT BEE DRINKING DECAF COFFEE"], ["ASSESS ANY BAD CODE AND TRY AGAIN"]], "outputs": [[14613198], [23294], [49374], [0], [0], [13565769], [10889952]]}
introductory
https://www.codewars.com/kata/5c46ea433dd41b19af1ca3b3
def hex_word_sum(s):
3,000
## Task Let's say we have a positive integer, `$n$`. You have to find the smallest possible positive integer that when multiplied by `$n$`, becomes a perfect power of integer `$k$`. A perfect power of `$k$` is any positive integer that can be represented as `$a^k$`. For example if `$k = 2$`, then `$36$` is a perfect p...
["from collections import Counter\nfrom math import ceil\n\nPRIMES = [2] + [n for n in range(3, 1000, 2) if all(n%d for d in range(3, int(n**0.5) +1, 2))]\n\ndef get_factors(n):\n factors = []\n for p in PRIMES:\n if p > n: break\n while n % p == 0:\n factors.append(p)\n n //= ...
{"fn_name": "mul_power", "inputs": [[100, 3], [36, 2], [72, 4], [5, 2], [1152, 3]], "outputs": [[10], [1], [18], [5], [12]]}
introductory
https://www.codewars.com/kata/5ee98cf315741d00104499e5
def mul_power(n, k):
3,001
# Invalid Login - Bug Fixing #11 Oh NO! Timmy has moved divisions... but now he's in the field of security. Timmy, being the top coder he is, has allowed some bad code through. You must help Timmy and filter out any injected code! ## Task Your task is simple, search the password string for any injected code (Injecte...
["def validate(username, password):\n print (username, password)\n if username == 'Timmy' and password == 'password':\n return 'Successfully Logged in!'\n elif username == 'Alice' and password == 'alice':\n return 'Successfully Logged in!'\n elif username == 'Johny' and password == 'Hf7FAbf6':...
{"fn_name": "validate", "inputs": [["Timmy", "password"], ["Timmy", "h4x0r"], ["Alice", "alice"], ["Timmy", "password\"||\"\"==\""], ["Admin", "gs5bw\"||1==1//"]], "outputs": [["Successfully Logged in!"], ["Wrong username or password!"], ["Successfully Logged in!"], ["Wrong username or password!"], ["Wrong username or ...
introductory
https://www.codewars.com/kata/55e4c52ad58df7509c00007e
def validate(username, password):
3,002
## Task: You have to create a function `isPronic` to check whether the argument passed is a Pronic Number and return true if it is & false otherwise. ### Description: `Pronic Number` -A pronic number, oblong number, rectangular number or heteromecic number, is a number which is the product of two consecutive integers...
["import math\ndef is_pronic(n):\n return n >= 0 and math.sqrt(1 + 4 * n) % 1 == 0", "import math\n\n\ndef is_pronic(n):\n \"\"\"Return True if given number is pronic, else False.\"\"\"\n if n == 0: return True\n if n < 0: return False\n first_int = int(math.sqrt(n))\n second_int = first_int + 1\n ...
{"fn_name": "is_pronic", "inputs": [[2], [3], [4], [5], [6], [-3], [-27]], "outputs": [[true], [false], [false], [false], [true], [false], [false]]}
introductory
https://www.codewars.com/kata/55b1e5c4cbe09e46b3000034
def is_pronic(n):
3,003
```if:python Create a function `args_count`, that returns the count of passed arguments ``` ```if:kotlin Create a function `argsCount`, that returns the count of passed arguments ``` ```if:ruby Create a method `args_count`, that returns the count of passed arguments ``` ```if:julia Create a method `argscount`, that ret...
["def args_count(*args, **kwargs):\n return len(args) + len(kwargs)", "args_count=lambda*a,**b:len(a)+len(b)", "# Create a function args_count, that returns count of passed argument\ndef args_count(*args, **kwargs):\n return len(args) + len(kwargs)\n", "def args_count(*arg, **kwarg):\n return len(arg) + len(kw...
{"fn_name": "args_count", "inputs": [[100], [100, 2, 3]], "outputs": [[1], [3]]}
introductory
https://www.codewars.com/kata/5c44b0b200ce187106452139
def args_count(*args, **kwargs):
3,004
It's Friday night, and Chuck is bored. He's already run 1,000 miles, stopping only to eat a family sized bag of Heatwave Doritos and a large fistful of M&Ms. He just can't stop thinking about kicking something! There is only one thing for it, Chuck heads down to his local MMA gym and immediately challenges every figh...
["def head_smash(arr):\n try:\n return [a.replace('O', ' ') for a in arr] or 'Gym is empty'\n except TypeError:\n return \"This isn't the gym!!\"\n", "def head_smash(arr):\n try:\n return [x.replace('O', ' ') for x in arr] or 'Gym is empty'\n except:\n return 'This isn\\'t the gy...
{"fn_name": "head_smash", "inputs": [[["*****************************************", "** _O_ * _O_ * _O_ * _O_ **", "** /(.)J * C(.)J * /(.)J * C(.)J **", "** _| |_ * _| |_ * _( )_ * _( )_ *"]], [["*** _O_ ** _O_ ** _O_ ** _O_ ***", "*** /(.)J ** /(.)J ** C(.)J ** C(.)J ***"...
introductory
https://www.codewars.com/kata/57061b6fcb7293901a000ac7
def head_smash(arr):
3,005
We have a set of consecutive numbers from ```1``` to ```n```. We want to count all the subsets that do not contain consecutive numbers. E.g. If our set ```S1``` is equal to ```[1,2,3,4,5]``` The subsets that fulfill these property are: ``` [1],[2],[3],[4],[5],[1,3],[1,4],[1,5],[2,4],[2,5],[3,5],[1,3,5] ``` A total of ...
["def f(n):\n a, b = 0, 1\n for _ in range(n):\n a, b = b, a + b + 1\n return a", "def f(n):\n a, b = 1, 2\n for _ in range(n):\n a, b = b, a + b\n return a - 1", "f=lambda n,a=0,b=1:f(n-1,b,a+b) if n!=-2 else a-1 ", "def f(n):\n xs = [0, 1, 2]\n for i in range(n - len(xs) + 1):\n ...
{"fn_name": "f", "inputs": [[5], [3], [2], [20]], "outputs": [[12], [4], [2], [17710]]}
introductory
https://www.codewars.com/kata/591392af88a4994caa0000e0
def f(n):
3,006
Reducing Problems - Bug Fixing #8 Oh no! Timmy's reduce is causing problems, Timmy's goal is to calculate the two teams scores and return the winner but timmy has gotten confused and sometimes teams don't enter their scores, total the scores out of 3! Help timmy fix his program! Return true if team 1 wins or false if...
["def calculate_total(team1, team2):\n return sum(team1) > sum(team2)", "def calculate_total(t1, t2):\n return sum(t1) > sum(t2)", "def calculate_total(t1, t2):\n if sum(t1) > sum(t2):\n return True\n else:\n return False", "def calculate_total(t1s, t2s):\n return sum(t1s) > sum(t2s)", "def...
{"fn_name": "calculate_total", "inputs": [[[1, 2, 2], [1, 0, 0]], [[6, 45, 1], [1, 55, 0]], [[57, 2, 1], []], [[], [3, 4, 3]], [[], []]], "outputs": [[true], [false], [true], [false], [false]]}
introductory
https://www.codewars.com/kata/55d2603d506a40e162000056
def calculate_total(t1, t2):
3,007
Let's say we have a number, `num`. Find the number of values of `n` such that: there exists `n` consecutive **positive** values that sum up to `num`. A positive number is `> 0`. `n` can also be 1. ```python #Examples num = 1 #1 return 1 num = 15 #15, (7, 8), (4, 5, 6), (1, 2, 3, 4, 5) return 4 num = 48 #48, (15, 16,...
["def consecutive_sum(num):\n upper_limit = 1\n while True:\n if upper_limit * (upper_limit + 1) // 2 > num:\n break\n upper_limit += 1\n return sum([1 if i % 2 and not num % i else 1 if not i % 2 and num % i == i//2 else 0 for i in range(1, upper_limit)])", "from math import sqrt\ndef...
{"fn_name": "consecutive_sum", "inputs": [[1], [15], [48], [97]], "outputs": [[1], [4], [2], [2]]}
introductory
https://www.codewars.com/kata/5f120a13e63b6a0016f1c9d5
def consecutive_sum(num):
3,008
Failed Sort - Bug Fixing #4 Oh no, Timmy's Sort doesn't seem to be working? Your task is to fix the sortArray function to sort all numbers in ascending order
["def sort_array(value):\n return \"\".join(sorted(value))", "sort_array=lambda v: \"\".join(sorted(v))", "def sort_array(value):\n return \"\".join(sorted(list(value)))", "sort_array = lambda value: \"\".join(sorted(value, key=lambda a: int(a)))", "def sort_array(value):\n return \"\".join(sorted(value,key=la...
{"fn_name": "sort_array", "inputs": [["12345"], ["54321"], ["34251"], ["11111"], ["10101"]], "outputs": [["12345"], ["12345"], ["12345"], ["11111"], ["00111"]]}
introductory
https://www.codewars.com/kata/55c7f90ac8025ebee1000062
def sort_array(value):
3,009
In this Kata your task will be to return the count of pairs that have consecutive numbers as follows: ```Haskell pairs([1,2,5,8,-4,-3,7,6,5]) = 3 The pairs are selected as follows [(1,2),(5,8),(-4,-3),(7,6),5] --the first pair is (1,2) and the numbers in the pair are consecutive; Count = 1 --the second pair is (5,8) an...
["def pairs(ar):\n count = 0\n for i in range(0, len(ar), 2):\n try:\n a, b = ar[i], ar[i+1]\n except IndexError:\n return count\n \n if abs(a-b) == 1: \n count +=1\n \n return count", "def pairs(arr):\n return sum( abs(a-b)==1 for a,b in z...
{"fn_name": "pairs", "inputs": [[[1, 2, 5, 8, -4, -3, 7, 6, 5]], [[21, 20, 22, 40, 39, -56, 30, -55, 95, 94]], [[81, 44, 80, 26, 12, 27, -34, 37, -35]], [[-55, -56, -7, -6, 56, 55, 63, 62]], [[73, 72, 8, 9, 73, 72]]], "outputs": [[3], [2], [0], [4], [3]]}
introductory
https://www.codewars.com/kata/5a3e1319b6486ac96f000049
def pairs(ar):
3,010
Complete the solution so that it takes the object (JavaScript/CoffeeScript) or hash (ruby) passed in and generates a human readable string from its key/value pairs. The format should be "KEY = VALUE". Each key/value pair should be separated by a comma except for the last pair. **Example:** ```python solution({"a": 1...
["def solution(pairs):\n return ','.join(sorted('{} = {}'.format(k, pairs[k]) for k in pairs))", "def solution(pairs):\n return ','.join(['{} = {}'.format(*a) for a in sorted(pairs.items())])", "solution=lambda d:\",\".join(\"{} = {}\".format(*p)for p in sorted(d.items()))", "def solution(pairs):\n return ','....
{"fn_name": "solution", "inputs": [[{"a": 1, "b": 2}], [{"a": "b", "b": "a"}], [{"0": "a", "b": 2}], [{"b": 1, "c": 2, "e": 3}], [{}]], "outputs": [["a = 1,b = 2"], ["a = b,b = a"], ["0 = a,b = 2"], ["b = 1,c = 2,e = 3"], [""]]}
introductory
https://www.codewars.com/kata/51c7d8268a35b6b8b40002f2
def solution(pairs):
3,011
# Task You have some people who are betting money, and they all start with the same amount of money (this number>0). Find out if the given end-state of amounts is possible after the betting is over and money is redistributed. # Input/Output - `[input]` integer array arr the proposed end-state showing final a...
["def learn_charitable_game(arr):\n return sum(arr) % len(arr) == 0 and sum(arr) > 0", "def learn_charitable_game(arr):\n t = sum(arr)\n return t and t % len(arr) == 0", "from statistics import mean\n\ndef learn_charitable_game(arr):\n m = mean(arr)\n return int(m)==m and m>0", "from statistics import mean...
{"fn_name": "learn_charitable_game", "inputs": [[[100, 100, 100, 90, 1, 0, 0]], [[0, 0, 0, 0]], [[0, 56, 100]], [[33, 19, 38, 87, 93, 4]], [[11]]], "outputs": [[false], [false], [true], [false], [true]]}
introductory
https://www.codewars.com/kata/58a651ff27f95429f80000d0
def learn_charitable_game(arr):
3,012
In this Kata you need to write the method SharedBits that returns true if 2 integers share at least two '1' bits. For simplicity assume that all numbers are positive For example int seven = 7; //0111 int ten = 10; //1010 int fifteen = 15; //1111 SharedBits(seven, ten); //false SharedBits(seven, fifteen); //...
["def shared_bits(a, b):\n return bin(a & b).count('1') > 1", "def shared_bits(a, b):\n return bool(a & b & (a & b) - 1)", "def shared_bits(a, b):\n num = a & b\n count = bin(num).count(\"1\")\n if count >= 2:\n return True\n return False", "def shared_bits(a, b):\n return len(bin(a&b).strip...
{"fn_name": "shared_bits", "inputs": [[1, 2], [16, 8], [1, 1], [2, 3], [7, 10], [43, 77], [7, 15], [23, 7]], "outputs": [[false], [false], [false], [false], [false], [true], [true], [true]]}
introductory
https://www.codewars.com/kata/58a5aeb893b79949eb0000f1
def shared_bits(a, b):
3,013
# Task Given an integer `n`, find the maximal number you can obtain by deleting exactly one digit of the given number. # Example For `n = 152`, the output should be `52`; For `n = 1001`, the output should be `101`. # Input/Output - `[input]` integer `n` Constraints: `10 ≤ n ≤ 1000000.` - `[output]` ...
["def delete_digit(n):\n s = str(n)\n return int(max(s[:i] + s[i+1:] for i in range(len(s))))", "def delete_digit(n):\n # we just need to remove the last digit of a decreasing sequense of digits\n liststrn = list(str(n))\n for i in range(len(liststrn)):\n try:\n if liststrn[i+1] > lists...
{"fn_name": "delete_digit", "inputs": [[152], [1001], [10]], "outputs": [[52], [101], [1]]}
introductory
https://www.codewars.com/kata/5894318275f2c75695000146
def delete_digit(n):
3,014
Simple transposition is a basic and simple cryptography technique. We make 2 rows and put first a letter in the Row 1, the second in the Row 2, third in Row 1 and so on until the end. Then we put the text from Row 2 next to the Row 1 text and thats it. Complete the function that receives a string and encrypt it with t...
["def simple_transposition(text):\n return text[::2] + text[1::2]", "def simple_transposition(text):\n text1=text[0::2]\n text2=text[1::2]\n return text1+text2", "def simple_transposition(text):\n rowOne = True\n one = \"\"\n two = \"\"\n for x in text:\n if(rowOne):\n one += x...
{"fn_name": "simple_transposition", "inputs": [["Sample text"], ["Simple transposition"], ["All that glitters is not gold"], ["The better part of valor is discretion"], ["Conscience does make cowards of us all"], ["Imagination is more important than knowledge"]], "outputs": [["Sml etapetx"], ["Sml rnpstoipetasoiin"], [...
introductory
https://www.codewars.com/kata/57a153e872292d7c030009d4
def simple_transposition(text):
3,015
Given a credit card number we can determine who the issuer/vendor is with a few basic knowns. ```if:python Complete the function `get_issuer()` that will use the values shown below to determine the card issuer for a given card number. If the number cannot be matched then the function should return the string `Unknown`...
["def get_issuer(number):\n s = str(number)\n return (\"AMEX\" if len(s)==15 and s[:2] in (\"34\",\"37\") else\n \"Discover\" if len(s)==16 and s.startswith(\"6011\") else\n \"Mastercard\" if len(s)==16 and s[0]==\"5\" and s[1] in \"12345\" else\n \"VISA\" if len(s) ...
{"fn_name": "get_issuer", "inputs": [[4111111111111111], [4111111111111], [4012888888881881], [41111111111111], [411111111111111], [378282246310005], [348282246310005], [6011111111111117], [5105105105105100], [5105105105105106], [5205105105105106], [5305105105105106], [5405105105105106], [5505105105105106], [9111111111...
introductory
https://www.codewars.com/kata/5701e43f86306a615c001868
def get_issuer(number):
3,016
Check if given chord is minor or major. _____________________________________________________________ Rules: 1. Basic minor/major chord have three elements. 2. Chord is minor when interval between first and second element equals 3 and between second and third -> 4. 3. Chord is major when interval between first and ...
["from itertools import product\n\nNOTES = [['C'], ['C#', 'Db'], ['D'], ['D#', 'Eb'], ['E'], ['F'], ['F#', 'Gb'], ['G'], ['G#', 'Ab'], ['A'], ['A#', 'Bb'], ['B']]*2\nconfig = [('Major', 4), ('Minor', 3)]\n\nDCT_CHORDS = {c: mode for mode, offset in config\n for i in range(len(NOTES)//2)\n ...
{"fn_name": "minor_or_major", "inputs": [["C E G"], ["Db F Ab"], ["D F# A"], ["Eb G Bb"], ["E G# B"], ["F A C"], ["F# A# C#"], ["Gb Bb Db"], ["G B D"], ["Ab C Eb"], ["A C# E"], ["Bb D F"], ["B D# F#"], ["C Eb G"], ["C# E G#"], ["D F A"], ["D# F# A#"], ["Eb Gb Bb"], ["E G B"], ["F Ab C"], ["F# A C#"], ["G Bb D"], ["G# B...
introductory
https://www.codewars.com/kata/57052ac958b58fbede001616
def minor_or_major(chord):
3,017
# Task Vanya gets bored one day and decides to enumerate a large pile of rocks. He first counts the rocks and finds out that he has `n` rocks in the pile, then he goes to the store to buy labels for enumeration. Each of the labels is a digit from 0 to 9 and each of the `n` rocks should be assigned a unique number ...
["from math import log10\n\ndef rocks(n):\n return (n + 1) * int(log10(n) + 1) - (10 ** int(log10(n) + 1) - 1) // 9", "def rocks(n):\n ini, c = '9'*(len(str(n)[:-1])), 0\n while ini:\n c += (n-int(ini))*len(str(n))\n n, ini = int(ini), ini[:-1]\n return c+n", "def rocks(n):\n cost = 0\n ...
{"fn_name": "rocks", "inputs": [[1], [10], [13], [100], [36123011]], "outputs": [[1], [11], [17], [192], [277872985]]}
introductory
https://www.codewars.com/kata/58acf6c20b3b251d6d00002d
def rocks(n):
3,018
Kate likes to count words in text blocks. By words she means continuous sequences of English alphabetic characters (from a to z ). Here are examples: `Hello there, little user5453 374 ())$. I’d been using my sphere as a stool. Slow-moving target 839342 was hit by OMGd-63 or K4mp.` contains "words" `['Hello', 'there', ...
["from re import compile, finditer\n\nOMIT = {'a', 'the', 'on', 'at', 'of', 'upon', 'in', 'as'}\nREGEX = compile(r'[a-z]+')\n\n\ndef word_count(s):\n return sum(a.group() not in OMIT for a in finditer(REGEX, s.lower()))\n", "def word_count(s):\n return sum(1 for w in \"\".join(c if c.isalpha() else \" \" for c in...
{"fn_name": "word_count", "inputs": [["hello there"], ["hello there and a hi"], ["I'd like to say goodbye"], ["Slow-moving user6463 has been here"], ["%^&abc!@# wer45tre"], ["abc123abc123abc"], ["Really2374239847 long ^&#$&(*@# sequence"], ["Hello there, little user5453 374 ())$."]], "outputs": [[2], [4], [6], [6], [3]...
introductory
https://www.codewars.com/kata/56b3b27cadd4ad275500000c
def word_count(s):
3,019
**This Kata is intended as a small challenge for my students** All Star Code Challenge #18 Create a function called that accepts 2 string arguments and returns an integer of the count of occurrences the 2nd argument is found in the first one. If no occurrences can be found, a count of 0 should be returned. Notes: *...
["def str_count(strng, letter):\n counter = 0\n \n for chr in strng:\n if chr == letter:\n counter += 1\n \n return counter", "def str_count(strng, letter):\n return (strng.count(letter))", "def str_count(string, letter):\n return string.count(letter)", "str_count = lambda str...
{"fn_name": "str_count", "inputs": [["hello", "l"], ["hello", "e"], ["codewars", "c"], ["ggggg", "g"], ["hello world", "o"]], "outputs": [[2], [1], [1], [5], [2]]}
introductory
https://www.codewars.com/kata/5865918c6b569962950002a1
def str_count(strng, letter):
3,020
Kontti language is a finnish word play game. You add `-kontti` to the end of each word and then swap their characters until and including the first vowel ("aeiouy"); For example the word `tame` becomes `kome-tantti`; `fruity` becomes `koity-fruntti` and so on. If no vowel is present, the word stays the same. Write...
["import re\n\ndef kontti(s):\n return \" \".join( [ re.sub(\"([^aeiouy]*[aeiouy])(.*)\", r\"ko\\2-\\1ntti\", w, flags = re.I) for w in s.split() ] )", "from re import sub\nfrom functools import partial\nkontti = partial(sub, r'(?i)(\\S*?[aeiouy])(\\S*)', r'ko\\2-\\1ntti')", "import re\n\ndef kontti(s):\n return...
{"fn_name": "kontti", "inputs": [["lamppu"], ["lamppu sofia"], ["silly game"], ["aeiou"], ["xyz lamppu"], [""], ["lAmppU"], ["silly grrr"]], "outputs": [["komppu-lantti"], ["komppu-lantti kofia-sontti"], ["kolly-sintti kome-gantti"], ["koeiou-antti"], ["koz-xyntti komppu-lantti"], [""], ["komppU-lAntti"], ["kolly-sintt...
introductory
https://www.codewars.com/kata/570e1271e5c9a0cf2f000d11
def kontti(s):
3,021
The queen can be moved any number of unoccupied squares in a straight line vertically, horizontally, or diagonally, thus combining the moves of the rook and bishop. The queen captures by occupying the square on which an enemy piece sits. (wikipedia: https://en.wikipedia.org/wiki/Queen_(chess)). ## Task: Write a functi...
["from itertools import product\n\nBOARD = set(map(\"\".join,product(\"ABCDEFGH\", \"12345678\")))\n\ndef available_moves(position):\n if isinstance(position, str) and position in BOARD :\n\n return sorted(p for p in BOARD-{position} \n if abs(ord(p[0])-ord(position[0])) == abs(int(p[1])...
{"fn_name": "available_moves", "inputs": [[7]], "outputs": [[[]]]}
introductory
https://www.codewars.com/kata/5aa1031a7c7a532be30000e5
def available_moves(position):
3,022
In this kata, your job is to return the two distinct highest values in a list. If there're less than 2 unique values, return as many of them, as possible. The result should also be ordered from highest to lowest. Examples: ``` [4, 10, 10, 9] => [10, 9] [1, 1, 1] => [1] [] => [] ```
["def two_highest(ls):\n result = sorted(list(set(ls)), reverse=True)[:2]\n return result if isinstance(ls, (list)) else False", "def two_highest(list):\n return False if isinstance(list, str) else sorted(set(list), reverse=True)[0:2]", "import heapq\ndef two_highest(list_):\n return heapq.nlargest(2, set(l...
{"fn_name": "two_highest", "inputs": [[[]], [[15]], [[15, 20, 20, 17]]], "outputs": [[[]], [[15]], [[20, 17]]]}
introductory
https://www.codewars.com/kata/57ab3c09bb994429df000a4a
def two_highest(arg1):
3,023
# Task "AL-AHLY" and "Zamalek" are the best teams in Egypt, but "AL-AHLY" always wins the matches between them. "Zamalek" managers want to know what is the best match they've played so far. The best match is the match they lost with the minimum goal difference. If there is more than one match with the same differen...
["def best_match(goals1, goals2):\n return min( (a-b, -b, i) for i,(a,b) in enumerate(zip(goals1, goals2)) )[2]", "def best_match(goals1, goals2):\n bestDiff = goals1[0] - goals2[0]\n bestIndex = 0\n for i in range(len(goals1)):\n if goals1[i] - goals2[i] < bestDiff:\n bestIndex = i\n bestD...
{"fn_name": "best_match", "inputs": [[[6, 4], [1, 2]], [[1], [0]], [[1, 2, 3, 4, 5], [0, 1, 2, 3, 4]], [[3, 4, 3], [1, 1, 2]], [[4, 3, 4], [1, 1, 1]]], "outputs": [[1], [0], [4], [2], [1]]}
introductory
https://www.codewars.com/kata/58b38256e51f1c2af0000081
def best_match(goals1, goals2):
3,024
Make a program that filters a list of strings and returns a list with only your friends name in it. If a name has exactly 4 letters in it, you can be sure that it has to be a friend of yours! Otherwise, you can be sure he's not... Ex: Input = ["Ryan", "Kieran", "Jason", "Yous"], Output = ["Ryan", "Yous"] i.e. Note:...
["def friend(x):\n return [f for f in x if len(f) == 4]", "def friend(x):\n #Code\n names = []\n for name in x:\n if len(name) == 4:\n names.append(name)\n return names", "def friend(x):\n return [i for i in x if len(i) == 4]", "def friend(x):\n myFriends = [] # ...
{"fn_name": "friend", "inputs": [[["Ryan", "Kieran", "Mark"]], [["Ryan", "Jimmy", "123", "4", "Cool Man"]], [["Jimm", "Cari", "aret", "truehdnviegkwgvke", "sixtyiscooooool"]], [["Love", "Your", "Face", "1"]], [["Hell", "Is", "a", "badd", "word"]], [["Issa", "Issac", "Issacs", "ISISS"]], [["Robot", "Your", "MOMOMOMO"]],...
introductory
https://www.codewars.com/kata/55b42574ff091733d900002f
def friend(x):
3,025
Write a function that gets a sequence and value and returns `true/false` depending on whether the variable exists in a multidimentional sequence. Example: ``` locate(['a','b',['c','d',['e']]],'e'); // should return true locate(['a','b',['c','d',['e']]],'a'); // should return true locate(['a','b',['c','d',['e']]],'f');...
["def locate(seq, value): \n for s in seq:\n if s == value or (isinstance(s,list) and locate(s, value)): \n return True\n return False", "def locate(seq, value): \n f = 0\n for e in seq:\n if type(e) == list and not f:\n f = locate(e, value)\n elif e == value:\n ...
{"fn_name": "locate", "inputs": [[["a", "b", ["c", "d", ["e"]]], "a"], [["a", "b", ["c", "d", ["e"]]], "d"], [["a", "b", ["c", "d", ["e"]]], "e"], [["a", "b", ["c", "d", ["e"]]], "f"], [["a", "b", ["c", "d", ["e", ["a", "b", ["c", "d", ["e4"]]]]]], "e4"], [["a", "b", ["c", "d", ["e", ["a", "b", ["c", "d", ["e", ["a", "...
introductory
https://www.codewars.com/kata/52840d2b27e9c932ff0016ae
def locate(seq, value):
3,026
# Task **_Given_** a **_list of digits_**, *return the **_smallest number_** that could be formed from these digits, using the digits only once (ignore duplicates).* ___ # Notes: * Only **_positive integers_** *will be passed to the function (> 0 ), no negatives or zeros.* ___ # Input >> Output Examples ``` minVa...
["def min_value(digits):\n return int(\"\".join(map(str,sorted(set(digits)))))\n", "def min_value(digits):\n return int(\"\".join(str(x) for x in sorted(set(digits))))", "def min_value(digits):\n l = list(set(digits))\n l.sort(reverse=True)\n return sum(x * 10**i for i, x in enumerate(l))", "def min_val...
{"fn_name": "min_value", "inputs": [[[1, 3, 1]], [[4, 7, 5, 7]], [[4, 8, 1, 4]], [[5, 7, 9, 5, 7]], [[6, 7, 8, 7, 6, 6]], [[5, 6, 9, 9, 7, 6, 4]], [[1, 9, 1, 3, 7, 4, 6, 6, 7]], [[3, 6, 5, 5, 9, 8, 7, 6, 3, 5, 9]]], "outputs": [[13], [457], [148], [579], [678], [45679], [134679], [356789]]}
introductory
https://www.codewars.com/kata/5ac6932b2f317b96980000ca
def min_value(digits):
3,027
Given a board of `NxN`, distributed with tiles labeled `0` to `N² - 1`(inclusive): A solved grid will have the tiles in order of label, left to right, top to bottom. Return `true` if the board state is currently solved, and `false` if the board state is unsolved. Input will always be a square 2d array. For example...
["def is_solved(board):\n curr = 0;\n for r in board:\n for c in r:\n if c != curr:\n return False;\n curr+=1;\n return True;", "def is_solved(board):\n board = sum(board, [])\n return board == sorted(board)", "def is_solved(board):\n return all( v==w for x,...
{"fn_name": "is_solved", "inputs": [[[[1, 0], [3, 2]]], [[[1, 0, 4], [3, 2, 7], [8, 5, 6]]], [[[6, 7, 8], [0, 1, 2], [3, 4, 5]]]], "outputs": [[false], [false], [false]]}
introductory
https://www.codewars.com/kata/5e28b3ff0acfbb001f348ccc
def is_solved(board):
3,028
The factorial of a number, `n!`, is defined for whole numbers as the product of all integers from `1` to `n`. For example, `5!` is `5 * 4 * 3 * 2 * 1 = 120` Most factorial implementations use a recursive function to determine the value of `factorial(n)`. However, this blows up the stack for large values of `n` - mos...
["import math\n\ndef factorial(n):\n if n >= 0:\n return math.factorial(n)", "import math\ndef factorial(n):\n return math.factorial(n) if n >= 0 else None", "import math\ndef factorial(n):\n return None if n < 0 else math.factorial(n)", "def factorial(n):\n if n < 0:\n return None\n ret = ...
{"fn_name": "factorial", "inputs": [[1], [4], [5], [100], [0], [-25], [3000], [10000], [15000]], "outputs": [[1], [24], [120], [93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000], [1], [null], [41493596034378540...
introductory
https://www.codewars.com/kata/54f0d5447872e8ce9f00013d
def factorial(n):
3,029
> In information theory and computer science, the Levenshtein distance is a string metric for measuring the difference between two sequences. Informally, the Levenshtein distance between two words is the minimum number of single-character edits (i.e. insertions, deletions or substitutions) required to change one word i...
["def levenshtein(a,b):\n d = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]\n\n d[0][:] = list(range(len(b)+1))\n for i in range(1, len(a) + 1):\n d[i][0] = i\n\n for i, x in enumerate(a):\n for j, y in enumerate(b):\n d[i+1][j+1] = min(1 + d[i][j+1], 1 + d[i+1][j], d[i][j] + (1 i...
{"fn_name": "levenshtein", "inputs": [["kitten", "sitting"], ["book", "back"], ["book", "book"], ["qlzcfayxiz", "vezkvgejzb"], ["nayvyedosf", "sjxen"], ["sjxen", "sjxen"], ["peter", "peter"]], "outputs": [[3], [2], [0], [9], [9], [0], [0]]}
introductory
https://www.codewars.com/kata/545cdb4f61778e52810003a2
def levenshtein(a,b):
3,030
Take an integer `n (n >= 0)` and a digit `d (0 <= d <= 9)` as an integer. Square all numbers `k (0 <= k <= n)` between 0 and n. Count the numbers of digits `d` used in the writing of all the `k**2`. Call `nb_dig` (or nbDig or ...) the function taking `n` and `d` as parameters and returning this count. #Examples: ``` ...
["def nb_dig(n, d):\n return sum(str(i*i).count(str(d)) for i in range(n+1))", "def nb_dig(n, d):\n return str([n**2 for n in range(n + 1)]).count(str(d))\n", "def nb_dig(n, d):\n return ''.join(str(a ** 2) for a in range(n + 1)).count(str(d))\n", "def nb_dig(n, d):\n \n tot_occur = 0;\n \n for i in ...
{"fn_name": "nb_dig", "inputs": [[5750, 0], [11011, 2], [12224, 8], [11549, 1], [14550, 7], [8304, 7], [10576, 9], [12526, 1], [7856, 4], [14956, 1]], "outputs": [[4700], [9481], [7733], [11905], [8014], [3927], [7860], [13558], [7132], [17267]]}
introductory
https://www.codewars.com/kata/566fc12495810954b1000030
def nb_dig(n, d):
3,031
Your task is very simple. Just write a function `isAlphabetic(s)`, which takes an input string `s` in lowercase and returns `true`/`false` depending on whether the string is in alphabetical order or not. For example, `isAlphabetic('kata')` is False as 'a' comes after 'k', but `isAlphabetic('ant')` is True. Good luck ...
["def alphabetic(s):\n return sorted(s) == list(s)\n", "def alphabetic(s):\n return all(a<=b for a,b in zip(s, s[1:]))", "def alphabetic(s):\n for i in range(1, len(s)):\n if s[i - 1] > s[i]:\n return False\n return True", "def alphabetic(s):\n return s == ''.join(sorted(s)) ", "def ...
{"fn_name": "alphabetic", "inputs": [["asd"], ["codewars"], ["door"], ["cell"], ["z"], [""]], "outputs": [[false], [false], [true], [true], [true], [true]]}
introductory
https://www.codewars.com/kata/5a8059b1fd577709860000f6
def alphabetic(s):
3,032
The objective of this Kata is to write a function that creates a dictionary of factors for a range of numbers. The key for each list in the dictionary should be the number. The list associated with each key should possess the factors for the number. If a number possesses no factors (only 1 and the number itself), the...
["def factorsRange(n, m):\n return {i: [j for j in range(2, i) if i % j == 0] or ['None'] for i in range(n, m + 1)}", "def factorsRange(n, m):\n res = {}\n \n for num in range(n, m+1):\n factors = []\n \n for div in range(2, num // 2 + 1):\n if num % div == 0:\n ...
{"fn_name": "factorsRange", "inputs": [[2, 6], [5, 20], [2, 100], [10, 30], [200, 220]], "outputs": [[{"2": ["None"], "3": ["None"], "4": [2], "5": ["None"], "6": [2, 3]}], [{"5": ["None"], "6": [2, 3], "7": ["None"], "8": [2, 4], "9": [3], "10": [2, 5], "11": ["None"], "12": [2, 3, 4, 6], "13": ["None"], "14": [2, 7],...
introductory
https://www.codewars.com/kata/58bf3cd9c4492d942a0000de
def factorsRange(n, m):
3,033
Task ======= Make a custom esolang interpreter for the language Tick. Tick is a descendant of [Ticker](https://www.codewars.com/kata/esolang-ticker) but also very different data and command-wise. Syntax/Info ======== Commands are given in character format. Non-command characters should be ignored. Tick has an potent...
["def interpreter(tape):\n memory, ptr, output = {}, 0, \"\"\n \n for command in tape:\n if command == \">\": ptr += 1\n elif command == \"<\": ptr -= 1\n elif command == \"+\": memory[ptr] = (memory.get(ptr, 0) + 1) % 256\n elif command == \"*\": output += chr(memory[ptr])\n ...
{"fn_name": "interpreter", "inputs": [["++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++...
introductory
https://www.codewars.com/kata/587edac2bdf76ea23500011a
def interpreter(tape):
3,034
# Task Your task is to write a function for calculating the score of a 10 pin bowling game. The input for the function is a list of pins knocked down per roll for one player. Output is the player's total score. # Rules ## General rules Rules of bowling in a nutshell: * A game consists of 10 frames. In each frame th...
["def bowling_score(rolls):\n \"Compute the total score for a player's game of bowling.\"\n \n def is_spare(rolls):\n return 10 == sum(rolls[:2])\n\n def is_strike(rolls):\n return 10 == rolls[0]\n\n def calc_score(rolls, frame):\n return (sum(rolls) if frame == 10 else\n sum(rolls[:3]) + calc_...
{"fn_name": "bowling_score", "inputs": [[[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]], [[4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]], [[9, 1, 9, 1, 9, 1, 9, 1, 9, 1, 9, 1, 9, 1, 9, 1, 9, 1, 9, 1, 9]], [[10, 10, 10, 10, 10,...
introductory
https://www.codewars.com/kata/5427db696f30afd74b0006a3
def bowling_score(rolls):
3,035
In mathematics, a matrix (plural matrices) is a rectangular array of numbers. Matrices have many applications in programming, from performing transformations in 2D space to machine learning. One of the most useful operations to perform on matrices is matrix multiplication, which takes a pair of matrices and produces ...
["import numpy as np\n\ndef getMatrixProduct(a, b):\n try:\n return np.matmul(a, b).tolist()\n except:\n return - 1", "def getMatrixProduct(a, b):\n if len(a[0]) != len(b):\n return -1\n result = [[0 for i in range(len(b[0]))] for j in range(len(a))]\n for i in range(len(a)):\n ...
{"fn_name": "getMatrixProduct", "inputs": [[[[2, -2], [5, 3]], [[-1, 4], [7, -6]]], [[[1]], [[3]]], [[[1, 2], [3, 4]], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]], [[[7, 3], [2, 5], [6, 8], [9, 0]], [[7, 4, 9], [8, 1, 5]]], [[[1, 0.5], [-0.5, 1]], [[5, 0.25], [2, 0.5]]]], "outputs": [[[[-16, 20], [16, 2]]], [[[3]]], [-1], [[[73...
introductory
https://www.codewars.com/kata/573248f48e531896770001f9
def getMatrixProduct(a, b):
3,036
# Task Consider the following algorithm for constructing 26 strings S(1) .. S(26): ``` S(1) = "a"; For i in [2, 3, ..., 26]: S(i) = S(i - 1) + character(i) + S(i - 1).``` For example: ``` S(1) = "a" S(2) = S(1) + "b" + S(1) = "a" + "b" + "a" = "aba" S(3) = S(2) + "c" + S(2) = "aba" + "c" +"aba" = "abacaba" ... S(26)...
["def abacaba(k):\n return next(chr(97+i) for i,d in enumerate(f'{k:b}'[::-1]) if d=='1')", "def abacaba(k):\n return chr(96 + (k & -k).bit_length())", "def abacaba(k):\n return chr((k & -k).bit_length() + 96)", "def abacaba(k):\n n = 26\n if k % 2: return 'a'\n while k % pow(2, n) != 0: n -= 1\n r...
{"fn_name": "abacaba", "inputs": [[1], [2], [3], [4], [5], [6], [7], [8], [12], [16]], "outputs": [["a"], ["b"], ["a"], ["c"], ["a"], ["b"], ["a"], ["d"], ["c"], ["e"]]}
introductory
https://www.codewars.com/kata/589d237fdfdef0239a00002e
def abacaba(k):
3,037
# Task CodeBots decided to make a gift for CodeMaster's birthday. They got a pack of candies of various sizes from the store, but instead of giving the whole pack they are trying to make the biggest possible candy from them. On each turn it is possible: ``` to pick any two candies of the same size and merge them ...
["from collections import Counter\ndef obtain_max_number(arr):\n c = Counter(arr)\n while 1:\n find = next((k for k in c if c[k] > 1), None)\n if not find:return max(c)\n c[find] -= 2\n c[find*2] = c.get(find*2,0) + 1", "from bisect import insort\n\ndef obtain_max_number(arr):\n arr...
{"fn_name": "obtain_max_number", "inputs": [[[2, 4, 8, 1, 1, 15]], [[2, 2, 4, 8, 1, 1, 15]], [[2, 4, 8, 1, 1, 15, 15, 7, 7, 7, 7, 7, 7, 7]], [[2, 4, 8, 1, 1, 30, 30, 15, 15, 7, 7]], [[2, 4, 8, 1, 1, 119, 30, 30, 15, 15, 7, 7]], [[2, 4, 8, 1, 1, 32, 8, 8, 64, 30, 30, 15, 15, 7, 7]]], "outputs": [[16], [16], [30], [60], ...
introductory
https://www.codewars.com/kata/5893f03c779ce5faab0000f6
def obtain_max_number(arr):
3,038
In this Kata, you will be given a string and your task is to return the most valuable character. The value of a character is the difference between the index of its last occurrence and the index of its first occurrence. Return the character that has the highest value. If there is a tie, return the alphabetically lowest...
["def solve(st):\n return sorted((st.find(c) - st.rfind(c), c) for c in set(st))[0][1]", "def solve(st):\n return min(set(st), key=lambda c: (st.index(c)-st.rindex(c), c))", "def solve(s):\n d = {}\n for i,c in enumerate(s):\n if c not in d: d[c] = [i,i]\n else: d[c][-1] = i\n retu...
{"fn_name": "solve", "inputs": [["a"], ["aa"], ["bcd"], ["axyzxyz"], ["dcbadcba"], ["aabccc"], ["efgefg"], ["efghijefghi"], ["acefacef"], ["acefacefacef"]], "outputs": [["a"], ["a"], ["b"], ["x"], ["a"], ["c"], ["e"], ["e"], ["a"], ["a"]]}
introductory
https://www.codewars.com/kata/5dd5128f16eced000e4c42ba
def solve(st):
3,039
*This kata is inspired by [Project Euler Problem #387](https://projecteuler.net/problem=387)* --- A [Harshad number](https://en.wikipedia.org/wiki/Harshad_number) (or Niven number) is a number that is divisible by the sum of its digits. A *right truncatable Harshad number* is any Harshad number that, when recursively...
["def gen(n):\n if n >= 10**16: return\n for i in range(10):\n x = 10*n + i\n if x % sum(map(int, str(x))): continue\n yield x\n for y in gen(x): yield y\nL = sorted(x for n in range(1, 10) for x in gen(n))\n\nfrom bisect import bisect_left as bl, bisect_right as br\ndef rthn_between(a...
{"fn_name": "rthn_between", "inputs": [[0, 20], [30, 100], [90, 200], [200, 210], [1000, 2000], [2200, 2300], [9000002182976, 9000195371842]], "outputs": [[[10, 12, 18, 20]], [[30, 36, 40, 42, 45, 48, 50, 54, 60, 63, 70, 72, 80, 81, 84, 90, 100]], [[90, 100, 102, 108, 120, 126, 180, 200]], [[200, 201, 204, 207, 209, 21...
introductory
https://www.codewars.com/kata/5c824b7b9775761ada934500
def rthn_between(a, b):
3,040
# Description "It's the end of trick-or-treating and we have a list/array representing how much candy each child in our group has made out with. We don't want the kids to start arguing, and using our parental intuition we know trouble is brewing as many of the children in the group have received different amounts of ca...
["def candies(s):\n if not s or len(s) == 1:\n return -1\n return len(s) * max(s) - sum(s)\n", "def candies(s):\n return sum([max(s) - x for x in s]) if len(s) > 1 else -1", "def candies(s):\n return max(s) * len(s) - sum(s) if len(s) > 1 else -1", "def candies(s):\n return sum([max(s)-i for i in ...
{"fn_name": "candies", "inputs": [[[5, 8, 6, 4]], [[1, 2, 4, 6]], [[1, 2]], [[4, 2]], [[1, 3, 3, 7]], [[7, 7, 7, 7]], [[17, 20, 50, 61, 42, 44]], [[0]], [[]], [[4]], [[null]]], "outputs": [[9], [11], [1], [2], [14], [0], [132], [-1], [-1], [-1], [-1]]}
introductory
https://www.codewars.com/kata/55466644b5d240d1d70000ba
def candies(s):
3,041
Create a function that takes any sentence and redistributes the spaces (and adds additional spaces if needed) so that each word starts with a vowel. The letters should all be in the same order but every vowel in the sentence should be the start of a new word. The first word in the new sentence may start without a vowel...
["from re import sub\ndef vowel_start(st):\n return sub(r'(?<=.)([aeiou])', r' \\1', sub(r'[^a-z0-9]', '', st.lower()))\n", "def vowel_start(s): \n r = ''\n for letter in s:\n if letter in 'aeiouAEIOU':\n r+=' '+letter.lower()\n elif letter.isalnum():\n r+=letter.lower()\n ...
{"fn_name": "vowel_start", "inputs": [["It is beautiful weather today!"], ["Coding is great"], ["my number is 0208-533-2325"], ["oranges, apples, melon, pineapple"], ["under_score"]], "outputs": [["it isb e a ut if ulw e ath ert od ay"], ["c od ing isgr e at"], ["myn umb er is02085332325"], ["or ang es appl esm el onp ...
introductory
https://www.codewars.com/kata/5a02e9c19f8e2dbd50000167
def vowel_start(st):
3,042
Calculate the trace of a square matrix. A square matrix has `n` rows and `n` columns, where `n` is any integer > 0. The entries of the matrix can contain any number of integers. The function should return the calculated trace of the matrix, or `nil/None` if the array is empty or not square; you can otherwise assume the...
["def trace(matrix):\n if not matrix or len(matrix) != len(matrix[0]):\n return None\n return sum(matrix[i][i] for i in range(len(matrix)))", "def trace(matrix):\n if matrix and set(map(len,matrix))=={len(matrix)}:\n return sum(matrix[x][x] for x in range(len(matrix)))", "trace=lambda m: sum(m[i]...
{"fn_name": "trace", "inputs": [[[[1, 2, 3], [4, 5, 6], [7, 8, 9]]], [[[0, 0], [0, 0]]], [[[0, 0, 0], [0, 0, 0], [0, 0, 0]]], [[[1, 0, 0], [0, 1, 0], [0, 0, -2]]], [[[0]]], [[[1]]], [[[-300]]], [[]], [[[]]], [[[1, 2], [1, 2], [1, 2]]], [[[1, 2, 3], [1, 2, 3]]]], "outputs": [[15], [0], [0], [0], [0], [1], [-300], [null]...
introductory
https://www.codewars.com/kata/55208f16ecb433c5c90001d2
def trace(matrix):
3,043
Given some positive integers, I wish to print the integers such that all take up the same width by adding a minimum number of leading zeroes. No leading zeroes shall be added to the largest integer. For example, given `1, 23, 2, 17, 102`, I wish to print out these numbers as follows: ```python 001 023 002 017 102 ```...
["def print_nums(*arr):\n if not arr: return ''\n ln = len(str(max(arr)))\n return '\\n'.join(str(c).zfill(ln) for c in arr)", "def print_nums(*num):\n return \"\\n\".join([str(x).zfill(len(str(max(num)))) for x in num])\n", "def print_nums(*args):\n return \"\\n\".join(\"{:0{}}\".format(n, len(str(max(a...
{"fn_name": "print_nums", "inputs": [[2], [1, 12, 34], [1009, 2], [1, 1, 13], [2, 5, 8], [1, 8, 27]], "outputs": [["2"], ["01\n12\n34"], ["1009\n0002"], ["01\n01\n13"], ["2\n5\n8"], ["01\n08\n27"]]}
introductory
https://www.codewars.com/kata/58311faba317216aad000168
def print_nums(*args):
3,044
In this Kata, you will be given a string and your task is to determine if that string can be a palindrome if we rotate one or more characters to the left. ```Haskell solve("4455") = true, because after 1 rotation, we get "5445" which is a palindrome solve("zazcbaabc") = true, because after 3 rotations, we get "abczazc...
["def solve(s):\n return any(s[i+1:] + s[:i+1] == s[i::-1] + s[:i:-1] for i in range(len(s)))", "def solve(s):\n for i in range(len(s)):\n xs = s[i:] + s[:i]\n if xs == xs[::-1]:\n return True\n return False\n", "def solve(s):\n for i in range(len(s)):\n if s == s[::-1]:\n ...
{"fn_name": "solve", "inputs": [["aaab"], ["abcabc"], ["4455"], ["zazcbaabc"], ["223456776543"], ["432612345665"], ["qponmlkjihgfeeiefghijklmnopqrsttsr"]], "outputs": [[false], [false], [true], [true], [true], [false], [false]]}
introductory
https://www.codewars.com/kata/5a8fbe73373c2e904700008c
def solve(s):
3,045
Given 2 elevators (named "left" and "right") in a building with 3 floors (numbered `0` to `2`), write a function `elevator` accepting 3 arguments (in order): - `left` - The current floor of the left elevator - `right` - The current floor of the right elevator - `call` - The floor that called an elevator It should re...
["def elevator(left, right, call):\n return \"left\" if abs(call - left) < abs(call - right) else \"right\"", "def elevator(left, right, call):\n if abs(left-call) >= abs(right-call):\n return \"right\"\n else:\n return \"left\"", "def elevator(left, right, call):\n return \"left\" if abs(left...
{"fn_name": "elevator", "inputs": [[0, 1, 0], [0, 1, 1], [0, 1, 2], [0, 0, 0], [0, 2, 1], [0, 0, 1], [0, 0, 2], [0, 2, 0], [0, 2, 2], [1, 0, 0], [1, 0, 1], [1, 0, 2], [1, 1, 0], [1, 1, 1], [1, 1, 2], [1, 2, 0], [1, 2, 1], [1, 2, 2], [2, 0, 0], [2, 0, 1], [2, 0, 2], [2, 1, 0], [2, 1, 1], [2, 1, 2], [2, 2, 0], [2, 2, 1],...
introductory
https://www.codewars.com/kata/5c374b346a5d0f77af500a5a
def elevator(left, right, call):
3,047
Write ```python function repeating_fractions(numerator, denominator) ``` that given two numbers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part has repeated digits, replace those digits with a single digit in parentheses. For example: ```python re...
["import re\ndef repeating_fractions(n, d):\n (i, d) = str(n * 1.0 / d).split('.')\n return i + '.' + re.sub(r'([0-9])\\1+', r'(\\1)', d)", "repeating_fractions = lambda n,d: __import__('re').sub(r\"(\\d)(\\1+)(?!\\.)\",r\"(\\1)\",str(n/float(d)))", "import re\n\ndef repeating_fractions(num, den):\n d, f = str(num...
{"fn_name": "repeating_fractions", "inputs": [[0, 1], [18018018, 80000000000], [1, 1], [1, 2], [1, 3], [1554, 70]], "outputs": [["0.0"], ["0.(0)(2)5(2)5(2)5"], ["1.0"], ["0.5"], ["0.(3)"], ["22.2"]]}
introductory
https://www.codewars.com/kata/5613475e4778aab4d600004f
def repeating_fractions(n,d):
3,048
Write function alternateCase which switch every letter in string from upper to lower and from lower to upper. E.g: Hello World -> hELLO wORLD
["def alternateCase(s):\n return s.swapcase()", "alternateCase = str.swapcase", "def alternateCase(s):\n return ''.join(c.swapcase() for c in s)", "def alternateCase(s):\n '''\nSalvador Dali - The Persistence of Memory\n ;!>,!!!>\n <! ;!!!`\n !! `!!!.\n !!`,!!!>\n !! !!!!!\n ;!! !!...
{"fn_name": "alternateCase", "inputs": [["ABC"], [""], [" "], ["Hello World"], ["cODEwARS"], ["i LIKE MAKING KATAS VERY MUCH"], ["HuMpTy DuMpTy SaT On A WaLl"], ["aBracaDabRa"], ["Hickory DICKORY dock"], ["Jack JUMPED over THE CaNdLeStIcK"]], "outputs": [["abc"], [""], [" "], ["hELLO wORLD"], ["CodeWars"], ["I like mak...
introductory
https://www.codewars.com/kata/57a62154cf1fa5b25200031e
def alternateCase(s):
3,049
Write a function that replaces 'two', 'too' and 'to' with the number '2'. Even if the sound is found mid word (like in octopus) or not in lowercase grandma still thinks that should be replaced with a 2. Bless her. ```text 'I love to text' becomes 'I love 2 text' 'see you tomorrow' becomes 'see you 2morrow' 'look at th...
["import re\n\ndef textin(txt ):\n return re.sub(r'(two|too|to)', '2', txt, flags=re.I)", "import re\n\ndef textin(str):\n return re.sub('(?i)t[wo]?o','2',str)", "textin = lambda s: __import__(\"re\").sub(r\"(?i)t[wo]?o\", \"2\", s)", "import re\n\n\ndef textin(stg):\n return re.sub(r\"too|two|to\", \"2\", stg, ...
{"fn_name": "textin", "inputs": [["I love to text"], ["see you tomorrow"], ["look at that octopus"], ["BECAUSE I WANT TO"]], "outputs": [["I love 2 text"], ["see you 2morrow"], ["look at that oc2pus"], ["BECAUSE I WANT 2"]]}
introductory
https://www.codewars.com/kata/5a043fbef3251a5a2b0002b0
def textin(st):
3,050
Write a function called `LCS` that accepts two sequences and returns the longest subsequence common to the passed in sequences. ### Subsequence A subsequence is different from a substring. The terms of a subsequence need not be consecutive terms of the original sequence. ### Example subsequence Subsequences of `"abc"...
["def lcs(x, y):\n if len(x) == 0 or len(y) == 0:\n return ''\n if x[-1] == y[-1]:\n return lcs(x[:-1], y[:-1]) + x[-1]\n else:\n lcs1 = lcs(x,y[:-1])\n lcs2 = lcs(x[:-1],y)\n if len(lcs1) > len(lcs2):\n return lcs1\n else:\n return lcs2\n", "from...
{"fn_name": "lcs", "inputs": [["a", "b"], ["a", "a"], ["abc", "ac"], ["abcdef", "abc"], ["abcdef", "acf"], ["anothertest", "notatest"], ["132535365", "123456789"], ["finaltest", "zzzfinallyzzz"]], "outputs": [[""], ["a"], ["ac"], ["abc"], ["acf"], ["nottest"], ["12356"], ["final"]]}
introductory
https://www.codewars.com/kata/52756e5ad454534f220001ef
def lcs(x, y):
3,051
The idea for this Kata came from 9gag today.[here](http://9gag.com/gag/amrb4r9) [screen]:("http://img-9gag-fun.9cache.com/photo/amrb4r9_700b.jpg") You'll have to translate a string to Pilot's alphabet (NATO phonetic alphabet) [wiki](https://en.wikipedia.org/wiki/NATO_phonetic_alphabet). Like this: **Input:** `If, ...
["import string\n\ndb = { 'A':'Alfa','B':'Bravo','C':'Charlie','D':'Delta','E':'Echo',\n 'F':'Foxtrot','G':'Golf','H':'Hotel','I':'India','J':'Juliett',\n 'K':'Kilo','L':'Lima','M':'Mike','N':'November','O':'Oscar',\n 'P':'Papa','Q':'Quebec','R':'Romeo','S':'Sierra','T':'Tango',\n 'U':'Uniform',...
{"fn_name": "to_nato", "inputs": [["If you can read"], ["Did not see that coming"]], "outputs": [["India Foxtrot Yankee Oscar Uniform Charlie Alfa November Romeo Echo Alfa Delta"], ["Delta India Delta November Oscar Tango Sierra Echo Echo Tango Hotel Alfa Tango Charlie Oscar Mike India November Golf"]]}
introductory
https://www.codewars.com/kata/586538146b56991861000293
def to_nato(words):
3,052
### Description: Remove all exclamation marks from sentence except at the end. ### Examples ``` remove("Hi!") == "Hi!" remove("Hi!!!") == "Hi!!!" remove("!Hi") == "Hi" remove("!Hi!") == "Hi!" remove("Hi! Hi!") == "Hi Hi!" remove("Hi") == "Hi" ```
["def remove(s):\n return s.replace('!', '')+ '!'*(len(s)- len(s.rstrip('!')))", "import re\n\ndef remove(s):\n return re.sub(r'!+(?!!*$)', '', s)", "def remove(s):\n end_i = len(s.rstrip('!'))\n return s[:end_i].replace('!', '') + s[end_i:]", "def remove(s):\n num = 0\n for letter in s[::-1]:\n ...
{"fn_name": "remove", "inputs": [["Hi!"], ["Hi!!!"], ["!Hi"], ["!Hi!"], ["Hi! Hi!"], ["Hi"]], "outputs": [["Hi!"], ["Hi!!!"], ["Hi"], ["Hi!"], ["Hi Hi!"], ["Hi"]]}
introductory
https://www.codewars.com/kata/57faefc42b531482d5000123
def remove(s):
3,053
Create a function `close_compare` that accepts 3 parameters: `a`, `b`, and an optional `margin`. The function should return whether `a` is lower than, close to, or higher than `b`. `a` is "close to" `b` if `margin` is higher than or equal to the difference between `a` and `b`. When `a` is lower than `b`, return `-1`. ...
["def close_compare(a, b, margin = 0):\n return 0 if abs(a - b) <= margin else -1 if b > a else 1", "def close_compare(a, b, margin=0):\n if a == b or abs(a - b) <= margin:\n return 0\n if a < b:\n return -1\n if a > b:\n return 1", "def close_compare(a, b, margin=0):\n if a-b>margin...
{"fn_name": "close_compare", "inputs": [[4, 5], [5, 5], [6, 5], [2, 5, 3], [5, 5, 3], [8, 5, 3], [8.1, 5, 3], [1.99, 5, 3]], "outputs": [[-1], [0], [1], [0], [0], [0], [1], [-1]]}
introductory
https://www.codewars.com/kata/56453a12fcee9a6c4700009c
def close_compare(a, b, margin=0):
3,054
A [sequence or a series](http://world.mathigon.org/Sequences), in mathematics, is a string of objects, like numbers, that follow a particular pattern. The individual elements in a sequence are called terms. A simple example is `3, 6, 9, 12, 15, 18, 21, ...`, where the pattern is: _"add 3 to the previous term"_. In thi...
["def sum_of_n(n):\n return [(-1 if n < 0 else 1) * sum(range(i+1)) for i in range(abs(n)+1)]\n", "def sum_of_n(n):\n output = [0]\n sign = 1\n if n < 0: sign = -1\n for numb in range(1, abs(n) + 1):\n output.append(sign * (numb + abs(output[numb - 1])))\n return output", "def sum_of_n(n):\n ...
{"fn_name": "sum_of_n", "inputs": [[3], [-4], [1], [0], [10]], "outputs": [[[0, 1, 3, 6]], [[0, -1, -3, -6, -10]], [[0, 1]], [[0]], [[0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55]]]}
introductory
https://www.codewars.com/kata/5436f26c4e3d6c40e5000282
def sum_of_n(n):
3,055
Create a function that takes 2 positive integers in form of a string as an input, and outputs the sum (also as a string): If either input is an empty string, consider it as zero.
["def sum_str(a, b):\n return str(int(a or 0) + int(b or 0))", "def sum_str(a, b):\n return str(int('0' + a) + int('0' + b))", "def sum_str(*values):\n return str(sum(int(s or '0') for s in values))\n", "def sum_str(a, b):\n print(a, b)\n if a == \"\" or a == None: a = \"0\"\n if b == \"\" or b == Non...
{"fn_name": "sum_str", "inputs": [["4", "5"], ["34", "5"], ["9", ""], ["", "9"]], "outputs": [["9"], ["39"], ["9"], ["9"]]}
introductory
https://www.codewars.com/kata/5966e33c4e686b508700002d
def sum_str(a, b):
3,056
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are: 2332 110011 54322345 You'll be given 2 numbers as arguments: ```(num,s)```. Write a function which returns an array of ```s``` number of numerical palindromes tha...
["def palindrome(num,s):\n if not (type(num) == type(s) == int) or num < 0 or s < 0:\n return \"Not valid\"\n \n ans, num = [], max(num, 11)\n while len(ans) != s:\n if num == int(str(num)[::-1]):\n ans.append(num)\n num += 1\n return ans", "def palindrome(num, s):\n if...
{"fn_name": "palindrome", "inputs": [[6, 4], [75, 1], [19, 3], [101, 2], ["ACCDDCCA", 3], [773, "1551"], [-4505, 15]], "outputs": [[[11, 22, 33, 44]], [[77]], [[22, 33, 44]], [[101, 111]], ["Not valid"], ["Not valid"], ["Not valid"]]}
introductory
https://www.codewars.com/kata/58e09234ca6895c7b300008c
def palindrome(num,s):
3,057
A **bouncy number** is a positive integer whose digits neither increase nor decrease. For example, `1235` is an increasing number, `5321` is a decreasing number, and `2351` is a bouncy number. By definition, all numbers under `100` are non-bouncy, and `101` is the first bouncy number. To complete this kata, you must wr...
["def is_bouncy(n):\n return sorted(str(n)) != list(str(n)) and sorted(str(n)) != list(str(n))[::-1]", "def is_bouncy(n):\n s = str(n)\n decrease = increase = False\n for a, b in zip(s, s[1:]):\n if a < b:\n increase = True\n elif a > b:\n decrease = True\n return decr...
{"fn_name": "is_bouncy", "inputs": [[0], [99], [101], [120], [122], [221], [2379], [29340], [234689], [98874], [92722983], [129347924210]], "outputs": [[false], [false], [true], [true], [false], [false], [false], [true], [false], [false], [true], [true]]}
introductory
https://www.codewars.com/kata/5769a78c6f2dea72b3000027
def is_bouncy(number):
3,058
In recreational mathematics, a magic square is an arrangement of distinct numbers (i.e., each number is used once), usually integers, in a square grid, where the numbers in each row, and in each column, and the numbers in the main and secondary diagonals, all add up to the same number, called the "magic constant." For...
["def is_magical(sq):\n return sum(sq[2:7:2])==sum(sq[::4])==sum(sq[::3])==sum(sq[1::3])==sum(sq[2::3])==sum(sq[:3])==sum(sq[3:6])==sum(sq[6:])", "def is_magical(sq):\n return len(set( [sum(sq[i*3:(i+1)*3]) for i in range(3)] # lines\n + [sum(sq[i::3]) for i in range(3)] ...
{"fn_name": "is_magical", "inputs": [[[4, 9, 2, 3, 5, 7, 8, 1, 6]], [[4, 9, 2, 3, 5, 7, 8, 6, 1]], [[1, 2, 3, 4, 5, 6, 7, 8, 9]], [[9, 4, 7, 3, 5, 2, 8, 6, 1]], [[8, 1, 6, 3, 5, 7, 4, 9, 2]]], "outputs": [[true], [false], [false], [false], [true]]}
introductory
https://www.codewars.com/kata/57be6a612eaf7cc3af000178
def is_magical(sq):
3,059
You have an award-winning garden and everyday the plants need exactly 40mm of water. You created a great piece of JavaScript to calculate the amount of water your plants will need when you have taken into consideration the amount of rain water that is forecast for the day. Your jealous neighbour hacked your computer an...
["def rain_amount(mm):\n if mm < 40:\n return \"You need to give your plant \" + str(40 - mm) + \"mm of water\"\n else:\n return \"Your plant has had more than enough water for today!\"", "def rain_amount(mm):\n if mm < 40:\n return 'You need to give your plant {}mm of water'.for...
{"fn_name": "rain_amount", "inputs": [[100], [40], [39], [5], [0]], "outputs": [["Your plant has had more than enough water for today!"], ["Your plant has had more than enough water for today!"], ["You need to give your plant 1mm of water"], ["You need to give your plant 35mm of water"], ["You need to give your plant 4...
introductory
https://www.codewars.com/kata/57158fb92ad763bb180004e7
def rain_amount(mm):
3,060
In the board game Talisman, when two players enter combat the outcome is decided by a combat score, equal to the players power plus any modifiers plus the roll of a standard 1-6 dice. The player with the highest combat score wins and the opposing player loses a life. In the case of a tie combat ends with neither player...
["def get_required(player,enemy):\n p_sum = sum(player)\n e_sum = sum(enemy)\n \n diff = p_sum - e_sum\n \n if diff == 0:\n return 'Random'\n \n if diff > 5:\n return 'Auto-win'\n \n if diff < -5:\n return 'Auto-lose'\n \n if diff == -5:\n return 'Pray for...
{"fn_name": "get_required", "inputs": [[[8, 1], [3, 0]], [[2, 0], [8, 1]], [[4, 0], [4, 0]], [[6, 0], [8, 0]], [[8, 0], [6, 0]], [[4, 3], [6, 0]], [[1, 0], [5, 0]], [[3, 3], [5, 3]], [[1, 10], [1, 4]], [[3, 3], [6, 0]], [[7, 2], [6, 8]]], "outputs": [["Auto-win"], ["Auto-lose"], ["Random"], ["(1..3)"], ["(5..6)"], ["(6...
introductory
https://www.codewars.com/kata/541837036d821665ee0006c2
def get_required(player,enemy):
3,061
Complete the function to find the count of the most frequent item of an array. You can assume that input is an array of integers. For an empty array return `0` ## Example ```python input array: [3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3] ouptut: 5 ``` The most frequent number in the array is `-1` and it occurs `5` t...
["def most_frequent_item_count(collection):\n if collection:\n return max([collection.count(item) for item in collection])\n return 0", "from collections import Counter\n\n\ndef most_frequent_item_count(collection):\n return Counter(collection).most_common(1)[0][1] if collection else 0\n", "def most_fre...
{"fn_name": "most_frequent_item_count", "inputs": [[[3, -1, -1]], [[3, -1, -1, -1, 2, 3, -1, 3, -1, 2, 4, 9, 3]], [[]], [[9]]], "outputs": [[2], [5], [0], [1]]}
introductory
https://www.codewars.com/kata/56582133c932d8239900002e
def most_frequent_item_count(collection):
3,062
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are: 2332 110011 54322345 For a given number `num`, write a function to test if it's a numerical palindrome or not and return a boolean (true if it is and false if ...
["def palindrome(num):\n if type(num) is not int or num <1:\n return \"Not valid\"\n return num == int(str(num)[::-1])", "def palindrome(num):\n return str(num) == str(num)[::-1] if type(num) == int and num > 0 else \"Not valid\"", "def palindrome(n):\n try:\n return 1. * n == int(str(n)[::-1]...
{"fn_name": "palindrome", "inputs": [[1221], [110011], [1456009006541], [123322], [1], [152], [9999], ["ACCDDCCA"], ["@14AbC"], ["1221"], [-450]], "outputs": [[true], [true], [true], [false], [true], [false], [true], ["Not valid"], ["Not valid"], ["Not valid"], ["Not valid"]]}
introductory
https://www.codewars.com/kata/58ba6fece3614ba7c200017f
def palindrome(num):
3,063
Story Jumbo Juice makes a fresh juice out of fruits of your choice.Jumbo Juice charges $5 for regular fruits and $7 for special ones. Regular fruits are Banana, Orange, Apple, Lemon and Grapes. Special ones are Avocado, Strawberry and Mango. Others fruits that are not listed are also available upon request. Those extra...
["def mix_fruit(arr):\n regular = [\"banana\", \"orange\", \"apple\", \"lemon\", \"grapes\"]\n special = [\"avocado\", \"strawberry\", \"mango\"]\n return round(sum(5 if fruit.lower() in regular else (7 if fruit.lower() in special else 9) for fruit in arr)/len(arr))\n", "costs = { 'banana': 5, 'orange': 5, 'ap...
{"fn_name": "mix_fruit", "inputs": [[["banana", "mango", "avocado"]], [["melon", "Mango", "kiwi"]], [["watermelon", "cherry", "avocado"]], [["watermelon", "lime", "tomato"]], [["blackBerry", "coconut", "avocado"]], [["waterMelon", "mango"]], [["watermelon", "pEach"]], [["watermelon", "Orange", "grapes"]], [["watermelon...
introductory
https://www.codewars.com/kata/5905871c00881d0e85000015
def mix_fruit(arr):