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 |
|---|---|---|---|---|---|---|
4,465 | Write a function that rearranges an integer into its largest possible value.
```python
super_size(123456) # 654321
super_size(105) # 510
super_size(12) # 21
```
``` haskell
superSize 123456 `shouldBe` 654321
superSize 105 `shouldBe` 510
superSize 12 `shouldBe` 21
```
If the argument passed throu... | ["def super_size(n):\n return int(''.join(sorted(str(n), reverse = True)))", "def super_size(n):\n b = list(str(n))\n b.sort(reverse=True)\n return int(\"\".join(b))\n", "def super_size(n):\n return int(''.join(sorted(str(n)))[::-1])", "super_size=lambda n: int(\"\".join(sorted(str(n),reverse=True)))", "... | {"fn_name": "super_size", "inputs": [[69], [513], [2017], [414], [608719], [123456789], [700000000001], [666666], [2], [0]], "outputs": [[96], [531], [7210], [441], [987610], [987654321], [710000000000], [666666], [2], [0]]} | introductory | https://www.codewars.com/kata/5709bdd2f088096786000008 |
def super_size(n):
|
4,466 | # Task
**Your task** is to implement function `printNumber` (`print_number` in C/C++ and Python `Kata.printNumber` in Java) that returns string that represents given number in text format (see examples below).
Arguments:
- `number` — Number that we need to print (`num` in C/C++/Java)
- `char` — Character for buildi... | ["L = (\n (' #### ', ' ## ', ' #### ', ' #### ', '## ##', '######', ' ## ', '######', ' #### ', ' #### ').__getitem__,\n ('## ##', ' ### ', '## ##', '## ##', '## ##', '## ', ' ## ', '## ##', '## ##', '## ##').__getitem__,\n ('## ##', '# ## ', ' ## ', ' ## ', '## ##', '##### ', ' ###... | {"fn_name": "print_number", "inputs": [[99, "$"], [12345, "*"], [67890, "@"]], "outputs": [["$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n$ $\n$ $$$$ $$$$ $$$$ $$$$ $$$$ $\n$ $$ $$ $$ $$ $$ $$ $$ $$ $$ $$ $\n$ $$ $$ $$ $$ $$ $$ $$ $$ $$ $$ $\n$ $$ $$ $$ $$ ... | introductory | https://www.codewars.com/kata/5bc5c0f8eba26e792400012a |
def print_number(number, char):
|
4,467 | Write a function that takes a string and returns an array of the repeated characters (letters, numbers, whitespace) in the string.
If a charater is repeated more than once, only show it once in the result array.
Characters should be shown **by the order of their first repetition**. Note that this may be different fro... | ["def remember(str_):\n seen = set()\n res = []\n for i in str_: \n res.append(i) if i in seen and i not in res else seen.add(i)\n return res\n", "from collections import Counter\n\ndef remember(str_):\n seen, lst = Counter(), []\n for c in str_:\n if seen[c] == 1: lst.append(c)\n ... | {"fn_name": "remember", "inputs": [["apple"], ["limbojackassin the garden"], ["11pinguin"], ["Claustrophobic"], ["apPle"], ["11 pinguin"], ["pippi"], ["Pippi"], ["kamehameha"], [""]], "outputs": [[["p"]], [["a", "s", "i", " ", "e", "n"]], [["1", "i", "n"]], [["o"]], [[]], [["1", "i", "n"]], [["p", "i"]], [["p", "i"]], ... | introductory | https://www.codewars.com/kata/55a243393fb3e87021000198 |
def remember(str_):
|
4,468 | ## Task
Given a positive integer as input, return the output as a string in the following format:
Each element, corresponding to a digit of the number, multiplied by a power of 10 in such a way that with the sum of these elements you can obtain the original number.
## Examples
Input | Output
--- | ---
0 | ""... | ["def simplify(n): \n output = []\n exp = 0\n \n while n:\n n, r = divmod(n, 10)\n if r:\n output.append(f\"{r}*{10**exp}\" if exp else f\"{r}\")\n exp += 1\n \n return \"+\".join(output[::-1])", "def simplify(number):\n num = str(number)\n result = []\n for i,... | {"fn_name": "simplify", "inputs": [[8964631], [56], [999], [11], [991], [47], [234], [196587], [660], [600], [9090], [10104], [80008], [90000], [0]], "outputs": [["8*1000000+9*100000+6*10000+4*1000+6*100+3*10+1"], ["5*10+6"], ["9*100+9*10+9"], ["1*10+1"], ["9*100+9*10+1"], ["4*10+7"], ["2*100+3*10+4"], ["1*100000+9*100... | introductory | https://www.codewars.com/kata/5800b6568f7ddad2c10000ae |
def simplify(n):
|
4,469 | A Narcissistic Number is a number of length n in which the sum of its digits to the power of n is equal to the original number. If this seems confusing, refer to the example below.
Ex: 153, where n = 3 (number of digits in 153)
1^(3) + 5^(3) + 3^(3) = 153
Write a method is_narcissistic(i) (in Haskell: isNarcissistic ... | ["def is_narcissistic(n):\n num = str(n)\n length = len(num)\n return sum(int(a) ** length for a in num) == n\n", "def is_narcissistic(i):\n return sum([int(n)**len(str(i)) for n in str(i)])==i", "def is_narcissistic(n):\n t = str(n)\n l = len(t)\n \n return n == sum(int(d) ** l for d in t)", "is_narcis... | {"fn_name": "is_narcissistic", "inputs": [[153], [370], [371], [407], [1634], [8208], [9474], [54748], [92727], [93084], [548834], [1741725], [4210818], [9800817], [9926315], [24678050], [88593477], [146511208], [472335975], [534494836], [912985153], [4679307774], [115132219018763992565095597973971522401]], "outputs": ... | introductory | https://www.codewars.com/kata/56b22765e1007b79f2000079 |
def is_narcissistic(i):
|
4,470 | In a small town the population is `p0 = 1000` at the beginning of a year. The population
regularly increases by `2 percent` per year and moreover `50` new inhabitants per year
come to live in the town.
How many years does the town need to see its population
greater or equal to `p = 1200` inhabitants?
```
At the end o... | ["def nb_year(population, percent, aug, target):\n year = 0\n while population < target:\n population += population * percent / 100. + aug\n year += 1\n return year", "def nb_year(p0, percent, aug, p, years = 0):\n if p0 < p:\n return nb_year(p0 + int(p0 * percent / 100) + aug, percent,... | {"fn_name": "nb_year", "inputs": [[1500, 5, 100, 5000], [1500000, 2.5, 10000, 2000000], [1500000, 0.25, 1000, 2000000], [1500000, 0.25, -1000, 2000000], [1500000, 0.25, 1, 2000000], [1500000, 0.0, 10000, 2000000]], "outputs": [[15], [10], [94], [151], [116], [50]]} | introductory | https://www.codewars.com/kata/563b662a59afc2b5120000c6 |
def nb_year(p0, percent, aug, p):
|
4,471 | # Task
N lamps are placed in a line, some are switched on and some are off. What is the smallest number of lamps that need to be switched so that on and off lamps will alternate with each other?
You are given an array `a` of zeros and ones - `1` mean switched-on lamp and `0` means switched-off.
Your task is to find ... | ["def lamps(a):\n n = sum(1 for i, x in enumerate(a) if x != i % 2)\n return min(n, len(a) - n)", "def lamps(a):\n return min(sum(1 for i, n in enumerate(a) if n == i % 2), sum(1 for i, n in enumerate(a) if n != i % 2))", "def lamps(a):\n case1c = 0\n case2c = 0\n for i in range(len(a)):\n if i %... | {"fn_name": "lamps", "inputs": [[[1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1]], [[1, 0, 1]], [[1, 0, 1, 0]], [[0, 1, 0, 1, 0]], [[1, 0, 1, 0, 0, 1, 0, 1]], [[1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0]]], "outputs": [[5], [0], [0], [0], [4], [5]]} | introductory | https://www.codewars.com/kata/58a3c1f12f949e21b300005c |
def lamps(a):
|
4,472 | A population of bears consists of black bears, brown bears, and white bears.
The input is an array of two elements.
Determine whether the offspring of the two bears will return `'black'`, `'brown'`, `'white'`, `'dark brown'`, `'grey'`, `'light brown'`, or `'unknown'`.
Elements in the the array will always be a stri... | ["DEFAULT = 'unknown'\nCOLORS = {'black'+'brown': 'dark brown',\n 'black'+'white': 'grey',\n 'brown'+'white': 'light brown'}\n\ndef bear_fur(bears):\n b1,b2 = sorted(bears)\n return b1 if b1==b2 else COLORS.get(b1+b2, DEFAULT)\n", "def bear_fur(bears):\n return {('black', 'black') : 'blac... | {"fn_name": "bear_fur", "inputs": [[["black", "black"]], [["white", "white"]], [["brown", "brown"]], [["black", "brown"]], [["black", "white"]], [["white", "brown"]], [["pink", "black"]]], "outputs": [["black"], ["white"], ["brown"], ["dark brown"], ["grey"], ["light brown"], ["unknown"]]} | introductory | https://www.codewars.com/kata/5b011461de4c7f8d78000052 |
def bear_fur(bears):
|
4,473 | In this Kata you are a game developer and have programmed the #1 MMORPG(Massively Multiplayer Online Role Playing Game) worldwide!!! Many suggestions came across you to make the game better, one of which you are interested in and will start working on at once.
Players in the game have levels from 1 to 170, XP(short fo... | ["def xp_to_target_lvl(*args):\n if len(args) < 2:\n return 'Input is invalid.'\n \n current_xp, target_lvl = args\n \n if not isinstance(target_lvl, int):\n return 'Input is invalid.'\n \n if not (0 < target_lvl < 171):\n return 'Input is invalid.'\n \n if current_xp... | {"fn_name": "xp_to_target_lvl", "inputs": [[0, 5], [12345, 17], [313, 2], [832696988485, 170], [769832696988484, 170], [10395, 11], [31428, "47"], [1, 171], [7392984749, 900], [123, 0], [-987654321, 99], [999999, [101]], [10396, 11], [0, 1], [2017, 4], [769832696988485, 170]], "outputs": [[1808], [29535], [1], [7690000... | introductory | https://www.codewars.com/kata/593dbaccdf1adef94100006c |
def xp_to_target_lvl(current_xp=None, target_lvl=None):
|
4,474 | Timothy (age: 16) really likes to smoke. Unfortunately, he is too young to buy his own cigarettes and that's why he has to be extremely efficient in smoking.
It's now your task to create a function that calculates how many cigarettes Timothy can smoke out of the given amounts of `bars` and `boxes`:
- a bar has 10 box... | ["def start_smoking(bars, boxes):\n return int(22.5 * (10 * bars + boxes) - 0.5)", "def start_smoking(bars, boxes):\n return ((10 * bars + boxes) * 90 - bool(bars + boxes)) // 4", "def start_smoking(bars,boxes):\n total = bars * 10 * 18 + boxes * 18\n n = total\n while total >= 1: \n total /= 5\n ... | {"fn_name": "start_smoking", "inputs": [[0, 1], [1, 0], [1, 1]], "outputs": [[22], [224], [247]]} | introductory | https://www.codewars.com/kata/5a0aae48ba2a14cfa600016d |
def start_smoking(bars,boxes):
|
4,475 | If you have not ever heard the term **Arithmetic Progrossion**, refer to:
http://www.codewars.com/kata/find-the-missing-term-in-an-arithmetic-progression/python
And here is an unordered version. Try if you can survive lists of **MASSIVE** numbers (which means time limit should be considered). :D
Note: Don't be afrai... | ["def find(seq):\n return (min(seq)+max(seq))*(len(seq)+1)/2-sum(seq)", "def find(a):\n return (max(a) + min(a)) * (len(a) + 1) / 2 - sum(a)", "def find(seq):\n a,b,c = max(seq), min(seq), len(seq)\n z = list(range(b, a, (a-b)//c))\n return list(set(z)-set(seq))[0]\n", "def find(nums):\n # hmm, quite fa... | {"fn_name": "find", "inputs": [[[3, 9, 1, 11, 13, 5]], [[5, -1, 0, 3, 4, -3, 2, -2]], [[2, -2, 8, -8, 4, -4, 6, -6]]], "outputs": [[7], [1], [0]]} | introductory | https://www.codewars.com/kata/568fca718404ad457c000033 |
def find(seq):
|
4,476 | Find the closest prime number under a certain integer ```n``` that has the maximum possible amount of even digits.
For ```n = 1000```, the highest prime under ```1000``` is ```887```, having two even digits (8 twice)
Naming ```f()```, the function that gives that prime, the above case and others will be like the foll... | ["from bisect import bisect_left as bisect\n\nn = 5000000\nsieve, PED, PED_DATA = [0]*((n>>1)+1), [], []\nfor i in range(3, n+1, 2):\n if not sieve[i>>1]:\n for j in range(i**2>>1, (n+1)>>1, i): sieve[j] = 1\n s = str(i)\n nEveD = sum(s.count(d) for d in \"02468\")\n if nEveD:\n ... | {"fn_name": "f", "inputs": [[1000], [10000], [500], [487]], "outputs": [[887], [8887], [487], [467]]} | introductory | https://www.codewars.com/kata/582dcda401f9ccb4f0000025 |
def f(n):
|
4,477 | Given a number, write a function to output its reverse digits. (e.g. given 123 the answer is 321)
Numbers should preserve their sign; i.e. a negative number should still be negative when reversed.
### Examples
```
123 -> 321
-456 -> -654
1000 -> 1
``` | ["def reverse_number(n):\n \"\"\"\n Reverse a number, preserve negative sign\n \"\"\"\n s = str(n)\n ret = int(\"-{}\".format(s[:0:-1]) if \"-\" in s else s[::-1])\n return ret", "def reverse_number(n):\n rev = 0\n temp = n\n dig = 0\n if( n < 0):\n n = abs(n)\n while(n > 0):\n ... | {"fn_name": "reverse_number", "inputs": [[123], [-123], [1000], [4321234], [5], [0], [98989898]], "outputs": [[321], [-321], [1], [4321234], [5], [0], [89898989]]} | introductory | https://www.codewars.com/kata/555bfd6f9f9f52680f0000c5 |
def reverse_number(n):
|
4,478 | Hello everyone.
I have a simple challenge for you today. In mathematics, the formula for finding the sum to infinity of a geometric sequence is:
**ONLY IF** `-1 < r < 1`
where:
* `a` is the first term of the sequence
* `r` is the common ratio of the sequence (calculated by dividing one term in the sequence by th... | ["def sum_to_infinity(sequence):\n return round(sequence[0]/(1-(sequence[1]/sequence[0])), 3) if abs(sequence[1]/sequence[0]) < 1 else \"No Solutions\"", "def sum_to_infinity(sequence):\n sequence = [float(x) for x in sequence]\n a, r = sequence[0], sequence[1] / sequence[0]\n if -1 < r < 1:\n return... | {"fn_name": "sum_to_infinity", "inputs": [[[1, 0.5, 0.25, 0.125]], [[250, 100, 40, 16]], [[21, 4.2, 0.84, 0.168]], [[5, -2.5, 1.25, -0.625]]], "outputs": [[2], [416.667], [26.25], [3.333]]} | introductory | https://www.codewars.com/kata/589b137753a9a4ab5700009a |
def sum_to_infinity(sequence):
|
4,479 | Given an array (or list or vector) of arrays (or, guess what, lists or vectors) of integers, your goal is to return the sum of a specific set of numbers, starting with elements whose position is equal to the main array length and going down by one at each step.
Say for example the parent array (etc, etc) has 3 sub-arr... | ["def elements_sum(arr, d=0):\n return sum(r[i] if i<len(r) else d for i,r in enumerate(reversed(arr)))", "def elements_sum(arr, d=0):\n a=len(arr) \n res=0\n for i in arr:\n if len(i)>=a:\n res+=i[a-1]\n else:\n res+=d\n a-=1\n return res", "def elements_sum... | {"fn_name": "elements_sum", "inputs": [[[[3, 2, 1, 0], [4, 6, 5, 3, 2], [9, 8, 7, 4]]], [[[3], [4, 6, 5, 3, 2], [9, 8, 7, 4]]], [[[3, 2, 1, 0], [4, 6, 5, 3, 2], []]], [[[3, 2, 1, 0], [4, 6, 5, 3, 2], []], 5], [[[3, 2], [4], []]]], "outputs": [[16], [15], [7], [12], [0]]} | introductory | https://www.codewars.com/kata/5b5e0ef007a26632c400002a |
def elements_sum(arr, d=0):
|
4,480 | Write a simple parser that will parse and run Deadfish.
Deadfish has 4 commands, each 1 character long:
* `i` increments the value (initially `0`)
* `d` decrements the value
* `s` squares the value
* `o` outputs the value into the return array
Invalid characters should be ignored.
```python
parse("iiisdoso") ==> ... | ["def parse(data):\n value = 0\n res=[]\n for c in data:\n if c==\"i\": value+=1\n elif c==\"d\": value-=1\n elif c==\"s\": value*=value\n elif c==\"o\": res.append(value)\n return res", "def parse(data):\n arr = []\n value = 0\n for c in data:\n if c == \"i\":\n ... | {"fn_name": "parse", "inputs": [["ooo"], ["ioioio"], ["idoiido"], ["isoisoiso"], ["codewars"]], "outputs": [[[0, 0, 0]], [[1, 2, 3]], [[0, 1]], [[1, 4, 25]], [[0]]]} | introductory | https://www.codewars.com/kata/51e0007c1f9378fa810002a9 |
def parse(data):
|
4,481 | Imagine there's a big cube consisting of n^3 small cubes. Calculate, how many small cubes are not visible from outside.
For example, if we have a cube which has 4 cubes in a row, then the function should return 8, because there are 8 cubes inside our cube (2 cubes in each dimension) | ["def not_visible_cubes(n):\n return max(n - 2, 0) ** 3", "def not_visible_cubes(n):\n return max(0,(n-2)) ** 3", "def not_visible_cubes(n):\n if n > 1:\n return (n-2)**3\n else:\n return 0", "def not_visible_cubes(n):\n if 0 <= n <= 2: return 0\n return (n - 2)**3", "import math\ndef no... | {"fn_name": "not_visible_cubes", "inputs": [[0], [1], [2], [3], [4], [5], [7], [12], [18], [10002]], "outputs": [[0], [0], [0], [1], [8], [27], [125], [1000], [4096], [1000000000000]]} | introductory | https://www.codewars.com/kata/560d6ebe7a8c737c52000084 |
def not_visible_cubes(n):
|
4,482 | # Task
Given array of integers `sequence` and some integer `fixedElement`, output the number of `even` values in sequence before the first occurrence of `fixedElement` or `-1` if and only if `fixedElement` is not contained in sequence.
# Input/Output
`[input]` integer array `sequence`
A non-empty array of positiv... | ["def even_numbers_before_fixed(s, f):\n return len([x for x in s[:s.index(f)] if x%2 == 0]) if f in s else -1", "def even_numbers_before_fixed(sequence, fixed_element):\n ans = 0\n for s in sequence:\n if s == fixed_element:\n return ans\n ans += (s % 2 == 0)\n return -1", "def eve... | {"fn_name": "even_numbers_before_fixed", "inputs": [[[1, 4, 2, 6, 3, 1], 6], [[2, 2, 2, 1], 3], [[2, 3, 4, 3], 3], [[1, 3, 4, 3], 3]], "outputs": [[2], [-1], [1], [0]]} | introductory | https://www.codewars.com/kata/5912701a89fc3d0a6a000169 |
def even_numbers_before_fixed(sequence, fixed_element):
|
4,483 | ## Description
You are a *Fruit Ninja*, your skill is cutting fruit. All the fruit will be cut in half by your knife. For example:
```
[ "apple", "pear", "banana" ] --> ["app", "le", "pe", "ar", "ban", "ana"]
```
As you see, all fruits are cut in half. You should pay attention to `"apple"`: if you cannot cu... | ["FRUIT_NAMES = {'blueberry', 'pear', 'durian', 'ginkgo', 'peach', 'apple', 'cantaloupe', 'fig', 'mangosteen', 'watermelon', 'pineapple', 'cherry', 'pomegranate', 'carambola', 'hawthorn', 'persimmon', 'apricot', 'plum', 'litchi', 'mango', 'jujube', 'lemon', 'orange', 'tomato', 'banana', 'coconut', 'grape', 'pitaya'}\nd... | {"fn_name": "cut_fruits", "inputs": [[["apple", "pear", "banana"]], [["apple", "pear", "banana", "bomb"]], [[]]], "outputs": [[["app", "le", "pe", "ar", "ban", "ana"]], [["app", "le", "pe", "ar", "ban", "ana", "bomb"]], [[]]]} | introductory | https://www.codewars.com/kata/57d60363a65454701d000e11 |
def cut_fruits(fruits):
|
4,484 | Write a function called calculate that takes 3 values. The first and third values are numbers. The second value is a character. If the character is "+" , "-", "*", or "/", the function will return the result of the corresponding mathematical function on the two numbers. If the string is not one of the specified charact... | ["def calculate(num1, operation, num2): \n # your code here\n try :\n return eval(\"{} {} {}\".format(num1, operation, num2))\n except (ZeroDivisionError, SyntaxError):\n return None", "def calculate(num1, operation, num2):\n ops = {\"+\": (lambda x, y: x + y), \"-\": (lambda x, y: x - y), \"*... | {"fn_name": "calculate", "inputs": [[3.2, "+", 8], [3.2, "-", 8], [3.2, "/", 8], [3.2, "*", 8], [-3, "+", 0], [-3, "-", 0], [-2, "/", -2], [-3, "*", 0], [-3, "/", 0], [-3, "w", 0], [-3, "w", 1]], "outputs": [[11.2], [-4.8], [0.4], [25.6], [-3], [-3], [1], [0], [null], [null], [null]]} | introductory | https://www.codewars.com/kata/5296455e4fe0cdf2e000059f |
def calculate(num1, operation, num2):
|
4,485 | You task is to implement an simple interpreter for the notorious esoteric language [HQ9+](https://esolangs.org/wiki/HQ9+) that will work for a single character input:
- If the input is `'H'`, return `'Hello World!'`
- If the input is `'Q'`, return the input
- If the input is `'9'`, return the full lyrics of [99 Bottle... | ["LINES = \"{0} of beer on the wall, {0} of beer.\\nTake one down and pass it around, {1} of beer on the wall.\"\nSONG = '\\n'.join( LINES.format(\"{} bottles\".format(n), \"{} bottle\".format(n-1)+\"s\"*(n!=2)) for n in range(99,1,-1) )\nSONG += \"\"\"\n1 bottle of beer on the wall, 1 bottle of beer.\nTake one down an... | {"fn_name": "HQ9", "inputs": [["X"], ["H"], ["Q"]], "outputs": [[null], ["Hello World!"], ["Q"]]} | introductory | https://www.codewars.com/kata/591588d49f4056e13f000001 |
def HQ9(code):
|
4,486 | Create a function that takes a string and an integer (`n`).
The function should return a string that repeats the input string `n` number of times.
If anything other than a string is passed in you should return `"Not a string"`
## Example
```
"Hi", 2 --> "HiHi"
1234, 5 --> "Not a string"
``` | ["def repeat_it(string,n):\n return string * n if isinstance(string,str) else 'Not a string'", "def repeat_it(string,n):\n if type(string) is not str:\n return 'Not a string'\n return string * n", "repeat_it = lambda s, m: s*m if type(s) is str else \"Not a string\"", "def repeat_it(s, n):\n return s... | {"fn_name": "repeat_it", "inputs": [["*", 3], ["Hello", 11], ["243624", 22], [[], 3], [24, 3], [true, 3], ["Hello", 0]], "outputs": [["***"], ["HelloHelloHelloHelloHelloHelloHelloHelloHelloHelloHello"], ["2436242436242436242436242436242436242436242436242436242436242436242436242436242436242436242436242436242436242436242... | introductory | https://www.codewars.com/kata/557af9418895e44de7000053 |
def repeat_it(string,n):
|
4,487 | Write a function that takes a single array as an argument (containing multiple strings and/or positive numbers and/or arrays), and returns one of four possible string values, depending on the ordering of the lengths of the elements in the input array:
Your function should return...
- “Increasing” - if the lengths of ... | ["def order_type(arr):\n if not arr : return 'Constant'\n arr = list( map(len, [str(elt) if type(elt)==int else elt for elt in arr] ))\n cmp =sorted(arr)\n if arr == [arr[0]]*len(arr) : s='Constant'\n elif arr == cmp : s='Increasing'\n elif arr == cmp[::-1] : s='Decreasing'\n else... | {"fn_name": "order_type", "inputs": [[[1, "b", ["p"], 2]], [[123, 1234, 12345, 123456]], [["a", "abc", "abcde", "ab"]], [[[1, 2, 3, 4], [5, 6, 7], [8, 9]]], [[1, 2, 3, 4, 56]], [[["ab", "cdef", "g"], ["hi", "jk", "lmnopq"], ["rst", "uv", "wx"], ["yz"]]], [[[1, 23, 456, 78910], ["abcdef", "ghijklmno", "pqrstuvwxy"], [[1... | introductory | https://www.codewars.com/kata/57f669477c9a2b1b9700022d |
def order_type(arr):
|
4,488 | `Description:`
Given an input array (`arr`) of positive integers, the objective is to return an output array where each index represents the amount of times an element appeared (frequency) in the input array.
More specifically, the element at each index of the output array will be an array (bucket) containing intege... | ["from collections import Counter\n\ndef bucketize(*arr):\n c = Counter(arr)\n c = {i: sorted([k for k, v in list(c.items()) if v == i]) for i in list(c.values())}\n return [c[e] if e in c else None for e in range(len(arr) + 1)]\n", "from collections import Counter\n\ndef bucketize(*a):\n D = {}\n for k,... | {"fn_name": "bucketize", "inputs": [[2, 2, 4, 4, 6, 6, 9, 9, 9, 9], [3, 3, 3, 3, 2], [5, 5, 5, 5, 5], [77, 3, 40, 40, 40], [16, 7, 5, 3, 6, 23]], "outputs": [[[null, null, [2, 4, 6], null, [9], null, null, null, null, null, null]], [[null, [2], null, null, [3], null]], [[null, null, null, null, null, [5]]], [[null, [3,... | introductory | https://www.codewars.com/kata/5ac95cb05624bac42e000005 |
def bucketize(*arr):
|
4,489 | You are given a list/array which contains only integers (positive and negative). Your job is to sum only the numbers that are the same and consecutive. The result should be one list.
Extra credit if you solve it in one line. You can assume there is never an empty list/array and there will always be an integer.
Same ... | ["from itertools import groupby\n\ndef sum_consecutives(s):\n return [sum(group) for c, group in groupby(s)]", "def sum_consecutives(s):\n prev = None\n x = []\n for i in s:\n if i == prev:\n x[-1] += i\n else:\n x.append(i)\n prev = i\n return x", "from itertoo... | {"fn_name": "sum_consecutives", "inputs": [[[1, 4, 4, 4, 0, 4, 3, 3, 1]], [[1, 1, 7, 7, 3]], [[-5, -5, 7, 7, 12, 0]], [[3, 3, 3, 3, 1]], [[2, 2, -4, 4, 5, 5, 6, 6, 6, 6, 6, 1]], [[1, 1, 1, 1, 1, 3]], [[1, -1, -2, 2, 3, -3, 4, -4]], [[0, 1, 1, 2, 2]]], "outputs": [[[1, 12, 0, 4, 6, 1]], [[2, 14, 3]], [[-10, 14, 12, 0]],... | introductory | https://www.codewars.com/kata/55eeddff3f64c954c2000059 |
def sum_consecutives(s):
|
4,490 | The Collatz conjecture is one of the most famous one. Take any positive integer n, if it is even divide it by 2, if it is odd multiply it by 3 and add 1 and continue indefinitely.The conjecture is that whatever is n the sequence will reach 1. There is many ways to approach this problem, each one of them had given beaut... | ["from functools import lru_cache\n\n@lru_cache(maxsize=None)\ndef rec(n): return 1 + (0 if n==1 else rec(3*n+1) if n&1 else rec(n//2))\n\nmemo = [[0, None], [1, 1]]\ndef max_collatz_length(n):\n if not (type(n) == int and n > 0): return []\n while n >= len(memo):\n x = rec(len(memo))\n if x > memo[... | {"fn_name": "max_collatz_length", "inputs": [[0], [1], [4], [30], [1000], [1000000], ["a"], [-1], [["a"]]], "outputs": [[[]], [[1, 1]], [[3, 8]], [[27, 112]], [[871, 179]], [[837799, 525]], [[]], [[]], [[]]]} | introductory | https://www.codewars.com/kata/53a9ee602f150d5d6b000307 |
def max_collatz_length(n):
|
4,491 | In this Kata, you will be given two strings `a` and `b` and your task will be to return the characters that are not common in the two strings.
For example:
```Haskell
solve("xyab","xzca") = "ybzc"
--The first string has 'yb' which is not in the second string.
--The second string has 'zc' which is not in the first s... | ["def solve(a,b):\n s = set(a)&set(b)\n return ''.join(c for c in a+b if c not in s)", "def solve(a,b):\n return \"\".join([c for c in a if not c in b]+[c for c in b if not c in a])", "def solve(a,b):\n unique=[]\n for i in a:\n if i not in b:\n unique.append(i)\n for i in b:\n ... | {"fn_name": "solve", "inputs": [["xyab", "xzca"], ["xyabb", "xzca"], ["abcd", "xyz"], ["xxx", "xzca"]], "outputs": [["ybzc"], ["ybbzc"], ["abcdxyz"], ["zca"]]} | introductory | https://www.codewars.com/kata/5a262cfb8f27f217f700000b |
def solve(a,b):
|
4,492 | You're looking through different hex codes, and having trouble telling the difference between #000001 and #100000
We need a way to tell which is red, and which is blue!
That's where you create ```hex_color()```!
It should read an RGB input, and return whichever value (red, blue, or green) is of greatest concentr... | ["colors = {\n (1, 0, 0): 'red',\n (0, 1, 0): 'green',\n (0, 0, 1): 'blue',\n (1, 0, 1): 'magenta',\n (1, 1, 0): 'yellow',\n (0, 1, 1): 'cyan',\n (1, 1, 1): 'white',\n}\n\ndef hex_color(codes):\n codes = codes or '0 0 0'\n items = [int(c) for c in codes.split()]\n m = max(items)\n retur... | {"fn_name": "hex_color", "inputs": [[""], ["000 000 000"], ["121 245 255"], ["027 100 100"], ["021 021 021"], ["255 000 000"], ["000 147 000"], ["212 103 212"], ["101 101 092"]], "outputs": [["black"], ["black"], ["blue"], ["cyan"], ["white"], ["red"], ["green"], ["magenta"], ["yellow"]]} | introductory | https://www.codewars.com/kata/57e17750621bca9e6f00006f |
def hex_color(codes):
|
4,493 | As you probably know, Fibonacci sequence are the numbers in the following integer sequence:
1, 1, 2, 3, 5, 8, 13...
Write a method that takes the index as an argument and returns last digit from fibonacci number. Example:
getLastDigit(15) - 610. Your method must return 0 because the last digit of 610 is 0.
Fibonacci ... | ["def get_last_digit(index):\n a, b = 0, 1\n for _ in range(index):\n a, b = b, (a+b) % 10\n return a\n", "def get_last_digit(index):\n last, tmp, index = 0, 1, index % 60\n for i in range(index):\n last, tmp = tmp, (last + tmp) % 10\n return last\n", "def get_last_digit(index):\n ret... | {"fn_name": "get_last_digit", "inputs": [[193150], [300], [20001], [800], [1001], [100], [260], [1111], [1234], [99999], [10], [234], [193241], [79], [270]], "outputs": [[5], [0], [6], [5], [1], [5], [5], [9], [7], [6], [5], [2], [1], [1], [0]]} | introductory | https://www.codewars.com/kata/56b7251b81290caf76000978 |
def get_last_digit(index):
|
4,494 | Our football team finished the championship.
The result of each match look like "x:y". Results of all matches are recorded in the collection.
For example:
```["3:1", "2:2", "0:1", ...]```
Write a function that takes such collection and counts the points of our team in the championship.
Rules for counting points for e... | ["def points(games):\n count = 0\n for score in games:\n res = score.split(':')\n if res[0]>res[1]:\n count += 3\n elif res[0] == res[1]:\n count += 1\n return count", "def points(a):\n return sum((x >= y) + 2 * (x > y) for x, y in (s.split(\":\") for s in a))", "d... | {"fn_name": "points", "inputs": [[["1:0", "2:0", "3:0", "4:0", "2:1", "3:1", "4:1", "3:2", "4:2", "4:3"]], [["1:1", "2:2", "3:3", "4:4", "2:2", "3:3", "4:4", "3:3", "4:4", "4:4"]], [["0:1", "0:2", "0:3", "0:4", "1:2", "1:3", "1:4", "2:3", "2:4", "3:4"]], [["1:0", "2:0", "3:0", "4:0", "2:1", "1:3", "1:4", "2:3", "2:4", ... | introductory | https://www.codewars.com/kata/5bb904724c47249b10000131 |
def points(games):
|
4,495 | I've got a crazy mental illness.
I dislike numbers a lot. But it's a little complicated:
The number I'm afraid of depends on which day of the week it is...
This is a concrete description of my mental illness:
Monday --> 12
Tuesday --> numbers greater than 95
Wednesday --> 34
Thursday --> 0
Friday -->... | ["def am_I_afraid(day,num):\n return {\n 'Monday': num == 12,\n 'Tuesday': num > 95,\n 'Wednesday': num == 34,\n 'Thursday': num == 0,\n 'Friday': num % 2 == 0,\n 'Saturday': num == 56,\n 'Sunday': num == 666 or num == -666,\n }[day]\n", "afraid = {\n 'Monday'... | {"fn_name": "am_I_afraid", "inputs": [["Monday", 13], ["Monday", 12], ["Tuesday", 0], ["Tuesday", 100], ["Tuesday", 95], ["Wednesday", 35], ["Wednesday", 34], ["Thursday", 2], ["Thursday", 0], ["Friday", 5], ["Friday", 4], ["Saturday", 55], ["Saturday", 56], ["Sunday", 55], ["Sunday", 666], ["Sunday", -666]], "outputs"... | introductory | https://www.codewars.com/kata/55b1fd84a24ad00b32000075 |
def am_I_afraid(day,num):
|
4,496 | The hamming distance of two equal-length strings is the number of positions, in which the two string differ. In other words, the number of character substitutions required to transform one string into the other.
For this first Kata, you will write a function ```hamming_distance(a, b)``` with two equal-length strings ... | ["def hamming_distance(a, b):\n return sum(c != d for c, d in zip(a, b))\n", "def hamming_distance(a, b): return sum(ch1 != ch2 for ch1, ch2 in zip(a, b))", "def hamming_distance(a, b):\n result=0\n for i in range(len(a)):\n if a[i]!=b[i]:\n result+=1;\n return result;\n", "def hamming_dis... | {"fn_name": "hamming_distance", "inputs": [["100101", "101001"], ["1010", "0101"], ["100101011011010010010", "101100010110010110101"]], "outputs": [[2], [4], [9]]} | introductory | https://www.codewars.com/kata/5624e574ec6034c3a20000e6 |
def hamming_distance(a, b):
|
4,497 | Given an array of one's and zero's that represents a positive binary number convert the number to two's complement value.
Two's complement is the way most computers represent positive or negative integers. The most significant bit is negative.
Examples:
-8 4 2 1
[1,1,1,1] = -1
[1,0,0,0] = -8
[1,1,0,1] = -3
To ... | ["def positive_to_negative(binary):\n return [1 - d if 1 in binary[i:] else d for i, d in enumerate(binary, 1)]\n", "def positive_to_negative(b):\n last = next((i for i in range(len(b) - 1, -1, -1) if b[i]), 0)\n return [1 - d for d in b[:last]] + b[last:]", "def positive_to_negative(arr):\n flip = [0 if n ... | {"fn_name": "positive_to_negative", "inputs": [[[0, 0, 0, 0]], [[0, 0, 1, 0]], [[0, 0, 1, 1]], [[0, 1, 0, 0]]], "outputs": [[[0, 0, 0, 0]], [[1, 1, 1, 0]], [[1, 1, 0, 1]], [[1, 1, 0, 0]]]} | introductory | https://www.codewars.com/kata/5becace7063291bebf0001d5 |
def positive_to_negative(binary):
|
4,498 | Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost digit and skip... | ["def solution(roman):\n dict = {\n \"M\": 1000,\n \"D\": 500,\n \"C\": 100,\n \"L\": 50,\n \"X\": 10,\n \"V\": 5,\n \"I\": 1\n }\n\n last, total = 0, 0\n for c in list(roman)[::-1]:\n if last == 0:\n total += dict[c]\n elif last > di... | {"fn_name": "solution", "inputs": [["XXI"], ["I"], ["IV"], ["MMVIII"], ["MDCLXVI"]], "outputs": [[21], [1], [4], [2008], [1666]]} | introductory | https://www.codewars.com/kata/51b6249c4612257ac0000005 |
def solution(roman):
|
4,499 | # Convergents of e
The square root of 2 can be written as an infinite continued fraction.

The infinite continued fraction can be written, √2 = [1;(2)], (2) indicates that 2 repeats ad infinitum. In a similar way, √23 = [4;(1,3,1,8)].
It ... | ["e = [1, 2]\nfor n in range(1, 10 ** 4):\n for f in 1, 2 * n, 1:\n e.append(f * e[-1] + e[-2])\nconvergents_of_e = lambda n: sum(map(int, str(e[n])))", "def convergents_of_e(n):\n def b(n):\n return n // 3 * 2 if n % 3 == 0 else 1\n x, y = b(n), 1\n for k in range(n - 1, 0, -1):\n x, y... | {"fn_name": "convergents_of_e", "inputs": [[57], [125], [298], [938], [3756], [18287], [2132], [9999], [788], [8787]], "outputs": [[125], [298], [938], [3756], [18287], [108346], [9469], [55534], [3151], [48461]]} | introductory | https://www.codewars.com/kata/5a8d63930025e92f4c000086 |
def convergents_of_e(n):
|
4,500 | You get any card as an argument. Your task is to return a suit of this card.
Our deck (is preloaded):
```python
DECK = ['2S','3S','4S','5S','6S','7S','8S','9S','10S','JS','QS','KS','AS',
'2D','3D','4D','5D','6D','7D','8D','9D','10D','JD','QD','KD','AD',
'2H','3H','4H','5H','6H','7H','8H','9H','10H','JH... | ["def define_suit(card):\n d = {'C': 'clubs', 'S':'spades', 'D':'diamonds','H':'hearts'}\n return d[card[-1]]\n", "def define_suit(card):\n return {'C':'clubs', 'S':'spades', 'D':'diamonds', 'H':'hearts'}[card[-1]]", "def define_suit(card):\n return {'C':'clubs','D':'diamonds','H':'hearts','S':'spades'}[car... | {"fn_name": "define_suit", "inputs": [["3C"], ["QS"], ["9D"], ["JH"]], "outputs": [["clubs"], ["spades"], ["diamonds"], ["hearts"]]} | introductory | https://www.codewars.com/kata/5a360620f28b82a711000047 |
def define_suit(card):
|
4,501 | You are given a string of words (x), for each word within the string you need to turn the word 'inside out'. By this I mean the internal letters will move out, and the external letters move toward the centre.
If the word is even length, all letters will move. If the length is odd, you are expected to leave the 'middl... | ["import re\n\ndef inside_out(s):\n return re.sub(r'\\S+', lambda m: inside_out_word(m.group()), s)\n\ndef inside_out_word(s):\n i, j = len(s) // 2, (len(s) + 1) // 2\n return s[:i][::-1] + s[i:j] + s[j:][::-1]", "def swap(word):\n m = len(word) // 2\n if len(word) % 2 == 0:\n return word[:m][::-1... | {"fn_name": "inside_out", "inputs": [["man i need a taxi up to ubud"], ["what time are we climbing up the volcano"], ["take me to semynak"], ["massage yes massage yes massage"], ["take bintang and a dance please"]], "outputs": [["man i ende a atix up to budu"], ["hwta item are we milcgnib up the lovcona"], ["atek me to... | introductory | https://www.codewars.com/kata/57ebdf1c2d45a0ecd7002cd5 |
def inside_out(s):
|
4,502 | Well met with Fibonacci bigger brother, AKA Tribonacci.
As the name may already reveal, it works basically like a Fibonacci, but summing the last 3 (instead of 2) numbers of the sequence to generate the next. And, worse part of it, regrettably I won't get to hear non-native Italian speakers trying to pronounce it :(
... | ["def tribonacci(signature, n):\n res = signature[:n]\n for i in range(n - 3): res.append(sum(res[-3:]))\n return res", "def tribonacci(signature,n):\n while len(signature) < n:\n signature.append(sum(signature[-3:]))\n \n return signature[:n]", "def tribonacci(signature, n):\n s = signature.copy(... | {"fn_name": "tribonacci", "inputs": [[[1, 1, 1], 10], [[0, 0, 1], 10], [[0, 1, 1], 10], [[1, 0, 0], 10], [[0, 0, 0], 10], [[1, 2, 3], 10], [[3, 2, 1], 10], [[1, 1, 1], 1], [[300, 200, 100], 0], [[0.5, 0.5, 0.5], 30]], "outputs": [[[1, 1, 1, 3, 5, 9, 17, 31, 57, 105]], [[0, 0, 1, 1, 2, 4, 7, 13, 24, 44]], [[0, 1, 1, 2, ... | introductory | https://www.codewars.com/kata/556deca17c58da83c00002db |
def tribonacci(signature,n):
|
4,503 | When you want to get the square of a binomial of two variables x and y, you will have:
`$(x+y)^2 = x^2 + 2xy + y ^2$`
And the cube:
`$(x+y)^3 = x^3 + 3x^2y + 3xy^2 +y^3$`
It is known from many centuries ago that for an exponent n, the result of a binomial x + y raised to the n-th power is:
Or using the sumation no... | ["def f(n):\n return [2**i for i in range(n+1)]+[(2**(n+1))-1]", "def f(n):\n return [1 << i for i in range(n+1)] + [(1 << (n+1)) - 1]", "def f(n):\n result = [1]\n for i in range(n):\n result.append(result[-1]*2)\n result.append(sum(result))\n return result", "f=lambda n:[2**x for x in range(n... | {"fn_name": "f", "inputs": [[0], [1], [2], [3], [6], [10]], "outputs": [[[1, 1]], [[1, 2, 3]], [[1, 2, 4, 7]], [[1, 2, 4, 8, 15]], [[1, 2, 4, 8, 16, 32, 64, 127]], [[1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2047]]]} | introductory | https://www.codewars.com/kata/584a6d9d7d22f8fa09000094 |
def f(n):
|
4,504 | Share price
===========
You spent all your saved money to buy some shares.
You bought it for `invested`, and want to know how much it's worth, but all the info you can quickly get are just the change the shares price made in percentages.
Your task:
----------
Write the function `sharePrice()` that calculates, and re... | ["def share_price(invested, changes):\n for change in changes:\n invested = invested * (100 + change) / 100.0\n return format(invested, '.2f')", "def share_price(invested, changes):\n sum=float(invested)\n for i in changes:\n sum=sum+(sum/100*i)\n return str('{:.2f}'.format(float(sum)))", "... | {"fn_name": "share_price", "inputs": [[100, []], [100, [-50, 50]], [100, [-50, 100]], [100, [-20, 30]], [1000, [0, 2, 3, 6]]], "outputs": [["100.00"], ["75.00"], ["100.00"], ["104.00"], ["1113.64"]]} | introductory | https://www.codewars.com/kata/5603a4dd3d96ef798f000068 |
def share_price(invested, changes):
|
4,505 | Create an identity matrix of the specified size( >= 0).
Some examples:
```
(1) => [[1]]
(2) => [ [1,0],
[0,1] ]
[ [1,0,0,0,0],
[0,1,0,0,0],
(5) => [0,0,1,0,0],
[0,0,0,1,0],
[0,0,0,0,1] ]
``` | ["def get_matrix(n):\n return [[1 if i==j else 0 for i in range(n)] for j in range(n)]", "import numpy\ndef get_matrix(n):\n return numpy.eye(n, dtype=int).tolist()", "get_matrix=lambda n: [[int(i==j) for j in range(n)] for i in range(n)]", "def get_matrix(n):\n return [[int(i == j) for j in range(n)] for i i... | {"fn_name": "get_matrix", "inputs": [[0], [1], [2], [3], [5]], "outputs": [[[]], [[[1]]], [[[1, 0], [0, 1]]], [[[1, 0, 0], [0, 1, 0], [0, 0, 1]]], [[[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]]]} | introductory | https://www.codewars.com/kata/5a34da5dee1aae516d00004a |
def get_matrix(n):
|
4,506 | In your class, you have started lessons about geometric progression.
Since you are also a programmer, you have decided to write a function that will print first `n` elements of the sequence with the given constant `r` and first element `a`.
Result should be separated by comma and space.
### Example
```python
geometr... | ["def geometric_sequence_elements(a, r, n):\n return ', '.join(str(a * r ** i) for i in range(n))\n", "def geometric_sequence_elements(a, r, n):\n l = []\n for _ in range(n):\n l.append(str(a))\n a *= r\n return \", \".join(l)\n", "def geometric_sequence_elements(a, r, n):\n return \", \".j... | {"fn_name": "geometric_sequence_elements", "inputs": [[2, 3, 5], [2, 2, 10], [1, -2, 10]], "outputs": [["2, 6, 18, 54, 162"], ["2, 4, 8, 16, 32, 64, 128, 256, 512, 1024"], ["1, -2, 4, -8, 16, -32, 64, -128, 256, -512"]]} | introductory | https://www.codewars.com/kata/55caef80d691f65cb6000040 |
def geometric_sequence_elements(a, r, n):
|
4,507 | Create a function that accepts 3 inputs, a string, a starting location, and a length. The function needs to simulate the string endlessly repeating in both directions and return a substring beginning at the starting location and continues for length.
Example:
```python
endless_string('xyz', -23, 6) == 'yzxyzx'
```
To... | ["from itertools import cycle, islice\n\ndef endless_string(string, start, length):\n i = (start + (length + 1 if length < 0 else 0)) % len(string)\n return ''.join(islice(cycle(string), i, i + abs(length)))", "from itertools import cycle, islice\n\ndef endless_string(stg, i, l):\n i = min(i, i+l) % len(stg) +... | {"fn_name": "endless_string", "inputs": [["xyz", -23, 6], ["xyz", 0, 4], ["xyz", 19, 2], ["xyz", -4, -4], ["abcdefghijklmnopqrstuvwxyz", 29, 1], ["Hello! How are you?", -14, 27], ["1x2x3x4x", 1532, 100], ["1x2x3x4x", -1532, -100], ["112233", 0, 0], ["112233", -1, 0], ["112233", 15824, 0]], "outputs": [["yzxyzx"], ["xyz... | introductory | https://www.codewars.com/kata/57048c1275263af10b00063e |
def endless_string(string, start, length):
|
4,508 | A *Vampire number* is a positive integer `z` with a factorization `x * y = z` such that
- `x` and `y` have the same number of digits and
- the multiset of digits of `z` is equal to the multiset of digits of `x` and `y`.
- Additionally, to avoid trivialities, `x` and `y` may not both end with `0`.
In this case, `x` an... | ["is_vampire = lambda x, y: sorted(f\"{x}{y}\") == sorted(f\"{x*y}\") and x%10 + y%10 > 0\nvampires = sorted({x*y for p in (1, 2) for x in range(10**p, 10**(p+1)) for y in range(x, 10**(p+1)) if is_vampire(x, y)})\n\ndef VampireNumber(k):\n return vampires[k-1]", "vampire_number = VampireNumber = (0, 1260, 1395, 143... | {"fn_name": "VampireNumber", "inputs": [[10], [100], [155]], "outputs": [[105210], [336960], [939658]]} | introductory | https://www.codewars.com/kata/558d5c71c68d1e86b000010f |
def VampireNumber(k):
|
4,509 | Your task is to validate rhythm with a meter.
_________________________________________________
Rules:
1. Rhythmic division requires that in one whole note (1) there are two half notes (2) or four quarter notes (4) or eight eighth notes (8).
Examples: 1 = 2 + 2, 1 = 4 + 4 + 4 + 4 ...
Note that: 2 = 4 + 4, 4 = 8 + 8... | ["def is_valid_bar(bar, meter):\n total = 0\n for n in bar:\n n = int(n)\n if n & (n - 1):\n return False\n total += 1.0 / n\n return total == meter\n\ndef validate_rhythm(meter, score):\n n, d = meter\n if d & (d - 1):\n return \"Invalid rhythm\"\n bars = score.... | {"fn_name": "validate_rhythm", "inputs": [[[8, 8], "1|22|4444|88888888"], [[4, 4], "1|22|4444|88888888"], [[2, 2], "1|22|4444|88888888"], [[1, 1], "1|22|4444|88888888"], [[3, 4], "24|444|888888"], [[4, 8], "2|44|8888"], [[2, 4], "2|44|8888"], [[1, 2], "2|44|8888"], [[10, 8], "14|444488|888824"], [[6, 4], "222|444444|88... | introductory | https://www.codewars.com/kata/57091b473f1008c03f001a2a |
def validate_rhythm(meter, score):
|
4,510 | Complete the function/method so that it takes CamelCase string and returns the string in snake_case notation. Lowercase characters can be numbers. If method gets number, it should return string.
Examples:
``` javascript
// returns test_controller
toUnderscore('TestController');
// returns movies_and_books
toUndersc... | ["import re\n\ndef to_underscore(string):\n return re.sub(r'(.)([A-Z])', r'\\1_\\2', str(string)).lower() \n", "def to_underscore(string):\n string = str(string)\n camel_case = string[0].lower()\n for c in string[1:]:\n camel_case += '_{}'.format(c.lower()) if c.isupper() else c\n return camel_... | {"fn_name": "to_underscore", "inputs": [["TestController"], ["ThisIsBeautifulDay"], ["Am7Days"], ["My3CodeIs4TimesBetter"], [5]], "outputs": [["test_controller"], ["this_is_beautiful_day"], ["am7_days"], ["my3_code_is4_times_better"], ["5"]]} | introductory | https://www.codewars.com/kata/529b418d533b76924600085d |
def to_underscore(string):
|
4,511 | Write a function that will check whether the permutation of an input string is a palindrome. Bonus points for a solution that is efficient and/or that uses _only_ built-in language functions. Deem yourself **brilliant** if you can come up with a version that does not use _any_ function whatsoever.
# Example
`madam... | ["def permute_a_palindrome (input): \n return sum( input.count(c)%2 for c in set(input) ) < 2\n", "def permute_a_palindrome (txt): \n return len([txt.count(c) for c in txt if txt.count(c) % 2]) < 2\n", "def permute_a_palindrome(stg): \n return sum(stg.count(c) % 2 for c in set(stg)) == len(stg) % 2\n", "def perm... | {"fn_name": "permute_a_palindrome", "inputs": [["a"], ["aa"], ["baa"], ["aab"], ["baabcd"], ["racecars"], ["abcdefghba"], [""]], "outputs": [[true], [true], [true], [true], [false], [false], [false], [true]]} | introductory | https://www.codewars.com/kata/58ae6ae22c3aaafc58000079 |
def permute_a_palindrome(stg):
|
4,512 | Consider the following series:
`0,1,2,3,4,5,6,7,8,9,10,22,11,20,13,24...`There is nothing special between numbers `0` and `10`.
Let's start with the number `10` and derive the sequence. `10` has digits `1` and `0`. The next possible number that does not have a `1` or a `0` is `22`. All other numbers between `10` and... | ["masks = [0] * 10\nfor i in range(10 ** 4):\n for c in str(i):\n masks[int(c)] |= 1 << i\n\ndef find_num(n):\n seq, x = 1, 0\n for j in range(n):\n M = seq\n for m in masks:\n if x & m:\n M |= m\n x = ~M & (M+1)\n seq |= x\n return x.bit_length()... | {"fn_name": "find_num", "inputs": [[1], [5], [11], [100], [500]], "outputs": [[1], [5], [22], [103], [476]]} | introductory | https://www.codewars.com/kata/599688d0e2800dda4e0001b0 |
def find_num(n):
|
4,513 | You will be given an array of numbers.
For each number in the array you will need to create an object.
The object key will be the number, as a string. The value will be the corresponding character code, as a string.
Return an array of the resulting objects.
All inputs will be arrays of numbers. All character codes... | ["def num_obj(s):\n return [{str(i) : chr(i)} for i in s]", "def num_obj(s):\n return [{str(n) : chr(n)} for n in s]", "def num_obj(s):\n return [{str(nb) : chr(nb)} for nb in s]", "def num_obj(s):\n return [{str(a): chr(a)} for a in s]", "def num_obj(s):\n return [{str(c): chr(c)} for c in s]", "def num... | {"fn_name": "num_obj", "inputs": [[[118, 117, 120]], [[101, 121, 110, 113, 113, 103]], [[118, 103, 110, 109, 104, 106]], [[107, 99, 110, 107, 118, 106, 112, 102]], [[100, 100, 116, 105, 117, 121]]], "outputs": [[[{"118": "v"}, {"117": "u"}, {"120": "x"}]], [[{"101": "e"}, {"121": "y"}, {"110": "n"}, {"113": "q"}, {"113... | introductory | https://www.codewars.com/kata/57ced2c1c6fdc22123000316 |
def num_obj(s):
|
4,514 | In this Kata you must convert integers numbers from and to a negative-base binary system.
Negative-base systems can accommodate all the same numbers as standard place-value systems, but both positive and negative numbers are represented without the use of a minus sign (or, in computer representation, a sign bit); this... | ["def int_to_negabinary(i):\n ds = []\n while i != 0:\n ds.append(i & 1)\n i = -(i >> 1)\n return ''.join(str(d) for d in reversed(ds)) if ds else '0'\n \ndef negabinary_to_int(s):\n i = 0\n for c in s:\n i = -(i << 1) + int(c)\n return i", "def int_to_negabinary(i):\n i, s ... | {"fn_name": "int_to_negabinary", "inputs": [[0], [6], [-6], [45], [-45], [4587], [-4587], [65535], [65536], [-65536], [2147483648], [-2147483648]], "outputs": [["0"], ["11010"], ["1110"], ["1111101"], ["11010111"], ["1011000111111"], ["11001000010101"], ["10000000000000011"], ["10000000000000000"], ["110000000000000000... | introductory | https://www.codewars.com/kata/54c14c1b86b33df1ff000026 |
def int_to_negabinary(i):
|
4,515 | Your task is to find the number couple with the greatest difference from a given array of number-couples.
All number couples will be given as strings and all numbers in them will be positive integers.
For instance: ['56-23','1-100']; in this case, you should identify '1-100' as the number couple with the greatest ... | ["def diff(arr):\n r = arr and max(arr, key = lambda x : abs(eval(x)))\n return bool(arr and eval(r)) and r", "def diff(arr):\n r = [abs(eval(s)) for s in arr]\n return arr[r.index(max(r))] if r and max(r) else False\n", "def diff(arr):\n r = [abs(int(w.split('-')[0])-int(w.split('-')[1])) for w in arr]\... | {"fn_name": "diff", "inputs": [[["43-45", "1021-55", "000-18888", "92-34", "76-32", "99-1", "1020-54"]], [["1-2", "2-4", "5-7", "8-9", "44-45"]], [["1-1000", "2-1000", "100-67", "98-45", "8-9"]], [["33-33", "77-77"]], [["23-67", "67-23", "88-88", "45-46"]], [["45896-2354", "4654-556767", "2455-423522", "3455-355", "34-... | introductory | https://www.codewars.com/kata/56b12e3ad2387de332000041 |
def diff(arr):
|
4,516 | Make a program that takes a value (x) and returns "Bang" if the number is divisible by 3, "Boom" if it is divisible by 5, "BangBoom" if it divisible by 3 and 5, and "Miss" if it isn't divisible by any of them.
Note: Your program should only return one value
Ex: Input: 105 --> Output: "BangBoom"
Ex: Input: 9 --> Output... | ["def multiple(x):\n return 'Bang' * (x % 3 == 0) + 'Boom' * (x % 5 == 0) or 'Miss'", "def multiple(x):\n if x % 15 == 0: return \"BangBoom\"\n if x % 5 == 0: return \"Boom\"\n if x % 3 == 0: return \"Bang\"\n return \"Miss\"", "def multiple(x):\n val = ''\n if x % 3 == 0:\n val += 'Bang'\n ... | {"fn_name": "multiple", "inputs": [[30], [3], [98], [65], [23], [15], [4], [2], [45], [90], [21], [7], [6], [10003823], [41535], [712], [985], [164523]], "outputs": [["BangBoom"], ["Bang"], ["Miss"], ["Boom"], ["Miss"], ["BangBoom"], ["Miss"], ["Miss"], ["BangBoom"], ["BangBoom"], ["Bang"], ["Miss"], ["Bang"], ["Miss"]... | introductory | https://www.codewars.com/kata/55a8a36703fe4c45ed00005b |
def multiple(x):
|
4,517 | Complete the function that takes a string as an input, and return a list of all the unpaired characters (i.e. they show up an odd number of times in the string), in the order they were encountered as an array.
In case of multiple appearances to choose from, take the last occurence of the unpaired character.
**Notes:... | ["from collections import Counter\n\ndef odd_one_out(s):\n d = Counter(reversed(s))\n return [x for x in d if d[x] % 2][::-1]", "def odd_one_out(s):\n d = {}\n for i in s:\n if i in d:\n del d[i]\n else:\n d[i] = None\n return list(d.keys())", "from collections import ... | {"fn_name": "odd_one_out", "inputs": [["Hello World"], ["Codewars"], ["woowee"], ["wwoooowweeee"], ["racecar"], ["Mamma"], ["Mama"], ["\u00bc x 4 = 1"], ["\u00bc x 4 = 1 and \u00bd x 4 = 2"]], "outputs": [[["H", "e", " ", "W", "r", "l", "d"]], [["C", "o", "d", "e", "w", "a", "r", "s"]], [[]], [[]], [["e"]], [["M"]], [[... | introductory | https://www.codewars.com/kata/55b080eabb080cd6f8000035 |
def odd_one_out(s):
|
4,518 | Write a function that returns the index of the first occurence of the word "Wally". "Wally" must not be part of another word, but it can be directly followed by a punctuation mark. If no such "Wally" exists, return -1.
Examples:
"Wally" => 0
"Where's Wally" => 8
"Where's Waldo" => -1
"DWally Wallyd .Wally" => -... | ["from re import compile\n\ndef wheres_wally(string):\n m = compile('(^|.*[\\s])(Wally)([\\.,\\s\\']|$)').match(string)\n return m.start(2) if m else -1", "import re\n\ndef wheres_wally(string):\n return next((m.start() for m in re.finditer(r'((?<= )W|^W)ally\\b', string)), -1)", "from re import search\ndef wh... | {"fn_name": "wheres_wally", "inputs": [[""], ["WAlly"], ["wAlly"], ["DWally"], [".Wally"], ["Wallyd"], ["wally mollyWally Wallybrolly 'Wally"], ["Walley ,Wally -Wally ;Wally +Wally :Wally"], ["Walley Wally, Wally- Wally: Wally+ Wally:"], ["12Wally Wally01 W.ally"], ["Where's Waldo"], ["Wally"], ["Wally Wally"], ["W all... | introductory | https://www.codewars.com/kata/55f91a98db47502cfc00001b |
def wheres_wally(string):
|
4,519 | # Task
**_Given_** *a number* , **_Return_** **_The Maximum number _** *could be formed from the digits of the number given* .
___
# Notes
* **_Only Natural numbers_** *passed to the function , numbers Contain digits [0:9] inclusive*
* **_Digit Duplications_** *could occur* , So also **_consider it when formin... | ["def max_number(n):\n return int(''.join(sorted(str(n), reverse=True)))", "max_number = lambda n: int(\"\".join(sorted(str(n)))[::-1])", "def max_number(n):\n n = \"\".join(sorted(str(n), reverse=True))\n return int(n)", "max_number= lambda n : int(''.join(sorted(list(str(n)),reverse=True)))\n", "max_number=... | {"fn_name": "max_number", "inputs": [[213], [7389], [63792], [566797], [1000000]], "outputs": [[321], [9873], [97632], [977665], [1000000]]} | introductory | https://www.codewars.com/kata/5a4ea304b3bfa89a9900008e |
def max_number(n):
|
4,520 | Rick wants a faster way to get the product of the largest pair in an array. Your task is to create a performant solution to find the product of the largest two integers in a unique array of positive numbers. All inputs will be valid.
Passing [2, 6, 3] should return 18, the product of [6, 3].
```Disclaimer: Mr. Roll wi... | ["import heapq\ndef max_product(a):\n x = heapq.nlargest(2,a)\n return x[0]*x[1]", "def max_product(a): \n first_max = 0\n second_max = 0\n for x in a:\n if x > first_max:\n second_max = first_max\n first_max = x\n elif x > second_max:\n second_max = x\n ... | {"fn_name": "max_product", "inputs": [[[56, 335, 195, 443, 6, 494, 252]], [[154, 428, 455, 346]], [[39, 135, 47, 275, 37, 108, 265, 457, 2, 133, 316, 330, 153, 253, 321, 411]], [[136, 376, 10, 146, 105, 63, 234]], [[354, 463, 165, 62, 472, 53, 347, 293, 252, 378, 420, 398, 255, 89]], [[346, 446, 26, 425, 432, 349, 123,... | introductory | https://www.codewars.com/kata/5784c89be5553370e000061b |
def max_product(a):
|
4,521 | Vasya wants to climb up a stair of certain amount of steps (Input parameter 1). There are 2 simple rules that he has to stick to.
1. Vasya can climb 1 or 2 steps at each move.
2. Vasya wants the number of moves to be a multiple of a certain integer. (Input parameter 2).
### Task:
What is the `MINIMAL` number of moves... | ["def numberOfSteps(steps, m):\n if (steps < m):\n return -1\n \n \n if (steps % 2 == 0 and (steps / 2) % m == 0):\n return (steps / 2)\n \n \n return (steps / 2) + m - ((steps / 2) % m)\n", "def numberOfSteps(steps, m):\n return next((n for n in range((steps+1)//2, steps+1) if n % m =... | {"fn_name": "numberOfSteps", "inputs": [[10, 2], [3, 5], [29, 7], [2, 2], [1, 2], [10000, 2], [10000, 3], [10000, 10], [9999, 3], [9999, 2], [9999, 10], [9999, 9], [18, 10], [19, 10], [20, 10], [7688, 5], [4608, 5], [3979, 2], [5, 2]], "outputs": [[6], [-1], [21], [2], [-1], [5000], [5001], [5000], [5001], [5000], [500... | introductory | https://www.codewars.com/kata/55251c0d2142d7b4ab000aef |
def numberOfSteps(steps, m):
|
4,522 | **DESCRIPTION:**
Your strict math teacher is teaching you about right triangles, and the Pythagorean Theorem --> a^2 + b^2 = c^2 whereas a and b are the legs of the right triangle and c is the hypotenuse of the right triangle. On the test however, the question asks: What are the possible integer lengths for the othe... | ["def side_len(x, y):\n return [z for z in range(abs(x-y)+1,x+y) if z*z not in (abs(x*x-y*y), x*x+y*y)]", "def side_len(x, y):\n return [i for i in range(abs(x-y)+1, abs(x+y)) if i != (x*x+y*y)**0.5 and i != abs(y*y-x*x)**0.5]", "def side_len(x, y):\n return [i for i in range(y-x+1,x+y) if abs(i**2-y**2) != x*... | {"fn_name": "side_len", "inputs": [[1, 1], [3, 4], [4, 6], [5, 12], [8, 10]], "outputs": [[[1]], [[2, 3, 4, 6]], [[3, 4, 5, 6, 7, 8, 9]], [[8, 9, 10, 11, 12, 14, 15, 16]], [[3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]]]} | introductory | https://www.codewars.com/kata/5e81303e7bf0410025e01031 |
def side_len(x, y):
|
4,523 | In this Kata, you will be given an integer `n` and your task will be to return `the largest integer that is <= n and has the highest digit sum`.
For example:
```
solve(100) = 99. Digit Sum for 99 = 9 + 9 = 18. No other number <= 100 has a higher digit sum.
solve(10) = 9
solve(48) = 48. Note that 39 is also an option, ... | ["def solve(n):\n x = str(n)\n res = [x] + [str(int(x[:i]) - 1) + '9' * (len(x) - i) for i in range(1, len(x))]\n return int(max(res, key=lambda x: (sum(map(int, x)), int(x))))", "def dig_sum(n):\n return sum(map(int, str(n)))\n\ndef solve(n):\n candidates = [n] + [ n // 10**i * 10**i - 1 for i in range(... | {"fn_name": "solve", "inputs": [[79320], [99004], [99088], [99737], [29652], [100], [48], [521], [1], [2], [3], [39188], [5], [10], [1000], [10000], [999999999992], [59195], [19930], [110], [1199], [120], [18], [2090], [72694]], "outputs": [[78999], [98999], [98999], [98999], [28999], [99], [48], [499], [1], [2], [3], ... | introductory | https://www.codewars.com/kata/5b162ed4c8c47ea2f5000023 |
def solve(n):
|
4,524 | A number is simply made up of digits.
The number 1256 is made up of the digits 1, 2, 5, and 6.
For 1256 there are 24 distinct permutations of the digits:
1256, 1265, 1625, 1652, 1562, 1526, 2156, 2165, 2615, 2651, 2561, 2516,
5126, 5162, 5216, 5261, 5621, 5612, 6125, 6152, 6251, 6215, 6521, 6512.
Your goal ... | ["from itertools import permutations\n\ndef permutation_average(n):\n perms = [float(''.join(e)) for e in permutations(str(n))]\n return int(round(sum(perms) / len(perms)))\n", "def permutation_average(n):\n n = str(n)\n n, l = sum(map(int, n)) / float(len(n)), len(n)\n \n n = n * ((10 ** l - 1) / 9)\... | {"fn_name": "permutation_average", "inputs": [[2], [25], [737]], "outputs": [[2], [38], [629]]} | introductory | https://www.codewars.com/kata/56b18992240660a97c00000a |
def permutation_average(n):
|
4,525 | Given the number pledged for a year, current value and name of the month, return string that gives information about the challenge status:
- ahead of schedule
- behind schedule
- on track
- challenge is completed
Examples:
`(12, 1, "February")` - should return `"You are on track."`
`(12, 1, "March")` - should retur... | ["import calendar\n\nM = {calendar.month_name[i]: i - 1 for i in range(1, 13)}\n\n\ndef check_challenge(pledged, current, month):\n if pledged == current:\n return \"Challenge is completed.\"\n m = M[month]\n per_month, rest = divmod(pledged, 12)\n todo = per_month * m + (min(rest, m))\n delta = c... | {"fn_name": "check_challenge", "inputs": [[12, 5, "January"], [12, 1, "February"], [12, 1, "March"], [12, 12, "September"], [12, 5, "March"], [100, 5, "March"], [100, 52, "July"], [100, 51, "July"], [100, 53, "July"]], "outputs": [["You are on track."], ["You are on track."], ["You are 1 behind schedule."], ["Challenge... | introductory | https://www.codewars.com/kata/584acd331b8b758fe700000d |
def check_challenge(pledged, current, month):
|
4,526 | *SCHEDULE YOUR DA(RRA)Y*
The best way to have a productive day is to plan out your work schedule. Given the following three inputs, please create an an array of time alloted to work, broken up with time alloted with breaks:
Input 1: Hours - Number of hours available to you to get your work done!
Inpu... | ["def day_plan(hours, tasks, duration):\n td, hm, tmo = tasks * duration, hours * 60, tasks - 1\n if td > hm: return \"You're not sleeping tonight!\"\n arr = [0] * (tasks + tmo)\n arr[::2], arr[1::2] = [duration] * tasks, [round((hm - td) / (tmo or 1))] * tmo\n return arr\n", "def day_plan(hours, tasks, ... | {"fn_name": "day_plan", "inputs": [[8, 5, 30], [3, 5, 60], [2, 2, 60], [2, 1, 60], [2, 0, 60]], "outputs": [[[30, 82, 30, 82, 30, 82, 30, 82, 30]], ["You're not sleeping tonight!"], [[60, 0, 60]], [[60]], [[]]]} | introductory | https://www.codewars.com/kata/581de9a5b7bad5d369000150 |
def day_plan(hours, tasks, duration):
|
4,527 | Steve and Josh are bored and want to play something. They don't want to think too much, so they come up with a really simple game. Write a function called winner and figure out who is going to win.
They are dealt the same number of cards. They both flip the card on the top of their deck. Whoever has a card with higher... | ["def winner(deck_Steve, deck_Josh):\n deck = ['2','3','4','5','6','7','8','9','T','J','Q','K','A']\n Steve = 0\n Josh = 0\n for i in range(len(deck_Steve)):\n if deck.index(deck_Steve[i]) > deck.index(deck_Josh[i]):\n Steve += 1\n elif deck.index(deck_Steve[i]) < deck.index(deck_Jo... | {"fn_name": "winner", "inputs": [[["A", "7", "8"], ["K", "5", "9"]], [["T"], ["T"]], [["T", "9"], ["T", "8"]], [[], []]], "outputs": [["Steve wins 2 to 1"], ["Tie"], ["Steve wins 1 to 0"], ["Tie"]]} | introductory | https://www.codewars.com/kata/53417de006654f4171000587 |
def winner(deck_steve, deck_josh):
|
4,528 | ## Your task
You are given a dictionary/hash/object containing some languages and your test results in the given languages. Return the list of languages where your test score is at least `60`, in descending order of the results.
Note: the scores will always be unique (so no duplicate values)
## Examples
```python
{... | ["def my_languages(results):\n return sorted((l for l,r in results.items() if r>=60), reverse=True, key=results.get)", "# def my_languages(dict):\n# store = []\n# for key, value in dict.items():\n# if value >= 60:\n# store.append((key, value))\n# store.sort(key=lambda x: x[-1])\n# ... | {"fn_name": "my_languages", "inputs": [[{"Java": 10, "Ruby": 80, "Python": 65}], [{"Hindi": 60, "Greek": 71, "Dutch": 93}], [{"C++": 50, "ASM": 10, "Haskell": 20}]], "outputs": [[["Ruby", "Python"]], [["Dutch", "Greek", "Hindi"]], [[]]]} | introductory | https://www.codewars.com/kata/5b16490986b6d336c900007d |
def my_languages(results):
|
4,529 | Truncate the given string (first argument) if it is longer than the given maximum length (second argument). Return the truncated string with a `"..."` ending.
Note that inserting the three dots to the end will add to the string length.
However, if the given maximum string length num is less than or equal to 3, then t... | ["def truncate_string(s,n):\n return s if len(s)<=n else s[:n if n<=3 else n-3]+'...'", "def truncate_string(s, n):\n return s if n>=len(s) else s[:n]+'...' if n<=3 else s[:n-3]+'...'", "def truncate_string(str,n):\n if len(str) <= n:\n return str\n if n <= 3:\n return str[0:n] + \"...\"\n ... | {"fn_name": "truncate_string", "inputs": [["pippi", 3], ["Peter Piper picked a peck of pickled peppers", 14], ["A-tisket a-tasket A green and yellow basket", 43], ["A-tisket a-tasket A green and yellow basket", 45], ["A-", 1], ["Chingel loves his Angel so much!!!", 27], ["I like ice-cream.Do you?", 19], ["Seems like yo... | introductory | https://www.codewars.com/kata/57af26297f75b57d1f000225 |
def truncate_string(str,n):
|
4,530 | Write a function `consonantCount`, `consonant_count` or `ConsonantCount` that takes a string of English-language text and returns the number of consonants in the string.
Consonants are all letters used to write English excluding the vowels `a, e, i, o, u`. | ["def consonant_count(str):\n return sum(1 for c in str if c.isalpha() and c.lower() not in \"aeiou\")\n", "import re\n\ndef consonant_count(s):\n return len(re.sub(r'[aeiou\\d\\s\\W\\_]', '', s))", "import re\n\ndef consonant_count(s):\n return len(re.sub(r'[^b-df-hj-np-tv-z]', '', s, flags=re.I))", "VOWELS =... | {"fn_name": "consonant_count", "inputs": [[""], ["aaaaa"], ["helLo world"], ["h^$&^#$&^elLo world"], ["0123456789"], ["012345_Cb"]], "outputs": [[0], [0], [7], [7], [0], [2]]} | introductory | https://www.codewars.com/kata/564e7fc20f0b53eb02000106 |
def consonant_count(s):
|
4,531 | Convert integers to binary as simple as that. You would be given an integer as a argument and you have to return its binary form.
To get an idea about how to convert a decimal number into a binary number, visit here.
**Notes**: negative numbers should be handled as two's complement; assume all numbers are integers sto... | ["def to_binary(n):\n return \"{:0b}\".format(n & 0xffffffff)", "def to_binary(n):\n return bin(n if n >= 0 else 2 ** 32 + n)[2:]", "def to_binary(n):\n return bin(n % 2**32)[2:]", "def to_binary(n):\n return format(n & 0xffffffff, 'b')", "def to_binary(n):\n return bin(n & (2**32 - 1))[2:]", "def to_bin... | {"fn_name": "to_binary", "inputs": [[2], [3], [4], [5], [7], [10], [-3], [0], [1000], [-15], [-1000], [-999999], [999999]], "outputs": [["10"], ["11"], ["100"], ["101"], ["111"], ["1010"], ["11111111111111111111111111111101"], ["0"], ["1111101000"], ["11111111111111111111111111110001"], ["111111111111111111111100000110... | introductory | https://www.codewars.com/kata/55606aeebf1f0305f900006f |
def to_binary(n):
|
4,532 | Basic regex tasks. Write a function that takes in a numeric code of any length. The function should check if the code begins with 1, 2, or 3 and return `true` if so. Return `false` otherwise.
You can assume the input will always be a number. | ["def validate_code(code):\n return str(code).startswith(('1', '2', '3'))\n", "def validate_code(code):\n return str(code)[0] in '123'", "def validate_code(code):\n import re\n return bool(re.match(r\"^[123]\\d*$\",str(code)))\n", "def validate_code(code):\n import re\n return bool(re.match('[123]',st... | {"fn_name": "validate_code", "inputs": [[123], [248], [8], [321], [9453]], "outputs": [[true], [true], [false], [true], [false]]} | introductory | https://www.codewars.com/kata/56a25ba95df27b7743000016 |
def validate_code(code):
|
4,533 | The image shows how we can obtain the Harmonic Conjugated Point of three aligned points A, B, C.
- We choose any point L, that is not in the line with A, B and C. We form the triangle ABL
- Then we draw a line from point C that intersects the sides of this triangle at points M and N respectively.
- We draw the diago... | ["def harmon_pointTrip(xA, xB, xC):\n a, b, c = list(map(float, [xA, xB, xC]))\n # Yay for algebra!\n d = ((a * c) + (b * c) - (2 * a * b)) / (2 * c - a - b)\n return round(d, 4)\n", "def harmon_pointTrip(xA, xB, xC):\n return round((xA*xC + xB*xC - 2*xA*xB) / (2*xC - xA - xB), 4)", "def harmon_pointTrip... | {"fn_name": "harmon_pointTrip", "inputs": [[2, 10, 20], [3, 9, 18], [6, 10, 11], [4, 12, 24], [5, 17, 20]], "outputs": [[7.1429], [6.75], [9.3333], [9.0], [15.0]]} | introductory | https://www.codewars.com/kata/5600e00e42bcb7b9dc00014e |
def harmon_pointTrip(xA, xB, xC):
|
4,534 | We have the number ```12385```. We want to know the value of the closest cube but higher than 12385. The answer will be ```13824```.
Now, another case. We have the number ```1245678```. We want to know the 5th power, closest and higher than that number. The value will be ```1419857```.
We need a function ```find_next... | ["def find_next_power(val, pow_):\n return int(val ** (1.0 / pow_) + 1) ** pow_", "import math\n\ndef find_next_power(val, pow_):\n next_power_value = math.floor( 1 + val ** (1/pow_))\n return next_power_value ** pow_", "def find_next_power(val, pow_):\n return int(val ** (1 / pow_) + 1) ** pow_", "def find... | {"fn_name": "find_next_power", "inputs": [[12385, 3], [1245678, 5], [1245678, 6]], "outputs": [[13824], [1419857], [1771561]]} | introductory | https://www.codewars.com/kata/56ba65c6a15703ac7e002075 |
def find_next_power(val, pow_):
|
4,535 | The goal of this Kata is to remind/show you, how Z-algorithm works and test your implementation.
For a string str[0..n-1], Z array is of same length as string. An element Z[i] of Z array stores length of the longest substring starting from str[i] which is also a prefix of str[0..n-1]. The first entry of Z array is mea... | ["def prefix1(a, b):\n cnt = 0\n for i, j in zip(a, b):\n if i == j:\n cnt += 1\n else:\n return cnt\n return cnt \ndef prefix2(a, b, num):\n for i in range(num, -1, -1):\n if b.startswith(a[:i]):\n return i\ndef zfunc(str_):\n z = []\n k = len(... | {"fn_name": "zfunc", "inputs": [["ababcaba"], [""], ["aaaaaaaa"], ["ababababab"], ["aaaa$aaaa"], ["abracadabra"]], "outputs": [[[8, 0, 2, 0, 0, 3, 0, 1]], [[]], [[8, 7, 6, 5, 4, 3, 2, 1]], [[10, 0, 8, 0, 6, 0, 4, 0, 2, 0]], [[9, 3, 2, 1, 0, 4, 3, 2, 1]], [[11, 0, 0, 1, 0, 1, 0, 4, 0, 0, 1]]]} | introductory | https://www.codewars.com/kata/56d30dadc554829d55000578 |
def zfunc(str_):
|
4,536 | Create a function that takes an input String and returns a String, where all the uppercase words of the input String are in front and all the lowercase words at the end.
The order of the uppercase and lowercase words should be the order in which they occur.
If a word starts with a number or special character, skip the... | ["def capitals_first(string):\n return ' '.join([word for word in string.split() if word[0].isupper()] + [word for word in string.split() if word[0].islower()])\n", "def capitals_first(string):\n # biggies first...\n words = string.split()\n st1 = []\n st2 = []\n for word in words:\n if word[0]... | {"fn_name": "capitals_first", "inputs": [["hey You, Sort me Already"], ["sense Does to That Make you?"], ["i First need Thing In coffee The Morning"], ["123 baby You and Me"], ["Life gets Sometimes pretty !Hard"]], "outputs": [["You, Sort Already hey me"], ["Does That Make sense to you?"], ["First Thing In The Morning ... | introductory | https://www.codewars.com/kata/55c353487fe3cc80660001d4 |
def capitals_first(text):
|
4,537 | Gray code is a form of binary encoding where transitions between consecutive numbers differ by only one bit. This is a useful encoding for reducing hardware data hazards with values that change rapidly and/or connect to slower hardware as inputs. It is also useful for generating inputs for Karnaugh maps.
Here is an ex... | ["def bin2gray(bits):\n bits.reverse()\n return list(reversed([x if i >= len(bits) - 1 or bits[i + 1] == 0 else 1 - x for i, x in enumerate(bits)]))\n \ndef gray2bin(bits):\n for i, x in enumerate(bits):\n if i > 0 and bits[i - 1] != 0: bits[i] = 1 - x\n return bits", "def bitlist(func):\n def wrapper(bits):... | {"fn_name": "bin2gray", "inputs": [[[1, 0, 1]], [[1, 1]], [[1]], [[0]], [[1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0]], [[1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0]]], "outputs": [[[1, 1, 1]], [[1,... | introductory | https://www.codewars.com/kata/5416ce834c2460b4d300042d |
def bin2gray(bits):
|
4,538 | You are going to be given a string. Your job is to return that string in a certain order that I will explain below:
Let's say you start with this: `012345`
The first thing you do is reverse it:`543210`
Then you will take the string from the 1st position and reverse it again:`501234`
Then you will take the string ... | ["def reverse_fun(n):\n for i in range(len(n)):\n n = n[:i] + n[i:][::-1]\n return n", "def reverse_fun(n):\n l = len(n)\n return ''.join(b+a for a,b in zip(list(n[:l//2])+[''], n[l//2:][::-1]))", "def reverse_fun(n):\n n = n[::-1]\n for i in range(1, len(n)):\n n = n[:i] + n[i:][::-1]\n... | {"fn_name": "reverse_fun", "inputs": [["012"], ["012345"], ["0123456789"], ["Hello"]], "outputs": [["201"], ["504132"], ["9081726354"], ["oHlel"]]} | introductory | https://www.codewars.com/kata/566efcfbf521a3cfd2000056 |
def reverse_fun(n):
|
4,539 | You are trying to cross a river by jumping along stones. Every time you land on a stone, you hop forwards by the value of that stone. If you skip *over* a stone then its value doesn't affect you in any way. Eg:
```
x--x-----x-->
[1][2][5][1]
```
Of course, crossing from the other side might give you a different ans... | ["def hop_across(lst):\n def one_side(lst):\n i = 0\n steps = 0\n while i < len(lst):\n i += lst[i]\n steps += 1\n return steps\n return one_side(lst) + one_side(lst[::-1])", "def hop_across(lst): return dist(lst)+dist(lst[::-1])\n\ndef dist(lst):\n s,i=0,0\n ... | {"fn_name": "hop_across", "inputs": [[[1]], [[2]], [[1, 1]], [[2, 1]], [[2, 1, 1]], [[1, 2, 1, 2]], [[1, 2, 5, 1]], [[2, 2, 3, 1, 1, 2, 1]]], "outputs": [[2], [2], [4], [3], [5], [5], [5], [7]]} | introductory | https://www.codewars.com/kata/5a60d519400f93fc450032e5 |
def hop_across(lst):
|
4,540 | Check if given numbers are prime numbers.
If number N is prime ```return "Probable Prime"``` else ``` return "Composite"```.
HINT: Upper bount is really big so you should use an efficient algorithm.
Input
1 < N ≤ 10^(100)
Example
prime_or_composite(2) # should return Probable Prime
prime_or_composite(200) #... | ["def prime_or_composite(n):\n if n < 4: return 'Probable Prime'\n if n % 2 == 0: return 'Composite'\n d, r = n - 1, 0\n while d % 2 == 0:\n d, r = d // 2, r + 1\n for a in [2, 31]:\n x = pow(a, d, n)\n if x in (1, n - 1):\n continue\n for _ in range(r-1):\n ... | {"fn_name": "prime_or_composite", "inputs": [[2], [3], [5], [9], [12]], "outputs": [["Probable Prime"], ["Probable Prime"], ["Probable Prime"], ["Composite"], ["Composite"]]} | introductory | https://www.codewars.com/kata/5742e725f81ca04d64000c11 |
def prime_or_composite(n):
|
4,541 | # Task
You are given an array of integers `a` and a non-negative number of operations `k`, applied to the array. Each operation consists of two parts:
```
find the maximum element value of the array;
replace each element a[i] with (maximum element value - a[i]).```
How will the array look like after `k` such operation... | ["def array_operations(a, n):\n li = []\n for i in range(n):\n m = max(a)\n a = [m-i for i in a] \n if a in li:\n if not n & 1 : return li[-1]\n return a\n li.append(a)\n return a", "def array_operations(a, k):\n for _ in range(2 + (k & 1)):\n m = max(a)\n ... | {"fn_name": "array_operations", "inputs": [[[-4, 0, -1, 0], 2], [[0, -1, 0, 0, -1, -1, -1, -1, 1, -1], 1], [[-1], 10000]], "outputs": [[[0, 4, 3, 4]], [[1, 2, 1, 1, 2, 2, 2, 2, 0, 2]], [[0]]]} | introductory | https://www.codewars.com/kata/589aca25fef1a81a10000057 |
def array_operations(a, k):
|
4,542 | Let’s get to know our hero: Agent #134 - Mr. Slayer.
He was sent by his CSV agency to Ancient Rome in order to resolve some important national issues. However, something incredible has happened - the enemies have taken Julius Caesar as a prisoner!!!
Caesar, not a simple man as you know, managed to send cryptic messag... | ["from string import ascii_letters as az\n\n\ndef caesar_crypto_encode(text, shift):\n if not text:\n return ''\n sh = shift % 52\n return str.translate(text, str.maketrans(az, az[sh:] + az[:sh])).strip()", "from string import ascii_lowercase, ascii_uppercase\nS = ascii_lowercase+ascii_uppercase\nD = {c... | {"fn_name": "caesar_crypto_encode", "inputs": [["123,.)(!?", 10], ["", 10], [null, 10], [" ", 10], ["Hello world!", 127], ["eBIIL TLOIA!", -127], ["ksdjai8983hdk?}{", 15], ["Hello world!", 0]], "outputs": [["123,.)(!?"], [""], [""], [""], ["eBIIL TLOIA!"], ["Hello world!"], ["zHsypx8983wsz?}{"], ["Hello world!"]]} | introductory | https://www.codewars.com/kata/576fac714bc84c312c0000b7 |
def caesar_crypto_encode(text, shift):
|
4,543 | Why would we want to stop to only 50 shades of grey? Let's see to how many we can go.
Write a function that takes a number n as a parameter and return an array containing n shades of grey in hexadecimal code (`#aaaaaa` for example). The array should be sorted in ascending order starting with `#010101`, `#020202`, etc... | ["def shades_of_grey(n):\n if n > 254:\n n = 254\n return [\"#%02x%02x%02x\" % (i,i,i) for i in range(1,n+1)]", "def shades_of_grey(n):\n return [ '#{0:02x}{0:02x}{0:02x}'.format(i+1) for i in range(min(254, n)) ]", "form = '#'+'{0:0>2}'*3\nshades_of_grey=lambda n:[form.format(hex(i)[2:])for i in range(1,min(n+... | {"fn_name": "shades_of_grey", "inputs": [[-1], [0], [1], [254], [5000]], "outputs": [[[]], [[]], [["#010101"]], [["#010101", "#020202", "#030303", "#040404", "#050505", "#060606", "#070707", "#080808", "#090909", "#0a0a0a", "#0b0b0b", "#0c0c0c", "#0d0d0d", "#0e0e0e", "#0f0f0f", "#101010", "#111111", "#121212", "#131313... | introductory | https://www.codewars.com/kata/54d22119beeaaaf663000024 |
def shades_of_grey(n):
|
4,544 | # Task
Consider the following operation:
We take a positive integer `n` and replace it with the sum of its `prime factors` (if a prime number is presented multiple times in the factorization of `n`, then it's counted the same number of times in the sum).
This operation is applied sequentially first to the given... | ["def factor_sum(n):\n while True:\n i=2\n s=0\n a=n\n while i<=n:\n if n%i==0:\n s+=i\n n/=i\n if n==1:\n break\n else:\n i+=1\n \n if a!=s:\n n=s\n ... | {"fn_name": "factor_sum", "inputs": [[24], [35], [156], [4], [31]], "outputs": [[5], [7], [5], [4], [31]]} | introductory | https://www.codewars.com/kata/589d2bf7dfdef0817e0001aa |
def factor_sum(n):
|
4,545 | Create your own mechanical dartboard that gives back your score based on the coordinates of your dart.
Task:
Use the scoring rules for a standard dartboard:
Finish method:
```python
def get_score(x,y):
```
The coordinates are `(x, y)` are always relative to the center of the board (0, 0). The unit is millimeters.... | ["from math import atan2, degrees\n\ndef get_score(x,y):\n r, a = (x*x + y*y)**0.5, degrees(atan2(y, x)) + 9\n t = str([6,13,4,18,1,20,5,12,9,14,11,8,16,7,19,3,17,2,15,10][int(a + 360 if a < 0 else a)//18])\n for l, s in [(6.35, 'DB'),(15.9,'SB'),(99,t),(107,'T'+t),(162,t),(170,'D'+t)]:\n if r <= l: ret... | {"fn_name": "get_score", "inputs": [[-133.69, -147.38], [4.06, 0.71], [2.38, -6.06], [-5.43, 117.95], [-73.905, -95.94], [55.53, -87.95], [-145.19, 86.53]], "outputs": [["X"], ["DB"], ["SB"], ["20"], ["7"], ["T2"], ["D9"]]} | introductory | https://www.codewars.com/kata/5870db16056584eab0000006 |
def get_score(x,y):
|
4,546 | Mothers arranged a dance party for the children in school. At that party, there are only mothers and their children. All are having great fun on the dance floor when suddenly all the lights went out. It's a dark night and no one can see each other. But you were flying nearby and you can see in the dark and have ability... | ["def find_children(dancing_brigade):\n return ''.join(sorted(dancing_brigade,key=lambda c:(c.upper(),c.islower())))", "def find_children(s):\n return ''.join( sorted(sorted(s), key=str.lower) )", "#wow this is very long :)\ndef find_children(people) :\n string = []\n answer = []\n symbol = ''\n index = -1\n ... | {"fn_name": "find_children", "inputs": [["abBA"], ["AaaaaZazzz"], ["CbcBcbaA"], ["xXfuUuuF"], [""]], "outputs": [["AaBb"], ["AaaaaaZzzz"], ["AaBbbCcc"], ["FfUuuuXx"], [""]]} | introductory | https://www.codewars.com/kata/58539230879867a8cd00011c |
def find_children(dancing_brigade):
|
4,547 | Create a __moreZeros__ function which will __receive a string__ for input, and __return an array__ (or null terminated string in C) containing only the characters from that string whose __binary representation of its ASCII value__ consists of _more zeros than ones_.
You should __remove any duplicate characters__, kee... | ["def more_zeros(s):\n results = []\n \n for letter in s:\n dec_repr = bin(ord(letter))[2:]\n if (dec_repr.count(\"0\") > dec_repr.count(\"1\")) and (letter not in results):\n results.append(letter)\n \n return results\n", "def more_zeros(s):\n L=[]\n L1=[]\n L2=[]\n ... | {"fn_name": "more_zeros", "inputs": [["abcde"], ["thequickbrownfoxjumpsoverthelazydog"], ["THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG"], ["abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_"], ["DIGEST"], ["abcdabcd"], ["Forgiveness is the fragrance that the violet sheds on the heal that has crushed it"]], "outpu... | introductory | https://www.codewars.com/kata/5d41e16d8bad42002208fe1a |
def more_zeros(s):
|
4,548 | ## Sum Even Fibonacci Numbers
* Write a func named SumEvenFibonacci that takes a parameter of type int and returns a value of type int
* Generate all of the Fibonacci numbers starting with 1 and 2 and ending on the highest number before exceeding the parameter's value
#### Each new number in the Fibonacci sequence... | ["def SumEvenFibonacci(limit):\n a,b,s = 1,1,0\n while a <= limit:\n if not a%2: s += a\n a,b = b, a+b\n return s", "def SumEvenFibonacci(limit):\n a, b, result = 1, 2, 0\n while b <= limit:\n if b % 2 == 0:\n result += b\n a, b = b, a + b\n return result\n", "fr... | {"fn_name": "SumEvenFibonacci", "inputs": [[1], [2], [8], [111111], [8675309], [144100000], [65140000], [7347000000], [10000000000000], [123456789000000]], "outputs": [[0], [2], [10], [60696], [4613732], [82790070], [82790070], [6293134512], [8583840088782], [154030760585064]]} | introductory | https://www.codewars.com/kata/5926624c9b424d10390000bf |
def SumEvenFibonacci(limit):
|
4,549 | # Your task
Oh no... more lemmings!! And in Lemmings Planet a huge battle
is being fought between the two great rival races: the green
lemmings and the blue lemmings. Everybody was now assigned
to battle and they will fight until one of the races completely
dissapears: the Deadly War has begun!
Every single lemming ha... | ["from heapq import *\n\ndef lemming_battle(battlefield, green, blue):\n hg, hb = ([-v for v in lst] for lst in (green,blue))\n heapify(hg) ; heapify(hb)\n \n while hb and hg:\n tmp_b,tmp_g = [],[]\n for _ in range(min(battlefield,len(hg),len(hb))):\n cmp = heappop(hg) - heappop(hb)... | {"fn_name": "lemming_battle", "inputs": [[5, [10], [10]], [2, [20, 10], [10, 10, 15]], [3, [50, 40, 30, 40, 50], [50, 30, 30, 20, 60]], [1, [20, 30], [15]]], "outputs": [["Green and Blue died"], ["Blue wins: 5"], ["Green wins: 10 10"], ["Green wins: 20 15"]]} | introductory | https://www.codewars.com/kata/5b7d2cca7a2013f79f000129 |
def lemming_battle(battlefield, green, blue):
|
4,550 | Get n seconds before the target time. See Example Test Cases about the format. | ["from datetime import *\n\ndef seconds_ago(s,n):\n return str(datetime.strptime(s, '%Y-%m-%d %H:%M:%S') - timedelta(seconds=n))", "from datetime import datetime,timedelta\n\ndef seconds_ago(s,n):\n t = datetime.strptime(s,'%Y-%m-%d %H:%M:%S')-timedelta(seconds=n)\n return str(t.year).zfill(4)+t.strftime('-%m-... | {"fn_name": "seconds_ago", "inputs": [["2000-01-01 00:00:00", 1], ["0001-02-03 04:05:06", 7]], "outputs": [["1999-12-31 23:59:59"], ["0001-02-03 04:04:59"]]} | introductory | https://www.codewars.com/kata/5a631508e626c5f127000055 |
def seconds_ago(s,n):
|
4,551 | We have a matrix of integers with m rows and n columns.
We want to calculate the total sum for the matrix:
As you can see, the name "alternating sum" of the title is due to the sign of the terms that changes from one term to its contiguous one and so on.
Let's see an example:
```
matrix = [[1, 2, 3], [-3, -2, 1]... | ["def score_matrix(matrix):\n return sum((-1) ** (i+j) * matrix[i][j] for i in range(len(matrix)) for j in range(len(matrix[i])))\n", "def score_matrix(matrix):\n return sum(\n (-1)**(i+j) * x\n for i, row in enumerate(matrix)\n for j, x in enumerate(row)\n )", "def score_matrix(matrix):\n... | {"fn_name": "score_matrix", "inputs": [[[[1, 2, 3], [-3, -2, 1], [3, -1, 2]]]], "outputs": [[8]]} | introductory | https://www.codewars.com/kata/5720eb05e8d6c5b24a0014c5 |
def score_matrix(matrix):
|
4,552 | You are given an array of unique numbers. The numbers represent points. The higher the number the higher the points.
In the array [1,3,2] 3 is the highest point value so it gets 1st place. 2 is the second highest so it gets second place. 1 is the 3rd highest so it gets 3rd place.
Your task is to return an array giv... | ["def rankings(arr):\n dct = {v:i for i,v in enumerate(sorted(arr, reverse=True),1)}\n return [dct[v] for v in arr]", "def rankings(a):\n s = sorted(a)[::-1]\n return [s.index(e) + 1 for e in a]", "def rankings(lst):\n std = sorted(lst, reverse=True)\n return [std.index(n) + 1 for n in lst]", "def ran... | {"fn_name": "rankings", "inputs": [[[1, 3, 2]], [[1, 2, 3, 4, 5]], [[3, 4, 1, 2, 5]], [[10, 20, 40, 50, 30]], [[1, 10]], [[22, 33, 18, 9, 110, 4, 1, 88, 6, 50]]], "outputs": [[[3, 1, 2]], [[5, 4, 3, 2, 1]], [[3, 2, 5, 4, 1]], [[5, 4, 2, 1, 3]], [[2, 1]], [[5, 4, 6, 7, 1, 9, 10, 2, 8, 3]]]} | introductory | https://www.codewars.com/kata/58e16de3a312d34d000000bd |
def rankings(arr):
|
4,553 | Simple, given a string of words, return the length of the shortest word(s).
String will never be empty and you do not need to account for different data types. | ["def find_short(s):\n return min(len(x) for x in s.split())", "def find_short(s):\n return len(min(s.split(' '), key=len))", "def find_short(s):\n return min(map(len, s.split(' ')))", "def find_short(s):\n s = s.split() # splits the string into a list of individual words\n l = min(s, key = len) # finds ... | {"fn_name": "find_short", "inputs": [["bitcoin take over the world maybe who knows perhaps"], ["turns out random test cases are easier than writing out basic ones"], ["lets talk about javascript the best language"], ["i want to travel the world writing code one day"], ["Lets all go on holiday somewhere very cold"]], "o... | introductory | https://www.codewars.com/kata/57cebe1dc6fdc20c57000ac9 |
def find_short(s):
|
4,554 | # Letterss of Natac
In a game I just made up that doesn’t have anything to do with any other game that you may or may not have played, you collect resources on each turn and then use those resources to build things like roads, settlements and cities. If you would like to try other kata about this game, they can be foun... | ["from collections import Counter\n\ndef play_if_enough(hand, play):\n h = Counter(hand)\n p = Counter(play)\n if p&h == p:\n h.subtract(p)\n return (True, \"\".join(h.elements()))\n return (False, hand)", "from collections import Counter\n\ndef play_if_enough(hand, play):\n hand, play = Co... | {"fn_name": "play_if_enough", "inputs": [["", "bw"]], "outputs": [[[false, ""]]]} | introductory | https://www.codewars.com/kata/59e0069781618a7950000995 |
def play_if_enough(hand, play):
|
4,555 | # Do names have colors?
*Now they do.*
Make a function that takes in a name (Any string two chars or longer really, but the name is the idea) and use the ascii values of it's substrings to produce the hex value of its color! Here is how it's going to work:
* The first two hexadecimal digits are the *SUM* of the valu... | ["from operator import sub, mul\nfrom functools import reduce\n\ndef string_color(string):\n if len(string) < 2:\n return None\n r = sum(map(ord, list(string))) % 256\n g = reduce(mul, list(map(ord, list(string)))) % 256\n b = abs(reduce(sub, list(map(ord, list(string))))) % 256\n return '{:02X}{:... | {"fn_name": "string_color", "inputs": [["A"], [""], ["John Doe"], ["CodeWars"]], "outputs": [[null], [null], ["C70033"], ["182892"]]} | introductory | https://www.codewars.com/kata/5705c699cb729350870003b7 |
def string_color(name):
|
4,556 | Given a string of integers, count how many times that integer repeats itself, then return a string showing the count and the integer.
Example: `countMe('1123')` (`count_me` in Ruby)
- Here 1 comes twice so `` will be `"21"`
- then 2 comes once so `` will be `"12"`
- then 3 comes once so `` will be `"13"`
hence outp... | ["def count_me(data):\n if not data.isdigit():\n return ''\n \n result = []\n count = 1\n last = data[0]\n \n for char in data[1:]:\n if char == last:\n count += 1\n else:\n result.append(str(count) + last)\n last = char\n count = 1\n... | {"fn_name": "count_me", "inputs": [["1123"], ["1"], ["11"], ["a"], ["a123"], ["21"], ["1211"], ["12322212223443"], [""], ["123a"]], "outputs": [["211213"], ["11"], ["21"], [""], [""], ["1211"], ["111221"], ["111213321132132413"], [""], [""]]} | introductory | https://www.codewars.com/kata/559af787b4b8eac78b000022 |
def count_me(data):
|
4,557 | # Scenario
**_Several people_** are standing in *a row divided into two teams*.
The **_first person_** goes into **_team 1_**, **_the second_** goes into **_team 2_**, **_the third_** goes into **_team 1_**, and so on.
___
# Task
**_Given_** *an array of positive integers (the weights of the people)*, **_return_** ... | ["def row_weights(array):\n return sum(array[::2]), sum(array[1::2])\n", "def row_weights(array):\n evens = sum(i for index, i in enumerate(array) if index%2==0)\n return (evens, sum(array)-evens)", "row_weights = lambda arr: (sum(arr[::2]), sum(arr[1::2]))", "def row_weights(array):\n a = array[::2]\n b... | {"fn_name": "row_weights", "inputs": [[[80]], [[100, 50]], [[50, 60, 70, 80]], [[13, 27, 49]], [[70, 58, 75, 34, 91]], [[29, 83, 67, 53, 19, 28, 96]], [[0]], [[100, 51, 50, 100]], [[39, 84, 74, 18, 59, 72, 35, 61]], [[0, 1, 0]]], "outputs": [[[80, 0]], [[100, 50]], [[120, 140]], [[62, 27]], [[236, 92]], [[211, 164]], [... | introductory | https://www.codewars.com/kata/5abd66a5ccfd1130b30000a9 |
def row_weights(array):
|
4,558 | # Task
You are a lifelong fan of your local football club, and proud to say you rarely miss a game. Even though you're a superfan, you still hate boring games. Luckily, boring games often end in a draw, at which point the winner is determined by a penalty shoot-out, which brings some excitement to the viewing experienc... | ["def penaltyShots(shots, score):\n return (2 if shots > 4 else 5 - shots + 1) - abs(score[0] - score[1])\n", "def penaltyShots(shots, score):\n # coding and coding..\n if score[0] == score[1] ==0 and shots==0:\n return 6\n elif shots >= 5 and score[0] == score[1] != 0:\n return 2\n elif sh... | {"fn_name": "penaltyShots", "inputs": [[2, [1, 2]], [10, [10, 10]], [5, [5, 5]], [0, [0, 0]], [1, [0, 0]], [1, [0, 1]], [1, [1, 1]], [3, [3, 3]], [3, [1, 3]], [100, [100, 100]]], "outputs": [[3], [2], [2], [6], [5], [4], [5], [3], [1], [2]]} | introductory | https://www.codewars.com/kata/59073712f98c4718b5000022 |
def penaltyShots(shots, score):
|
4,559 | The [Ones' Complement](https://en.wikipedia.org/wiki/Ones%27_complement) of a binary number is the number obtained by swapping all the 0s for 1s and all the 1s for 0s. For example:
```
onesComplement(1001) = 0110
onesComplement(1001) = 0110
```
For any given binary number,formatted as a string, return the Ones' Compl... | ["def ones_complement(n):\n return n.translate(str.maketrans(\"01\",\"10\"))", "def ones_complement(binary_number):\n return binary_number.translate(str.maketrans('01', '10'))", "def ones_complement(binary_number):\n return \"\".join([ \"1\" if binary_number[x] == \"0\" else \"0\" for x in range(0, len(binary_nu... | {"fn_name": "ones_complement", "inputs": [["0"], ["1"], ["01"], ["10"], ["1101"]], "outputs": [["1"], ["0"], ["10"], ["01"], ["0010"]]} | introductory | https://www.codewars.com/kata/59b11f57f322e5da45000254 |
def ones_complement(binary_number):
|
4,560 | Mr. Khalkhoul, an amazing teacher, likes to answer questions sent by his students via e-mail, but he often doesn't have the time to answer all of them. In this kata you will help him by making a program that finds
some of the answers.
You are given a `question` which is a string containing the question and some `infor... | ["def answer(question, information):\n score, info = max((sum(word in info.lower().split() for word in question.lower().split()), info) for info in information)\n return None if not score else info\n", "import re\n\ndef answer(question, information):\n pattern = re.compile(r'\\b({})\\b'.format('|'.join(set(que... | {"fn_name": "answer", "inputs": [["is khalkhoul dumb", ["no he is NOT", "i guess so"]]], "outputs": [["no he is NOT"]]} | introductory | https://www.codewars.com/kata/59476f9d7325addc860000b9 |
def answer(question, information):
|
4,561 | Consider the string `"adfa"` and the following rules:
```Pearl
a) each character MUST be changed either to the one before or the one after in alphabet.
b) "a" can only be changed to "b" and "z" to "y".
```
From our string, we get:
```Pearl
"adfa" -> ["begb","beeb","bcgb","bceb"]
Another example: "bd" -> ["ae","ac","... | ["def solve(st):\n return all(True if ord(x) - ord(y) in [-2, 0, 2] else False for x, y in zip(st, st[::-1]))\n", "def solve(st):\n return all(abs(ord(x) - ord(y)) in {0, 2} for x, y in zip(st, st[::-1]))", "def solve(stg):\n return all(ord(x) - ord(y) in {-2, 0, 2} for x, y in zip(stg, stg[::-1]))", "solve=la... | {"fn_name": "solve", "inputs": [["abba"], ["abaazaba"], ["abccba"], ["adfa"], ["ae"], ["abzy"], ["ababbaba"], ["sq"], ["kxbkwgyydkcbtjcosgikfdyhuuprubpwthgflucpyylbofvqxkkvqthmdnywpaunfihvupbwpruwfybdmgeuocltdaidyyewmbzm"]], "outputs": [[true], [false], [true], [true], [false], [false], [true], [true], [true]]} | introductory | https://www.codewars.com/kata/5b7bd90ef643c4df7400015d |
def solve(st):
|
4,562 | Flash has invited his nemesis The Turtle (He actually was a real villain! ) to play his favourite card game, SNAP. In this game a 52 card deck is dealt out so both Flash and the Turtle get 26 random cards.
Each players cards will be represented by an array like below
Flash’s pile:
```[ 'A', '5', 'Q', 'Q', '6', '2', ... | ["def round(flash_pile, turtle_pile):\n faceup_pile = []\n while turtle_pile:\n for pile in flash_pile, turtle_pile:\n faceup_pile.append(pile.pop(0))\n if len(faceup_pile) >= 2 and faceup_pile[-1] == faceup_pile[-2]:\n flash_pile.extend(faceup_pile)\n re... | {"fn_name": "snap", "inputs": [[["3", "K", "5", "A", "5", "6", "7", "J", "7", "9", "10", "Q", "Q", "6", "8", "7", "4", "J", "8", "9", "K", "J", "10", "4", "K", "4"], ["2", "8", "9", "Q", "A", "K", "6", "3", "J", "2", "4", "3", "3", "8", "A", "2", "6", "7", "9", "10", "A", "5", "Q", "10", "2", "5"]], [["9", "5", "4", "4... | introductory | https://www.codewars.com/kata/5b49cc5a578c6ab6b200004c |
def snap(flash_pile, turtle_pile):
|
4,563 | Having two standards for a keypad layout is inconvenient!
Computer keypad's layout:
Cell phone keypad's layout:
Solve the horror of unstandartized keypads by providing a function that converts computer input to a number as if it was typed by a phone.
Example:
"789" -> "123"
Notes:
You get a string wit... | ["def computer_to_phone(numbers):\n return \"\".join([str({0:0, 1:7, 2:8, 3:9, 4:4, 5:5, 6:6, 7:1, 8:2, 9:3}[int(n)]) for n in numbers])", "def computer_to_phone(numbers):\n return numbers.translate(str.maketrans('123789', '789123'))", "tbl = str.maketrans('789456123', '123456789')\n\ndef computer_to_phone(numbers)... | {"fn_name": "computer_to_phone", "inputs": [["0789456123"], ["000"], ["94561"], [""], ["919"]], "outputs": [["0123456789"], ["000"], ["34567"], [""], ["373"]]} | introductory | https://www.codewars.com/kata/5572392fee5b0180480001ae |
def computer_to_phone(numbers):
|
4,564 | Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number.
Example:
```python
create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) # => returns "(123) 456-7890"
```
```f#
createPhoneNumber [1; 2; 3; 4; 5; 6; 7; 8; 9; 0] // => returns "... | ["def create_phone_number(n):\n return \"({}{}{}) {}{}{}-{}{}{}{}\".format(*n)", "def create_phone_number(n):\n n = ''.join(map(str,n))\n return '(%s) %s-%s'%(n[:3], n[3:6], n[6:])", "def create_phone_number(n):\n str1 = ''.join(str(x) for x in n[0:3])\n str2 = ''.join(str(x) for x in n[3:6])\n str3 = ''... | {"fn_name": "create_phone_number", "inputs": [[[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]], [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], [[0, 2, 3, 0, 5, 6, 0, 8, 9, 0]], [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]], "outputs": [["(123) 456-7890"], ["(111) 111-1111"], ["(023) 056-0890"], ["(000) 000-0000"]]} | introductory | https://www.codewars.com/kata/525f50e3b73515a6db000b83 |
def create_phone_number(n):
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.