problem_id int64 2.36k 5k | question stringlengths 52 14k | solutions stringlengths 79 675k | input_output stringlengths 37 505k | difficulty stringclasses 1
value | url stringlengths 36 94 | starter_code stringlengths 0 952 |
|---|---|---|---|---|---|---|
3,164 | Finish the solution so that it takes an input `n` (integer) and returns a string that is the decimal representation of the number grouped by commas after every 3 digits.
Assume: `0 <= n < 2147483647`
## Examples
```
1 -> "1"
10 -> "10"
100 -> "100"
1000 -> "... | ["def group_by_commas(n):\n return '{:,}'.format(n)", "group_by_commas=\"{:,}\".format\n", "def group_by_commas(n):\n return f'{n:,}'", "group_by_commas = lambda n:'{:,}'.format(n)", "def group_by_commas(n):\n n = [i for i in str(n)]\n for i in range(len(n) -4, -1, -3):\n n.insert(i+1, ',')\n retu... | {"fn_name": "group_by_commas", "inputs": [[1], [12], [123], [1234], [12345], [123456], [1234567], [12345678], [123456789], [1234567890]], "outputs": [["1"], ["12"], ["123"], ["1,234"], ["12,345"], ["123,456"], ["1,234,567"], ["12,345,678"], ["123,456,789"], ["1,234,567,890"]]} | introductory | https://www.codewars.com/kata/5274e122fc75c0943d000148 |
def group_by_commas(n):
|
3,165 | Introduction
It's been more than 20 minutes since the negligent waiter has taken your order for the house special prime tofu steak with a side of chili fries.
Out of boredom, you start fiddling around with the condiments tray. To be efficient, you want to be familiar with the choice of sauces and spices before your o... | ["from math import log2\n\ndef t(n):\n if n == 0:\n return 0\n k = int(log2(n))\n i = n - 2**k\n if i == 0:\n return (2**(2*k+1)+1) // 3\n else:\n return t(2**k) + 2*t(i) + t(i+1) - 1\n\ntoothpick = t", "from functools import lru_cache\n\nmsb = lru_cache(maxsize=None)(lambda n: 1 << ... | {"fn_name": "toothpick", "inputs": [[0], [3], [16], [32], [49], [89], [327], [363], [366], [512], [656], [1038], [1052], [1222], [1235], [1302], [1735], [1757], [1974], [2048]], "outputs": [[0], [7], [171], [683], [1215], [3715], [52239], [60195], [62063], [174763], [209095], [699451], [700379], [757295], [762019], [83... | introductory | https://www.codewars.com/kata/5c258f3c48925d030200014b |
def toothpick(n):
|
3,166 | # Task
Suppose there are `n` people standing in a circle and they are numbered 1 through n in order.
Person 1 starts off with a sword and kills person 2. He then passes the sword to the next person still standing, in this case person 3. Person 3 then uses the sword to kill person 4, and passes it to person 5. This... | ["def circle_slash(n):\n return int(bin(n)[3:]+'1', 2)", "from math import log\n\ndef circle_slash(n):\n return 2 * (n - 2 ** int(log(n, 2))) + 1", "from math import log2\ndef circle_slash(n):\n m = 2 ** int(log2(n))\n return n % m * 2 + 1", "def circle_slash(n):\n return int(\"{:b}\".format(n)[1:]+'1', 2)... | {"fn_name": "circle_slash", "inputs": [[5], [11], [1], [2], [3], [4], [8], [16], [15], [31]], "outputs": [[3], [7], [1], [1], [3], [1], [1], [1], [15], [31]]} | introductory | https://www.codewars.com/kata/58a6ac309b5762b7aa000030 |
def circle_slash(n):
|
3,167 | The objective is to return all pairs of integers from a given array of integers that have a difference of 2.
The result array should be sorted in ascending order of values.
Assume there are no duplicate integers in the array. The order of the integers in the input array should not matter.
## Examples
~~~if-not:pyth... | ["def twos_difference(a):\n s = set(a)\n return sorted((x, x + 2) for x in a if x + 2 in s)", "def twos_difference(lst): \n return [(num,num+2) for num in sorted(lst) if num+2 in lst] \n \n", "def twos_difference(arr):\n arr = sorted(arr)\n b = []\n for i in range(len(arr)):\n for... | {"fn_name": "twos_difference", "inputs": [[[1, 2, 3, 4]], [[1, 3, 4, 6]], [[0, 3, 1, 4]], [[4, 1, 2, 3]], [[6, 3, 4, 1, 5]], [[3, 1, 6, 4]], [[1, 3, 5, 6, 8, 10, 15, 32, 12, 14, 56]], [[1, 4, 7, 10]], [[]]], "outputs": [[[[1, 3], [2, 4]]], [[[1, 3], [4, 6]]], [[[1, 3]]], [[[1, 3], [2, 4]]], [[[1, 3], [3, 5], [4, 6]]], ... | introductory | https://www.codewars.com/kata/5340298112fa30e786000688 |
def twos_difference(lst):
|
3,168 | Pirates have notorious difficulty with enunciating. They tend to blur all the letters together and scream at people.
At long last, we need a way to unscramble what these pirates are saying.
Write a function that will accept a jumble of letters as well as a dictionary, and output a list of words that the pirate might ... | ["def grabscrab(said, possible_words):\n return [ word for word in possible_words if sorted(word) == sorted(said) ]", "from collections import Counter\n\ndef grabscrab(word, possible_words):\n ws = Counter(word)\n return [s for s in possible_words if Counter(s) == ws]", "def grabscrab(word, possible):\n sw ... | {"fn_name": "grabscrab", "inputs": [["trisf", ["first"]], ["oob", ["bob", "baobab"]], ["ainstuomn", ["mountains", "hills", "mesa"]], ["oolp", ["donkey", "pool", "horse", "loop"]], ["ortsp", ["sport", "parrot", "ports", "matey"]], ["ourf", ["one", "two", "three"]]], "outputs": [[["first"]], [[]], [["mountains"]], [["poo... | introductory | https://www.codewars.com/kata/52b305bec65ea40fe90007a7 |
def grabscrab(word, possible_words):
|
3,169 | We have the following sequence:
```python
f(0) = 0
f(1) = 1
f(2) = 1
f(3) = 2
f(4) = 4;
f(n) = f(n-1) + f(n-2) + f(n-3) + f(n-4) + f(n-5);
```
Your task is to give the number of total values for the odd terms of the sequence up to the n-th term (included). (The number n (of n-th term) will be given as a positive inte... | ["def count_odd_pentaFib(n):\n return 2 * (n // 6) + [0, 1, 2, 2, 2, 2][n % 6] - (n >= 2)", "buf = [0,1,1,2,4]\ndef count_odd_pentaFib(n):\n while len(buf)<=n:\n buf.append(sum(buf[-5:]))\n return len([i for i in set(buf[:n+1]) if i&1])\n", "def count_odd_pentaFib(n):\n if n == 0 :\n return 0\... | {"fn_name": "count_odd_pentaFib", "inputs": [[0], [1], [2]], "outputs": [[0], [1], [1]]} | introductory | https://www.codewars.com/kata/55c9172ee4bb15af9000005d |
def count_odd_pentaFib(n):
|
3,170 | Create a function `longer` that accepts a string and sorts the words in it based on their respective lengths in an ascending order. If there are two words of the same lengths, sort them alphabetically. Look at the examples below for more details.
```python
longer("Another Green World") => Green World Another
longer("D... | ["def longer(s):\n return ' '.join(sorted(s.split(), key=lambda w: (len(w), w)) )", "def longer(s):\n return ' '.join(sorted(s.split(' '),key = lambda x: (len(x),x)))", "def longer(s):\n return ' '.join(sorted(s.split(), key=lambda item: (len(item), item)))", "def longer(s): #or longer = lambda s: if you'... | {"fn_name": "longer", "inputs": [["Another Green World"], ["Darkness on the edge of Town"], ["Have you ever Seen the Rain"], ["Like a Rolling Stone"], ["This will be our Year"], ["hello Hello"]], "outputs": [["Green World Another"], ["of on the Town edge Darkness"], ["the you Have Rain Seen ever"], ["a Like Stone Rolli... | introductory | https://www.codewars.com/kata/5963314a51c68a26600000ae |
def longer(s):
|
3,171 | You are stacking some boxes containing gold weights on top of each other. If a box contains more weight than the box below it, it will crash downwards and combine their weights. e.g. If we stack [2] on top of [1], it will crash downwards and become a single box of weight [3]
```
[2]
[1] --> [3]
```
Given an array of ar... | ["from functools import reduce\n\ndef crashing_weights(weights):\n return reduce(lambda a, b: [a1 + b1 if a1 > b1 else b1 for a1, b1 in zip(a, b)], weights)", "def crashing_weights(weights):\n lst = [0] * len(weights[0])\n for line in weights:\n lst = [b if a <= b else a+b for a,b in zip(lst, line)]\n ... | {"fn_name": "crashing_weights", "inputs": [[[[1]]], [[[1, 2]]], [[[2], [1]]]], "outputs": [[[1]], [[1, 2]], [[3]]]} | introductory | https://www.codewars.com/kata/5a4a167ad8e1453a0b000050 |
def crashing_weights(weights):
|
3,172 | A chess position can be expressed as a string using the Forsyth–Edwards Notation (FEN). Your task is to write a parser that reads in a FEN-encoded string and returns a depiction of the board using the Unicode chess symbols (♔,♕,♘,etc.). The board should be drawn from the perspective of the active color (i.e. the side ... | ["from pprint import *\nuni= {'q': '\\u2655', 'B': '\\u265D', 'p': '\\u2659', 'K': '\\u265A',\n 'N': '\\u265E', 'Q': '\\u265B', 'P': '\\u265F', 'R': '\\u265C',\n 'n': '\\u2658', 'r': '\\u2656', 'b': '\\u2657', 'k': '\\u2654',\n 1:\"\\u2587\",0:\"\\uFF3F\"}\ndef parse_fen... | {"fn_name": "parse_fen", "inputs": [["8/8/8/8/8/8/8/8 w - -"], ["8/8/8/8/8/8/8/8 b - -"], ["k7/8/8/8/8/8/8/7K w - -"], ["k7/8/8/8/8/8/8/7K b - -"], ["rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"], ["7k/1p4rp/p2B4/3P1r2/1P6/8/P6P/R6K b - - 0 31"], ["r3kr2/1qp2ppp/p3p3/3nP3/1pB5/1P2P3/P4PPP/2RQ1RK1 b q - 2 1... | introductory | https://www.codewars.com/kata/56876fd23475fa415e000031 |
def parse_fen(string):
|
3,173 | ### Unfinished Loop - Bug Fixing #1
Oh no, Timmy's created an infinite loop! Help Timmy find and fix the bug in his unfinished for loop! | ["def create_array(n):\n res=[]\n i=1\n while i<=n:\n res+=[i]\n i+= 1\n return res", "def create_array(n):\n return [i for i in range(1,n+1)]", "create_array = lambda n: list(range(1,n+1))", "\ndef create_array(n):\n res = []\n i = 1\n while i <= n:\n res.append(i)\n ... | {"fn_name": "create_array", "inputs": [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]], "outputs": [[[1]], [[1, 2]], [[1, 2, 3]], [[1, 2, 3, 4]], [[1, 2, 3, 4, 5]], [[1, 2, 3, 4, 5, 6]], [[1, 2, 3, 4, 5, 6, 7]], [[1, 2, 3, 4, 5, 6, 7, 8]], [[1, 2, 3, 4, 5, 6, 7, 8, 9]], [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]]} | introductory | https://www.codewars.com/kata/55c28f7304e3eaebef0000da |
def create_array(n):
|
3,174 | Complete the function that calculates the derivative of a polynomial. A polynomial is an expression like: 3x^(4) - 2x^(2) + x - 10
### How to calculate the derivative:
* Take the exponent and multiply it with the coefficient
* Reduce the exponent by 1
For example: 3x^(4) --> (4*3)x^((4-1)) = 12x^(3)
### Good to kno... | ["import re\n\nmy_regexp = (r'(?P<sign>[+\\-]?)'\n r'(?P<coeff>\\d*)'\n r'x'\n r'(?:\\^(?P<exp>\\d+))?')\n\nas_int = lambda s: int(s) if s else 1\n\ndef derivative(eq):\n result = ''\n for monom in re.finditer(my_regexp, eq):\n sign, coeff, exp = monom.groups()\n ... | {"fn_name": "derivative", "inputs": [["4x+1"], ["-4x-1"], ["x^2+2x+1"], ["0"], ["-100"], ["-x^2+3x+4"], ["-x^5-x^4-x^3"], ["10x^9+10x^3+10x"], ["100x^5+12x^3-3x-3"], ["-1000x^7+200x^4+6x^2+x+1000"]], "outputs": [["4"], ["-4"], ["2x+2"], ["0"], ["0"], ["-2x+3"], ["-5x^4-4x^3-3x^2"], ["90x^8+30x^2+10"], ["500x^4+36x^2-3"... | introductory | https://www.codewars.com/kata/56d060d90f9408fb3b000b03 |
def derivative(eq):
|
3,175 | Write a function
```javascript
tripledouble(num1,num2)
```
```python
triple_double(num1, num2)
```
which takes numbers `num1` and `num2` and returns `1` if there is a straight triple of a number at any place in `num1` and also a straight double of the **same** number in `num2`.
If this isn't the case, return `0`
##... | ["def triple_double(num1, num2):\n return any([i * 3 in str(num1) and i * 2 in str(num2) for i in '0123456789'])", "def triple_double(num1, num2):\n for x in range(10):\n if str(x) * 3 in str(num1):\n if str(x) * 2 in str(num2):\n return 1\n return 0", "def triple_double(num1, ... | {"fn_name": "triple_double", "inputs": [[451999277, 41177722899], [1222345, 12345], [12345, 12345], [666789, 12345667], [10560002, 100], [1112, 122]], "outputs": [[1], [0], [0], [1], [1], [0]]} | introductory | https://www.codewars.com/kata/55d5434f269c0c3f1b000058 |
def triple_double(num1, num2):
|
3,176 | Implement `String#to_cents`, which should parse prices expressed as `$1.23` and return number of cents, or in case of bad format return `nil`. | ["import re\n\n\ndef to_cents(amount):\n m = re.match(r'\\$(\\d+)\\.(\\d\\d)\\Z', amount)\n return int(m.expand(r'\\1\\2')) if m else None\n", "from re import compile, match\n\nREGEX = compile(r'\\$(?P<integer>\\d+)\\.(?P<frac>\\d{0,2})$')\n\n\ndef to_cents(amount):\n m = match(REGEX, amount)\n if m and m.g... | {"fn_name": "to_cents", "inputs": [[""], ["1"], ["1.23"], ["$1"], ["$1.23"], ["$99.99"], ["$12345678.90"], ["$9.69"], ["$9.70"], ["$9.71"], ["$1.23\n"], ["\n$1.23"], ["$0.69"], ["$9.69$4.3.7"], ["$9.692"]], "outputs": [[null], [null], [null], [null], [123], [9999], [1234567890], [969], [970], [971], [null], [null], [69... | introductory | https://www.codewars.com/kata/56833b76371e86f8b6000015 |
def to_cents(amount):
|
3,177 | A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward. Examples of numerical palindromes are: `2332, 110011, 54322345`
For a given number ```num```, write a function which returns an array of all the numerical palindromes contained within each number. The arra... | ["def palindrome(num):\n if not isinstance(num, int) or num < 0:\n return \"Not valid\"\n n = str(num)\n l = len(n)\n result = {int(n[i:j]) for i in range(l-1) for j in range(i+2, l+1) if int(n[i]) and n[i:j] == n[i:j][::-1]}\n return sorted(result) if result else \"No palindromes found\"\n", "pal... | {"fn_name": "palindrome", "inputs": [[2], [34322122], [10015885], [4444], [1002001], [141221001], [1551], [13598], ["ACCDDCCA"], ["1551"], [-4505]], "outputs": [["No palindromes found"], [[22, 212, 343, 22122]], [[88, 1001, 5885]], [[44, 444, 4444]], [[1002001]], [[22, 141, 1001, 1221]], [[55, 1551]], ["No palindromes ... | introductory | https://www.codewars.com/kata/58e2708f9bd67fee17000080 |
def palindrome(num):
|
3,178 | Our friendly friend Pete is really a nice person, but he tends to be rather... Inappropriate.
And possibly loud, if given enough ethanol and free rein, so we ask you to write a function that should take its not always "clean" speech and cover as much as possible of it, in order not to offend some more sensible spirits... | ["import re\n\nPATTERN = re.compile(r'(?P<first>(?:(?<=[.!?] )|^)\\w+)|(?P<other>\\w+)')\n\ndef pete_talk(speech,ok=[]):\n\n def watchYourMouth(m):\n w = (m.group(\"first\") or m.group(\"other\")).lower()\n if w not in ok and len(w) > 1: w = w[0] + '*'*(len(w)-2) + w[-1]\n if m.group(\"first\"):... | {"fn_name": "pete_talk", "inputs": [["I want to punch someone in the face"], ["uh!"], ["What the hell am I doing here? And where is my wallet? PETE SMASH!"], ["I want to punch someone in the face", ["someone", "face"]], ["I want to punch someone in the face", ["drink", "job", "girls"]]], "outputs": [["I w**t to p***h s... | introductory | https://www.codewars.com/kata/571d0c80eed4a1c850000ef2 |
def pete_talk(speech, ok = []):
|
3,179 | # Task
You are given three integers `l, d and x`. Your task is:
```
• determine the minimal integer n
such that l ≤ n ≤ d, and the sum of its digits equals x.
• determine the maximal integer m
such that l ≤ m ≤ d, and the sum of its digits equals x.
```
It is guaranteed that such numbers always exist.
# Inp... | ["def min_and_max(l, d, x):\n listOfCorect = [num for num in list(range(l,d+1)) if sum(map(int,str(num))) == x] \n return [min(listOfCorect), max(listOfCorect)]", "def min_and_max(l, d, x):\n for n in range(l, d+1):\n if sum(map(int, str(n))) == x: break\n \n for m in range(d, l-1, -1):\n ... | {"fn_name": "min_and_max", "inputs": [[100, 200, 10], [123, 456, 5], [99, 501, 5], [99, 234, 1], [99, 234, 19], [99, 5001, 27], [99, 5001, 28], [2000, 7000, 3]], "outputs": [[[109, 190]], [[131, 410]], [[104, 500]], [[100, 100]], [[199, 199]], [[999, 4995]], [[1999, 4996]], [[2001, 3000]]]} | introductory | https://www.codewars.com/kata/58fd52b59a9f65c398000096 |
def min_and_max(l, d, x):
|
3,180 | Bleatrix Trotter the sheep has devised a strategy that helps her fall asleep faster. First, she picks a number N. Then she starts naming N, 2 × N, 3 × N, and so on.
Whenever she names a number, she thinks about all of the digits in that number. She keeps track of which digits (0, 1, 2, 3, 4, 5, 6, 7, 8, and 9) she has ... | ["def trotter(n):\n i, numStr, numList =0,'',['0','1','2','3','4','5','6','7','8','9']\n if n==0:\n return('INSOMNIA')\n while all([i in numStr for i in numList])!=True:\n i+=1\n numStr = numStr+str(n*i)\n return(i*n)", "def trotter(k):\n if k == 0:\n return \"INSOMNIA\"\n ... | {"fn_name": "trotter", "inputs": [[1692], [2], [7], [100], [1], [11], [163444], [206929], [459923], [691520], [0], [12500], [1250000]], "outputs": [[5076], [90], [70], [900], [10], [110], [653776], [620787], [4139307], [2074560], ["INSOMNIA"], [900000], [90000000]]} | introductory | https://www.codewars.com/kata/59245b3c794d54b06600002a |
def trotter(n):
|
3,181 | ## If/else syntax debug
While making a game, your partner, Greg, decided to create a function to check if the user is still alive called `checkAlive`/`CheckAlive`/`check_alive`. Unfortunately, Greg made some errors while creating the function.
`checkAlive`/`CheckAlive`/`check_alive` should return true if the player's... | ["def check_alive(health):\n if health <= 0:\n return False\n else:\n return True\n \nprint(check_alive(0))", "def check_alive(health):\n if health <= 0:\n return False\n else:\n return True", "def check_alive(health: int):\n return health > 0", "def check_alive(health):\n ... | {"fn_name": "check_alive", "inputs": [[5], [0], [-5]], "outputs": [[true], [false], [false]]} | introductory | https://www.codewars.com/kata/57089707fe2d01529f00024a |
def check_alive(health):
|
3,182 | Looking at consecutive powers of `2`, starting with `2^1`:
`2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, ...`
Note that out of all the digits `0-9`, the last one ever to appear is `7`. It only shows up for the first time in the number `32768 (= 2^15)`.
So let us define LAST DIGIT TO APPE... | ["digits = lambda x: set(str(x))\n\ndef LDTA(n):\n if digits(n) == digits(n*n):\n return None\n \n seen = []\n x = n\n \n while len(seen) < 10:\n for d in str(x):\n if d not in seen:\n seen.append(d)\n x *= n\n \n return int(seen[-1])", "def LDT... | {"fn_name": "LDTA", "inputs": [[100], [2], [3], [8], [1111], [3000]], "outputs": [[null], [7], [0], [7], [9], [5]]} | introductory | https://www.codewars.com/kata/5ccfcfad7306d900269da53f |
def LDTA(n):
|
3,183 | Task
======
Make a custom esolang interpreter for the language [InfiniTick](https://esolangs.org/wiki/InfiniTick). InfiniTick is a descendant of [Tick](https://esolangs.org/wiki/tick) but also very different. Unlike Tick, InfiniTick has 8 commands instead of 4. It also runs infinitely, stopping the program only when a... | ["def interpreter(tape):\n memory, ptr, output, iCmd = {}, 0, \"\", 0\n \n while True:\n cmd = tape[iCmd]\n if cmd == \">\": ptr += 1\n elif cmd == \"<\": ptr -= 1\n elif cmd == \"+\": memory[ptr] = (memory.get(ptr, 0) + 1) % 256\n elif cmd == \"-\": memory[ptr] = (memo... | {"fn_name": "interpreter", "inputs": [["\\h*&"], ["+-*&"]], "outputs": [["\u0000"], ["\u0000"]]} | introductory | https://www.codewars.com/kata/58817056e7a31c2ceb000052 |
def interpreter(tape):
|
3,184 | Sam has opened a new sushi train restaurant - a restaurant where sushi is served on plates that travel around the bar on a conveyor belt and customers take the plate that they like.
Sam is using Glamazon's new visual recognition technology that allows a computer to record the number of plates at a customer's table and... | ["def total_bill(s):\n return 2*(s.count(\"r\") - s.count(\"r\")//5)", "def total_bill(s):\n num = s.count('r') \n return (num-num//5)*2", "def total_bill(s):\n s = s.replace(\" \",\"\")\n return 2 * (len(s)-len(s)//5)", "def total_bill(s):\n return (s.count('r') - s.count('r') // 5) * 2", "def total_... | {"fn_name": "total_bill", "inputs": [["rr"], ["rr rrr"], ["rr rrr rrr rr"], ["rrrrrrrrrrrrrrrrrr rr r"], [""]], "outputs": [[4], [8], [16], [34], [0]]} | introductory | https://www.codewars.com/kata/59619e4609868dd923000041 |
def total_bill(s):
|
3,185 | In this kata your mission is to rotate matrix counter - clockwise N-times.
So, you will have 2 inputs:
1)matrix
2)a number, how many times to turn it
And an output is turned matrix.
Example:
matrix = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, ... | ["def ccw(matrix):\n return [list(row) for row in zip(*map(reversed, matrix))]\n\ndef rotate_against_clockwise(matrix, times):\n for __ in range(times % 4):\n matrix = ccw(matrix)\n return matrix", "import numpy as np\n\ndef rotate_against_clockwise(matrix, times):\n return np.rot90(matrix, times).to... | {"fn_name": "rotate_against_clockwise", "inputs": [[[[1, 2], [3, 4]], 1], [[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 1], [[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], 2], [[[1, 2, 3, 4, 5, 6, 7, 8], [9, 10, 11, 12, 13, 14, 15, 16], [17, 18, 19, 20, 21, 22, 23, 24], [25, 26, 27... | introductory | https://www.codewars.com/kata/5919f3bf6589022915000023 |
def rotate_against_clockwise(matrix, times):
|
3,186 | # Task
Your task is to find the similarity of given sorted arrays `a` and `b`, which is defined as follows:
you take the number of elements which are present in both arrays and divide it by the number of elements which are present in at least one array.
It also can be written as a formula `similarity(A, B) = #(A... | ["def similarity(a, b):\n try:\n return len(set(a) & set(b)) / len(set(a) | set(b))\n except:\n return 0", "def similarity(*args):\n a,b = map(set, args)\n return len(a&b) / len(a|b)", "def similarity(a, b):\n c = a + b\n lst1 = []\n lst2 = []\n for i in set(c):\n if c.count... | {"fn_name": "similarity", "inputs": [[[1, 2, 3], [1, 2, 3]], [[1, 2, 3], [4, 5, 6]], [[1, 2, 4, 6, 7], [2, 3, 4, 7]], [[1, 2, 6, 8, 9], [0, 1, 4, 5, 6, 8, 9]], [[0, 1, 3, 4, 5, 6, 9, 14, 15, 16, 17, 18, 19], [1, 4, 10, 12, 13, 14, 15, 16]]], "outputs": [[1], [0], [0.5], [0.5], [0.3125]]} | introductory | https://www.codewars.com/kata/58a6841442fd72aeb4000080 |
def similarity(a, b):
|
3,187 | Implement a function to calculate the sum of the numerical values in a nested list. For example :
```python
sum_nested([1, [2, [3, [4]]]]) -> 10
``` | ["def sum_nested(lst):\n return sum(sum_nested(x) if isinstance(x,list) else x for x in lst)", "def sum_nested(lst):\n total = 0\n for ele in lst:\n total += ele if type(ele) != list else sum_nested(ele)\n \n return total", "import re\n\ndef sum_nested(lst):\n return sum(map(int, re.findall... | {"fn_name": "sum_nested", "inputs": [[[1]], [[1, 2, 3, 4]], [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]], [[]], [[[1], []]], [[[1, 2, 3, 4]]], [[[], []]], [[1, [1], [[1]], [[[1]]]]], [[1, [1], [1, [1]], [1, [1], [1, [1]]]]], [[[[[], [], [[[[[[[[[[]]]]]]]]]]], [], [], [[[], [[]]]]], []]]], "outputs": [[1], [10], [55], [0], [1],... | introductory | https://www.codewars.com/kata/5a15a4db06d5b6d33c000018 |
def sum_nested(lst):
|
3,188 | # Base reduction
## Input
A positive integer:
```
0 < n < 1000000000
```
## Output
The end result of the base reduction.
If it cannot be fully reduced (reduced down to a single-digit number), return -1.
Assume that if 150 conversions from base 11 take place in a row, the number cannot be fully reduced.
## Descri... | ["def basereduct(x):\n for _ in range(150):\n x = int(str(x), int(max(str(x))) + 1 + ('9' in str(x)))\n if x < 10: return x\n return -1", "def basereduct(x):\n limit = x * 1000000\n while x >= 10 and x <= limit:\n s = str(x)\n base = int(max(s)) + 1\n x = int(s, 11 if base... | {"fn_name": "basereduct", "inputs": [[10], [5], [7], [7], [15]], "outputs": [[2], [5], [7], [7], [3]]}
| introductory | https://www.codewars.com/kata/5840e31f770be1636e0000d3 |
def basereduct(x):
|
3,189 | The Story:
Aliens from Kepler 27b have immigrated to Earth! They have learned English and go to our stores, eat our food, dress like us, ride Ubers, use Google, etc. However, they speak English a little differently. Can you write a program that converts our English to their Alien English?
Task:
Write a function conve... | ["def convert(st):\n return st.replace('o','u').replace('a','o')", "def convert(s):\n return s.translate(str.maketrans('ao', 'ou'))", "def convert(st):\n return st.translate(str.maketrans('ao','ou'))", "def convert(st):\n return st.translate(str.maketrans('oa', 'uo'))", "def convert(stg):\n alien = str.m... | {"fn_name": "convert", "inputs": [["codewars"], ["hello"]], "outputs": [["cudewors"], ["hellu"]]} | introductory | https://www.codewars.com/kata/5874657211d7d6176a00012f |
def convert(st):
|
3,190 | Consider the number `1176` and its square (`1176 * 1176) = 1382976`. Notice that:
* the first two digits of `1176` form a prime.
* the first two digits of the square `1382976` also form a prime.
* the last two digits of `1176` and `1382976` are the same.
Given two numbers representing a range (`a, b`), how many numb... | ["ls = ['11', '13', '17', '19', '23', '29', '31', '37', '41', '43', '47', '53', '59', '61', '67', '71', '73', '79', '83', '89', '97']\ndef solve(a,b):\n i = a\n s = 0\n while i < b:\n if (i*i-i)%100==0 and str(i)[:2] in ls and str(i*i)[:2] in ls:\n s += 1\n i += 1\n return s", "from... | {"fn_name": "solve", "inputs": [[2, 1200], [1176, 1200], [2, 100000], [2, 1000000], [100000, 1000000]], "outputs": [[1], [1], [247], [2549], [2302]]} | introductory | https://www.codewars.com/kata/59a9466f589d2af4c50001d8 |
def solve(a,b):
|
3,191 | # Introduction
Digital Cypher assigns to each letter of the alphabet unique number. For example:
```
a b c d e f g h i j k l m
1 2 3 4 5 6 7 8 9 10 11 12 13
n o p q r s t u v w x y z
14 15 16 17 18 19 20 21 22 23 24 25 26
```
Instead of letters in encrypted word we write the corre... | ["from itertools import cycle\nfrom string import ascii_lowercase\n\ndef decode(code, key):\n keys = cycle(map(int, str(key)))\n return ''.join(ascii_lowercase[n - next(keys) - 1] for n in code)", "def decode(code, key):\n key=str(key)\n return \"\".join([chr(code[i] +96 - int(key[i%len(key)])) for i in r... | {"fn_name": "decode", "inputs": [[[20, 12, 18, 30, 21], 1939], [[14, 10, 22, 29, 6, 27, 19, 18, 6, 12, 8], 1939]], "outputs": [["scout"], ["masterpiece"]]} | introductory | https://www.codewars.com/kata/592edfda5be407b9640000b2 |
def decode(code, key):
|
3,192 | Your friend has been out shopping for puppies (what a time to be alive!)... He arrives back with multiple dogs, and you simply do not know how to respond!
By repairing the function provided, you will find out exactly how you should respond, depending on the number of dogs he has.
The number of dogs will always be a n... | ["def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Woah that's a lot of dogs!\", \"101 DALMATIONS!!!\"]\n return dogs[0] if n <= 10 else dogs[1] if n <=50 else dogs[3] if n == 101 else dogs[2]", "def how_many_dalmatians(n):\n dogs = [\"Hardly any\", \"More than a handful!\", \"Wo... | {"fn_name": "how_many_dalmatians", "inputs": [[26], [8], [14], [80], [100], [50], [10], [101]], "outputs": [["More than a handful!"], ["Hardly any"], ["More than a handful!"], ["Woah that's a lot of dogs!"], ["Woah that's a lot of dogs!"], ["More than a handful!"], ["Hardly any"], ["101 DALMATIONS!!!"]]} | introductory | https://www.codewars.com/kata/56f6919a6b88de18ff000b36 |
def how_many_dalmatians(n):
|
3,193 | Raj was to move up through a pattern of stairs of a given number **(n)**. Help him to get to the top using the function **stairs**.
##Keep in mind :
* If **n<1** then return ' ' .
* There are a lot of spaces before the stair starts except for **pattern(1)**
##Examples :
pattern(1)
1 1
pattern(... | ["def stairs(n):\n return \"\\n\".join(step(i).rjust(4 * n - 1) for i in range(1, n+1))\n\n\ndef step(n):\n h = \" \".join(str(i % 10) for i in range(1, n+1))\n return f\"{h} {h[::-1]}\"", "from itertools import chain\n\ndef stairs(n):\n if n < 1:\n return \" \"\n w = 4 * n - 1\n xs = [str(i % ... | {"fn_name": "stairs", "inputs": [[3], [7], [10], [16]], "outputs": [[" 1 1\n 1 2 2 1\n1 2 3 3 2 1"], [" 1 1\n 1 2 2 1\n 1 2 3 3 2 1\n 1 2 3 4 4 3 2 1\n 1 2 3 4 5 5 4 3 2 1\n 1 2 3 4 5 6 6 5 4 3 2 1\n1 2 3 4 5 6 7 7 6 5 4 3 2 1"], ["... | introductory | https://www.codewars.com/kata/566c3f5b9de85fdd0e000026 |
def stairs(n):
|
3,194 | In case you might be unlucky enough not to know the best dark fantasy franchise ever, Berserk tells the story of a man that, hating gratuitous violence, decided to become a mercenary (thus one who sells violence, no gratuity anymore!) and starts an epic struggle against apparently unsormountable odds, unsure if he real... | ["def berserk_rater(synopsis):\n n = sum([score(s.upper()) for s in synopsis])\n return 'worstest episode ever' if n < 0 else 'bestest episode ever' if n > 10 else str(n)\n \ndef score(s):\n return 5 if 'CLANG' in s else -2 if 'CG' in s else -1", "import re\n\nCG = re.compile(r\"\\bcg\\b\", flags=re.I)\nCLA... | {"fn_name": "berserk_rater", "inputs": [[["is this the CG from a P2 game?", "Hell, no! Even the CG in the Dreamcast game was more fluid than this!", "Well, at least Gatsu does his clang even against a mere rabbit", "Hey, Cosette was not in this part of the story!", "Ops, everybody dead again! Well, how boring..."]], [[... | introductory | https://www.codewars.com/kata/57fa3a33e8c829780a0001d2 |
def berserk_rater(synopsis):
|
3,195 | Write a function that checks the braces status in a string, and return `True` if all braces are properly closed, or `False` otherwise. Available types of brackets: `()`, `[]`, `{}`.
**Please note, you need to write this function without using regex!**
## Examples
```python
'([[some](){text}here]...)' => True
'{([])... | ["brackets = {\"}\":\"{\",\"]\":\"[\",\")\":\"(\"}\n\ndef braces_status(s):\n stack = []\n \n for c in s:\n if c in \"[({\":\n stack.append(c)\n elif c in \"])}\":\n if not stack or stack.pop() != brackets[c]:\n return False\n \n return not stack", "def ... | {"fn_name": "braces_status", "inputs": [["[()]"], ["{[]}"], ["{[()]}"], ["([)]"], ["([[some](){text}here]...)"], ["}"], ["[()]]"], ["[()]{("], ["()[]{}()"], ["[[[["]], "outputs": [[true], [true], [true], [false], [true], [false], [false], [false], [true], [false]]} | introductory | https://www.codewars.com/kata/58983deb128a54b530000be6 |
def braces_status(s):
|
3,196 | Triangular numbers count the number of objects that can form an equilateral triangle. The nth triangular number forms an equilateral triangle with n dots on each side (including the vertices).
Here is a graphic example for the triangular numbers of 1 to 5:
```
n=1: triangular number: 1
*
n=2: triangular number: 3
*
*... | ["def triangular_range(start, stop):\n return {i:i*(i+1)/2 for i in range(stop) if start <= i*(i+1)/2 <= stop}\n", "from math import ceil\n\ndef root(n): return ((1+8*n)**.5-1)/2\n\ndef triangular_range(s,e):\n return {i: -~i*i>>1 for i in range(ceil(root(s)), int(root(e))+1)}", "def triangular_range(start, stop)... | {"fn_name": "triangular_range", "inputs": [[1, 3], [5, 16]], "outputs": [[{"1": 1, "2": 3}], [{"3": 6, "4": 10, "5": 15}]]} | introductory | https://www.codewars.com/kata/5620dc848370b4ad750000a1 |
def triangular_range(start, stop):
|
3,197 | In Spanish, the conjugated verb changes by adding suffixes and according to the person we're talking about. There's something similar in English when we talk about "She", "He"or "It" (3rd person singular):
With the verb "run":
**He / She / It runS**
As you can see, the rule (at least with regular verbs) is to add t... | ["SUFFIXES = {'a': ['o', 'as', 'a', 'amos', 'ais', 'an'],\n 'e': ['o', 'es', 'e', 'emos', 'eis', 'en'],\n 'i': ['o', 'es', 'e', 'imos', 'is', 'en']}\n\ndef conjugate(verb):\n return {verb: [verb[:-2] + s for s in SUFFIXES[verb[-2]]]}", "def conjugate(verb):\n d = {'ar': ['o', 'as', 'a', 'am... | {"fn_name": "conjugate", "inputs": [["caminar"], ["comer"], ["vivir"]], "outputs": [[{"caminar": ["camino", "caminas", "camina", "caminamos", "caminais", "caminan"]}], [{"comer": ["como", "comes", "come", "comemos", "comeis", "comen"]}], [{"vivir": ["vivo", "vives", "vive", "vivimos", "vivis", "viven"]}]]} | introductory | https://www.codewars.com/kata/5a81b78d4a6b344638000183 |
def conjugate(verb):
|
3,198 | The first input array is the key to the correct answers to an exam, like ["a", "a", "b", "d"]. The second one contains a student's submitted answers.
The two arrays are not empty and are the same length. Return the score for this array of answers, giving +4 for each correct answer, -1 for each incorrect answer, and +... | ["def check_exam(arr1, arr2):\n return max(0, sum(4 if a == b else -1 for a, b in zip(arr1, arr2) if b))", "def check_exam(arr1,arr2):\n score = 0\n for i in range(0,4):\n if arr1[i] == arr2[i]:\n score += 4\n elif arr1[i] == \"\" or arr2[i] == \"\":\n score += 0\n el... | {"fn_name": "check_exam", "inputs": [[["a", "a", "b", "b"], ["a", "c", "b", "d"]], [["a", "a", "c", "b"], ["a", "a", "b", ""]], [["a", "a", "b", "c"], ["a", "a", "b", "c"]], [["b", "c", "b", "a"], ["", "a", "a", "c"]]], "outputs": [[6], [7], [16], [0]]} | introductory | https://www.codewars.com/kata/5a3dd29055519e23ec000074 |
def check_exam(arr1,arr2):
|
3,199 | Say hello!
Write a function to greet a person. Function will take name as input and greet the person by saying hello.
Return null/nil/None if input is empty string or null/nil/None.
Example:
```python
greet("Niks") --> "hello Niks!"
greet("") --> None # Return None if input is empty string
greet(None) --> None ... | ["def greet(name):\n return f\"hello {name}!\" if name else None", "def greet(name):\n if name:\n return f\"hello {name}!\"", "def greet(s):\n if s: return f\"hello {s}!\"", "def greet(name=None):\n return \"hello {}!\".format(name) if name else None\n", "def greet(n):\n if n:\n return f\"h... | {"fn_name": "greet", "inputs": [["Niks"], ["Nick"], [""], [null]], "outputs": [["hello Niks!"], ["hello Nick!"], [null], [null]]} | introductory | https://www.codewars.com/kata/55955a48a4e9c1a77500005a |
def greet(name):
|
3,200 | When you divide the successive powers of `10` by `13` you get the following remainders of the integer divisions:
`1, 10, 9, 12, 3, 4`.
Then the whole pattern repeats.
Hence the following method:
Multiply the right most digit of the number with the left most number
in the sequence shown above, the second right mo... | ["array = [1, 10, 9, 12, 3, 4]\n\ndef thirt(n):\n total = sum([int(c) * array[i % 6] for i, c in enumerate(reversed(str(n)))])\n if n == total:\n return total\n return thirt(total)\n", "import itertools as it\n\ndef thirt(n):\n if n < 100: return n\n \n pattern = it.cycle([1, 10, 9, 12, 3, 4])\... | {"fn_name": "thirt", "inputs": [[8529], [85299258], [5634], [1111111111], [987654321]], "outputs": [[79], [31], [57], [71], [30]]} | introductory | https://www.codewars.com/kata/564057bc348c7200bd0000ff |
def thirt(n):
|
3,201 | Write a regex to validate a 24 hours time string.
See examples to figure out what you should check for:
Accepted:
01:00 - 1:00
Not accepted:
24:00
You should check for correct length and no spaces. | ["import re\n\n_24H = re.compile(r'^([01]?\\d|2[0-3]):[0-5]\\d$')\n\nvalidate_time = lambda time: bool(_24H.match(time))\n", "import re\n\n\ndef validate_time(timestamp):\n return bool(re.match(r'(2[0-3]|[01]?\\d):[0-5]\\d$', timestamp))\n", "import re\ndef validate_time(time):\n return bool(re.match('^[0-1]?[0-9... | {"fn_name": "validate_time", "inputs": [["1:00"], ["13:1"], ["12:60"], ["12: 60"], ["24:00"], ["00:00"], ["24o:00"], ["24:000"], [""], ["09:00"], ["2400"], ["foo12:00bar"], ["010:00"], ["1;00"]], "outputs": [[true], [false], [false], [false], [false], [true], [false], [false], [false], [true], [false], [false], [false]... | introductory | https://www.codewars.com/kata/56a4a3d4043c316002000042 |
def validate_time(time):
|
3,202 | # Personalized greeting
Create a function that gives a personalized greeting. This function takes two parameters: `name` and `owner`.
Use conditionals to return the proper message:
case | return
--- | ---
name equals owner | 'Hello boss'
otherwise | 'Hello guest' | ["def greet(name, owner):\n return \"Hello boss\" if name == owner else \"Hello guest\"", "def greet(name, owner):\n return \"Hello {}\".format(\"boss\" if name == owner else \"guest\")", "def greet(name, owner):\n return f\"Hello {'boss' if name == owner else 'guest'}\"", "def greet(name, owner):\n if name... | {"fn_name": "greet", "inputs": [["Daniel", "Daniel"], ["Greg", "Daniel"]], "outputs": [["Hello boss"], ["Hello guest"]]} | introductory | https://www.codewars.com/kata/5772da22b89313a4d50012f7 |
def greet(name, owner):
|
3,203 | Implement `String#parse_mana_cost`, which parses [Magic: the Gathering mana costs](http://mtgsalvation.gamepedia.com/Mana_cost) expressed as a string and returns a `Hash` with keys being kinds of mana, and values being the numbers.
Don't include any mana types equal to zero.
Format is:
* optionally natural number re... | ["\nimport re\ndef parse_mana_cost(mana):\n n={c:mana.lower().count(c) for c in 'wubrg' if mana.lower().count(c)>0}\n m=re.split(r'\\D',mana) \n if sum(n.values())+sum([len(c) for c in m]) != len(mana): return None\n p = sum([int(c) for c in m if c!=''])\n if p>0: n['*']=p\n return n\n", "import re\... | {"fn_name": "parse_mana_cost", "inputs": [[""], ["0"], ["1"], ["4"], ["15"], ["2rr"], ["1wbg"], ["1WWU"], ["0r"], ["2x"], ["2R"], ["2\n"], ["\n2"], ["1b"], ["1bb"], ["1bbb"], ["1bg"], ["1bgu"], ["1br"], ["1brg"], ["1g"], ["1gg"], ["1ggg"], ["1ggu"], ["1ggw"], ["1gu"], ["1guu"], ["1gw"], ["1gwu"], ["1gww"], ["1r"], ["1r... | introductory | https://www.codewars.com/kata/5686004a2c7fade6b500002d |
def parse_mana_cost(mana):
|
3,204 | # Let's play Psychic
A box contains green, red, and blue balls. The total number of balls is given by `n` (`0 < n < 50`).
Each ball has a mass that depends on the ball color. Green balls weigh `5kg`, red balls weigh `4kg`, and blue balls weigh `3kg`.
Given the total number of balls in the box, `n`, and a total mass... | ["def Guess_it(n,m):\n result = []\n for x in range(0,n+1):\n b, r, g = 4 * n + x - m, m - 3 * n - 2 * x, x\n if all(y >= 0 for y in (b,r,g)):\n result.append([g,r,b])\n return result\n\n", "def Guess_it(n,m):\n\n def get_sum_balls(a, b, c): return sum([a,b,c])\n def get_sum_mass... | {"fn_name": "Guess_it", "inputs": [[3, 12], [40, 180], [30, 130], [32, 148], [18, 80], [18, 74], [50, 180], [50, 172]], "outputs": [[[[0, 3, 0], [1, 1, 1]]], [[[20, 20, 0], [21, 18, 1], [22, 16, 2], [23, 14, 3], [24, 12, 4], [25, 10, 5], [26, 8, 6], [27, 6, 7], [28, 4, 8], [29, 2, 9], [30, 0, 10]]], [[[10, 20, 0], [11,... | introductory | https://www.codewars.com/kata/55b2d9bd2d3e974dfb000030 |
def Guess_it(n,m):
|
3,205 | Create a function that checks if a number `n` is divisible by two numbers `x` **AND** `y`. All inputs are positive, non-zero digits.
```JS
Examples:
1) n = 3, x = 1, y = 3 => true because 3 is divisible by 1 and 3
2) n = 12, x = 2, y = 6 => true because 12 is divisible by 2 and 6
3) n = 100, x = 5, y = 3 => fa... | ["def is_divisible(n,x,y):\n return n % x == 0 and n % y == 0", "def is_divisible(n, x, y):\n return n % x == n % y == 0", "def is_divisible(n,x,y):\n #your code here\n if n % x == 0 and n % y == 0:\n return True\n else:\n return False", "def is_divisible(n, x, y):\n return not n % x and... | {"fn_name": "is_divisible", "inputs": [[3, 2, 2], [3, 3, 4], [12, 3, 4], [8, 3, 4], [48, 3, 4], [100, 5, 10], [100, 5, 3], [4, 4, 2], [5, 2, 3], [17, 17, 17], [17, 1, 17]], "outputs": [[false], [false], [true], [false], [true], [true], [false], [true], [false], [true], [true]]} | introductory | https://www.codewars.com/kata/5545f109004975ea66000086 |
def is_divisible(n,x,y):
|
3,206 | Write a function that takes as its parameters *one or more numbers which are the diameters of circles.*
The function should return the *total area of all the circles*, rounded to the nearest integer in a string that says "We have this much circle: xyz".
You don't know how many circles you will be given, but you can... | ["import math\n\ndef sum_circles(*args):\n t = round(sum([math.pi * (d**2) / 4 for d in args]))\n return 'We have this much circle: {}'.format(int(t))", "from math import pi\n\ndef sum_circles(*args):\n return \"We have this much circle: %.0f\" % sum([(d/2.0)**2 * pi for d in args])", "from math import pi\n\nd... | {"fn_name": "sum_circles", "inputs": [[48, 7, 8, 9, 10], [1], [1, 1, 1, 2, 3, 4, 5], [894, 5778, 4839, 476], [4.5456, 746.5, 98.34, 344.543], [1, 1, 1], [13.58, 14.9, 56.99, 107.321], [56894.04839, 843975.4839, 4.08437403489], [5, 6, 7, 8, 9, 10, 105083, 48839, 4853, 28, 483]], "outputs": [["We have this much circle: 2... | introductory | https://www.codewars.com/kata/56143efa9d32b3aa65000016 |
def sum_circles(*args):
|
3,207 | Complete the solution so that it reverses all of the words within the string passed in.
Example:
```python
reverseWords("The greatest victory is that which requires no battle")
// should return "battle no requires which that is victory greatest The"
``` | ["def reverseWords(str):\n return \" \".join(str.split(\" \")[::-1])", "def reverseWords(str):\n return ' '.join(reversed(str.split(' ')))", "def reverseWords(string):\n return ' '.join(reversed(string.split()))", "def reverseWords(str):\n k = str.split(' ')\n k.reverse()\n str = ' '.join(k)\n retu... | {"fn_name": "reverseWords", "inputs": [["hello world!"]], "outputs": [["world! hello"]]} | introductory | https://www.codewars.com/kata/51c8991dee245d7ddf00000e |
def reverseWords(s):
|
3,208 | There is a queue for the self-checkout tills at the supermarket. Your task is write a function to calculate the total time required for all the customers to check out!
### input
```if-not:c
* customers: an array of positive integers representing the queue. Each integer represents a customer, and its value is the amoun... | ["def queue_time(customers, n):\n l=[0]*n\n for i in customers:\n l[l.index(min(l))]+=i\n return max(l)", "import heapq\n\ndef queue_time(customers, n):\n heap = [0] * n\n for time in customers:\n heapq.heapreplace(heap, heap[0] + time)\n return max(heap)\n", "def queue_time(customers, n... | {"fn_name": "queue_time", "inputs": [[[], 1], [[5], 1], [[2], 5], [[1, 2, 3, 4, 5], 1], [[1, 2, 3, 4, 5], 100], [[2, 2, 3, 3, 4, 4], 2]], "outputs": [[0], [5], [2], [15], [5], [9]]} | introductory | https://www.codewars.com/kata/57b06f90e298a7b53d000a86 |
def queue_time(customers, n):
|
3,209 | # Problem
In China,there is an ancient mathematical book, called "The Mathematical Classic of Sun Zi"(《孙子算经》). In the book, there is a classic math problem: “今有物不知其数,三三数之剩二,五五数之剩三,七七数之剩二,问物几何?”
Ahh, Sorry. I forgot that you don't know Chinese. Let's translate it to English:
There is a unkown positive integer `n`. W... | ["def find_unknown_number(x,y,z): \n return (x*70 + y*21 + z*15) % 105 or 105", "def find_unknown_number(x,y,z):\n for i in range(1,1000):\n if i%3 == x and i%5 == y and i%7 == z:\n return i", "def find_unknown_number(x,y,z):\n return min(set(range(x or 3, 106, 3)) & set(range(y or 5, ... | {"fn_name": "find_unknown_number", "inputs": [[2, 3, 2], [1, 2, 3], [1, 3, 5], [0, 0, 0], [1, 1, 1]], "outputs": [[23], [52], [103], [105], [1]]} | introductory | https://www.codewars.com/kata/59cdb2b3a25c8c6d56000005 |
def find_unknown_number(x,y,z):
|
3,210 | You receive the name of a city as a string, and you need to return a string that shows how many times each letter shows up in the string by using an asterisk (`*`).
For example:
```
"Chicago" --> "c:**,h:*,i:*,a:*,g:*,o:*"
```
As you can see, the letter `c` is shown only once, but with 2 asterisks.
The return str... | ["from collections import Counter\n\n\ndef get_strings(city):\n return \",\".join(f\"{char}:{'*'*count}\" for char, count in Counter(city.replace(\" \", \"\").lower()).items())", "from collections import Counter\n\n\ndef get_strings(city):\n return \",\".join(\n f\"{char}:{'*'*count}\"\n for char, c... | {"fn_name": "get_strings", "inputs": [["Chicago"], ["Bangkok"], ["Las Vegas"], ["Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch"]], "outputs": [["c:**,h:*,i:*,a:*,g:*,o:*"], ["b:*,a:*,n:*,g:*,k:**,o:*"], ["l:*,a:**,s:**,v:*,e:*,g:*"], ["l:***********,a:***,n:****,f:*,i:***,r:****,p:*,w:****,g:*******,y:****... | introductory | https://www.codewars.com/kata/5b358a1e228d316283001892 |
def get_strings(city):
|
3,211 | # It's too hot, and they can't even…
One hot summer day Pete and his friend Billy decided to buy watermelons. They chose the biggest crate. They rushed home, dying of thirst, and decided to divide their loot, however they faced a hard problem.
Pete and Billy are great fans of even numbers, that's why they want to div... | ["def divide(weight):\n return weight > 2 and weight % 2 == 0", "def divide(weight):\n return weight % 2 == 0 and weight > 2", "divide=lambda weight: weight%2==0 and weight>2", "def divide(weight):\n if weight % 2 == 0 and weight > 2: \n return True\n else:\n return False", "def divide(w): ret... | {"fn_name": "divide", "inputs": [[4], [2], [5], [88], [100], [67], [90], [10], [99], [32]], "outputs": [[true], [false], [false], [true], [true], [false], [true], [true], [false], [true]]} | introductory | https://www.codewars.com/kata/55192f4ecd82ff826900089e |
def divide(weight):
|
3,212 | The marketing team is spending way too much time typing in hashtags.
Let's help them with our own Hashtag Generator!
Here's the deal:
- It must start with a hashtag (`#`).
- All words must have their first letter capitalized.
- If the final result is longer than 140 chars it must return `false`.
- If the input or ... | ["def generate_hashtag(s):\n output = \"#\"\n \n for word in s.split():\n output += word.capitalize()\n \n return False if (len(s) == 0 or len(output) > 140) else output\n", "def generate_hashtag(s):\n ans = '#'+ str(s.title().replace(' ',''))\n return s and not len(ans)>140 and ans or False... | {"fn_name": "generate_hashtag", "inputs": [[""], ["Codewars"], ["Codewars "], ["Codewars Is Nice"], ["codewars is nice"], ["CodeWars is nice"], ["c i n"], ["codewars is nice"], ["Looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo... | introductory | https://www.codewars.com/kata/52449b062fb80683ec000024 |
def generate_hashtag(s):
|
3,213 | Beaches are filled with sand, water, fish, and sun. Given a string, calculate how many times the words `"Sand"`, `"Water"`, `"Fish"`, and `"Sun"` appear without overlapping (regardless of the case).
## Examples
```python
sum_of_a_beach("WAtErSlIde") ==> 1
sum_of_a_beach("GolDeNSanDyWateRyBeaChSuNN... | ["import re\ndef sum_of_a_beach(beach):\n return len(re.findall('Sand|Water|Fish|Sun', beach, re.IGNORECASE))", "def sum_of_a_beach(beach):\n return sum(beach.lower().count(fun) for fun in [\"sand\", \"water\", \"fish\", \"sun\"])", "import re\ndef sum_of_a_beach(beach):\n return len(re.findall(\"sand|water|fi... | {"fn_name": "sum_of_a_beach", "inputs": [["SanD"], ["sunshine"], ["sunsunsunsun"], ["123FISH321"], ["weoqipurpoqwuirpousandiupqwoieurioweuwateruierqpoiweurpouifiShqowieuqpwoeuisUn"], ["sAnDsandwaTerwatErfishFishsunsunsandwater"], ["joifjepiojfoiejfoajoijawoeifjowejfjoiwaefjiaowefjaofjwoj fawojef "], ["jwefjwjfsandsandw... | introductory | https://www.codewars.com/kata/5b37a50642b27ebf2e000010 |
def sum_of_a_beach(beach):
|
3,214 | Create a function which accepts one arbitrary string as an argument, and return a string of length 26.
The objective is to set each of the 26 characters of the output string to either `'1'` or `'0'` based on the fact whether the Nth letter of the alphabet is present in the input (independent of its case).
So if an `'... | ["def change(st):\n new = \"\"\n st = st.lower()\n for letter in \"abcdefghijklmnopqrstuvwxyz\":\n if letter in st:\n new += \"1\"\n else:\n new += \"0\"\n return new\n", "def change(s):\n s = set(s.lower())\n return \"\".join(\"1\" if x in s else \"0\" for x in map... | {"fn_name": "change", "inputs": [["a **& bZ"], ["Abc e $$ z"], ["!!a$%&RgTT"], [""], ["abcdefghijklmnopqrstuvwxyz"], ["aaaaaaaaaaa"], ["&%&%/$%$%$%$%GYtf67fg34678hgfdyd"]], "outputs": [["11000000000000000000000001"], ["11101000000000000000000001"], ["10000010000000000101000000"], ["00000000000000000000000000"], ["11... | introductory | https://www.codewars.com/kata/52dbae61ca039685460001ae |
def change(st):
|
3,215 | ## Number pyramid
Number pyramid is a recursive structure where each next row is constructed by adding adjacent values of the current row. For example:
```
Row 1 [1 2 3 4]
Row 2 [3 5 7]
Row 3 [8 12]
Row 4 [20]
```
___
## Task
Given the first row of the number... | ["from operator import mul\n\ndef reduce_pyramid(base):\n return sum(map(mul, base, comb_n(len(base) - 1)))\n\ndef comb_n(n):\n c = 1\n for k in range(0, n + 1):\n yield c\n c = c * (n - k) // (k + 1)\n", "def reduce_pyramid(base):\n c, t, ll = 1, 0, len(base) -1\n for i, v in enumerate(bas... | {"fn_name": "reduce_pyramid", "inputs": [[[1]], [[3, 5]], [[3, 9, 4]], [[5, 6, 7, 8]], [[13, 1, 21, 9]], [[13, 76, 21, 42, 63]]], "outputs": [[1], [8], [25], [52], [88], [674]]} | introductory | https://www.codewars.com/kata/5cc2cd9628b4200020880248 |
def reduce_pyramid(base):
|
3,216 | My friend John likes to go to the cinema. He can choose between system A and system B.
```
System A : he buys a ticket (15 dollars) every time
System B : he buys a card (500 dollars) and a first ticket for 0.90 times the ticket price,
then for each additional ticket he pays 0.90 times the price paid for the previous t... | ["import math \n\ndef movie(card, ticket, perc):\n num = 0\n priceA = 0\n priceB = card\n \n while math.ceil(priceB) >= priceA:\n num += 1\n priceA += ticket\n priceB += ticket * (perc ** num)\n \n return num", "from itertools import takewhile, count, accumulate\ndef movie(card, ticket, perc):\n sys_b = accum... | {"fn_name": "movie", "inputs": [[500, 15, 0.9], [100, 10, 0.95], [0, 10, 0.95], [250, 20, 0.9], [500, 20, 0.9], [2500, 20, 0.9]], "outputs": [[43], [24], [2], [21], [34], [135]]} | introductory | https://www.codewars.com/kata/562f91ff6a8b77dfe900006e |
def movie(card, ticket, perc):
|
3,217 | You will have a list of rationals in the form
```
lst = [ [numer_1, denom_1] , ... , [numer_n, denom_n] ]
```
or
```
lst = [ (numer_1, denom_1) , ... , (numer_n, denom_n) ]
```
where all numbers are positive integers. You have to produce their sum `N / D` in an irreducible form: this means that `N` and `D` have only ... | ["from fractions import Fraction\n\ndef sum_fracts(lst):\n if lst:\n ret = sum(Fraction(a, b) for (a, b) in lst)\n return ret.numerator if ret.denominator == 1 else [ret.numerator, ret.denominator]\n", "from fractions import Fraction\ndef sum_fracts(lst):\n s = sum(Fraction(*f) for f in lst)\n if... | {"fn_name": "sum_fracts", "inputs": [[[[1, 2], [1, 3], [1, 4]]], [[[1, 3], [5, 3]]], [[[12, 3], [15, 3]]], [[[2, 7], [1, 3], [1, 12]]], [[[69, 130], [87, 1310], [3, 4]]], [[[77, 130], [84, 131], [60, 80]]], [[[6, 13], [187, 1310], [31, 41]]], [[[8, 15], [7, 111], [4, 25]]], [[]], [[[81345, 15786], [87546, 11111111], [4... | introductory | https://www.codewars.com/kata/5517fcb0236c8826940003c9 |
def sum_fracts(lst):
|
3,218 | Scheduling is how the processor decides which jobs(processes) get to use the processor and for how long. This can cause a lot of problems. Like a really long process taking the entire CPU and freezing all the other processes. One solution is Shortest Job First(SJF), which today you will be implementing.
SJF works by, ... | ["def SJF(jobs, index):\n return sum(j for i, j in enumerate(jobs)\n if j < jobs[index] or (j == jobs[index] and i <= index))\n", "SJF = lambda jobs, index: sum(j for i, j in enumerate(jobs) if j <= jobs[index] and (jobs[i] != jobs[index] or i <= index))", "def SJF(jobs, index):\n return sum(n for... | {"fn_name": "SJF", "inputs": [[[100], 0], [[3, 10, 20, 1, 2], 0], [[3, 10, 20, 1, 2], 1], [[3, 10, 10, 20, 1, 2], 1], [[3, 10, 10, 20, 1, 2], 2], [[3, 10, 20, 1, 2, 3], 5], [[3, 10, 20, 1, 2, 10, 10], 5]], "outputs": [[100], [6], [16], [16], [26], [9], [26]]} | introductory | https://www.codewars.com/kata/550cc572b9e7b563be00054f |
def SJF(jobs, index):
|
3,219 | We are interested in collecting the sets of six prime numbers, that having a starting prime p, the following values are also primes forming the sextuplet ```[p, p + 4, p + 6, p + 10, p + 12, p + 16]```
The first sextuplet that we find is ```[7, 11, 13, 17, 19, 23]```
The second one is ```[97, 101, 103, 107, 109, 113]... | ["def find_primes_sextuplet(limit):\n for p in [7, 97, 16057, 19417, 43777, 1091257, 1615837, 1954357, 2822707, 2839927, 3243337, 3400207, 6005887]:\n if p * 6 + 48 > limit:\n return [p, p + 4, p + 6, p + 10, p + 12, p + 16]", "n = 6005904\nsieve = [True] * (n // 2)\nfor i in range(3, int(n**0.5) +... | {"fn_name": "find_primes_sextuplet", "inputs": [[70], [600], [2000000]], "outputs": [[[7, 11, 13, 17, 19, 23]], [[97, 101, 103, 107, 109, 113]], [[1091257, 1091261, 1091263, 1091267, 1091269, 1091273]]]} | introductory | https://www.codewars.com/kata/57bf7fae3b3164dcac000352 |
def find_primes_sextuplet(sum_limit):
|
3,220 | The sum of divisors of `6` is `12` and the sum of divisors of `28` is `56`. You will notice that `12/6 = 2` and `56/28 = 2`. We shall say that `(6,28)` is a pair with a ratio of `2`. Similarly, `(30,140)` is also a pair but with a ratio of `2.4`. These ratios are simply decimal representations of fractions.
`(6,28)` ... | ["from collections import defaultdict\nfrom fractions import Fraction\nfrom bisect import bisect_left as bisect\n\nharmonic = [0] + [Fraction(sum({y for x in range(1,int(n**.5)+1) for y in [x, n//x] if not n%x}), n) for n in range(1,7001)]\n\nharmonicity = defaultdict(set)\nfor n,h in enumerate(harmonic): harmonicity[h... | {"fn_name": "solve", "inputs": [[1, 100], [1, 200], [1, 300], [200, 1000], [1, 1000], [100, 1000], [800, 2000]], "outputs": [[6], [36], [252], [1104], [2619], [2223], [2352]]} | introductory | https://www.codewars.com/kata/59bf97cd4f98a8b1cd00007e |
def solve(a,b):
|
3,221 | Given an array of integers, find the one that appears an odd number of times.
There will always be only one integer that appears an odd number of times. | ["def find_it(seq):\n for i in seq:\n if seq.count(i)%2!=0:\n return i", "def find_it(seq):\n counts = dict()\n for n in seq:\n if n not in counts:\n counts[n] = 0\n \n counts[n] += 1\n \n for n, n_count in list(counts.items()):\n if n_count % ... | {"fn_name": "find_it", "inputs": [[[20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5]], [[1, 1, 2, -2, 5, 2, 4, 4, -1, -2, 5]], [[20, 1, 1, 2, 2, 3, 3, 5, 5, 4, 20, 4, 5]], [[10]], [[1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 1]]], "outputs": [[5], [-1], [5], [10], [10]]} | introductory | https://www.codewars.com/kata/54da5a58ea159efa38000836 |
def find_it(seq):
|
3,222 | Given two integers `a` and `b`, which can be positive or negative, find the sum of all the numbers between including them too and return it. If the two numbers are equal return `a` or `b`.
**Note:** `a` and `b` are not ordered!
## Examples
```python
get_sum(1, 0) == 1 // 1 + 0 = 1
get_sum(1, 2) == 3 // 1 + 2 = 3... | ["def get_sum(a,b):\n return sum(range(min(a, b), max(a, b) + 1))", "def get_sum(a, b):\n return (a + b) * (abs(a - b) + 1) // 2", "def get_sum(a,b):\n soma=0\n if a==b:\n return a\n elif a > b:\n for i in range(b,a+1):\n soma += i\n return soma\n else:\n for i i... | {"fn_name": "get_sum", "inputs": [[0, 1], [1, 2], [5, -1], [505, 4], [321, 123], [0, -1], [-50, 0], [-1, -5], [-5, -5], [-505, 4], [-321, 123], [0, 0], [-5, -1], [5, 1], [-17, -17], [17, 17]], "outputs": [[1], [3], [14], [127759], [44178], [-1], [-1275], [-15], [-5], [-127755], [-44055], [0], [-15], [15], [-17], [17]]} | introductory | https://www.codewars.com/kata/55f2b110f61eb01779000053 |
def get_sum(a,b):
|
3,223 | The first positive integer, `n`, with its value `4n² + 1`, being divisible by `5` and `13` is `4`. (condition 1)
It can be demonstrated that we have infinite numbers that may satisfy the above condition.
If we name **ai**, the different terms of the sequence of numbers with this property, we define `S(n)` as:
We a... | ["def sierpinski():\n x = s = 0\n while 1:\n for a in 4, 9, 56, 61:\n s += x + a\n yield s\n x += 65\n\ns = sierpinski()\nS = [next(s)]\n\nfrom bisect import bisect_left\ndef find_closest_value(m):\n while S[-1] < m: S.append(next(s))\n i = bisect_left(S, m)\n return m... | {"fn_name": "find_closest_value", "inputs": [[1], [5000], [7500], [8300], [14313], [20005], [18331], [18332]], "outputs": [[4], [5074], [7293], [8320], [14313], [20293], [17944], [18720]]} | introductory | https://www.codewars.com/kata/5be0af91621daf08e1000185 |
def find_closest_value(m):
|
3,224 | Given two numbers (m and n) :
- convert all numbers from m to n to binary
- sum them as if they were in base 10
- convert the result to binary
- return as string
Eg: with the numbers 1 and 4
1 // 1 to binary is 1
+ 10 // 2 to binary is 10
+ 11 // 3 to binary is 11
+100 // 4 to binary is 100
----
122 // 122 in ... | ["def binary_pyramid(m,n):\n return bin(sum(int(bin(i)[2:]) for i in range(m, n+1)))[2:]", "def binary_pyramid(m,n):\n return '{:b}'.format(sum(map(int, map('{:b}'.format, range(m,n+1)))))", "def binary_pyramid(m,n):\n return bin(int(sum(int(bin(i)[2:]) for i in range(m,n+1))))[2:]", "binary_pyramid=lambda m,n... | {"fn_name": "binary_pyramid", "inputs": [[1, 4], [1, 6], [6, 20], [21, 60], [100, 100], [1, 1], [0, 1], [0, 0], [1, 100], [100, 1000]], "outputs": [["1111010"], ["101001101"], ["1110010110100011"], ["1100000100010001010100"], ["100001100100101000100"], ["1"], ["1"], ["0"], ["10011101010010110000101010"], ["111111001111... | introductory | https://www.codewars.com/kata/5596700a386158e3aa000011 |
def binary_pyramid(m,n):
|
3,225 | Given an array (a list in Python) of integers and an integer `n`, find all occurrences of `n` in the given array and return another array containing all the index positions of `n` in the given array.
If `n` is not in the given array, return an empty array `[]`.
Assume that `n` and all values in the given array will a... | ["def find_all(array, n):\n return [index for index, item in enumerate(array) if item == n]", "def find_all(array, n):\n res = []\n for i in range(len(array)):\n if array[i] == n:\n res.append(i)\n return res", "def find_all(array, n):\n return [ i for i,v in enumerate(array) if v==n ]"... | {"fn_name": "find_all", "inputs": [[[6, 9, 3, 4, 3, 82, 11], 3], [[6, 9, 3, 4, 3, 82, 11], 99], [[10, 16, 20, 6, 14, 11, 20, 2, 17, 16, 14], 16], [[20, 20, 10, 13, 15, 2, 7, 2, 20, 3, 18, 2, 3, 2, 16, 10, 9, 9, 7, 5, 15, 5], 20]], "outputs": [[[2, 4]], [[]], [[1, 9]], [[0, 1, 8]]]} | introductory | https://www.codewars.com/kata/59a9919107157a45220000e1 |
def find_all(array, n):
|
3,226 | Task:
Given an array arr of strings complete the function landPerimeter by calculating the total perimeter of all the islands. Each piece of land will be marked with 'X' while the water fields are represented as 'O'. Consider each tile being a perfect 1 x 1piece of land. Some examples for better visualization:
['XOOXO... | ["def land_perimeter(arr):\n \n I,J = len(arr),len(arr[0])\n \n P = 0\n for i in range(I):\n for j in range(J):\n if arr[i][j] == 'X':\n if i == 0 or arr[i-1][j] == 'O': P += 1\n if i == I-1 or arr[i+1][j] == 'O': P += 1\n if j == 0 or arr... | {"fn_name": "land_perimeter", "inputs": [[["OXOOOX", "OXOXOO", "XXOOOX", "OXXXOO", "OOXOOX", "OXOOOO", "OOXOOX", "OOXOOO", "OXOOOO", "OXOOXX"]], [["OXOOO", "OOXXX", "OXXOO", "XOOOO", "XOOOO", "XXXOO", "XOXOO", "OOOXO", "OXOOX", "XOOOO", "OOOXO"]], [["XXXXXOOO", "OOXOOOOO", "OOOOOOXO", "XXXOOOXO", "OXOXXOOX"]], [["XOOOX... | introductory | https://www.codewars.com/kata/5839c48f0cf94640a20001d3 |
def land_perimeter(arr):
|
3,227 | ### Task
Yes, your eyes are no problem, this is toLoverCase (), not toLowerCase (), we want to make the world full of love.
### What do we need to do?
You need to add a prototype function to the String, the name is toLoverCase. Function can convert the letters in the string, converted to "L", "O", "V", "E", ... | ["def to_lover_case(string):\n return \"\".join(\"LOVE\"[(ord(c) - 97) % 4] if c.isalpha() else c for c in string)", "from string import ascii_lowercase\n\ndef to_lover_case(s):\n return s.lower().translate(str.maketrans(ascii_lowercase, ('LOVE' * 7)[:26]))", "def to_lover_case(strng):\n from string import asc... | {"fn_name": "to_lover_case", "inputs": [["LOVE"], ["love"], ["abcd"], ["ebcd"], ["Hello World!"], ["jrvz,"]], "outputs": [["EVOL"], ["EVOL"], ["LOVE"], ["LOVE"], ["ELEEV VVOEE!"], ["OOOO,"]]} | introductory | https://www.codewars.com/kata/5713b0253b510cd97f001148 |
def to_lover_case(string):
|
3,228 | Write
```python
word_pattern(pattern, string)
```
that given a ```pattern``` and a string ```str```, find if ```str``` follows the same sequence as ```pattern```.
For example:
```python
word_pattern('abab', 'truck car truck car') == True
word_pattern('aaaa', 'dog dog dog dog') == True
word_pattern('abab', 'apple bana... | ["def word_pattern(pattern, string):\n x = list(pattern)\n y = string.split(\" \")\n return (len(x) == len(y) and \n len(set(x)) == len(set(y)) == len(set(zip(x, y)))\n )", "def word_pattern(pattern, string):\n return [pattern.index(any) for any in pattern] == [string.split().index(any) for any in... | {"fn_name": "word_pattern", "inputs": [["abab", "apple banana apple banana"], ["abba", "car truck truck car"], ["abab", "apple banana banana apple"], ["aaaa", "cat cat cat cat"], ["aaaa", "cat cat dog cat"], ["bbbabcb", "c# c# c# javascript c# python c#"], ["abcdef", "apple banana cat donkey elephant flower"], ["xyzzyx... | introductory | https://www.codewars.com/kata/562846dd1f77ab7c00000033 |
def word_pattern(pattern, string):
|
3,229 | Wilson primes satisfy the following condition.
Let ```P``` represent a prime number.
Then ```((P-1)! + 1) / (P * P)``` should give a whole number.
Your task is to create a function that returns ```true``` if the given number is a Wilson prime. | ["def am_i_wilson(n):\n return n in (5, 13, 563)", "def am_i_wilson(n):\n #Piece of shit instead of code for piece of shit instead of instructions. \n #It is really hard to imagine even worse exercise than this for 8 kyu.\n #Extreamly outdated for 2019 it no longer has place in here. \n return True if n == ... | {"fn_name": "am_i_wilson", "inputs": [[0], [1], [5], [8], [9], [11], [13], [101], [563], [569]], "outputs": [[false], [false], [true], [false], [false], [false], [true], [false], [true], [false]]} | introductory | https://www.codewars.com/kata/55dc4520094bbaf50e0000cb |
def am_i_wilson(n):
|
3,230 | You're a programmer in a SEO company. The SEO specialist of your company gets the list of all project keywords everyday, then he looks for the longest keys to analyze them.
You will get the list with keywords and must write a simple function that returns the biggest search keywords and sorts them in lexicographical or... | ["def the_biggest_search_keys(*keys):\n L = sorted(keys, key=lambda key: (-len(key), key))\n i = next((i for i,key in enumerate(L) if len(key) != len(L[0])), None)\n return str(L[:i])[1:-1] or \"''\"", "def the_biggest_search_keys(*arg):\n mx = len(max(arg, key=len, default = ''))\n return \", \".join(so... | {"fn_name": "the_biggest_search_keys", "inputs": [["key1", "key22", "key333"], ["coding", "sorting", "tryruby"], ["small keyword", "how to coding?", "very nice kata", "a lot of keys", "I like Ruby!!!"], ["pippi"]], "outputs": [["'key333'"], ["'sorting', 'tryruby'"], ["'I like Ruby!!!', 'how to coding?', 'very nice kata... | introductory | https://www.codewars.com/kata/58ac1abdff4e78738f000805 |
def the_biggest_search_keys(*keys):
|
3,231 | # Task
Given an initial string `s`, switch case of the minimal possible number of letters to make the whole string written in the upper case or in the lower case.
# Input/Output
`[input]` string `s`
String of odd length consisting of English letters.
3 ≤ inputString.length ≤ 99.
`[output]` a string
The resulting... | ["def case_unification(s):\n return s.lower() if sum(1 for i in s if i.islower()) > sum(1 for i in s if i.isupper()) else s.upper()", "def case_unification(s):\n return s.upper() if sum(c.islower() for c in s) < len(s)/2 else s.lower()", "def case_unification(str):\n return str.lower() if sum(1 for ch in str i... | {"fn_name": "case_unification", "inputs": [["asdERvT"], ["oyTYbWQ"], ["bbiIRvbcW"], ["rWTmvcoRWEWQQWR"]], "outputs": [["asdervt"], ["OYTYBWQ"], ["bbiirvbcw"], ["RWTMVCORWEWQQWR"]]} | introductory | https://www.codewars.com/kata/59126cd3379de6ca5f00019c |
def case_unification(s):
|
3,232 | As part of this Kata, you need to find the length of the sequence in an array, between the first and the second occurrence of a specified number.
For example, for a given array `arr`
[0, -3, 7, 4, 0, 3, 7, 9]
Finding length between two `7`s like
lengthOfSequence([0, -3, 7, 4, 0, 3, 7, 9], 7)
wo... | ["def length_of_sequence(arr, n):\n if arr.count(n) != 2:\n return 0\n a = arr.index(n)\n b = arr.index(n, a + 1)\n return b - a + 1", "def length_of_sequence(arr,n):\n return (len(arr) - arr[::-1].index(n) - 1) - arr.index(n) + 1 if arr.count(n) == 2 else 0", "def length_of_sequence(arr,n):\n ... | {"fn_name": "length_of_sequence", "inputs": [[[1], 0], [[1], 1], [[-7, 3, -7, -7, 2, 1], -7], [[-7, 3, -7, -7, 2, -7], -7]], "outputs": [[0], [0], [0], [0]]} | introductory | https://www.codewars.com/kata/5566b0dd450172dfc4000005 |
def length_of_sequence(arr,n):
|
3,233 | # Task
We have a N×N `matrix` (N<10) and a robot.
We wrote in each point of matrix x and y coordinates of a point of matrix.
When robot goes to a point of matrix, reads x and y and transfer to point with x and y coordinates.
For each point in the matrix we want to know if robot returns back to it after `EXA... | ["def robot_transfer(matrix, k):\n c = 0\n for l, i in enumerate(matrix):\n for o, j in enumerate(i):\n x, y = j.split(\",\")\n current,count,new = [l, o],0,[]\n while count < k and current != new:\n new = [int(x), int(y)] ; x, y = matrix[int(x)][int(y)].spli... | {"fn_name": "robot_transfer", "inputs": [[[["0,1", "0,0", "1,2"], ["1,1", "1,0", "0,2"], ["2,1", "2,0", "0,0"]], 2], [[["0,1", "0,0"], ["1,1", "1,0"]], 2]], "outputs": [[8], [4]]} | introductory | https://www.codewars.com/kata/58aaa3ca821a767300000017 |
def robot_transfer(matrix, k):
|
3,234 | You will be given a certain array of length ```n```, such that ```n > 4```, having positive and negative integers but there will be no zeroes and all the elements will occur once in it.
We may obtain an amount of ```n``` sub-arrays of length ```n - 1```, removing one element at a time (from left to right).
For each ... | ["from functools import reduce\nfrom operator import mul\n\n\ndef select_subarray(arr):\n total = sum(arr)\n m = reduce(mul, arr)\n qs = [\n (abs((m // x) / (total - x)) if total - x else float(\"inf\"), i)\n for i, x in enumerate(arr)\n ]\n q = min(qs)\n result = [[i, arr[i]] for x, i i... | {"fn_name": "select_subarray", "inputs": [[[1, 23, 2, -8, 5]], [[1, 3, 23, 4, 2, -8, 5, 18]], [[2, -8, 5, 18]], [[10, 20, -30, 100, 200]]], "outputs": [[[3, -8]], [[2, 23]], [[1, -8]], [[[3, 100], [4, 200]]]]} | introductory | https://www.codewars.com/kata/581bb3c1c221fb8e790001ef |
def select_subarray(arr):
|
3,235 | In genetics a reading frame is a way to divide a sequence of nucleotides (DNA bases) into a set of consecutive non-overlapping triplets (also called codon). Each of this triplets is translated into an amino-acid during a translation process to create proteins.
Input
---
In a single strand of DNA you find 3 Reading fra... | ["def decompose_single_strand(dna): \n return '\\n'.join('Frame {}: {}'.format(k+1, frame(dna, k)) for k in range(3))\n \ndef frame(s, k):\n return ' '.join(([s[:k]] if k else []) + [s[i:i+3] for i in range(k, len(s), 3)]) ", "def decompose_single_strand(single_strand):\n f1 = 'Frame 1: {}'.format... | {"fn_name": "decompose_single_strand", "inputs": [["AGGTGACACCGCAAGCCTTATATTAGC"]], "outputs": [["Frame 1: AGG TGA CAC CGC AAG CCT TAT ATT AGC\nFrame 2: A GGT GAC ACC GCA AGC CTT ATA TTA GC\nFrame 3: AG GTG ACA CCG CAA GCC TTA TAT TAG C"]]} | introductory | https://www.codewars.com/kata/57507369b0b6d1b5a60001b3 |
def decompose_single_strand(single_strand):
|
3,236 | ## MTV Cribs is back!

_If you haven't solved it already I recommend trying [this kata](https://www.codewars.com/kata/5834a44e44ff289b5a000075) first._
## Task
Given `n` representing the number of floors build a penthouse li... | ["def my_crib(n):\n wide = 4 + 3 + 6 * (n - 1)\n door = 2 + n - 1\n roof = 3 + 2 * (n - 1)\n r = '{0}{1}{0}\\n'.format(' ' * (wide // 2 - n), '_' * (3 + 2 * (n - 1)))\n for i in range(1, roof):\n r += '{0}/{1}\\\\{0}\\n'.format(' ' * (wide // 2 - n - i), '_' * (3 + 2 * (n - 1) + 2 * (i -1)))\n ... | {"fn_name": "my_crib", "inputs": [[1], [2], [3]], "outputs": [[" ___ \n /___\\ \n/_____\\\n| _ |\n|_|_|_|"], [" _____ \n /_____\\ \n /_______\\ \n /_________\\ \n/___________\\\n| |\n| ___ |\n| | | |\n|___|___|___|"], [" _______ \n /_______\\ \n /_________\\ ... | introductory | https://www.codewars.com/kata/58360d112fb0ba255300008b |
def my_crib(n):
|
3,237 | ```if-not:sql
Create a function (or write a script in Shell) that takes an integer as an argument and returns "Even" for even numbers or "Odd" for odd numbers.
```
```if:sql
## SQL Notes:
You will be given a table, `numbers`, with one column `number`.
Return a table with a column `is_even` containing "Even" or "Odd" ... | ["def even_or_odd(number):\n return 'Odd' if number % 2 else 'Even'", "def even_or_odd(number):\n return 'Even' if number % 2 == 0 else 'Odd'", "def even_or_odd(number):\n if number % 2 == 0:\n return \"Even\"\n else:\n return \"Odd\"", "def even_or_odd(number):\n return [\"Even\", \"Odd\"][number % 2]", "... | {"fn_name": "even_or_odd", "inputs": [[2], [1], [0], [1545452], [7], [78], [17], [74156741], [100000], [-123], [-456]], "outputs": [["Even"], ["Odd"], ["Even"], ["Even"], ["Odd"], ["Even"], ["Odd"], ["Odd"], ["Even"], ["Odd"], ["Even"]]} | introductory | https://www.codewars.com/kata/53da3dbb4a5168369a0000fe |
def even_or_odd(number):
|
3,238 | Hey CodeWarrior,
we've got a lot to code today!
I hope you know the basic string manipulation methods, because this kata will be all about them.
Here we go...
## Background
We've got a very long string, containing a bunch of User IDs. This string is a listing, which seperates each user ID with a comma and a whites... | ["def get_users_ids(string):\n return [w.replace(\"uid\", \"\", 1).strip() for w in string.lower().replace(\"#\", \"\").split(\",\")]", "def get_users_ids(strng):\n result = []\n for a in strng.split(','):\n result.append(a.lower().replace('#', '').replace('uid', '', 1).strip())\n return result", "de... | {"fn_name": "get_users_ids", "inputs": [["uid12345"], [" uidabc "], ["#uidswagger"], ["uidone, uidtwo"], ["uidCAPSLOCK"], ["uid##doublehashtag"], [" uidin name whitespace"], ["uidMultipleuid"], ["uid12 ab, uid#, uidMiXeDcHaRs"], [" uidT#e#S#t# "]], "outputs": [[["12345"]], [["abc"]], [["swagger"]], [["one", "two"]]... | introductory | https://www.codewars.com/kata/56326c13e63f90538d00004e |
def get_users_ids(s):
|
3,239 | # Task
Four men, `a, b, c and d` are standing in a line, one behind another.
There's a wall between the first three people (a, b and c) and the last one (d).
a, b and c are lined up in order of height, so that person a can see the backs of b and c, person b can see the back of c, and c can see just the wall.
... | ["def guess_hat_color(a,b,c,d):\n return 1 if b == c else 2", "guess_hat_color=lambda a,b,c,d:2-(b==c)", "guess_hat_color=lambda a,b,c,d:1+(b!=c)", "def guess_hat_color(a,b,c,d):\n if a == d:\n return 1\n else:\n return 2", "def guess_hat_color(a,b,c,d):\n return (b != c) + 1", "guess_hat_colo... | {"fn_name": "guess_hat_color", "inputs": [["white", "black", "white", "black"], ["white", "black", "black", "white"]], "outputs": [[2], [1]]} | introductory | https://www.codewars.com/kata/58c21c4ff130b7cab400009e |
def guess_hat_color(a,b,c,d):
|
3,240 | Normally, we decompose a number into binary digits by assigning it with powers of 2, with a coefficient of `0` or `1` for each term:
`25 = 1*16 + 1*8 + 0*4 + 0*2 + 1*1`
The choice of `0` and `1` is... not very binary. We shall perform the *true* binary expansion by expanding with powers of 2, but with a coefficient o... | ["def true_binary(n):\n return [(c == '1') * 2 - 1 for c in '1' + bin(n)[2:-1]]", "def true_binary(n):\n return [-1 if x == '0' else 1 for x in bin(n)[1:-1]]", "def true_binary(n):\n return [1] + [1 if b=='1' else -1 for b in bin(n)[2:-1]]", "def true_binary(n):\n return [1 if d == \"1\" else -1 for d in (... | {"fn_name": "true_binary", "inputs": [[25], [47], [1], [3], [1234567]], "outputs": [[[1, 1, 1, -1, -1]], [[1, 1, -1, 1, 1, 1]], [[1]], [[1, 1]], [[1, 1, -1, -1, 1, -1, 1, 1, -1, 1, -1, 1, 1, -1, 1, -1, -1, -1, -1, 1, 1]]]} | introductory | https://www.codewars.com/kata/59a818191c55c44f3900053f |
def true_binary(n):
|
3,241 | # Task
A newspaper is published in Walrusland. Its heading is `s1` , it consists of lowercase Latin letters.
Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string.
After that walrus erase several letters from this string in orde... | ["import re\n\n\ndef buy_newspaper(s1, s2):\n p = re.sub(r\"(.)\", r\"\\1?\", s1)\n return -1 if set(s2) - set(s1) else len(re.findall(p, s2)) - 1", "from collections import deque\n\ndef buy_newspaper(s1,s2):\n if set(s2) - set(s1):\n return -1\n q = deque(s1)\n n = 0\n for c in s2:\n i ... | {"fn_name": "buy_newspaper", "inputs": [["abc", "bcac"], ["abc", "xyz"], ["abc", "abcabc"], ["abc", "abccba"], ["abc", "aaaaaa"]], "outputs": [[2], [-1], [2], [4], [6]]} | introductory | https://www.codewars.com/kata/596c26187bd547f3a6000050 |
def buy_newspaper(s1,s2):
|
3,242 | # Task
Given an integer array `arr`. Your task is to remove one element, maximize the product of elements.
The result is the element which should be removed. If more than one valid results exist, return the smallest one.
# Input/Output
`[input]` integer array `arr`
non-empty unsorted integer array. It contains p... | ["def maximum_product(arr):\n if arr.count(0) > 1:\n return min(arr)\n neg = [n for n in arr if n < 0]\n pos = [n for n in arr if n >= 0]\n if len(neg) % 2:\n return min(neg) if 0 in arr else max(neg)\n else:\n return min(pos) if pos else min(neg)", "from operator import mul\nfrom fu... | {"fn_name": "maximum_product", "inputs": [[[1, 2, 3]], [[-1, 2, -3]], [[-1, -2, -3]], [[-1, -2, -3, -4]], [[0, 1, 2, 3]], [[0, -1, -2, -3]], [[0, -1, -2, -3, -4]], [[0, -1, 2, -3, 4]], [[0, -1, 2, 3]], [[0, -1, -2, -3, 4]], [[0, 0, 1]], [[0, 0, -1]], [[0, -1, 1]], [[0, 0, -1, 1]], [[0, 0, 0]], [[0, 0, 1, 2, 3]], [[-1, ... | introductory | https://www.codewars.com/kata/592e2446dc403b132d0000be |
def maximum_product(arr):
|
3,243 | It's been a tough week at work and you are stuggling to get out of bed in the morning.
While waiting at the bus stop you realise that if you could time your arrival to the nearest minute you could get valuable extra minutes in bed.
There is a bus that goes to your office every 15 minute, the first bus is at `06:00`, ... | ["def bus_timer(current_time):\n h, m = map(int, current_time.split(':'))\n\n if h<6:\n m = (5 - h) * 60 + 60 - m\n elif h == 23 and m > 55:\n return 355 + 60 - m\n else:\n m = 15 - m % 15\n\n if m > 4:\n return m - 5\n else:\n return m + 10", "def bus_timer(time):... | {"fn_name": "bus_timer", "inputs": [["10:00"], ["10:45"], ["15:05"], ["06:10"], ["05:10"], ["04:50"], ["05:55"], ["23:57"], ["00:00"], ["23:55"]], "outputs": [[10], [10], [5], [0], [45], [65], [0], [358], [355], [0]]} | introductory | https://www.codewars.com/kata/5736378e3f3dfd5a820000cb |
def bus_timer(current_time):
|
3,244 | You and your best friend Stripes have just landed your first high school jobs! You'll be delivering newspapers to your neighbourhood on weekends. For your services you'll be charging a set price depending on the quantity of the newspaper bundles.
The cost of deliveries is:
- $3.85 for 40 newspapers
- $1.93 for 20
- $... | ["def cheapest_quote(n):\n prices = [(40, 3.85), (20, 1.93), (10, 0.97), (5, 0.49), (1, 0.10)]\n result = 0\n for q, c in prices:\n result += n // q * c\n n = n % q\n return round(result, 2)\n \n", "def f(n, v):\n # Removes remainders from Calculation\n # Technically not doing... | {"fn_name": "cheapest_quote", "inputs": [[1], [5], [10], [20], [40], [41], [80], [26], [0], [499]], "outputs": [[0.1], [0.49], [0.97], [1.93], [3.85], [3.95], [7.7], [2.52], [0.0], [48.06]]} | introductory | https://www.codewars.com/kata/56ed5f13c4e5d6c5b3000745 |
def cheapest_quote(n):
|
3,245 | You know combinations: for example,
if you take 5 cards from a 52 cards deck you have 2,598,960 different combinations.
In mathematics the number of x combinations you can take from a set of n elements
is called the binomial coefficient of n and x, or more often `n choose x`.
The formula to compute `m = n choose x` i... | ["def checkchoose(m, n):\n c = 1\n for x in range(n // 2 + 1):\n if c == m: return x\n c = c * (n-x) // (x+1)\n else: return -1\n", "from math import factorial\n\ndef choose(n, x):\n return factorial(n) // (factorial(x) * factorial(n-x)) if x else 1\n\ndef checkchoose(m, n):\n for x in rang... | {"fn_name": "checkchoose", "inputs": [[1, 6], [6, 4], [4, 4], [4, 2], [35, 7], [36, 7], [184756, 20], [184756, 10], [3268760, 25], [155117520, 30], [155117530, 30]], "outputs": [[0], [2], [1], [-1], [3], [-1], [10], [-1], [10], [15], [-1]]} | introductory | https://www.codewars.com/kata/55be10de92aad5ef28000023 |
def checkchoose(m, n):
|
3,246 | Goal
Given a list of elements [a1, a2, ..., an], with each ai being a string, write a function **majority** that returns the value that appears the most in the list.
If there's no winner, the function should return None, NULL, nil, etc, based on the programming language.
Example
majority(["A", "B", "A"]) returns "A"... | ["from collections import Counter\n\ndef majority(arr):\n mc = Counter(arr).most_common(2)\n if arr and (len(mc) == 1 or mc[0][1] != mc[1][1]):\n return mc[0][0]", "def majority(arr):\n dic = {}\n n = 0\n c = 0\n for x in arr:\n if not x in dic:\n dic[x] = 1\n else:\n dic[x] += 1\... | {"fn_name": "majority", "inputs": [[["A", "B", "A"]], [["A", "B", "C"]], [["A", "B", "B", "A"]], [["A", "A", "A", "A"]], [["A"]], [["A", "A", "A", "BBBBBBBB"]], [["A", "B", "C", "C"]], [[]], [["B", "C", "", ""]]], "outputs": [["A"], [null], [null], ["A"], ["A"], ["A"], ["C"], [null], [""]]} | introductory | https://www.codewars.com/kata/5af974846bf32304a2000e98 |
def majority(arr):
|
3,247 | # Task
Some people are standing in a row in a park. There are trees between them which cannot be moved.
Your task is to rearrange the people by their heights in a non-descending order without moving the trees.
# Example
For `a = [-1, 150, 190, 170, -1, -1, 160, 180]`, the output should be
`[-1, 150, 160, 170,... | ["def sort_by_height(a):\n s = iter(sorted(x for x in a if x != -1))\n return [x if x == -1 else next(s) for x in a]", "def sort_by_height(arr):\n heights = iter(sorted(i for i in arr if i > 0))\n for idx, i in enumerate(arr):\n if i > 0:\n arr[idx] = next(heights)\n return arr", "def s... | {"fn_name": "sort_by_height", "inputs": [[[-1, 150, 190, 170, -1, -1, 160, 180]], [[-1, -1, -1, -1, -1]], [[4, 2, 9, 11, 2, 16]]], "outputs": [[[-1, 150, 160, 170, -1, -1, 180, 190]], [[-1, -1, -1, -1, -1]], [[2, 2, 4, 9, 11, 16]]]} | introductory | https://www.codewars.com/kata/589577f0d1b93ae32a000001 |
def sort_by_height(a):
|
3,248 | In music, if you double (or halve) the pitch of any note you will get to the same note again.
"Concert A" is fixed at 440 Hz, and every other note is defined based on that. 880 Hz is also an A, as is 1760 Hz, as is 220 Hz.
There are 12 notes in Western music: A, A#, B, C, C#, D, D#, E, F, F#, G, G#. You are given a p... | ["notes = {\n440: \"A\",\n466.16: \"A#\",\n493.88: \"B\",\n523.25: \"C\",\n554.37: \"C#\",\n587.33: \"D\",\n622.25: \"D#\",\n659.25: \"E\",\n698.46: \"F\",\n739.99: \"F#\",\n783.99: \"G\",\n830.61: \"G#\"\n}\n\ndef get_note(pitch):\n\n for note in notes:\n if note >= pitch and note % pitch == 0:\n ... | {"fn_name": "get_note", "inputs": [[440], [220], [880], [523.25], [261.625], [1046.5]], "outputs": [["A"], ["A"], ["A"], ["C"], ["C"], ["C"]]} | introductory | https://www.codewars.com/kata/5a0599908ba914a6cf000138 |
def get_note(pitch):
|
3,249 | #### Background:
A linear regression line has an equation in the form `$Y = a + bX$`, where `$X$` is the explanatory variable and `$Y$` is the dependent variable. The parameter `$b$` represents the *slope* of the line, while `$a$` is called the *intercept* (the value of `$y$` when `$x = 0$`).
For more details visi... | ["import numpy as np\n\ndef regressionLine(x, y):\n \"\"\" Return the a (intercept)\n and b (slope) of Regression Line \n (Y on X).\n \"\"\"\n a,b = np.polyfit(x,y,1)\n return round(b,4),round(a,4)\n \n", "def regressionLine(x, y):\n \"\"\" Return the a (intercept)\n and b (slope)... | {"fn_name": "regressionLine", "inputs": [[[25, 30, 35, 40, 45, 50], [78, 70, 65, 58, 48, 42]], [[56, 42, 72, 36, 63, 47, 55, 49, 38, 42, 68, 60], [147, 125, 160, 118, 149, 128, 150, 145, 115, 140, 152, 155]], [[0, 10, 20, 30, 40], [0.51, 0.55, 0.57, 0.59, 0.63]]], "outputs": [[[114.381, -1.4457]], [[80.7777, 1.138]], [... | introductory | https://www.codewars.com/kata/5515395b9cd40b2c3e00116c |
def regressionLine(x, y):
|
3,250 | Bob is a theoretical coder - he doesn't write code, but comes up with theories, formulas and algorithm ideas. You are his secretary, and he has tasked you with writing the code for his newest project - a method for making the short form of a word. Write a function ```shortForm```(C# ```ShortForm```, Python ```short_for... | ["from re import *\ndef short_form(s):\n return sub(r\"(?<!^)[aeiou](?=.)\", '', s, flags=I)", "import re\n\ndef short_form(s):\n regex = re.compile(\"(?!^)[aeiou](?!$)\", re.I)\n return re.sub(regex, \"\", s)\n", "def short_form(s):\n return s[0]+''.join(x for x in s[1:-1] if x not in 'aeiouAEIOU')+s[-1]",... | {"fn_name": "short_form", "inputs": [["typhoid"], ["fire"], ["destroy"], ["kata"], ["codewars"], ["assert"], ["insane"], ["nice"], ["amazing"], ["incorrigible"], ["HeEllO"], ["inCRediBLE"], ["IMpOsSiblE"], ["UnInTENtiONAl"], ["AWESOme"], ["rhythm"], ["hymn"], ["lynx"], ["nymph"], ["pygmy"]], "outputs": [["typhd"], ["fr... | introductory | https://www.codewars.com/kata/570cbe88f616a8f4f50011ac |
def short_form(s):
|
3,251 | Given a positive number n > 1 find the prime factor decomposition of n.
The result will be a string with the following form :
```
"(p1**n1)(p2**n2)...(pk**nk)"
```
where ```a ** b``` means ```a``` to the power of ```b```
with the p(i) in increasing order and n(i) empty if
n(i) is 1.
```
Example: n = 86240 should retu... | ["def primeFactors(n):\n ret = ''\n for i in range(2, n + 1):\n num = 0\n while(n % i == 0):\n num += 1\n n /= i\n if num > 0:\n ret += '({}{})'.format(i, '**%d' % num if num > 1 else '')\n if n == 1:\n return ret\n", "def primeFactors(n):\n ... | {"fn_name": "primeFactors", "inputs": [[7775460], [7919], [18195729], [933555431], [342217392], [35791357], [782611830], [775878912]], "outputs": [["(2**2)(3**3)(5)(7)(11**2)(17)"], ["(7919)"], ["(3)(17**2)(31)(677)"], ["(7537)(123863)"], ["(2**4)(3)(11)(43)(15073)"], ["(7)(5113051)"], ["(2)(3**2)(5)(7**2)(11)(13)(17)(... | introductory | https://www.codewars.com/kata/54d512e62a5e54c96200019e |
def primeFactors(n):
|
3,252 | Complete the code which should return `true` if the given object is a single ASCII letter (lower or upper case), `false` otherwise. | ["def is_letter(s):\n return len(s) == 1 and s.isalpha()", "import re\n\ndef is_letter(stg):\n return bool(re.match(r\"[a-z]\\Z\", stg, re.I))", "import re\ndef is_letter(s):\n return bool(re.fullmatch(\"[A-Za-z]\",s))", "is_letter=lambda s:(s==s[-1:])&s.isalpha()", "import re\ndef is_letter(s):\n return re... | {"fn_name": "is_letter", "inputs": [[""], ["a"], ["X"], ["7"], ["_"], ["ab"], ["a\n"]], "outputs": [[false], [true], [true], [false], [false], [false], [false]]} | introductory | https://www.codewars.com/kata/567de72e8b3621b3c300000b |
def is_letter(s):
|
3,253 | As you may know, once some people pass their teens, they jokingly only celebrate their 20th or 21st birthday, forever. With some maths skills, that's totally possible - you only need to select the correct number base!
For example, if they turn 32, that's exactly 20 - in base 16... Already 39? That's just 21, in base 1... | ["def womens_age(n):\n return f\"{n}? That's just {20+n%2}, in base {n//2}!\"", "womens_age = lambda n: f\"{n}? That's just 2{n % 2}, in base {n // 2}!\"", "def womens_age(n):\n return f\"{n}? That's just 2{n % 2}, in base {n // 2}!\"", "def womens_age(n):\n return f\"{n}? That's just {21 if n % 2 else 20}, in... | {"fn_name": "womens_age", "inputs": [[32], [39], [22], [65], [83]], "outputs": [["32? That's just 20, in base 16!"], ["39? That's just 21, in base 19!"], ["22? That's just 20, in base 11!"], ["65? That's just 21, in base 32!"], ["83? That's just 21, in base 41!"]]} | introductory | https://www.codewars.com/kata/5e96332d18ac870032eb735f |
def womens_age(n):
|
3,254 | ~~~if-not:ruby,python
Return `1` when *any* odd bit of `x` equals 1; `0` otherwise.
~~~
~~~if:ruby,python
Return `true` when *any* odd bit of `x` equals 1; `false` otherwise.
~~~
Assume that:
* `x` is an unsigned, 32-bit integer;
* the bits are zero-indexed (the least significant bit is position 0)
## Examples
```
... | ["MATCH = int('10'*16,2)\n\ndef any_odd(x): return bool(MATCH & x)", "def any_odd(n):\n return 1 if '1' in bin(n)[2:][-2::-2] else 0", "def any_odd(x):\n return x & 0xaaaaaaaa != 0", "def any_odd(x):\n return int(\"1\" in f\"{x:032b}\"[::2])", "def any_odd(x):\n bin = \"{0:b}\".format(x)\n bin = bin[::-1... | {"fn_name": "any_odd", "inputs": [[2863311530], [128], [131], [2], [24082], [0], [85], [1024], [1], [1365]], "outputs": [[true], [true], [true], [true], [true], [false], [false], [false], [false], [false]]} | introductory | https://www.codewars.com/kata/5d6f49d85e45290016bf4718 |
def any_odd(x):
|
3,255 | Given a string, remove any characters that are unique from the string.
Example:
input: "abccdefee"
output: "cceee" | ["from collections import Counter\n\ndef only_duplicates(string):\n cs = Counter(string)\n return ''.join(c for c in string if cs[c] > 1)", "def only_duplicates(string):\n return \"\".join([x for x in string if string.count(x) > 1])", "only_duplicates = lambda s: ''.join(c for c in s if s.count(c) > 1)", "def ... | {"fn_name": "only_duplicates", "inputs": [["abccdefee"], ["hello"], ["colloquial"], ["foundersandcoders"], ["12314256aaeff"]], "outputs": [["cceee"], ["ll"], ["ollol"], ["ondersndoders"], ["1212aaff"]]} | introductory | https://www.codewars.com/kata/5a1dc4baffe75f270200006b |
def only_duplicates(string):
|
3,256 | Let's take an integer number, ``` start``` and let's do the iterative process described below:
- we take its digits and raise each of them to a certain power, ```n```, and add all those values up. (result = ```r1```)
- we repeat the same process with the value ```r1``` and so on, ```k``` times.
Let's do it with ```s... | ["def sum_pow_dig_seq(num, exp, k):\n seq = []\n \n for step in range(k):\n seq.append(num)\n num = sum( int(dig) ** exp for dig in str(num) )\n \n if num in seq:\n cycle_start = seq.index(num)\n cycle = seq[cycle_start:]\n last_term = cycle[(k - cyc... | {"fn_name": "sum_pow_dig_seq", "inputs": [[420, 3, 5], [420, 4, 30], [420, 5, 100]], "outputs": [[[3, [153], 1, 153]], [[12, [13139, 6725, 4338, 4514, 1138, 4179, 9219], 7, 1138]], [[23, [9045, 63198, 99837, 167916, 91410, 60075, 27708, 66414, 17601, 24585, 40074, 18855, 71787, 83190, 92061, 66858, 84213, 34068, 41811,... | introductory | https://www.codewars.com/kata/572f32ed3bd44719f8000a54 |
def sum_pow_dig_seq(start, n, k):
|
3,257 | **This Kata is intended as a small challenge for my students**
All Star Code Challenge #19
You work for an ad agency and your boss, Bob, loves a catchy slogan. He's always jumbling together "buzz" words until he gets one he likes. You're looking to impress Boss Bob with a function that can do his job for him.
Create... | ["def slogan_maker(array):\n print(array)\n from itertools import permutations \n array = remove_duplicate(array)\n return [' '.join(element) for element in list(permutations(array, len(array)))]\n \ndef remove_duplicate(old_list): \n final_list = [] \n for num in old_list: \n if num not in ... | {"fn_name": "slogan_maker", "inputs": [[["super"]], [["super", "hot"]], [["super", "hot", "guacamole"]], [["super", "guacamole", "super", "super", "hot", "guacamole"]], [["testing", "testing", "testing"]]], "outputs": [[["super"]], [["super hot", "hot super"]], [["super hot guacamole", "super guacamole hot", "hot super... | introductory | https://www.codewars.com/kata/5865a407b359c45982000036 |
def slogan_maker(array):
|
3,258 | You are to write a function to transpose a guitar tab up or down a number of semitones. The amount to transpose is a number, positive or negative. The tab is given as an array, with six elements for each guitar string (fittingly passed as strings). Output your tab in a similar form.
Guitar tablature (or 'tab') is an a... | ["def transpose(amount, tab):\n stack, tab = [], list(map(list, tab))\n for n, col in reversed(list(enumerate(zip(*tab)))):\n if any(map(str.isdigit, col)):\n stack.append(col)\n elif stack:\n frets = [''.join(r).strip('-') for r in zip(*reversed(stack))]\n frets = [... | {"fn_name": "transpose", "inputs": [[2, ["e|-------5-7-----7-|-8-----8-2-----2-|-0---------0-----|-----------------|", "B|-----5-----5-----|---5-------3-----|---1---1-----1---|-0-1-1-----------|", "G|---5---------5---|-----5-------2---|-----2---------2-|-0-2-2-----------|", "D|-7-------6-------|-5-------4-------|-3----... | introductory | https://www.codewars.com/kata/5ac62974348c2203a90000c0 |
def transpose(amount, tab):
|
3,259 | # Background
My TV remote control has arrow buttons and an `OK` button.
I can use these to move a "cursor" on a logical screen keyboard to type words...
# Keyboard
The screen "keyboard" layout looks like this
#tvkb {
width : 400px;
border: 5px solid gray; border-collapse: collapse;
}
#tvkb td {
... | ["import re\n\nKEYBOARD = \"abcde123fghij456klmno789pqrst.@0uvwxyz_/* \"\nMAP = {c: (i//8, i%8) for i,c in enumerate(KEYBOARD)}\n\n\ndef manhattan(*pts): return 1 + sum( abs(z2-z1) for z1,z2 in zip(*pts))\n\ndef toggle(m):\n ups, end = m.group(1), m.group(2)\n off = '*' * bool(end)\n return f'*{ups.lower(... | {"fn_name": "tv_remote", "inputs": [["Code Wars"], ["does"], ["your"], ["solution"], ["work"], ["for"], ["these"], ["words"], ["DOES"], ["YOUR"], ["SOLUTION"], ["WORK"], ["FOR"], ["THESE"], ["WORDS"], ["Does"], ["Your"], ["Solution"], ["Work"], ["For"], ["These"], ["Words"], ["A"], ["AADVARKS"], ["A/A/A/A/"], ["1234567... | introductory | https://www.codewars.com/kata/5b277e94b6989dd1d9000009 |
def tv_remote(words):
|
3,260 | A function receives a certain numbers of integers ```n1, n2, n3 ..., np```(all positive and different from 0) and a factor ```k, k > 0```
The function rearranges the numbers ```n1, n2, ..., np``` in such order that generates the minimum number concatenating the digits and this number should be divisible by ```k```.
T... | ["from itertools import permutations\n\ndef rearranger(k, *args):\n perms = permutations(map(str, args), len(args))\n divisible_by_k = filter(lambda x: int(''.join(x)) % k == 0, perms)\n try:\n rearranged = min(divisible_by_k, key=lambda x: int(''.join(x)))\n return 'Rearrangement: {} generates: ... | {"fn_name": "rearranger", "inputs": [[4, 32, 3, 34, 7, 12], [10, 32, 3, 34, 7, 12]], "outputs": [["Rearrangement: 12, 3, 34, 7, 32 generates: 12334732 divisible by 4"], ["There is no possible rearrangement"]]} | introductory | https://www.codewars.com/kata/569e8353166da6908500003d |
def rearranger(k, *args):
|
3,261 | >When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said
# Description:
John learns to play poker with his uncle. His uncle told him: Poker to be in accordance with the order of "2 3 4 5 6 7 8 9 10 J Q K A". The same suit sho... | ["import re\nfrom collections import OrderedDict\nscale = \"2 3 4 5 6 7 8 9 10 J Q K A\".split(\" \")\ndef sort_poker(john, uncle):\n order = list(OrderedDict.fromkeys(re.findall(r\"([SDHC])[0-9JQKA]+\",uncle)))\n john = re.findall(r\"([SDHC])([0-9JQKA]+)\",john)\n return \"\".join(\"\".join(i) for i in sorte... | {"fn_name": "sort_poker", "inputs": [["D6H2S3D5SJCQSKC7D2C5H5H10SA", "S2S3S5HJHQHKC8C9C10D4D5D6D7"], ["D6H2S3D5SJCQSKC7D2C5H5H10SA", "C8C9C10D4D5D6D7S2S3S5HJHQHK"]], "outputs": [["S3SJSKSAH2H5H10C5C7CQD2D5D6"], ["C5C7CQD2D5D6S3SJSKSAH2H5H10"]]} | introductory | https://www.codewars.com/kata/580ed88494291dd28c000019 |
def sort_poker(john, uncle):
|
3,262 | ## Task
Create a function that given a sequence of strings, groups the elements that can be obtained by rotating others, ignoring upper or lower cases.
In the event that an element appears more than once in the input sequence, only one of them will be taken into account for the result, discarding the rest.
## Inpu... | ["def group_cities(seq):\n result = []\n sort_result =[]\n seq = list(dict.fromkeys(seq)) #removing duplicates\n for e, i in enumerate(seq):\n sort_result = [j for j in seq if len(j)==len(i) and j.lower() in 2*(i.lower())]\n if not sorted(sort_result) in result :\n result.append(so... | {"fn_name": "group_cities", "inputs": [[["Tokyo", "London", "Rome", "Donlon", "Kyoto", "Paris", "Okyot"]], [["Tokyo", "London", "Rome", "Donlon"]], [["Rome", "Rome", "Rome", "Donlon", "London"]], [["Ab", "Aa"]], [[]]], "outputs": [[[["Kyoto", "Okyot", "Tokyo"], ["Donlon", "London"], ["Paris"], ["Rome"]]], [[["Donlon", ... | introductory | https://www.codewars.com/kata/5e98712b7de14f0026ef1cc1 |
def group_cities(seq):
|
3,263 | In this Kata, you will be given a series of times at which an alarm goes off. Your task will be to determine the maximum time interval between alarms. Each alarm starts ringing at the beginning of the corresponding minute and rings for exactly one minute. The times in the array are not in chronological order. Ignore du... | ["from datetime import datetime\n\ndef solve(arr):\n dts = [datetime(2000, 1, 1, *map(int, x.split(':'))) for x in sorted(arr)]\n delta = max(int((b - a).total_seconds() - 60) for a, b in zip(dts, dts[1:] + [dts[0].replace(day=2)]))\n return '{:02}:{:02}'.format(*divmod(delta//60, 60))", "def solve(arr):\n ... | {"fn_name": "solve", "inputs": [[["14:51"]], [["23:00", "04:22", "18:05", "06:24"]], [["21:14", "15:34", "14:51", "06:25", "15:30"]]], "outputs": [["23:59"], ["11:40"], ["09:10"]]} | introductory | https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2 |
def solve(arr):
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.