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,761
Find the length between 2 co-ordinates. The co-ordinates are made of integers between -20 and 20 and will be given in the form of a 2D array: (0,0) and (5,-7) would be [ [ 0 , 0 ] , [ 5, -7 ] ] The function must return the answer rounded to 2 decimal places in the form of a string. ```python length_of_line([[0, 0],...
["from math import sqrt\ndef length_of_line(array):\n x1, y1, x2, y2 = array[0][0], array[0][1], array[1][0], array[1][1]\n return '{:.2f}'.format((sqrt((x2-x1)**2 + (y2-y1)**2)))", "import math\ndef length_of_line(array):\n return \"{:.02f}\".format(math.sqrt((array[1][0] - array[0][0])**2 + (array[1][1] - array[...
{"fn_name": "length_of_line", "inputs": [[[[0, 0], [1, 1]]], [[[0, 0], [-5, -6]]], [[[0, 0], [10, 15]]], [[[0, 0], [5, 1]]], [[[0, 0], [5, 4]]], [[[0, 0], [-7, 4]]], [[[0, 0], [0, 0]]], [[[-3, 4], [10, 5]]]], "outputs": [["1.41"], ["7.81"], ["18.03"], ["5.10"], ["6.40"], ["8.06"], ["0.00"], ["13.04"]]}
introductory
https://www.codewars.com/kata/55f1786c296de4952f000014
def length_of_line(array):
2,762
You are working at a lower league football stadium and you've been tasked with automating the scoreboard. The referee will shout out the score, you have already set up the voice recognition module which turns the ref's voice into a string, but the spoken score needs to be converted into a pair for the scoreboard! e.g...
["def scoreboard(string):\n scores = {'nil': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9}\n return [scores[x] for x in string.split() if x in scores]", "PTS = {w:i for i,w in enumerate('nil one two three four five six seven eight nine'.split())}\n\ndef scor...
{"fn_name": "scoreboard", "inputs": [["The score is four nil"], ["new score: two three"], ["two two"], ["Arsenal just conceded another goal, two nil"]], "outputs": [[[4, 0]], [[2, 3]], [[2, 2]], [[2, 0]]]}
introductory
https://www.codewars.com/kata/5b6c220fa0a661fbf200005d
def scoreboard(string):
2,763
In mathematics, a [Diophantine equation](https://en.wikipedia.org/wiki/Diophantine_equation) is a polynomial equation, usually with two or more unknowns, such that only the integer solutions are sought or studied. In this kata we want to find all integers `x, y` (`x >= 0, y >= 0`) solutions of a diophantine equation o...
["import math\ndef sol_equa(n):\n res = []\n for i in range(1, int(math.sqrt(n)) + 1):\n if n % i == 0:\n j = n // i\n if (i + j) % 2 == 0 and (j - i) % 4 == 0:\n x = (i + j) // 2\n y = (j - i) // 4\n res.append([x, y])\n \n r...
{"fn_name": "sol_equa", "inputs": [[5], [12], [13], [16], [17], [20], [9001], [9004], [9005], [9008], [90001], [90002], [90004], [90005], [90009], [900001], [900004], [900005], [9000001], [9000004], [90000001], [90000004], [900000012], [9000000041]], "outputs": [[[[3, 1]]], [[[4, 1]]], [[[7, 3]]], [[[4, 0]]], [[[9, 4]]...
introductory
https://www.codewars.com/kata/554f76dca89983cc400000bb
def sol_equa(n):
2,764
We are interested in collecting the triples of positive integers ```(a, b, c)``` that fulfill the following equation: ```python a² + b² = c³ ``` The first triple with the lowest values that satisfies the equation we have above is (2, 2 ,2). In effect: ```python 2² + 2² = 2³ 4 + 4 = 8 ``` The first pair of triples tha...
["from bisect import bisect_right as bisect\n\nRES = [[] for _ in range(11)]\n\nfor c in range(1,1001):\n c3 = c**3\n nSol = sum( ((c3-a**2)**.5).is_integer() for a in range(1,int((c3//2)**.5+1)))\n if 0 < nSol < 11: RES[nSol].append(c)\n \n\ndef find_abc_sumsqcube(c_max, nSol):\n return RES[nSol][:bisec...
{"fn_name": "find_abc_sumsqcube", "inputs": [[5, 1], [5, 2], [10, 2], [20, 8], [100, 8], [100, 3], [100, 2]], "outputs": [[[2]], [[5]], [[5, 10]], [[]], [[65, 85]], [[25, 100]], [[5, 10, 13, 17, 20, 26, 29, 34, 37, 40, 41, 45, 52, 53, 58, 61, 68, 73, 74, 80, 82, 89, 90, 97]]]}
introductory
https://www.codewars.com/kata/5618716a738b95cee8000062
def find_abc_sumsqcube(c_max, num_sol):
2,765
Cascading Style Sheets (CSS) is a style sheet language used for describing the look and formatting of a document written in a markup language. A style sheet consists of a list of rules. Each rule or rule-set consists of one or more selectors, and a declaration block. Selector describes which element it matches. Someti...
["import re\n\ndef compare(a, b):\n return a if specificity(a) > specificity(b) else b\n \ndef specificity(s):\n return [len(re.findall(r, s)) for r in (r'#\\w+', r'\\.\\w+', r'(^| )\\w+')]", "import re\ndef compare(a, b):\n\n def scoreCSS(s):\n d = {'#':0, '.':0, ' ':0}\n for c in re.findall(\"[#\\. ](?=...
{"fn_name": "compare", "inputs": [["body p", "div"], ["body", "html"], ["p a", "span"], ["div p span a", "div p span a b"], ["strong", "p b"], [".first", ".last"], [".foo.bar", ".x .y"], [".x .y", ".foo.bar"], [".red.apple", ".red"], [".test1 .test2.test3", ".test1 .test4 .test5 .test6"], [".box.box-first", ".box"], ["...
introductory
https://www.codewars.com/kata/5379fdfad08fab63c6000a63
def compare(a, b):
2,766
The number `198` has the property that `198 = 11 + 99 + 88, i.e., if each of its digits is concatenated twice and then summed, the result will be the original number`. It turns out that `198` is the only number with this property. However, the property can be generalized so that each digit is concatenated `n` times and...
["def check_concatenated_sum(n, r):\n return abs(n) == sum(int(e*r) for e in str(abs(n)) if r) ", "def check_concatenated_sum(number, n):\n return (10**n - 1)//9 * sum(map(int, str(abs(number)))) == abs(number)", "def check_concatenated_sum(num, n):\n return n and num % int('1' * n) == 0", "def check_concatena...
{"fn_name": "check_concatenated_sum", "inputs": [[2997, 3], [-198, 2], [-13332, 4], [-9, 1], [198, 0], [123, 2], [123456789, 2]], "outputs": [[true], [true], [true], [true], [false], [false], [false]]}
introductory
https://www.codewars.com/kata/59a1ec603203e862bb00004f
def check_concatenated_sum(num, n):
2,767
DNA sequencing data can be stored in many different formats. In this Kata, we will be looking at SAM formatting. It is a plain text file where every line (excluding the first header lines) contains data about a "read" from whatever sample the file comes from. Rather than focusing on the whole read, we will take two pie...
["import re\n\ndef is_matched(read):\n total = sum([int(num) for num in re.findall(r'\\d+', read[0])])\n \n if read[0] == str(len(read[1])) + 'M':\n return True\n elif len(read[1]) != total:\n return 'Invalid cigar'\n else:\n return False\n", "import re\n\ndef is_matched(read):\n ...
{"fn_name": "is_matched", "inputs": [[["36M", "CATAATACTTTACCTACTCTCAACAAATGCGGGAGA"]], [["10M6H", "GAGCGAGTGCGCCTTAC"]], [["12S", "TGTTTCTCCAAG"]]], "outputs": [[true], ["Invalid cigar"], [false]]}
introductory
https://www.codewars.com/kata/5b64d2cd83d64828ce000039
def is_matched(read):
2,768
Consider a sequence generation that follows the following steps. We will store removed values in variable `res`. Assume `n = 25`: ```Haskell -> [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25] Let's remove the first number => res = [1]. We get.. -> [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21...
["def solve(n):\n zoznam = [int(i) for i in range (2,n+1)]\n res=[1]\n while zoznam != []:\n res.append(zoznam[0])\n del zoznam[0::zoznam[0]] \n return sum(res)", "def solve(n):\n presum, arr = 1, list(range(2, n + 1))\n while arr[0] < len(arr):\n presum += arr[0]\n d...
{"fn_name": "solve", "inputs": [[7], [25], [50], [100], [1000], [10000]], "outputs": [[18], [107], [304], [993], [63589], [4721110]]}
introductory
https://www.codewars.com/kata/5a6761be145c4691ee000090
def solve(n):
2,769
# Task Consider the following ciphering algorithm: ``` For each character replace it with its code. Concatenate all of the obtained numbers. ``` Given a ciphered string, return the initial one if it is known that it consists only of lowercase letters. Note: here the character's code means its `decimal ASCII code`, t...
["def decipher(cipher):\n out = \"\"\n while cipher:\n l = 2 if cipher[0] == \"9\" else 3\n out += chr(int(cipher[:l]))\n cipher = cipher[l:]\n return out", "import re\n\ndef decipher(cipher):\n return re.sub(r'1?\\d\\d', lambda m: chr(int(m.group())), cipher)\n", "import re\ndef deciph...
{"fn_name": "decipher", "inputs": [["10197115121"], ["98"], ["122"]], "outputs": [["easy"], ["b"], ["z"]]}
introductory
https://www.codewars.com/kata/5888514674b58e929a000036
def decipher(cipher):
2,770
One suggestion to build a satisfactory password is to start with a memorable phrase or sentence and make a password by extracting the first letter of each word. Even better is to replace some of those letters with numbers (e.g., the letter `O` can be replaced with the number `0`): * instead of including `i` or `I` p...
["SWAP = {'i': '1', 'I': '1', 'o': '0', 'O': '0', 's': '5', 'S': '5'}\n\n\ndef make_password(phrase):\n return ''.join(SWAP.get(a[0], a[0]) for a in phrase.split())\n", "def make_password(phrase):\n new = \"\"\n phrase = phrase.replace(\"i\", \"1\").replace(\"I\", \"1\")\n phrase = phrase.replace(\"o\", \"0...
{"fn_name": "make_password", "inputs": [["Give me liberty or give me death"], ["Keep Calm and Carry On"]], "outputs": [["Gml0gmd"], ["KCaC0"]]}
introductory
https://www.codewars.com/kata/5637b03c6be7e01d99000046
def make_password(phrase):
2,771
Hofstadter sequences are a family of related integer sequences, among which the first ones were described by an American professor Douglas Hofstadter in his book Gödel, Escher, Bach. ### Task Today we will be implementing the rather chaotic recursive sequence of integers called Hofstadter Q. The Hofstadter Q is defin...
["def hofstadter_Q(n):\n try:\n return hofstadter_Q.seq[n]\n except IndexError:\n ans = hofstadter_Q(n - hofstadter_Q(n - 1)) + hofstadter_Q(n - hofstadter_Q(n - 2))\n hofstadter_Q.seq.append(ans)\n return ans\nhofstadter_Q.seq = [None, 1, 1]", "def hofstadter_Q(n):\n q = [1, 1]\n ...
{"fn_name": "hofstadter_Q", "inputs": [[1], [3], [7], [10], [100], [1000]], "outputs": [[1], [2], [5], [6], [56], [502]]}
introductory
https://www.codewars.com/kata/5897cdc26551af891c000124
def hofstadter_Q(n):
2,772
It's 3AM and you get the dreaded call from a customer: the program your company sold them is hanging. You eventually trace the problem down to a call to a function named `mystery`. Usually, `mystery` works fine and produces an integer result for an integer input. However, on certain inputs, the `mystery` function just ...
["def mystery_solved(n):\n \"\"\"\nRecreated mystery function from bytecode using the dis module.\n How to print the bytecode: import dis\n print(dis.dis(mystery)) \n Apparently, \n the function is a wrong implementation of the 5n+1 problem -> \n https://math.s...
{"fn_name": "wrap_mystery", "inputs": [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [18], [19], [20], [21], [22], [23], [24], [25], [26], [28], [29], [30], [31], [32], [33], [35], [36], [37], [38], [39], [40], [41], [42], [44], [45], [46], [47], [48], [49], [50], [51], [52], [5...
introductory
https://www.codewars.com/kata/55f9439929875c58a500007a
def wrap_mystery(n):
2,773
Mr. Scrooge has a sum of money 'P' that he wants to invest. Before he does, he wants to know how many years 'Y' this sum 'P' has to be kept in the bank in order for it to amount to a desired sum of money 'D'. The sum is kept for 'Y' years in the bank where interest 'I' is paid yearly. After paying taxes 'T' for the ye...
["def calculate_years(principal, interest, tax, desired):\n years = 0\n \n while principal < desired:\n principal += (interest * principal) * (1 - tax)\n years += 1\n \n return years\n", "from math import ceil, log\n\ndef calculate_years(principal, interest, tax, desired):\n if princ...
{"fn_name": "calculate_years", "inputs": [[1000, 0.05, 0.18, 1100], [1000, 0.01625, 0.18, 1200], [1000, 0.05, 0.18, 1000]], "outputs": [[3], [14], [0]]}
introductory
https://www.codewars.com/kata/563f037412e5ada593000114
def calculate_years(principal, interest, tax, desired):
2,774
### Background We **all** know about "balancing parentheses" (plus brackets, braces and chevrons) and even balancing characters that are identical. Read that last sentence again, I balanced different characters and identical characters twice and you didn't even notice... :) ### Kata Your challenge in this kata is ...
["def is_balanced(s, caps):\n stack = []\n openers, closers = caps[::2], caps[1::2]\n for char in s:\n if char in openers:\n if char in closers and stack and stack[-1] == char:\n stack.pop()\n else:\n stack.append(char)\n elif char in closers:\n...
{"fn_name": "is_balanced", "inputs": [["(Sensei says yes!)", "()"], ["(Sensei says no!", "()"], ["(Sensei [says] yes!)", "()[]"], ["(Sensei [says) no!]", "()[]"], ["Sensei says -yes-!", "--"], ["Sensei -says no!", "--"], ["Hello Mother can you hear me?", "()"], ["(Hello Mother can you hear me?)", "()"], ["(Hello Mother...
introductory
https://www.codewars.com/kata/55679d644c58e2df2a00009c
def is_balanced(source, caps):
2,775
You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other items. We want to create the text that should be displayed next to such an item. Implement a function `likes :: [String] -> String`, which must take in input array, containing the names of people who like...
["def likes(names):\n n = len(names)\n return {\n 0: 'no one likes this',\n 1: '{} likes this', \n 2: '{} and {} like this', \n 3: '{}, {} and {} like this', \n 4: '{}, {} and {others} others like this'\n }[min(4, n)].format(*names[:3], others=n-2)", "def likes(names):\n i...
{"fn_name": "likes", "inputs": [[[]], [["Peter"]], [["Jacob", "Alex"]], [["Max", "John", "Mark"]], [["Alex", "Jacob", "Mark", "Max"]]], "outputs": [["no one likes this"], ["Peter likes this"], ["Jacob and Alex like this"], ["Max, John and Mark like this"], ["Alex, Jacob and 2 others like this"]]}
introductory
https://www.codewars.com/kata/5266876b8f4bf2da9b000362
def likes(names):
2,776
Your task is to convert a given number into a string with commas added for easier readability. The number should be rounded to 3 decimal places and the commas should be added at intervals of three digits before the decimal point. There does not need to be a comma at the end of the number. You will receive both positi...
["def commas(num):\n return \"{:,.3f}\".format(num).rstrip(\"0\").rstrip(\".\")", "def commas(num):\n return f'{num:,.3f}'.rstrip('0').rstrip('.')", "import re\n\ndef commas(num):\n if isinstance(num, int):\n return format(num, ',')\n else:\n return re.sub('\\.?0+$', '', format(round(num, 3), ...
{"fn_name": "commas", "inputs": [[1], [1000], [100.2346], [1000000000.23], [9123.212], [-1], [-1000000.123], [-2000.0], [-999.9999], [-1234567.0001236]], "outputs": [["1"], ["1,000"], ["100.235"], ["1,000,000,000.23"], ["9,123.212"], ["-1"], ["-1,000,000.123"], ["-2,000"], ["-1,000"], ["-1,234,567"]]}
introductory
https://www.codewars.com/kata/56a115cadb39a2faa000001e
def commas(num):
2,777
Consider the following expansion: ```Haskell solve("3(ab)") = "ababab" -- "ab" repeats 3 times solve("2(a3(b))" = "abbbabbb" -- "a3(b)" == "abbb" repeats twice. ``` Given a string, return the expansion of that string. Input will consist of only lowercase letters and numbers (1 to 9) in valid parenthesis. There will ...
["def solve(s):\n s1 = s[::-1]\n s2 = ''\n for i in s1:\n if i.isalpha():\n s2 += i\n elif i.isdigit():\n s2 = s2*int(i)\n return s2[::-1]", "import re\n\ndef solve(s):\n ops, parts = [], ['']\n for c in re.findall(r'\\d*\\(|\\)|[a-z]+', s):\n if c == ')':\n ...
{"fn_name": "solve", "inputs": [["3(ab)"], ["2(a3(b))"], ["3(b(2(c)))"], ["k(a3(b(a2(c))))"]], "outputs": [["ababab"], ["abbbabbb"], ["bccbccbcc"], ["kabaccbaccbacc"]]}
introductory
https://www.codewars.com/kata/5a793fdbfd8c06d07f0000d5
def solve(st):
2,778
A faro shuffle of a deck of playing cards is a shuffle in which the deck is split exactly in half and then the cards in the two halves are perfectly interwoven, such that the original bottom card is still on the bottom and the original top card is still on top. For example, faro shuffling the list ```python ['ace', 't...
["def faro_cycles(n):\n x, cnt = 2, 1\n while x != 1 and n > 3:\n cnt += 1\n x = x*2 % (n-1)\n return cnt", "def faro_cycles(deck_size):\n arr, count = list(range(deck_size)), 0\n original_arr = arr\n while True:\n arr = arr[0:deck_size:2] + arr[1:deck_size:2]\n count += 1\...
{"fn_name": "faro_cycles", "inputs": [[2], [52], [542], [1250], [1954]], "outputs": [[1], [8], [540], [156], [30]]}
introductory
https://www.codewars.com/kata/57bc802c615f0ba1e3000029
def faro_cycles(deck_size):
2,779
In his publication Liber Abaci Leonardo Bonacci, aka Fibonacci, posed a problem involving a population of idealized rabbits. These rabbits bred at a fixed rate, matured over the course of one month, had unlimited resources, and were immortal. Beginning with one immature pair of these idealized rabbits that produce b p...
["def fib_rabbits(n, b):\n (i, a) = (1, 0)\n for m in range(n):\n (i, a) = (a * b, a + i)\n return a\n", "def fib_rabbits(n, b):\n x, y = 0, 1\n for _ in range(n):\n x, y = y, x * b + y\n return x", "def fib_rabbits(n, m):\n a,b = 0,1\n for i in range(n):\n a,b = b, b+a*m\n ...
{"fn_name": "fib_rabbits", "inputs": [[0, 4], [1, 4], [4, 0], [6, 3], [8, 12], [7, 4], [9, 8], [10, 2], [11, 33], [100, 3], [40, 6], [4, 100]], "outputs": [[0], [1], [1], [40], [8425], [181], [10233], [341], [58212793], [465790837923166086127602033842234887], [2431532871909060205], [201]]}
introductory
https://www.codewars.com/kata/5559e4e4bbb3925164000125
def fib_rabbits(n, b):
2,780
Chingel is practicing for a rowing competition to be held on this saturday. He is trying his best to win this tournament for which he needs to figure out how much time it takes to cover a certain distance. **Input** You will be provided with the total distance of the journey, speed of the boat and whether he is goin...
["def time(distance,boat_speed,stream):\n return round(distance/(boat_speed+int(stream.split()[-1])),2) if stream[0]==\"D\" else round(distance/(boat_speed-int(stream.split()[-1])), 2)", "def time(d, v, s):\n return round(d / (v + int(s.split()[1]) * (1 if s[0] == \"D\" else -1)), 2)", "def time(d, v, s):\n r...
{"fn_name": "time", "inputs": [[24, 10, "Downstream 2"], [24, 14, "Upstream 2"], [54, 28, "Downstream 3"], [60, 45, "Upstream 15"], [60, 45, "Downstream 15"]], "outputs": [[2], [2], [1.74], [2], [1]]}
introductory
https://www.codewars.com/kata/58162692c2a518f03a000189
def time(distance, boat_speed, stream):
2,781
##Background - the Collatz Conjecture: Imagine you are given a positive integer, `n`, then: * if `n` is even, calculate: `n / 2` * if `n` is odd, calculate: `3 * n + 1` Repeat until your answer is `1`. The Collatz conjecture states that performing this operation repeatedly, you will always eventually reach `1`. You...
["AVAILABLE_METHODS = {\n 'even' : lambda x: x / 2,\n 'odd': lambda x: 3 * x + 1\n}\n\ndef generator(x):\n temp = x\n temp_num = 0\n while temp > 1:\n if temp % 2 == 0:\n temp = AVAILABLE_METHODS['even'](temp)\n else:\n temp = AVAILABLE_METHODS['odd'](temp)\n te...
{"fn_name": "longest_collatz", "inputs": [[[1, 5, 27, 4]], [[64, 64, 27, 64]], [[75, 226, 113, 340]], [[340, 113, 226, 75]], [[75, 113, 226, 75]]], "outputs": [[27], [27], [75], [75], [75]]}
introductory
https://www.codewars.com/kata/57acc8c3e298a7ae4e0007e3
def longest_collatz(input_array):
2,782
Your job is to create a calculator which evaluates expressions in [Reverse Polish notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation). For example expression `5 1 2 + 4 * + 3 -` (which is equivalent to `5 + ((1 + 2) * 4) - 3` in normal notation) should evaluate to `14`. For your convenience, the input is ...
["import operator\n\ndef calc(expr):\n OPERATORS = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv}\n stack = [0]\n for token in expr.split(\" \"):\n if token in OPERATORS:\n op2, op1 = stack.pop(), stack.pop()\n stack.append(OPERATORS[token](op1,op2...
{"fn_name": "calc", "inputs": [[""], ["3"], ["3.5"], ["1 3 +"], ["1 3 *"], ["1 3 -"], ["4 2 /"], ["10000 123 +"], ["5 1 2 + 4 * + 3 -"]], "outputs": [[0], [3], [3.5], [4], [3], [-2], [2], [10123], [14]]}
introductory
https://www.codewars.com/kata/52f78966747862fc9a0009ae
def calc(expr):
2,783
## Grade book Complete the function so that it finds the mean of the three scores passed to it and returns the letter value associated with that grade. Numerical Score | Letter Grade --- | --- 90 <= score <= 100 | 'A' 80 <= score < 90 | 'B' 70 <= score < 80 | 'C' 60 <= score < 70 | 'D' 0 <= s...
["def get_grade(s1, s2, s3):\n m = (s1 + s2 + s3) / 3.0\n if 90 <= m <= 100:\n return 'A'\n elif 80 <= m < 90:\n return 'B'\n elif 70 <= m < 80:\n return 'C'\n elif 60 <= m < 70:\n return 'D'\n return \"F\"\n", "def get_grade(s1, s2, s3):\n mean = sum([s1,s2,s3])/3\n ...
{"fn_name": "get_grade", "inputs": [[95, 90, 93], [100, 85, 96], [92, 93, 94], [100, 100, 100], [70, 70, 100], [82, 85, 87], [84, 79, 85], [70, 70, 70], [75, 70, 79], [60, 82, 76], [65, 70, 59], [66, 62, 68], [58, 62, 70], [44, 55, 52], [48, 55, 52], [58, 59, 60], [0, 0, 0]], "outputs": [["A"], ["A"], ["A"], ["A"], ["B...
introductory
https://www.codewars.com/kata/55cbd4ba903825f7970000f5
def get_grade(s1, s2, s3):
2,784
Here we have a function that help us spam our hearty laughter. But is not working! I need you to find out why... Expected results: ```python spam(1) ==> "hue" spam(6) ==> "huehuehuehuehuehue" spam(14) ==> "huehuehuehuehuehuehuehuehuehuehuehuehuehue" ```
["#fix this code!\ndef spam(number):\n return 'hue' * number", "def spam(number):\n return ''.join(['hue' for i in range(number)])", "def spam(number):\n return number * 'hue'", "def spam(i):\n return 'hue' * int(i)", "#fix this code!\ndef spam(n):\n return 'hue'*n", "#fix this code!\ndef spam(number):\n...
{"fn_name": "spam", "inputs": [[1], [6], [14]], "outputs": [["hue"], ["huehuehuehuehuehue"], ["huehuehuehuehuehuehuehuehuehuehuehuehuehue"]]}
introductory
https://www.codewars.com/kata/52e9aa89b5acdd26d3000127
def spam(number):
2,785
# Task Let's define a `parameter` of number `n` as the least common multiple (LCM) of the sum of its digits and their product. Calculate the parameter of the given number `n`. # Input/Output `[input]` integer `n` A positive integer. It is guaranteed that no zero appears in `n`. `[output]` an integer The paramet...
["from fractions import Decimal, gcd\nfrom operator import mul\nfrom functools import reduce\n\nlcm = lambda a, b=1: a * b // gcd(a, b)\n\ndef parameter(n):\n digits = Decimal(n).as_tuple().digits\n return lcm(sum(digits), reduce(mul, digits))", "from math import gcd\n\ndef parameter(n):\n s, p = 0, 1\n for...
{"fn_name": "parameter", "inputs": [[1234], [1], [2], [22], [11], [239], [999999999], [91], [344], [123456789]], "outputs": [[120], [1], [2], [4], [2], [378], [387420489], [90], [528], [362880]]}
introductory
https://www.codewars.com/kata/5902f1839b8e720287000028
def parameter(n):
2,786
If I give you a date, can you tell me what day that date is? For example, december 8th, 2015 is a tuesday. Your job is to write the function ```day(d)``` which takes a string representation of a date as input, in the format YYYYMMDD. The example would be "20151208". The function needs to output the string representati...
["import datetime\nimport calendar\n\ndef day(date):\n return calendar.day_name[datetime.datetime.strptime(date,\"%Y%m%d\").weekday()]", "from datetime import datetime\n\nWEEKDAYS = ('Monday', 'Tuesday', 'Wednesday', 'Thursday',\n 'Friday', 'Saturday', 'Sunday')\n\n\ndef day(date):\n return WEEKDAYS[da...
{"fn_name": "day", "inputs": [["20151208"], ["20140728"], ["20160229"], ["20160301"], ["19000228"], ["19000301"]], "outputs": [["Tuesday"], ["Monday"], ["Monday"], ["Tuesday"], ["Wednesday"], ["Thursday"]]}
introductory
https://www.codewars.com/kata/5666bd1011beb6f768000073
def day(date):
2,787
You're familiar with [list slicing](https://docs.python.org/3/library/functions.html#slice) in Python and know, for example, that: ```python >>> ages = [12, 14, 63, 72, 55, 24] >>> ages[2:4] [63, 72] >>> ages[2:] [63, 72, 55, 24] >>> ages[:3] [12, 14, 63] ``` write a function `inverse_slice()` that takes three argume...
["def inverse_slice(items, a, b):\n return items[:a] + items[b:]", "def inverse_slice(items, a, b):\n del items[a:b]\n return items", "def inverse_slice(items, a, b):\n part1 = items[:a]\n part2 = items[b:]\n return (part1+part2)", "def inverse_slice(items, a, b):\n return [v for i,v in enumerate(ite...
{"fn_name": "inverse_slice", "inputs": [[[12, 14, 63, 72, 55, 24], 2, 4], [[12, 14, 63, 72, 55, 24], 0, 3], [["Intuition", "is", "a", "poor", "guide", "when", "facing", "probabilistic", "evidence"], 5, 13]], "outputs": [[[12, 14, 55, 24]], [[72, 55, 24]], [["Intuition", "is", "a", "poor", "guide"]]]}
introductory
https://www.codewars.com/kata/586ec0b8d098206cce001141
def inverse_slice(items, a, b):
2,788
Write a function that returns a sequence (index begins with 1) of all the even characters from a string. If the string is smaller than two characters or longer than 100 characters, the function should return "invalid string". For example: ````` "abcdefghijklm" --> ["b", "d", "f", "h", "j", "l"] "a" --> "i...
["def even_chars(st):\n if len(st) < 2 or len(st)> 100:\n return 'invalid string'\n else:\n return [st[i] for i in range(1, len(st), 2)]\n", "def even_chars(st): \n return list(st[1::2]) if 2<=len(st)<=100 else \"invalid string\" ", "def even_chars(stg): \n return list(stg[1::2]) if 1 < len(st...
{"fn_name": "even_chars", "inputs": [["a"], ["abcdefghijklm"], ["aBc_e9g*i-k$m"], [""], ["ab"], ["aiqbuwbjqwbckjdwbwkqbefhglqhfjbwqejbcadn.bcaw.jbhwefjbwqkvbweevkj.bwvwbhvjk.dsvbajdv.hwuvghwuvfhgw.vjhwncv.wecnaw.ecnvw.kejvhnw.evjkhweqv.kjhwqeev.kjbhdjk.vbaewkjva"]], "outputs": [["invalid string"], [["b", "d", "f", "h",...
introductory
https://www.codewars.com/kata/566044325f8fddc1c000002c
def even_chars(st):
2,789
Write function bmi that calculates body mass index (bmi = weight / height ^ 2). if bmi <= 18.5 return "Underweight" if bmi <= 25.0 return "Normal" if bmi <= 30.0 return "Overweight" if bmi > 30 return "Obese"
["def bmi(weight, height):\n bmi = weight / height ** 2\n if bmi <= 18.5:\n return \"Underweight\"\n elif bmi <= 25:\n return \"Normal\"\n elif bmi <= 30:\n return \"Overweight\"\n else:\n return \"Obese\"", "def bmi(weight, height):\n b = weight / height ** 2\n return [...
{"fn_name": "bmi", "inputs": [[50, 1.8], [80, 1.8], [90, 1.8], [110, 1.8], [50, 1.5]], "outputs": [["Underweight"], ["Normal"], ["Overweight"], ["Obese"], ["Normal"]]}
introductory
https://www.codewars.com/kata/57a429e253ba3381850000fb
def bmi(weight, height):
2,790
In this Kata, you will be given an array of strings and your task is to remove all consecutive duplicate letters from each string in the array. For example: * `dup(["abracadabra","allottee","assessee"]) = ["abracadabra","alote","asese"]`. * `dup(["kelless","keenness"]) = ["keles","kenes"]`. Strings will be ...
["from itertools import groupby\n\ndef dup(arry):\n return [\"\".join(c for c, grouper in groupby(i)) for i in arry]", "import re\n\ndef dup(arry):\n return list(map(lambda s: re.sub(r'(\\w)\\1+', r'\\1', s), arry))", "def dup(arry):\n array_new = []\n for string in arry:\n string_new = \"\"\n ...
{"fn_name": "dup", "inputs": [[["ccooddddddewwwaaaaarrrrsssss", "piccaninny", "hubbubbubboo"]], [["abracadabra", "allottee", "assessee"]], [["kelless", "keenness"]], [["Woolloomooloo", "flooddoorroommoonlighters", "chuchchi"]], [["adanac", "soonness", "toolless", "ppellee"]], [["callalloo", "feelless", "heelless"]], [[...
introductory
https://www.codewars.com/kata/59f08f89a5e129c543000069
def dup(arry):
2,791
Trigrams are a special case of the n-gram, where n is 3. One trigram is a continious sequence of 3 chars in phrase. [Wikipedia](https://en.wikipedia.org/wiki/Trigram) - return all trigrams for the given phrase - replace spaces with \_ - return an empty string for phrases shorter than 3 Example: trigrams('the qu...
["def trigrams(phrase):\n phrase = phrase.replace(\" \", \"_\")\n return \" \".join([phrase[i:i+3]for i in range(len(phrase)-2)])\n", "def trigrams(phrase):\n solution = ''\n if len(phrase) < 3:\n return solution\n phrase = phrase.replace(' ','_')\n for i in range(len(phrase)-2):\n solut...
{"fn_name": "trigrams", "inputs": [["the quick red"], ["Hi"]], "outputs": [["the he_ e_q _qu qui uic ick ck_ k_r _re red"], [""]]}
introductory
https://www.codewars.com/kata/55d8dc4c8e629e55dc000068
def trigrams(phrase):
2,792
The citizens of Codeland read each word from right to left, meaning that lexicographical comparison works differently in their language. Namely, string ```a``` is lexicographically smaller than string ```b``` if either: ```a``` is a suffix of ```b``` (in common sense, i.e. ```b``` ends with a substring equal to ```a```...
["def unusual_lex_order(a):\n return sorted(a, key=lambda k: k[::-1])", "def unusual_lex_order(arr):\n return sorted(arr, key=lambda s: s[::-1])", "def unusual_lex_order(arr):\n return sorted(arr, key = lambda x: x[::-1])", "def unusual_lex_order(arr):\n return sorted(arr, key = lambda word: word[::-1])", "...
{"fn_name": "unusual_lex_order", "inputs": [[["nigeb", "ta", "eht", "gninnigeb"]], [["a", "b", "a", "d", "c"]]], "outputs": [[["ta", "nigeb", "gninnigeb", "eht"]], [["a", "a", "b", "c", "d"]]]}
introductory
https://www.codewars.com/kata/5a438bc1e1ce0e129100005a
def unusual_lex_order(arr):
2,793
# Your Task The city of Darkishland has a strange hotel with infinite rooms. The groups that come to this hotel follow the following rules: * At the same time only members of one group can rent the hotel. * Each group comes in the morning of the check-in day and leaves the hotel in the evening of the check-out day. ...
["from math import floor\ndef group_size(S, D):\n return floor((2*D+S*(S-1))**.5+.5)", "from math import sqrt, ceil\n\n# 1st group spends in the hotel s days,\n# 2nd group - s + 1 days,\n# 3rd group - s + 2 days,\n# ...,\n# nth group - s + n - 1 days.\n#\n# The total number of days for n groups: n * (s + s + n -...
{"fn_name": "group_size", "inputs": [[1, 6], [3, 10], [3, 14], [10, 1000], [1, 1000], [5, 4], [5, 7], [10000, 1000000000000000], [2, 20000000000000], [10, 900000000000000000], [34545, 565], [234234, 6577], [10, 10]], "outputs": [[3], [5], [6], [46], [45], [5], [6], [44721361], [6324555], [1341640786], [34545], [234234]...
introductory
https://www.codewars.com/kata/5b9cf881d6b09fc9ee0002b1
def group_size(S, D):
2,794
Philip's just turned four and he wants to know how old he will be in various years in the future such as 2090 or 3044. His parents can't keep up calculating this so they've begged you to help them out by writing a programme that can answer Philip's endless questions. Your task is to write a function that takes two par...
["def calculate_age(year_of_birth, current_year):\n diff = abs(current_year - year_of_birth)\n plural = '' if diff == 1 else 's'\n if year_of_birth < current_year:\n return 'You are {} year{} old.'.format(diff, plural)\n elif year_of_birth > current_year:\n return 'You will be born in {} year{...
{"fn_name": "calculate_age", "inputs": [[2012, 2016], [1989, 2016], [2000, 2090], [2000, 1990], [2000, 2000], [900, 2900], [2010, 1990], [2010, 1500], [2011, 2012], [2000, 1999]], "outputs": [["You are 4 years old."], ["You are 27 years old."], ["You are 90 years old."], ["You will be born in 10 years."], ["You were bo...
introductory
https://www.codewars.com/kata/5761a717780f8950ce001473
def calculate_age(year_of_birth, current_year):
2,795
The cockroach is one of the fastest insects. Write a function which takes its speed in km per hour and returns it in cm per second, rounded down to the integer (= floored). For example: ```python cockroach_speed(1.08) == 30 ``` Note! The input is a Real number (actual type is language dependent) and is >= 0. The res...
["def cockroach_speed(s):\n return s // 0.036", "def cockroach_speed(s):\n cm_per_km = 100000\n sec_per_hour = 3600\n return int(s * cm_per_km / sec_per_hour)", "def cockroach_speed(s):\n cm_per_km = 100000\n sec_per_hour = 3600\n return s * cm_per_km // sec_per_hour\n", "def cockroach_speed(s):\n ...
{"fn_name": "cockroach_speed", "inputs": [[1.08], [1.09], [0]], "outputs": [[30], [30], [0]]}
introductory
https://www.codewars.com/kata/55fab1ffda3e2e44f00000c6
def cockroach_speed(s):
2,796
Create a function which answers the question "Are you playing banjo?". If your name starts with the letter "R" or lower case "r", you are playing banjo! The function takes a name as its only argument, and returns one of the following strings: ``` name + " plays banjo" name + " does not play banjo" ``` Names given a...
["def areYouPlayingBanjo(name):\n return name + (' plays' if name[0].lower() == 'r' else ' does not play') + \" banjo\";", "def areYouPlayingBanjo(name):\n if name[0].lower() == 'r':\n return name + ' plays banjo'\n else:\n return name + ' does not play banjo'", "def areYouPlayingBanjo(name):\n ...
{"fn_name": "areYouPlayingBanjo", "inputs": [["Adam"], ["Paul"], ["Ringo"], ["bravo"], ["rolf"]], "outputs": [["Adam does not play banjo"], ["Paul does not play banjo"], ["Ringo plays banjo"], ["bravo does not play banjo"], ["rolf plays banjo"]]}
introductory
https://www.codewars.com/kata/53af2b8861023f1d88000832
def areYouPlayingBanjo(name):
2,797
Mobile Display Keystrokes Do you remember the old mobile display keyboards? Do you also remember how inconvenient it was to write on it? Well, here you have to calculate how much keystrokes you have to do for a specific word. This is the layout: Return the amount of keystrokes of input str (! only letters, digits ...
["def mobile_keyboard(s):\n lookup = {\n c: i \n for s in \"1,2abc,3def,4ghi,5jkl,6mno,7pqrs,8tuv,9wxyz,*,0,#\".split(\",\") \n for i, c in enumerate(s, start=1)\n }\n return sum(lookup[c] for c in s)", "def mobile_keyboard(s):\n return sum((x+1) for x in range(5) for c in s if c in ['0...
{"fn_name": "mobile_keyboard", "inputs": [[""], ["123"], ["codewars"], ["zruf"], ["thisisasms"], ["longwordwhichdontreallymakessense"]], "outputs": [[0], [3], [26], [16], [37], [107]]}
introductory
https://www.codewars.com/kata/59564a286e595346de000079
def mobile_keyboard(s):
2,798
# altERnaTIng cAsE <=> ALTerNAtiNG CaSe Define `String.prototype.toAlternatingCase` (or a similar function/method *such as* `to_alternating_case`/`toAlternatingCase`/`ToAlternatingCase` in your selected language; **see the initial solution for details**) such that each lowercase letter becomes uppercase and each upper...
["def to_alternating_case(string):\n return string.swapcase()", "def to_alternating_case(string):\n return ''.join([c.upper() if c.islower() else c.lower() for c in string])", "to_alternating_case = str.swapcase", "def to_alternating_case(string):\n strn = \"\"\n for i in string:\n if i.isupper():\n ...
{"fn_name": "to_alternating_case", "inputs": [["hello world"], ["HELLO WORLD"], ["hello WORLD"], ["HeLLo WoRLD"], ["12345"], ["1a2b3c4d5e"], ["String.prototype.toAlternatingCase"]], "outputs": [["HELLO WORLD"], ["hello world"], ["HELLO world"], ["hEllO wOrld"], ["12345"], ["1A2B3C4D5E"], ["sTRING.PROTOTYPE.TOaLTERNATIN...
introductory
https://www.codewars.com/kata/56efc695740d30f963000557
def to_alternating_case(string):
2,799
You're in ancient Greece and giving Philoctetes a hand in preparing a training exercise for Hercules! You've filled a pit with two different ferocious mythical creatures for Hercules to battle! The formidable **"Orthus"** is a 2 headed dog with 1 tail. The mighty **"Hydra"** has 5 heads and 1 tail. Before Hercules ...
["def beasts(heads, tails):\n orthus = (5 * tails - heads) / 3\n hydra = tails - orthus\n return [orthus, hydra] if orthus >= 0 and hydra >= 0 else 'No solutions'", "def beasts(h,t):\n out= [(5*t-h)/3, (h-2*t)/3]\n return all(x.is_integer() and x>=0 for x in out) and out or 'No solutions'", "def beasts(h...
{"fn_name": "beasts", "inputs": [[123, 39], [371, 88], [24, 12], [113, 37], [635, 181], [25, 555], [12, 25], [54, 956], [5455, 54956], [0, 0], [-1, -1], [-45, 5], [99, 0], [0, 99], [5, -55]], "outputs": [[[24, 15]], [[23, 65]], [[12, 0]], [[24, 13]], [[90, 91]], ["No solutions"], ["No solutions"], ["No solutions"], ["N...
introductory
https://www.codewars.com/kata/5751aa92f2dac7695d000fb0
def beasts(heads, tails):
2,800
Two fishing vessels are sailing the open ocean, both on a joint ops fishing mission. On a high stakes, high reward expidition - the ships have adopted the strategy of hanging a net between the two ships. The net is **40 miles long**. Once the straight-line distance between the ships is greater than 40 miles, the net ...
["from math import sin, radians\n\ndef find_time_to_break(bearing_A, bearing_B):\n a = radians(abs(bearing_A - bearing_B) / 2)\n return 40 / (3 * sin(a)) if a else float(\"inf\")", "def find_time_to_break(bearing_A, bearing_B):\n import math\n if bearing_A == bearing_B:\n return float(\"inf\")\n r...
{"fn_name": "find_time_to_break", "inputs": [[90, 90]], "outputs": [[Infinity]]}
introductory
https://www.codewars.com/kata/5d4dd5c9af0c4c0019247110
def find_time_to_break(bearing_A, bearing_B):
2,801
< PREVIOUS KATA NEXT KATA > ## Task: You have to write a function `pattern` which returns the following Pattern(See Examples) upto desired number of rows. * Note:```Returning``` the pattern is not the same as ```Printing``` the pattern. ### Parameters: pattern( n , x , y...
["def pattern(n, x=1, y=1, *args):\n if n < 1:\n return \"\"\n result = []\n for i in range(1, n + 1):\n line = \" \" * (i - 1) + str(i % 10) + \" \" * (n - i)\n result.append((line + line[::-1][1:]) + (line[1:] + line[::-1][1:]) * (x - 1))\n return \"\\n\".join((result + result[::-1][1...
{"fn_name": "pattern", "inputs": [[4, 2, 3], [3, -29, 4], [5, -28, 0], [7, 2], [10, -2999], [5], [4, 2, 3, 5, 7, -8], [-3, -5, 0], [-11, 1, 3], [-25, 5, -9], [-25, -11, 9], [-3, -5], [-11, 3], [-9999999], [-25, 5, -9, 55, -8, -7, 8], [0, 1, 2], [0, -1, 0], [0, -1, 2], [0, 1, -2], [0, 1], [0, -1], [0], [0, -5, 8, -7, 10...
introductory
https://www.codewars.com/kata/558db3ca718883bd17000031
def pattern(n, x=1, y=1, *args):
2,802
*Based on this Numberphile video: https://www.youtube.com/watch?v=Wim9WJeDTHQ* --- Multiply all the digits of a nonnegative integer `n` by each other, repeating with the product until a single digit is obtained. The number of steps required is known as the **multiplicative persistence**. Create a function that calcu...
["def per(n):\n r = []\n while n>=10:\n p=1\n for i in str(n):\n p=p*int(i)\n r.append(p)\n n = p\n return r", "from functools import reduce\n\ndef per(n):\n r = []\n p = reduce(lambda a, b: a*b, map(int, str(n)))\n return r if p == n else [p] + per(p)", "from fu...
{"fn_name": "per", "inputs": [[1234567890], [123456789], [12345678], [1234567], [123456], [12345], [2379], [777], [25], [277777788888899], [3778888999]], "outputs": [[[0]], [[362880, 0]], [[40320, 0]], [[5040, 0]], [[720, 0]], [[120, 0]], [[378, 168, 48, 32, 6]], [[343, 36, 18, 8]], [[10, 0]], [[4996238671872, 43893964...
introductory
https://www.codewars.com/kata/5c942f40bc4575001a3ea7ec
def per(n):
2,803
# Task You are given a string consisting of `"D", "P" and "C"`. A positive integer N is called DPC of this string if it satisfies the following properties: ``` For each i = 1, 2, ... , size of the string: If i-th character is "D", then N can be divided by i If i-th character is "P", then N and i should be rela...
["from fractions import gcd\n\ndef DPC_sequence(s):\n n=1\n for i,c in enumerate(s,1):\n if c=='D':\n n=(n*i)//gcd(n,i)\n elif c=='P':\n if gcd(n,i)!=1: return -1\n elif c=='C':\n if gcd(n,i) in (1,i): return -1\n return n\n", "from fractions import gcd\n\n...
{"fn_name": "DPC_sequence", "inputs": [["DDPDD"], ["DDDDPDDCCCDDPDCCPCDCDDPCPCCDDCD"], ["DPCPDPPPDCPDPDPC"], ["DDDDDDCD"], ["CDDDPDDD"], ["DDDDDDPCCDPDPP"]], "outputs": [[20], [15782844], [-1], [-1], [-1], [-1]]}
introductory
https://www.codewars.com/kata/58a3b7185973c23795000049
def DPC_sequence(s):
2,804
# Task Christmas is coming, and your task is to build a custom Christmas tree with the specified characters and the specified height. # Inputs: - `chars`: the specified characters. - `n`: the specified height. A positive integer greater than 2. # Output: - A multiline string. Each line is separated by `\n`. A tree ...
["def custom_christmas_tree(chars, n):\n from itertools import cycle\n it = cycle(chars)\n tree = [' '.join(next(it) for j in range(i)).center(2 * n).rstrip() for i in range(1, n + 1)]\n tree.extend('|'.center(2 * n).rstrip() for _ in range(n // 3))\n return '\\n'.join(tree)", "from itertools import cycl...
{"fn_name": "custom_christmas_tree", "inputs": [["*@o", 3], ["*@o", 6], ["1234", 6], ["123456789", 3]], "outputs": [[" *\n @ o\n* @ o\n |"], [" *\n @ o\n * @ o\n * @ o *\n @ o * @ o\n* @ o * @ o\n |\n |"], [" 1\n 2 3\n 4 1 2\n 3 4 1 2\n 3 4 1 2 3\n4 1 2 3 4 1\n |\n |"], [" 1\n 2 3...
introductory
https://www.codewars.com/kata/5a405ba4e1ce0e1d7800012e
def custom_christmas_tree(chars, n):
2,805
The Fibonacci numbers are the numbers in the following integer sequence (Fn): >0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ... such as >F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1. Given a number, say prod (for product), we search two Fibonacci numbers F(n) and F(n+1) verifying >F(n) * F(n+1) = prod. ...
["def productFib(prod):\n a, b = 0, 1\n while prod > a * b:\n a, b = b, a + b\n return [a, b, prod == a * b]", "def productFib(prod):\n a,b = 0,1\n while a*b < prod:\n a,b = b, b+a\n return [a, b, a*b == prod]", "def productFib(prod):\n a, b = 0, 1\n rez = 0\n while rez < prod:\n a...
{"fn_name": "productFib", "inputs": [[4895], [5895], [74049690], [84049690], [193864606], [447577], [602070], [602070602070], [1120149658760], [256319508074468182850], [203023208030065646654504166904697594722575], [203023208030065646654504166904697594722576], [0], [1], [2], [3], [4], [5], [6], [7], [105]], "outputs": [...
introductory
https://www.codewars.com/kata/5541f58a944b85ce6d00006a
def productFib(prod):
2,806
# Task Imagine a standard chess board with only two white and two black knights placed in their standard starting positions: the white knights on b1 and g1; the black knights on b8 and g8. There are two players: one plays for `white`, the other for `black`. During each move, the player picks one of his knights and m...
["def whose_turn(positions):\n return sum(ord(c) for c in positions.replace(\";\", \"\")) % 2 == 0", "def whose_turn(positions):\n return sum(ord(c) for c in positions) & 1 == 1", "tbl = str.maketrans('', '', 'aceg1357;')\n\ndef whose_turn(positions):\n return not len(positions.translate(tbl)) % 2\n", "def who...
{"fn_name": "whose_turn", "inputs": [["b1;g1;b8;g8"], ["c3;g1;b8;g8"], ["g1;g2;g3;g4"], ["f8;h1;f3;c2"]], "outputs": [[true], [false], [true], [false]]}
introductory
https://www.codewars.com/kata/5897e572948beb7858000089
def whose_turn(positions):
2,807
Positive integers have so many gorgeous features. Some of them could be expressed as a sum of two or more consecutive positive numbers. ___ # Consider an Example : * `10` , could be expressed as a sum of `1 + 2 + 3 + 4 `. ___ # Task **_Given_** *Positive integer*, N , **_Return_** true if it could be expressed as a...
["from math import log2\n\ndef consecutive_ducks(n):\n return not log2(n).is_integer()", "def consecutive_ducks(n):\n while n % 2 == 0:\n n //= 2\n return n > 1", "def consecutive_ducks(n):\n '''\n find x + (x + 1) = n thus x exists if (n-1) % 2 == 0\n if not, find x + (x + 1) + (x + 2) = n\n ...
{"fn_name": "consecutive_ducks", "inputs": [[69], [8], [57], [6], [13], [16], [91], [75], [38], [25], [32], [65], [99], [522], [974], [755], [512], [739], [1006], [838], [1092], [727], [648], [1024], [851], [541], [1011], [822], [382131], [118070], [17209], [32768], [161997], [400779], [198331], [325482], [88441], [655...
introductory
https://www.codewars.com/kata/5dae2599a8f7d90025d2f15f
def consecutive_ducks(n):
2,808
Implement the [Polybius square cipher](http://en.wikipedia.org/wiki/Polybius_square). Replace every letter with a two digit number. The first digit is the row number, and the second digit is the column number of following square. Letters `'I'` and `'J'` are both 24 in this cipher: table#polybius-square {width: 100px...
["def polybius(text):\n letmap = { \"A\" : \"11\",\"B\" : \"12\",\"C\" : \"13\",\"D\" : \"14\",\"E\" : \"15\",\n \"F\" : \"21\",\"G\" : \"22\",\"H\" : \"23\",\"I\" : \"24\",\"J\" : \"24\", \"K\" : \"25\",\n \"L\" : \"31\",\"M\" : \"32\",\"N\" : \"33\",\"O\" : \"34\",\"P\" : \"35\",\n ...
{"fn_name": "polybius", "inputs": [["POLYBIUS"], ["CODEWARS"], ["POLYBIUS SQUARE CIPHER"]], "outputs": [["3534315412244543"], ["1334141552114243"], ["3534315412244543 434145114215 132435231542"]]}
introductory
https://www.codewars.com/kata/542a823c909c97da4500055e
def polybius(text):
2,809
# Convert number to reversed array of digits Given a random non-negative number, you have to return the digits of this number within an array in reverse order. ## Example: ``` 348597 => [7,9,5,8,4,3] ```
["def digitize(n):\n return [int(x) for x in str(n)[::-1]]", "def digitize(n):\n return [int(x) for x in reversed(str(n))]", "def digitize(n):\n result = []\n while n >= 1:\n result.append(n%10)\n n //= 10\n return result", "def digitize(n):\n return [int(c) for c in str(n)[::-1]]", "def...
{"fn_name": "digitize", "inputs": [[35231], [23582357], [984764738], [45762893920], [548702838394]], "outputs": [[[1, 3, 2, 5, 3]], [[7, 5, 3, 2, 8, 5, 3, 2]], [[8, 3, 7, 4, 6, 7, 4, 8, 9]], [[0, 2, 9, 3, 9, 8, 2, 6, 7, 5, 4]], [[4, 9, 3, 8, 3, 8, 2, 0, 7, 8, 4, 5]]]}
introductory
https://www.codewars.com/kata/5583090cbe83f4fd8c000051
def digitize(n):
2,810
Consider the word `"abode"`. We can see that the letter `a` is in position `1` and `b` is in position `2`. In the alphabet, `a` and `b` are also in positions `1` and `2`. Notice also that `d` and `e` in `abode` occupy the positions they would occupy in the alphabet, which are positions `4` and `5`. Given an array of ...
["def solve(arr):\n return [ sum(c == chr(97+i) for i,c in enumerate(w[:26].lower())) for w in arr ]", "from string import ascii_lowercase as alphabet\n\ndef solve(arr):\n return [sum(c == alphabet[i] for i,c in enumerate(word[:26].lower())) for word in arr]", "from operator import eq\nfrom string import ascii_lo...
{"fn_name": "solve", "inputs": [[["abode", "ABc", "xyzD"]], [["abide", "ABc", "xyz"]], [["IAMDEFANDJKL", "thedefgh", "xyzDEFghijabc"]], [["encode", "abc", "xyzD", "ABmD"]]], "outputs": [[[4, 3, 1]], [[4, 3, 0]], [[6, 5, 7]], [[1, 3, 1, 3]]]}
introductory
https://www.codewars.com/kata/59d9ff9f7905dfeed50000b0
def solve(arr):
2,811
Binary with 0 and 1 is good, but binary with only 0 is even better! Originally, this is a concept designed by Chuck Norris to send so called unary messages. Can you write a program that can send and receive this messages? Rules The input message consists of ASCII characters between 32 and 127 (7-bit) The encoded out...
["from re import compile\n\nREGEX1 = compile(r\"0+|1+\").findall\nREGEX2 = compile(r\"(0+) (0+)\").findall\nbinary = \"{:07b}\".format\n\ndef send(s):\n temp = ''.join(binary(ord(c)) for c in s)\n return ' '.join(\"0 \" + '0'*len(x) if x[0] == '1' else \"00 \" + x for x in REGEX1(temp))\n\ndef receive(s):\n te...
{"fn_name": "send", "inputs": [["C"], ["CC"], ["%"], ["Chuck Norris' keyboard has 2 keys: 0 and white space."], ["abcdefghijklmnopqrstuvwxyz"], ["!\"#$&"], ["Chuck Norris can divide by zero."], ["Chuck Norris counted to infinity - three times."]], "outputs": [["0 0 00 0000 0 00"], ["0 0 00 0000 0 000 00 0000 0 00"], ["...
introductory
https://www.codewars.com/kata/5e5ccbda30e9d0001ec77bb6
def send(s):
2,812
##Task: You have to write a function **pattern** which creates the following pattern upto n number of rows. * If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string. * If any odd number is passed as argument then the pattern should last upto the largest even number which is smaller th...
["def pattern(n):\n return '\\n'.join([str(i) * i for i in range(2, n + 1, 2)])\n", "def pattern(n):\n return \"\\n\".join(str(i) * i for i in range(2, n + 1, 2))", "def pattern(n):\n # Happy Coding ^_^\n result = []\n \n #If it's one return nothing\n if n == 1:\n return ''\n\n #just go t...
{"fn_name": "pattern", "inputs": [[2], [1], [5], [6], [0], [-25]], "outputs": [["22"], [""], ["22\n4444"], ["22\n4444\n666666"], [""], [""]]}
introductory
https://www.codewars.com/kata/55749101ae1cf7673800003e
def pattern(n):
2,813
Given an array of numbers (in string format), you must return a string. The numbers correspond to the letters of the alphabet in reverse order: a=26, z=1 etc. You should also account for `'!'`, `'?'` and `' '` that are represented by '27', '28' and '29' respectively. All inputs will be valid.
["def switcher(arr):\n d = {str(i): chr(123-i) for i in range(1,27)}\n d.update({'27':'!'})\n d.update({'28':'?'})\n d.update({'29':' '})\n d.update({'0':''})\n return ''.join([d[str(i)] for i in arr])", "import string\n\nletters = string.ascii_lowercase[::-1] + '!? '\ndef switcher(arr):\n return '...
{"fn_name": "switcher", "inputs": [[["24", "12", "23", "22", "4", "26", "9", "8"]], [["25", "7", "8", "4", "14", "23", "8", "25", "23", "29", "16", "16", "4"]], [["4", "24"]], [["12"]], [["12", "28", "25", "21", "25", "7", "11", "22", "15"]]], "outputs": [["codewars"], ["btswmdsbd kkw"], ["wc"], ["o"], ["o?bfbtpel"]]}
introductory
https://www.codewars.com/kata/57ebaa8f7b45ef590c00000c
def switcher(arr):
2,814
Triangular number is the amount of points that can fill equilateral triangle. Example: the number 6 is a triangular number because all sides of a triangle has the same amount of points. ``` Hint! T(n) = n * (n + 1) / 2, n - is the size of one side. T(n) - is the triangular number. ``` Given a number 'T' from interv...
["def is_triangular(t):\n x = int((t*2)**0.5)\n return t == x*(x+1)/2", "def is_triangular(t):\n return (8 * t + 1)**.5 % 1 == 0\n", "def is_triangular(t):\n return (8 * t + 1) ** 0.5 % 1 == 0", "def is_triangular(n):\n a = int((n * 2)**0.5)\n return n * 2 == a * (a + 1)\n", "TRIANGULAR = { x*(x+1)/2 ...
{"fn_name": "is_triangular", "inputs": [[1], [3], [6], [10], [15], [21], [28], [2], [7], [14], [27]], "outputs": [[true], [true], [true], [true], [true], [true], [true], [false], [false], [false], [false]]}
introductory
https://www.codewars.com/kata/56d0a591c6c8b466ca00118b
def is_triangular(t):
2,815
Your task is to make a program takes in a sentence (without puncuation), adds all words to a list and returns the sentence as a string which is the positions of the word in the list. Casing should not matter too. Example ----- `"Ask not what your COUNTRY can do for you ASK WHAT YOU CAN DO FOR YOUR country"` becomes...
["def compress(sentence):\n ref = []\n for i in sentence.lower().split():\n if i not in ref:\n ref.append(i)\n return ''.join([str(ref.index(n)) for n in sentence.lower().split()])", "def compress(sentence):\n memo = {}\n return ''.join(map(str, (memo.setdefault(s, len(memo)) for s in s...
{"fn_name": "compress", "inputs": [["The bumble bee"], ["SILLY LITTLE BOYS silly little boys"], ["Ask not what your COUNTRY can do for you ASK WHAT YOU CAN DO FOR YOUR country"], ["The number 0 is such a strange number Strangely it has zero meaning"]], "outputs": [["012"], ["012012"], ["01234567802856734"], ["012345617...
introductory
https://www.codewars.com/kata/59de469cfc3c492da80000c5
def compress(sentence):
2,816
In this kata, you will do addition and subtraction on a given string. The return value must be also a string. **Note:** the input will not be empty. ## Examples ``` "1plus2plus3plus4" --> "10" "1plus2plus3minus4" --> "2" ```
["def calculate(s):\n return str(sum(int(n) for n in s.replace(\"minus\", \"plus-\").split(\"plus\")))\n \n # I heard here and there that using eval is a very bad practice\u2026\n #return str(eval(s.replace(\"plus\", \"+\").replace(\"minus\", \"-\")))\n", "calculate = lambda s: str(eval(s.replace(\"plus\",\...
{"fn_name": "calculate", "inputs": [["1plus2plus3plus4"], ["1minus2minus3minus4"], ["1plus2plus3minus4"], ["1minus2plus3minus4"], ["1plus2minus3plus4minus5"]], "outputs": [["10"], ["-8"], ["2"], ["-2"], ["-1"]]}
introductory
https://www.codewars.com/kata/5809b62808ad92e31b000031
def calculate(s):
2,817
Deoxyribonucleic acid (DNA) is a chemical found in the nucleus of cells and carries the "instructions" for the development and functioning of living organisms. If you want to know more http://en.wikipedia.org/wiki/DNA In DNA strings, symbols "A" and "T" are complements of each other, as "C" and "G". You have functio...
["def DNA_strand(dna):\n pairs = [(\"A\", \"T\"), (\"C\", \"G\")]\n replacing_rules = pairs_to_dict(pairs)\n return \"\".join(list([replacing_rules[a] for a in dna]))\n\n\ndef pairs_to_dict(pairs):\n d = {}\n for pair in pairs: # Add two replacing rules for each pair\n d[pair[0]] = pair[1]\n ...
{"fn_name": "DNA_strand", "inputs": [["AAAA"], ["ATTGC"], ["GTAT"], ["AAGG"], ["CGCG"], ["GTATCGATCGATCGATCGATTATATTTTCGACGAGATTTAAATATATATATATACGAGAGAATACAGATAGACAGATTA"]], "outputs": [["TTTT"], ["TAACG"], ["CATA"], ["TTCC"], ["GCGC"], ["CATAGCTAGCTAGCTAGCTAATATAAAAGCTGCTCTAAATTTATATATATATATGCTCTCTTATGTCTATCTGTCTAAT"]...
introductory
https://www.codewars.com/kata/554e4a2f232cdd87d9000038
def DNA_strand(dna):
2,818
The goal of this exercise is to convert a string to a new string where each character in the new string is `"("` if that character appears only once in the original string, or `")"` if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate. ##...
["def duplicate_encode(word):\n return \"\".join([\"(\" if word.lower().count(c) == 1 else \")\" for c in word.lower()])", "from collections import Counter\n\ndef duplicate_encode(word):\n word = word.lower()\n counter = Counter(word)\n return ''.join(('(' if counter[c] == 1 else ')') for c in word)\n", "#T...
{"fn_name": "duplicate_encode", "inputs": [["din"], ["recede"], ["Success"], ["CodeWarrior"], ["Supralapsarian"], ["iiiiii"], ["(( @"], [" ( ( )"]], "outputs": [["((("], ["()()()"], [")())())"], ["()(((())())"], [")()))()))))()("], ["))))))"], ["))(("], [")))))("]]}
introductory
https://www.codewars.com/kata/54b42f9314d9229fd6000d9c
def duplicate_encode(word):
2,819
### Problem Context The [Fibonacci](http://en.wikipedia.org/wiki/Fibonacci_number) sequence is traditionally used to explain tree recursion. ```python def fibonacci(n): if n in [0, 1]: return n return fibonacci(n - 1) + fibonacci(n - 2) ``` This algorithm serves welll its educative purpose but it's...
["def memoized(f):\n cache = {}\n def wrapped(k):\n v = cache.get(k)\n if v is None:\n v = cache[k] = f(k)\n return v\n return wrapped\n\n@memoized\ndef fibonacci(n):\n if n in [0, 1]:\n return n\n return fibonacci(n - 1) + fibonacci(n - 2)", "from functools import ...
{"fn_name": "fibonacci", "inputs": [[70], [60], [50]], "outputs": [[190392490709135], [1548008755920], [12586269025]]}
introductory
https://www.codewars.com/kata/529adbf7533b761c560004e5
def fibonacci(n):
2,820
This kata is part of the collection [Mary's Puzzle Books](https://www.codewars.com/collections/marys-puzzle-books). Mary brought home a "spot the differences" book. The book is full of a bunch of problems, and each problem consists of two strings that are similar. However, in each string there are a few characters tha...
["def spot_diff(s1, s2):\n return [i for i in range(len(s1)) if s1[i] != s2[i]]", "def spot_diff(s1, s2):\n return [k for k in range(len(s1)) if s1[k] != s2[k]]", "def spot_diff(s1, s2):\n r=[]\n for i in range (len(s1)):\n if s1[i]!=s2[i]: r.append(i)\n return r", "def spot_diff(s1, s2):\n return [i for i...
{"fn_name": "spot_diff", "inputs": [["abcdefg", "abcqetg"], ["Hello World!", "hello world."], ["FixedGrey", "FixedGrey"], ["HACKER", "H4CK3R"], ["This is a really long sentence.", "That is a_really long sentence,"], ["", ""], ["abcdefghijklmnopqrstuvwxyz", "zyxwvutsrqponmlkjihgfedcba"], ["YOLO lol", "ROLO mom"], ["www....
introductory
https://www.codewars.com/kata/5881460c780e0dd207000084
def spot_diff(s1, s2):
2,821
Today was a sad day. Having bought a new beard trimmer, I set it to the max setting and shaved away at my joyous beard. Stupidly, I hadnt checked just how long the max setting was, and now I look like Ive just started growing it! Your task, given a beard represented as an arrayof arrays, is to trim the beard as follow...
["def trim(beard):\n return [[h.replace(\"J\", \"|\") for h in b] for b in beard[:-1]] + [[\"...\"]*len(beard[0])]", "def trim(beard):\n beard = [[\"|\" if p in \"|J\" else \"...\" for p in hair] for hair in beard]\n beard[-1] = [\"...\" for _ in beard[-1]]\n return beard", "def trim(a):\n return [[\"|\"...
{"fn_name": "trim", "inputs": [[[["J", "|"], ["J", "|"], ["...", "|"]]], [[["J", "|", "J"], ["J", "|", "|"], ["...", "|", "J"]]], [[["J", "|", "J", "J"], ["J", "|", "|", "J"], ["...", "|", "J", "|"]]]], "outputs": [[[["|", "|"], ["|", "|"], ["...", "..."]]], [[["|", "|", "|"], ["|", "|", "|"], ["...", "...", "..."]]], ...
introductory
https://www.codewars.com/kata/57efa1a2108d3f73f60000e9
def trim(beard):
2,822
In this kata, you'll be given an integer of range `0 <= x <= 99` and have to return that number spelt out in English. A few examples: ```python name_that_number(4) # returns "four" name_that_number(19) # returns "nineteen" name_that_number(99) # returns "ninety nine" ``` Words should be separated by only spaces a...
["WORDS = (\n (90, 'ninety'), (80, 'eighty'), (70, 'seventy'), (60, 'sixty'),\n (50, 'fifty'), (40, 'forty'), (30, 'thirty'), (20, 'twenty'),\n (19, 'nineteen'), (18, 'eighteen'), (17, 'seventeen'), (16, 'sixteen'),\n (15, 'fifteen'), (14, 'fourteen'), (13, 'thirteen'), (12, 'twelve'),\n (11, 'eleven'), ...
{"fn_name": "name_that_number", "inputs": [[1], [52], [21], [99], [0], [53], [23], [76]], "outputs": [["one"], ["fifty two"], ["twenty one"], ["ninety nine"], ["zero"], ["fifty three"], ["twenty three"], ["seventy six"]]}
introductory
https://www.codewars.com/kata/579ba41ce298a73aaa000255
def name_that_number(x):
2,823
Given an array, find the duplicates in that array, and return a new array of those duplicates. The elements of the returned array should appear in the order when they first appeared as duplicates. __*Note*__: numbers and their corresponding string representations should not be treated as duplicates (i.e., `"1" != 1`)....
["def duplicates(array):\n seen = []\n dups = []\n for char in array:\n if char not in seen:\n seen.append(char)\n elif char not in dups:\n dups.append(char)\n \n return dups\n", "def duplicates(arr):\n res = []\n for i, x in enumerate(arr):\n if arr[:i ...
{"fn_name": "duplicates", "inputs": [[[1, 2, 4, 4, 3, 3, 1, 5, 3, "5"]], [[0, 1, 2, 3, 4, 5]], [[1, 1, 2, 3, 4, 5, 4]]], "outputs": [[[4, 3, 1]], [[]], [[1, 4]]]}
introductory
https://www.codewars.com/kata/5558cc216a7a231ac9000022
def duplicates(array):
2,824
*This is the second Kata in the Ciphers series. This series is meant to test our coding knowledge.* ## Ciphers #2 - The reversed Cipher This is a lame method I use to write things such that my friends don't understand. It's still fairly readable if you think about it. ## How this cipher works First, you need to rever...
["def encode(s):\n return ' '.join( w[-2::-1] + w[-1] for w in s.split() )", "def encode(s):\n s, sub_s = s.split(' '), ''\n for char in s:\n sub_s += char[::-1][1:] + char[-1] + ' '\n return sub_s[:-1]", "encode=lambda s:\" \".join([i[::-1][1:]+i[::-1][0] for i in s.split()])", "import re\n\ndef enc...
{"fn_name": "encode", "inputs": [["Hello World!"]], "outputs": [["lleHo dlroW!"]]}
introductory
https://www.codewars.com/kata/59474c656ff02b21e20000fc
def encode(s):
2,825
A Magic Square contains the integers 1 to n^(2), arranged in an n by n array such that the columns, rows and both main diagonals add up to the same number.For doubly even positive integers (multiples of 4) the following method can be used to create a magic square. Fill an array with the numbers 1 to n^(2) in succession...
["def even_magic(n):\n return [ [ n*n-(y*n+x) if x%4==y%4 or (x%4+y%4)%4==3 else y*n+x+1 for x in range(n)] for y in range(n) ]", "def even_magic(n):\n l = list(range(1,n*n+1))\n for i in range(n*n//2):\n y,x = (i//n)%4,(i%n)%4\n if y==x or x+y==3: l[i],l[n*n-1-i] = l[n*n-1-i], l[i]\n return [...
{"fn_name": "even_magic", "inputs": [[4], [8]], "outputs": [[[[16, 2, 3, 13], [5, 11, 10, 8], [9, 7, 6, 12], [4, 14, 15, 1]]], [[[64, 2, 3, 61, 60, 6, 7, 57], [9, 55, 54, 12, 13, 51, 50, 16], [17, 47, 46, 20, 21, 43, 42, 24], [40, 26, 27, 37, 36, 30, 31, 33], [32, 34, 35, 29, 28, 38, 39, 25], [41, 23, 22, 44, 45, 19, 1...
introductory
https://www.codewars.com/kata/570e0a6ce5c9a0a8c4000bbb
def even_magic(n):
2,826
Write a function that when given a number >= 0, returns an Array of ascending length subarrays. ``` pyramid(0) => [ ] pyramid(1) => [ [1] ] pyramid(2) => [ [1], [1, 1] ] pyramid(3) => [ [1], [1, 1], [1, 1, 1] ] ``` **Note:** the subarrays should be filled with `1`s
["def pyramid(n):\n return [[1]*x for x in range(1, n+1)]", "def pyramid(n):\n return [ [1] * i for i in range(1, n+1) ]", "def pyramid(n):\n result = []\n for i in range (1, n + 1):\n result.append(i * [1])\n return result", "pyramid=lambda n:[-~i*[1]for i in range(n)]", "def pyramid(n):\n res...
{"fn_name": "pyramid", "inputs": [[0], [1], [2], [3]], "outputs": [[[]], [[[1]]], [[[1], [1, 1]]], [[[1], [1, 1], [1, 1, 1]]]]}
introductory
https://www.codewars.com/kata/515f51d438015969f7000013
def pyramid(n):
2,827
When provided with a number between 0-9, return it in words. Input :: 1 Output :: "One". If your language supports it, try using a switch statement.
["def switch_it_up(n):\n return ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine'][n]", "def switch_it_up(number):\n number_converter={0:\"Zero\",1:\"One\",2:\"Two\",3:\"Three\",4:\"Four\",5:\"Five\",6:\"Six\",7:\"Seven\",8:\"Eight\",9:\"Nine\"}\n return number_converter[number]", "def swi...
{"fn_name": "switch_it_up", "inputs": [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9]], "outputs": [["Zero"], ["One"], ["Two"], ["Three"], ["Four"], ["Five"], ["Six"], ["Seven"], ["Eight"], ["Nine"]]}
introductory
https://www.codewars.com/kata/5808dcb8f0ed42ae34000031
def switch_it_up(number):
2,828
A [Power Law](https://en.wikipedia.org/wiki/Power_law) distribution occurs whenever "a relative change in one quantity results in a proportional relative change in the other quantity." For example, if *y* = 120 when *x* = 1 and *y* = 60 when *x* = 2 (i.e. *y* halves whenever *x* doubles) then when *x* = 4, *y* = 30 and...
["from math import log\n\ndef power_law(p1, p2, x3):\n (x1, y1), (x2, y2) = p1, p2\n x1 += 1e-9; y1 += 1e-9\n return round(y1 * (y2 / y1) ** log(x3 / x1, x2 / x1))", "from math import log\n\ndef power_law(x1y1, x2y2, x3):\n a, b, c = x2y2[0]/x1y1[0], x2y2[1]/x1y1[1], x3/x1y1[0]\n try:\n return ro...
{"fn_name": "power_law", "inputs": [[[1, 120], [2, 60], 4], [[1, 120], [2, 60], 8], [[1, 120], [4, 30], 8], [[1, 120], [3, 60], 9], [[1, 120], [3, 60], 27], [[1, 120], [9, 30], 27], [[1, 81], [2, 27], 4], [[1, 81], [2, 27], 8], [[1, 81], [4, 9], 8], [[1, 81], [5, 27], 25], [[1, 81], [5, 27], 125], [[1, 81], [25, 9], 12...
introductory
https://www.codewars.com/kata/59b6ae2e5227dd0fbc000005
def power_law(x1y1, x2y2, x3):
2,829
# SpeedCode #2 - Array Madness ## Objective Given two **integer arrays** ```a, b```, both of ```length >= 1```, create a program that returns ```true``` if the **sum of the squares** of each element in ```a``` is **strictly greater than** the **sum of the cubes** of each element in ```b```. E.g. ```python array_madn...
["def array_madness(a,b):\n return sum(x ** 2 for x in a) > sum(x **3 for x in b)", "def array_madness(a,b):\n return sum(map(lambda a: a ** 2, a)) > sum(map(lambda b: b ** 3, b))", "def array_madness(a,b):\n sa=0\n sb=0\n for i in range(0,len(a)):\n sa+=a[i]**2\n for i in range(0,len(b)):\n ...
{"fn_name": "array_madness", "inputs": [[[4, 5, 6], [1, 2, 3]]], "outputs": [[true]]}
introductory
https://www.codewars.com/kata/56ff6a70e1a63ccdfa0001b1
def array_madness(a,b):
2,830
Simple enough this one - you will be given an array. The values in the array will either be numbers or strings, or a mix of both. You will not get an empty array, nor a sparse one. Your job is to return a single array that has first the numbers sorted in ascending order, followed by the strings sorted in alphabetic or...
["def db_sort(arr): \n return sorted(arr, key=lambda x: (isinstance(x,str),x))", "def db_sort(arr): \n n=[]\n s=[]\n for i in arr:\n if type(i) ==type( 'a'):\n s.append(i)\n else:\n n.append(i)\n return sorted(n)+sorted(s)", "def db_sort(arr): \n ints, strg = [], []...
{"fn_name": "db_sort", "inputs": [[[6, 2, 3, 4, 5]], [[14, 32, 3, 5, 5]], [[1, 2, 3, 4, 5]], [["Banana", "Orange", "Apple", "Mango", 0, 2, 2]], [["C", "W", "W", "W", 1, 2, 0]], [["Hackathon", "Katathon", "Code", "CodeWars", "Laptop", "Macbook", "JavaScript", 1, 5, 2]], [[66, "t", 101, 0, 1, 1]], [[78, 117, 110, 99, 104...
introductory
https://www.codewars.com/kata/57cc79ec484cf991c900018d
def db_sort(arr):
2,831
Given a sequence of numbers, find the largest pair sum in the sequence. For example ``` [10, 14, 2, 23, 19] --> 42 (= 23 + 19) [99, 2, 2, 23, 19] --> 122 (= 99 + 23) ``` Input sequence contains minimum two elements and every element is an integer.
["def largest_pair_sum(numbers): \n return sum(sorted(numbers)[-2:])", "from heapq import nlargest\n\ndef largest_pair_sum(a):\n return sum(nlargest(2, a))", "def largest_pair_sum(a): \n return a.pop(a.index(max(a))) + a.pop(a.index(max(a)))", "def largest_pair_sum(numbers): \n return sorted(numbers)[-2]+ma...
{"fn_name": "largest_pair_sum", "inputs": [[[10, 14, 2, 23, 19]], [[-100, -29, -24, -19, 19]], [[1, 2, 3, 4, 6, -1, 2]], [[-10, -8, -16, -18, -19]]], "outputs": [[42], [0], [10], [-18]]}
introductory
https://www.codewars.com/kata/556196a6091a7e7f58000018
def largest_pair_sum(numbers):
2,832
# Task You are given an array `a` of positive integers a. You may choose some integer `X` and update `a` several times, where to update means to perform the following operations: ``` pick a contiguous subarray of length not greater than the given k; replace all elements in the picked subarray with the chosen X. ``` Wh...
["def array_equalization(a, k):\n totals, ends = {}, {}\n for i, n in enumerate(a):\n if n not in ends: totals[n], ends[n] = 0, -1\n if i < ends[n]: continue\n count = (i - ends[n] - 1 + k - 1) // k\n totals[n] += count\n ends[n] = max(i, ends[n] + count * k)\n return min(t +...
{"fn_name": "array_equalization", "inputs": [[[1, 2, 2, 1, 2, 1, 2, 2, 2, 1, 1, 1], 2], [[5, 2, 3, 5, 2, 2, 3, 5, 1, 2, 5, 1, 2, 5, 3], 7], [[1, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1], 9]], "outputs": [[4], [2], [1]]}
introductory
https://www.codewars.com/kata/58a3c836623e8c72eb000188
def array_equalization(a, k):
2,833
In this kata you are given an array to sort but you're expected to start sorting from a specific position of the array (in ascending order) and optionally you're given the number of items to sort. #### Examples: ```python sect_sort([1, 2, 5, 7, 4, 6, 3, 9, 8], 2) //=> [1, 2, 3, 4, 5, 6, 7, 8, 9] sect_sort([9, 7, 4, 2...
["def sect_sort(lst, start, length=0):\n end = start + length if length else len(lst)\n return lst[:start] + sorted(lst[start:end]) + lst[end:]", "def sect_sort(arr, start, num=0):\n out = arr[:]\n s = slice(start, None if not num else start + num)\n out[s] = sorted(out[s])\n return out", "def sect_so...
{"fn_name": "sect_sort", "inputs": [[[1, 2, 5, 7, 4, 6, 3, 9, 8], 2], [[1, 2, 5, 7, 4, 6, 3, 9, 8], 8], [[9, 7, 4, 2, 5, 3, 1, 8, 6], 2, 5], [[1, 2, 5, 7, 4, 6, 3, 9, 8], 8, 3], [[], 0]], "outputs": [[[1, 2, 3, 4, 5, 6, 7, 8, 9]], [[1, 2, 5, 7, 4, 6, 3, 9, 8]], [[9, 7, 1, 2, 3, 4, 5, 8, 6]], [[1, 2, 5, 7, 4, 6, 3, 9, 8...
introductory
https://www.codewars.com/kata/58ef87dc4db9b24c6c000092
def sect_sort(lst, start, length=0):
2,834
"Point reflection" or "point symmetry" is a basic concept in geometry where a given point, P, at a given position relative to a mid-point, Q has a corresponding point, P1, which is the same distance from Q but in the opposite direction. ## Task Given two points P and Q, output the symmetric point of point P about Q. ...
["def symmetric_point(p, q):\n return [2*q[0] - p[0], 2*q[1] - p[1]]", "symmetric_point = lambda p, q: [2 * b - a for a, b in zip(p, q)]", "def symmetric_point(p, q):\n # your code here\n p1x = (q[0] - p[0]) + q[0]\n p1y = (q[1] - p[1]) + q[1]\n return [p1x, p1y]", "symmetric_point = lambda p,q: [2*q[0] ...
{"fn_name": "symmetric_point", "inputs": [[[0, 0], [1, 1]], [[2, 6], [-2, -6]], [[10, -10], [-10, 10]], [[1, -35], [-12, 1]], [[1000, 15], [-7, -214]], [[0, 0], [0, 0]]], "outputs": [[[2, 2]], [[-6, -18]], [[-30, 30]], [[-25, 37]], [[-1014, -443]], [[0, 0]]]}
introductory
https://www.codewars.com/kata/57bfea4cb19505912900012c
def symmetric_point(p, q):
2,836
Cheesy Cheeseman just got a new monitor! He is happy with it, but he just discovered that his old desktop wallpaper no longer fits. He wants to find a new wallpaper, but does not know which size wallpaper he should be looking for, and alas, he just threw out the new monitor's box. Luckily he remembers the width and the...
["def find_screen_height(width, ratio): \n a, b = map(int, ratio.split(\":\"))\n return f\"{width}x{int(width / a * b)}\"", "def find_screen_height(width, ratio): \n #Turns the string ratio into a list with the two numbers as elements\n z = ratio.split(\":\")\n \n #calculates the height value\n hei...
{"fn_name": "find_screen_height", "inputs": [[1024, "4:3"], [1280, "16:9"], [3840, "32:9"], [1600, "4:3"], [1280, "5:4"], [2160, "3:2"], [1920, "16:9"], [5120, "32:9"]], "outputs": [["1024x768"], ["1280x720"], ["3840x1080"], ["1600x1200"], ["1280x1024"], ["2160x1440"], ["1920x1080"], ["5120x1440"]]}
introductory
https://www.codewars.com/kata/5bbd279c8f8bbd5ee500000f
def find_screen_height(width, ratio):
2,837
Peter can see a clock in the mirror from the place he sits in the office. When he saw the clock shows 12:22 1 2 3 4 5 6 7 8 9 10 11 12 He knows that the time is 11:38 1 2 3 4 5 6 7 8 9 10 11 12 in the same manner: 05:25 --> 06:35 01:50 --> 10:10 11:58 --> 12:02 12:01 --> 11:59 Please complete the fun...
["def what_is_the_time(time_in_mirror):\n h, m = map(int, time_in_mirror.split(':'))\n return '{:02}:{:02}'.format(-(h + (m != 0)) % 12 or 12, -m % 60)", "def what_is_the_time(time_in_mirror):\n array = time_in_mirror.split(\":\")\n a = int(array[0])\n b = int(array[1])\n \n if a == 11: a = 12\n ...
{"fn_name": "what_is_the_time", "inputs": [["06:35"], ["11:59"], ["12:02"], ["04:00"], ["06:00"], ["12:00"]], "outputs": [["05:25"], ["12:01"], ["11:58"], ["08:00"], ["06:00"], ["12:00"]]}
introductory
https://www.codewars.com/kata/56548dad6dae7b8756000037
def what_is_the_time(time_in_mirror):
2,838
Given a string, you progressively need to concatenate the first letter from the left and the first letter to the right and "1", then the second letter from the left and the second letter to the right and "2", and so on. If the string's length is odd drop the central element. For example: ```python char_concat("abcdef...
["def char_concat(word, index = 1):\n if len(word) < 2: return ''\n return word[0:1] + word[-1:] + str(index) + char_concat(word[1:-1], index + 1)", "def char_concat(word):\n return ''.join([(word[i]+word[-1-i]+str(i+1))for i in range(len(word)//2)])\n", "def char_concat(word):\n return ''.join( \"{}{}{}\".form...
{"fn_name": "char_concat", "inputs": [["abc def"], ["CodeWars"], ["CodeWars Rocks"], ["1234567890"], ["$'D8KB)%PO@s"]], "outputs": [["af1be2cd3"], ["Cs1or2da3eW4"], ["Cs1ok2dc3eo4WR5a 6rs7"], ["101292383474565"], ["$s1'@2DO38P4K%5B)6"]]}
introductory
https://www.codewars.com/kata/55147ff29cd40b43c600058b
def char_concat(word):
2,839
You know how sometimes you write the the same word twice in a sentence, but then don't notice that it happened? For example, you've been distracted for a second. Did you notice that *"the"* is doubled in the first sentence of this description? As as aS you can see, it's not easy to spot those errors, especially if wor...
["def count_adjacent_pairs(st): \n words = st.lower().split(' ')\n currentWord = None\n count = 0\n for i, word in enumerate(words):\n if i+1 < len(words):\n if word == words[i+1]:\n if word != currentWord:\n currentWord = word\n count +...
{"fn_name": "count_adjacent_pairs", "inputs": [[""], ["orange Orange kiwi pineapple apple"], ["banana banana banana"], ["banana banana banana terracotta banana terracotta terracotta pie!"], ["pineapple apple"]], "outputs": [[0], [1], [1], [2], [0]]}
introductory
https://www.codewars.com/kata/5245a9138ca049e9a10007b8
def count_adjacent_pairs(st):
2,840
## Task An `ATM` ran out of 10 dollar bills and only has `100, 50 and 20` dollar bills. Given an amount between `40 and 10000 dollars (inclusive)` and assuming that the ATM wants to use as few bills as possible, determinate the minimal number of 100, 50 and 20 dollar bills the ATM needs to dispense (in that order)....
["def withdraw(n):\n n50 = 0\n n20, r = divmod(n, 20)\n if r == 10:\n n20 -= 2\n n50 += 1\n n100, n20 = divmod(n20, 5)\n return [n100, n50, n20]", "def withdraw(n):\n hundreds, fifties, rest = n // 100, (n % 100) // 50, n % 50\n if rest % 20 == 10:\n if fifties == 0:\n ...
{"fn_name": "withdraw", "inputs": [[40], [250], [260], [230], [60]], "outputs": [[[0, 0, 2]], [[2, 1, 0]], [[2, 0, 3]], [[1, 1, 4]], [[0, 0, 3]]]}
introductory
https://www.codewars.com/kata/58afce23b0e8046a960000eb
def withdraw(n):
2,841
Taking into consideration the [3.5 edition rules](http://www.dandwiki.com/wiki/SRD:Ability_Scores#Table:_Ability_Modifiers_and_Bonus_Spells), your goal is to build a function that takes an ability score (worry not about validation: it is always going to be a non negative integer), will return: * attribute modifier, as...
["def char_attribute(score):\n return ({\"modifier\": 0, \"maximum_spell_level\": -1, \"extra_spells\": []} if not score\n else {\"modifier\": score//2-5,\n \"maximum_spell_level\": -1 if score//2-5 < 0 else min(9, score -10) ,\n \"extra_spells\": [1+n//4 for n in r...
{"fn_name": "char_attribute", "inputs": [[0], [1], [5], [10], [20]], "outputs": [[{"modifier": 0, "maximum_spell_level": -1, "extra_spells": []}], [{"modifier": -5, "maximum_spell_level": -1, "extra_spells": []}], [{"modifier": -3, "maximum_spell_level": -1, "extra_spells": []}], [{"modifier": 0, "maximum_spell_level":...
introductory
https://www.codewars.com/kata/596a690510ffee5c0b00006a
def char_attribute(score):
2,842
Construct a function 'coordinates', that will return the distance between two points on a cartesian plane, given the x and y coordinates of each point. There are two parameters in the function, ```p1``` and ```p2```. ```p1``` is a list ```[x1,y1]``` where ```x1``` and ```y1``` are the x and y coordinates of the first ...
["def coordinates(p1,p2, precision = 0):\n return round(sum( (b-a)**2 for a,b in zip(p1,p2) )**.5, precision)", "import math\n\ndef coordinates(p1, p2, precision=0):\n return round(math.hypot(p1[0] - p2[0], p1[1] - p2[1]), precision)", "def coordinates(a, b, p = 0):\n return round(sum((i - j) ** 2 for i, j in ...
{"fn_name": "coordinates", "inputs": [[[3, 6], [14, 6]], [[-2, 5], [-2, -10], 2], [[1, 2], [4, 6]], [[5, 3], [10, 15], 2], [[-2, -10], [6, 5]], [[4, 7], [6, 2], 3], [[-4, -5], [-5, -4], 1], [[3, 8], [3, 8]], [[-3, 8], [3, 8]], [[3, 8], [3, -8]]], "outputs": [[11], [15], [5], [13], [17], [5.385], [1.4], [0], [6], [16]]}
introductory
https://www.codewars.com/kata/5944f3f8d7b6a5748d000233
def coordinates(p1, p2, precision=0):
2,843
You're about to go on a trip around the world! On this trip you're bringing your trusted backpack, that anything fits into. The bad news is that the airline has informed you, that your luggage cannot exceed a certain amount of weight. To make sure you're bringing your most valuable items on this journey you've decided...
["def pack_bagpack(scores, weights, capacity):\n load = [0] * (capacity + 1)\n for score, weight in zip(scores, weights):\n load = [max(l, weight <= w and load[w - weight] + score)\n for w, l in enumerate(load)]\n return load[-1]", "def pack_bagpack(S,W,C) :\n M = [0] * (1 + C)\n fo...
{"fn_name": "pack_bagpack", "inputs": [[[15, 10, 9, 5], [1, 5, 3, 4], 8], [[20, 5, 10, 40, 15, 25], [1, 2, 3, 8, 7, 4], 10], [[19, 8, 6, 20, 3, 16], [8, 2, 3, 10, 1, 5], 17], [[100, 5, 16, 18, 50], [25, 1, 3, 2, 15], 14]], "outputs": [[29], [60], [46], [39]]}
introductory
https://www.codewars.com/kata/5a51717fa7ca4d133f001fdf
def pack_bagpack(scores, weights, capacity):
2,844
Write a program that prints a chessboard with N rows and M columns with the following rules: The top left cell must be an asterisk (*) Any cell touching (left, right, up or down) a cell with an asterisk must be a dot (.) Any cell touching (left, right, up or down) a cell with a dot must be an asterisk. A chessboard of...
["def chessboard(s):\n N, M = map(int, s.split())\n row = \".*\" * M\n return \"\\n\".join( [row[:M] if i&1 else row[1:M+1] for i in range(N)] )", "chessboard = lambda s: '\\n'.join(([''.join(['.' if (x + y) % 2 else '*' for x in range(int(s.split()[1]))]) for y in range(int(s.split()[0]))]))", "from itertools...
{"fn_name": "chessboard", "inputs": [["0 0"], ["1 0"], ["0 1"], ["2 2"], ["3 3"], ["5 2"], ["8 8"]], "outputs": [[""], [""], [""], ["*.\n.*"], ["*.*\n.*.\n*.*"], ["*.\n.*\n*.\n.*\n*."], ["*.*.*.*.\n.*.*.*.*\n*.*.*.*.\n.*.*.*.*\n*.*.*.*.\n.*.*.*.*\n*.*.*.*.\n.*.*.*.*"]]}
introductory
https://www.codewars.com/kata/5749b82229d16cbc320015fe
def chessboard(s):
2,845
DNA is a biomolecule that carries genetic information. It is composed of four different building blocks, called nucleotides: adenine (A), thymine (T), cytosine (C) and guanine (G). Two DNA strands join to form a double helix, whereby the nucleotides of one strand bond to the nucleotides of the other strand at the corre...
["def check_DNA(seq1, seq2):\n if len(seq1) < len(seq2): seq1, seq2 = seq2, seq1\n seq2 = seq2[::-1].replace('C','g').replace('G','c').replace('T','a').replace('A','t').upper()\n return seq1.find(seq2) >= 0", "table = str.maketrans(\"ACGT\", \"TGCA\")\n\ndef check_DNA(seq1, seq2):\n seq1, seq2 = sorted((seq1, seq2),...
{"fn_name": "check_DNA", "inputs": [["GTCTTAGTGTAGCTATGCATGC", "GCATGCATAGCTACACTACGAC"], ["ATGCTACG", "CGTAGCAT"], ["AGTCTGTATGCATCGTACCC", "GGGTACGATGCATACAGACT"], ["TGCTACGTACGATCGACGATCCACGAC", "GTCGTGGATCGTCGATCGTACGTAGCA"], ["ATGCCTACGGCCATATATATTTAG", "CTAAATATGTATGGCCGTAGGCAT"], ["GTCACCGA", "TCGGCTGAC"], ["TAA...
introductory
https://www.codewars.com/kata/56fbb2b8fca8b97e4d000a31
def check_DNA(seq1, seq2):
2,846
You are provided with array of positive non-zero ints and int n representing n-th power (n >= 2). For the given array, calculate the sum of each value to the n-th power. Then subtract the sum of the original array. Example 1: Input: {1, 2, 3}, 3 --> (1 ^ 3 + 2 ^ 3 + 3 ^ 3 ) - (1 + 2 + 3) --> 36 - 6 --> Output: 30 Ex...
["def modified_sum(lst, p):\n return sum(n**p - n for n in lst)", "def modified_sum(a, n):\n return sum(i ** n for i in a) - sum(a)", "def modified_sum(a, n):\n return sum([x ** n - x for x in a])", "def modified_sum(a, n):\n return sum(i**n - i for i in a)", "def modified_sum(a, n):\n ans = 0\n for s...
{"fn_name": "modified_sum", "inputs": [[[1, 2, 3], 3], [[1, 2], 5], [[3, 5, 7], 2], [[1, 2, 3, 4, 5], 3], [[2, 7, 13, 17], 2], [[2, 5, 8], 3], [[2, 4, 6, 8], 6], [[5, 10, 15], 4], [[3, 6, 9, 12], 3]], "outputs": [[30], [30], [68], [210], [472], [630], [312940], [61220], [2670]]}
introductory
https://www.codewars.com/kata/58aed2cafab8faca1d000e20
def modified_sum(a, n):
2,847
You just took a contract with the Jedi council. They need you to write a function, `greet_jedi()`, which takes two arguments (a first name and a last name), works out the corresponding *Jedi name*, and returns a string greeting the Jedi. A person's *Jedi name* is the first three letters of their last name followed by ...
["def greet_jedi(first, last):\n return \"Greetings, master {}{}\".format(last[:3].capitalize(), first[:2].capitalize())", "def greet_jedi(f, l):\n return 'Greetings, master ' + l[0:3].capitalize() + f[0:2].capitalize()", "def greet_jedi(first, last):\n return 'Greetings, master %s%s' % (last[:3].capitalize(), f...
{"fn_name": "greet_jedi", "inputs": [["Beyonce", "Knowles"], ["Chris", "Angelico"], ["grae", "drake"]], "outputs": [["Greetings, master KnoBe"], ["Greetings, master AngCh"], ["Greetings, master DraGr"]]}
introductory
https://www.codewars.com/kata/585a29183d357b31f700023f
def greet_jedi(first, last):
2,848
Consider the array `[3,6,9,12]`. If we generate all the combinations with repetition that sum to `12`, we get `5` combinations: `[12], [6,6], [3,9], [3,3,6], [3,3,3,3]`. The length of the sub-arrays (such as `[3,3,3,3]` should be less than or equal to the length of the initial array (`[3,6,9,12]`). Given an array of...
["from itertools import combinations_with_replacement\n\ndef find(arr,n):\n return sum( sum(c) == n for x in range(1,len(arr)+1) for c in combinations_with_replacement(arr, x) )", "def find(arr,n):\n return(findl(arr,n,len(arr)))\ndef findl(arr,n,l):\n return(sum(findl(arr[1:],n-arr[0]*i,l-i) for i in range(l+...
{"fn_name": "find", "inputs": [[[1, 2, 3], 10], [[1, 2, 3], 7], [[1, 2, 3], 5], [[3, 6, 9, 12], 12], [[1, 4, 5, 8], 8], [[3, 6, 9, 12], 15], [[3, 6, 9, 12, 14, 18], 30]], "outputs": [[0], [2], [3], [5], [3], [5], [21]]}
introductory
https://www.codewars.com/kata/59f3178e3640cef6d90000d5
def find(arr,n):
2,849
Given an array of ints, return the index such that the sum of the elements to the right of that index equals the sum of the elements to the left of that index. If there is no such index, return `-1`. If there is more than one such index, return the left-most index. For example: ``` peak([1,2,3,5,3,2,1]) = 3, because ...
["def peak(arr):\n for i, val in enumerate(arr):\n if sum(arr[:i]) == sum(arr[i+1:]):\n return i\n return -1", "def peak(arr):\n for i in range(len(arr)):\n if sum(arr[:i]) == sum(arr[i+1:]): return i\n return -1", "def peak(arr):\n sl, sr = 0, sum(arr)\n for i,v in enumerate(...
{"fn_name": "peak", "inputs": [[[1, 2, 3, 5, 3, 2, 1]], [[1, 12, 3, 3, 6, 3, 1]], [[10, 20, 30, 40]]], "outputs": [[3], [2], [-1]]}
introductory
https://www.codewars.com/kata/5a61a846cadebf9738000076
def peak(arr):
2,850
Gordon Ramsay shouts. He shouts and swears. There may be something wrong with him. Anyway, you will be given a string of four words. Your job is to turn them in to Gordon language. Rules: Obviously the words should be Caps, Every word should end with '!!!!', Any letter 'a' or 'A' should become '@', Any other vowel ...
["def gordon(a):\n return '!!!! '.join(a.upper().split()).translate(str.maketrans('AEIOU', '@****'))+'!!!!'", "def gordon(s):\n return \" \".join(x + \"!!!!\" for x in s.upper().translate(str.maketrans(\"AIUEO\", \"@****\")).split())", "def gordon(a):\n return \" \".join(word.upper().translate(str.maketrans(\"...
{"fn_name": "gordon", "inputs": [["What feck damn cake"], ["are you stu pid"], ["i am a chef"], ["dont you talk tome"], ["how dare you feck"]], "outputs": [["WH@T!!!! F*CK!!!! D@MN!!!! C@K*!!!!"], ["@R*!!!! Y**!!!! ST*!!!! P*D!!!!"], ["*!!!! @M!!!! @!!!! CH*F!!!!"], ["D*NT!!!! Y**!!!! T@LK!!!! T*M*!!!!"], ["H*W!!!! D@R...
introductory
https://www.codewars.com/kata/57d1f36705c186d018000813
def gordon(a):
2,851
Oh no! Ghosts have reportedly swarmed the city. It's your job to get rid of them and save the day! In this kata, strings represent buildings while whitespaces within those strings represent ghosts. So what are you waiting for? Return the building(string) without any ghosts(whitespaces)! Example: Should return: If ...
["ghostbusters = lambda s: (s.replace(' ','') if (' ' in s) else\n \"You just wanted my autograph didn't you?\")", "import re\ndef ghostbusters(building):\n bs = re.subn('\\s','',building)\n return bs[0] if bs[1] else \"You just wanted my autograph didn't you?\"", "message = \"You just w...
{"fn_name": "ghostbusters", "inputs": [["Factor y"], ["O f fi ce"], ["BusStation"], ["Suite "], ["YourHouse"], ["H o t e l "]], "outputs": [["Factory"], ["Office"], ["You just wanted my autograph didn't you?"], ["Suite"], ["You just wanted my autograph didn't you?"], ["Hotel"]]}
introductory
https://www.codewars.com/kata/5668e3800636a6cd6a000018
def ghostbusters(building):
2,852
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said # Description: Given a string `str` that contains some "(" or ")". Your task is to find the longest substring in `str`(all brackets in the substring are closed). The resu...
["def find_longest(st):\n res,pos=0,[0]\n for i,b in enumerate(st,1):\n if b==\"(\": pos.append(i)\n else: \n try:pos.pop();res=max(res,i-pos[-1])\n except:pos.append(i)\n return res", "def find_longest(s):\n stack, m = [-1], 0\n for i,j in enumerate(s):\n if ...
{"fn_name": "find_longest", "inputs": [[")()("], ["((()"], ["((("], ["())((("], ["())()))))()()("]], "outputs": [[2], [2], [0], [2], [4]]}
introductory
https://www.codewars.com/kata/584c3e45710dca21be000088
def find_longest(st):
2,853
In this Kata, you will remove the left-most duplicates from a list of integers and return the result. ```python # Remove the 3's at indices 0 and 3 # followed by removing a 4 at index 1 solve([3, 4, 4, 3, 6, 3]) # => [4, 6, 3] ``` More examples can be found in the test cases. Good luck!
["def solve(arr): \n re = []\n for i in arr[::-1]:\n if i not in re:\n re.append(i)\n return re[::-1]", "def solve(arr): \n return list(dict.fromkeys(arr[::-1]))[::-1]", "def solve(arr): \n return [a for i,a in enumerate(arr) if a not in arr[i+1:]]", "def solve(arr): \n list = arr.co...
{"fn_name": "solve", "inputs": [[[3, 4, 4, 3, 6, 3]], [[1, 2, 1, 2, 1, 2, 3]], [[1, 2, 3, 4]], [[1, 1, 4, 5, 1, 2, 1]]], "outputs": [[[4, 6, 3]], [[1, 2, 3]], [[1, 2, 3, 4]], [[4, 5, 2, 1]]]}
introductory
https://www.codewars.com/kata/5ba38ba180824a86850000f7
def solve(arr):
2,854
### Happy Holidays fellow Code Warriors! Now, Dasher! Now, Dancer! Now, Prancer, and Vixen! On, Comet! On, Cupid! On, Donder and Blitzen! That's the order Santa wanted his reindeer...right? What do you mean he wants them in order by their last names!? Looks like we need your help Code Warrior! ### Sort Santa's Reinde...
["def sort_reindeer(reindeer_names):\n return sorted(reindeer_names, key=lambda s:s.split()[1])", "def sort_reindeer(names):\n return sorted(names, key=lambda x: x.split()[1])", "def lastname(name):\n name = name.split()\n return name[1]\n \ndef sort_reindeer(reindeer_names):\n reindeer_names.sort(key...
{"fn_name": "sort_reindeer", "inputs": [[["Kenjiro Mori", "Susumu Tokugawa", "Juzo Okita", "Akira Sanada"]], [[]], [["Yasuo Kodai", "Kenjiro Sado", "Daisuke Aihara", "Susumu Shima", "Akira Sanada", "Yoshikazu Okita", "Shiro Yabu", "Sukeharu Nanbu", "Sakezo Yamamoto", "Hikozaemon Ohta", "Juzo Mori", "Saburo Tokugawa"]],...
introductory
https://www.codewars.com/kata/52ab60b122e82a6375000bad
def sort_reindeer(reindeer_names):
2,855
The number 81 has a special property, a certain power of the sum of its digits is equal to 81 (nine squared). Eighty one (81), is the first number in having this property (not considering numbers of one digit). The next one, is 512. Let's see both cases with the details 8 + 1 = 9 and 9^(2) = 81 512 = 5 + 1 + 2 = 8 a...
["series = [0]\nfor a in range(2, 99):\n for b in range(2, 42):\n c = a**b\n if a == sum(map(int, str(c))):\n series.append(c)\npower_sumDigTerm = sorted(series).__getitem__", "def dig_sum(n):\n return sum(map(int, str(n)))\n\n\n\nterms = []\nfor b in range(2, 400):\n for p in range(2,...
{"fn_name": "power_sumDigTerm", "inputs": [[1], [2], [3], [4], [5], [6], [7]], "outputs": [[81], [512], [2401], [4913], [5832], [17576], [19683]]}
introductory
https://www.codewars.com/kata/55f4e56315a375c1ed000159
def power_sumDigTerm(n):
2,856
A binary gap within a positive number ```num``` is any sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of ```num```. For example: ```9``` has binary representation ```1001``` and contains a binary gap of length ```2```. ```529``` has binary representation...
["def gap(num):\n s = bin(num)[2:].strip(\"0\")\n return max(map(len, s.split(\"1\")))", "import re\ndef gap(num):\n x=re.findall('(?=(10+1))',bin(num).lstrip('0b')) \n return max([len(i)-2 for i in x]) if x else 0", "import re\n\ndef gap(num):\n\n n = 0\n\n for m in re.finditer('(?=(1(0+)1))', bin(nu...
{"fn_name": "gap", "inputs": [[9]], "outputs": [[2]]}
introductory
https://www.codewars.com/kata/55b86beb1417eab500000051
def gap(num):
2,857
Write function ```splitSentence``` which will create a list of strings from a string. Example: ```"hello world" -> ["hello", "world"]```
["splitSentence=str.split", "def splitSentence(s):\n return s.split()\n", "def splitSentence(s):\n# do something here\n return list(s.split(\" \"))", "yolo = split_sentence = splitSentence = str.split", "def splitSentence(s):\n return [i for i in s.split(' ')]\n", "def splitSentence(s):\n s_new = s.spli...
{"fn_name": "splitSentence", "inputs": [["This string is splitsville"], ["something"]], "outputs": [[["This", "string", "is", "splitsville"]], [["something"]]]}
introductory
https://www.codewars.com/kata/57a05e0172292dd8510001f7
def splitSentence(s):
2,858
# Task Miss X has only two combs in her possession, both of which are old and miss a tooth or two. She also has many purses of different length, in which she carries the combs. The only way they fit is horizontally and without overlapping. Given teeth' positions on both combs, find the minimum length of the purse she ...
["def combs(a, b):\n return min(mesh(a, b), mesh(b, a))\n\ndef mesh(a, b):\n for i in range(len(a)):\n for j, k in zip(a[i:], b):\n if j + k == '**': break\n else:\n return max(i + len(b), len(a))\n return len(a) + len(b) ", "def combs(comb1, comb2):\n options ...
{"fn_name": "combs", "inputs": [["*..*", "*.*"], ["*...*", "*.*"], ["*..*.*", "*.***"], ["*.*", "*.*"], ["*.**", "*.*"]], "outputs": [[5], [5], [9], [4], [5]]}
introductory
https://www.codewars.com/kata/58898b50b832f8046a0000ec
def combs(comb1, comb2):
2,859
Given an array of numbers, calculate the largest sum of all possible blocks of consecutive elements within the array. The numbers will be a mix of positive and negative values. If all numbers of the sequence are nonnegative, the answer will be the sum of the entire array. If all numbers in the array are negative, your ...
["def largest_sum(arr):\n sum = max_sum = 0\n for n in arr:\n sum = max(sum + n, 0)\n max_sum = max(sum, max_sum)\n return max_sum", "def largest_sum(arr):\n a, b, ar = 0, 0, arr[:]\n for i in ar:\n b+=i\n if b < 0: b = 0\n if b > a: a = b\n return a", "def largest_s...
{"fn_name": "largest_sum", "inputs": [[[-1, -2, -3]], [[]], [[1, 2, 3, 4]], [[31, -41, 59, 26, -53, 58, 97, -93, -23, 84]]], "outputs": [[0], [0], [10], [187]]}
introductory
https://www.codewars.com/kata/56001790ac99763af400008c
def largest_sum(arr):
2,860
Two strings ```a``` and b are called isomorphic if there is a one to one mapping possible for every character of ```a``` to every character of ```b```. And all occurrences of every character in ```a``` map to same character in ```b```. ## Task In this kata you will create a function that return ```True``` if two give...
["def isomorph(a, b):\n return [a.index(x) for x in a] == [b.index(y) for y in b]\n", "from itertools import zip_longest\n\ndef isomorph(a, b):\n return len(set(a)) == len(set(b)) == len(set(zip_longest(a, b)))", "def isomorph(s, t):\n if len(s) != len(t):\n return False\n p= set(zip(s, t))\n return all(l...
{"fn_name": "isomorph", "inputs": [["ESTATE", "DUELED"], ["XXX", "YYY"], ["CBAABC", "DEFFED"], ["RAMBUNCTIOUSLY", "THERMODYNAMICS"], ["DISCRIMINATIVE", "SIMPLIFICATION"], ["SEE", "SAW"], ["BANANA", "SENSE"], ["AB", "CC"], ["XXY", "XYY"], ["ABCBACCBA", "ABCBACCAB"], ["AA", "BBB"], ["abcdefghijk", "abcdefghijba"]], "outp...
introductory
https://www.codewars.com/kata/59dbab4d7997cb350000007f
def isomorph(a, b):
2,861
For a given 2D vector described by cartesian coordinates of its initial point and terminal point in the following format: ```python [[x1, y1], [x2, y2]] ``` Your function must return this vector's length represented as a floating point number. Error must be within 1e-7. Coordinates can be integers or floating point...
["def vector_length(vector):\n (x1,y1),(x2,y2) = vector\n return ((x1-x2)**2 + (y1-y2)**2) ** .5", "import math\n\n\ndef vector_length(vector):\n return math.hypot(vector[0][0] - vector[1][0],\n vector[0][1] - vector[1][1])\n", "import math\ndef vector_length(v):\n return math.sqrt(math.p...
{"fn_name": "vector_length", "inputs": [[[[0, 1], [0, 0]]], [[[0, 3], [4, 0]]], [[[1, -1], [1, -1]]]], "outputs": [[1], [5], [0]]}
introductory
https://www.codewars.com/kata/554dc2b88fbafd2e95000125
def vector_length(vector):