problem_id int64 0 5k | question stringlengths 50 14k | solutions stringlengths 12 1.21M | input_output stringlengths 0 23.6M | difficulty stringclasses 3
values | url stringlengths 36 108 | starter_code stringlengths 0 1.4k |
|---|---|---|---|---|---|---|
4,900 | Consider the sequence `S(n, z) = (1 - z)(z + z**2 + z**3 + ... + z**n)` where `z` is a complex number
and `n` a positive integer (n > 0).
When `n` goes to infinity and `z` has a correct value (ie `z` is in its domain of convergence `D`), `S(n, z)` goes to a finite limit
`lim` depending on `z`.
Experiment with `S(n,... | ["import math\n\ndef f(z, eps):\n if (abs(z) >= 1.0): return -1\n return int(math.log(eps) / math.log(abs(z)))\n", "from math import log\n\ndef f(z, eps):\n\n if z==0 or z==1 or (abs(z)**2<min([1,eps])): return 1\n elif abs(z)>=1: return -1\n else: return int(log(eps)/log(abs(z)))", "def f(z, eps, n=1):\... | {"fn_name": "f", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5b06c990908b7eea73000069 |
def f(z, eps):
|
4,901 | We all use 16:9, 16:10, 4:3 etc. ratios every day. Main task is to determine image ratio by its width and height dimensions.
Function should take width and height of an image and return a ratio string (ex."16:9").
If any of width or height entry is 0 function should throw an exception (or return `Nothing`). | ["from fractions import Fraction\n\ndef calculate_ratio(w, h):\n if w * h == 0:\n raise ValueError\n f = Fraction(w, h)\n return f\"{f.numerator}:{f.denominator}\"\n", "from fractions import gcd\n\ndef lcm(a, b):\n return a * b / gcd(a, b)\n\ndef calculate_ratio(w,h):\n if all(x > 0 for x in [w,h]... | {"fn_name": "calculate_ratio", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/55486cb94c9d3251560000ff |
def calculate_ratio(w, h):
|
4,902 | The built-in print function for Python class instances is not very entertaining.
In this Kata, we will implement a function ```show_me(instname)``` that takes an instance name as parameter and returns the string "Hi, I'm one of those (classname)s! Have a look at my (attrs).", where (classname) is the class name and (a... | ["def show_me(instname):\n attrs = sorted(instname.__dict__.keys())\n if len(attrs) == 1:\n attrs = attrs[0]\n else:\n attrs = '{} and {}'.format(', '.join(attrs[:-1]), attrs[-1])\n return 'Hi, I\\'m one of those {}s! Have a look at my {}.'\\\n .format(instname.__class__.__name__, attrs... | {"fn_name": "show_me", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/561f9d37e4786544e0000035 |
def show_me(instname):
|
4,903 | A sequence is usually a set or an array of numbers that has a strict way for moving from the nth term to the (n+1)th term.
If ``f(n) = f(n-1) + c`` where ``c`` is a constant value, then ``f`` is an arithmetic sequence.
An example would be (where the first term is 0 and the constant is 1) is [0, 1, 2, 3, 4, 5, ... and s... | ["def nthterm(first, n, c):\n return first + n * c", "def nthterm(first,n,d):\n return first+(n*d)", "def nthterm(first, n, c):\n if n == 0:\n return first\n else:\n return nthterm(first + c, n - 1, c)", "def nthterm(a,n,d):\n return a+(n*d)", "nthterm = lambda first, n, c: first + n * c", ... | {"fn_name": "nthterm", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/540f8a19a7d43d24ac001018 |
def nthterm(first, n, c):
|
4,904 | Write a function ```unpack()``` that unpacks a ```list``` of elements that can contain objects(`int`, `str`, `list`, `tuple`, `dict`, `set`) within each other without any predefined depth, meaning that there can be many levels of elements contained in one another.
Example:
```python
unpack([None, [1, ({2, 3}, {'foo':... | ["from collections import Iterable\n\ndef unpack(iterable):\n lst = []\n for x in iterable:\n if isinstance(x,dict): x = unpack(x.items())\n elif isinstance(x,str): x = [x]\n elif isinstance(x,Iterable): x = unpack(x)\n else: x = [x]\n lst.exten... | {"fn_name": "unpack", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/56ee74e7fd6a2c3c7800037e |
def unpack(l):
|
4,905 | You're given a mystery `puzzlebox` object. Examine it to make the tests pass and solve this kata. | ["def answer(puzzlebox):\n return 42", "def answer(puzzlebox):\n #print(dir(puzzlebox))\n #puzzlebox.hint\n #print(puzzlebox.hint_two)\n #print(puzzlebox.lock(puzzlebox.key))\n return 42\n pass", "# 09/01/2019\n# I did all the work in the Sample Test section, then after submitting my answer, all of... | {"fn_name": "answer", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/587f0871f297a6df780000cd |
def answer(puzzlebox):
|
4,906 | **See Also**
* [Traffic Lights - one car](.)
* [Traffic Lights - multiple cars](https://www.codewars.com/kata/5d230e119dd9860028167fa5)
---
# Overview
A character string represents a city road.
Cars travel on the road obeying the traffic lights..
Legend:
* `.` = Road
* `C` = Car
* `G` = GREEN traffic light
* `O` =... | ["def traffic_lights(road, n):\n lightsIdx = [ (i, 6*(c!='G')) for i,c in enumerate(road) if c in 'RG' ]\n car, ref = road.find('C'), road.replace('C','.')\n mut, out = list(ref), [road]\n \n for turn in range(1,n+1):\n \n for i,delta in lightsIdx: # Update al... | {"fn_name": "traffic_lights", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5d0ae91acac0a50232e8a547 |
def traffic_lights(road, n):
|
4,907 | # Task
When a candle finishes burning it leaves a leftover. makeNew leftovers can be combined to make a new candle, which, when burning down, will in turn leave another leftover.
You have candlesNumber candles in your possession. What's the total number of candles you can burn, assuming that you create new candles a... | ["def candles(candles, make_new):\n return candles + (candles - 1) // (make_new - 1)", "def candles(m, n):\n burn = leftover = 0\n while m:\n burn += m\n m, leftover = divmod(leftover + m, n)\n return burn", "def candles(a, b):\n return a + (a - 1) // (b - 1)", "from functools import lru_ca... | {"fn_name": "candles", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5884731139a9b4b7a8000002 |
def candles(m, n):
|
4,908 | In 1978 the British Medical Journal reported on an outbreak of influenza at a British boarding school. There were `1000` students. The outbreak began with one infected student.
We want to study the spread of the disease through the population of this school. The total population may be divided into three:
the infecte... | ["def epidemic(tm, n, s, i, b, a):\n def f(s, i, r): \n dt = tm / n\n for t in range(n):\n s, i, r = s-dt*b*s*i, i+dt*(b*s*i-a*i), r+dt*i*a\n yield i\n return int(max(f(s, i, 0)))", "def epidemic(tm, n, s0, i0, b, a):\n timing = 0\n dt = tm/n\n r0 = 0\n i_max = i0\... | {"fn_name": "epidemic", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/566543703c72200f0b0000c9 |
def epidemic(tm, n, s0, i0, b, a):
|
4,909 | Write a class Random that does the following:
1. Accepts a seed
```python
>>> random = Random(10)
>>> random.seed
10
```
2. Gives a random number between 0 and 1
```python
>>> random.random()
0.347957
>>> random.random()
0.932959
```
3. Gives a random int from a range
```python
>>> random.randint(0, 100)
67
>>> rand... | ["import hashlib\n\nclass Random():\n HASH_MAX = (1 << 32 * 4) - 1\n\n def __init__(self, seed):\n self.seed = seed\n def random(self):\n x = int(hashlib.md5(str(self.seed).encode()).hexdigest(), 16)\n self.seed += 1\n return x / self.HASH_MAX\n def randint(self, start, end):\n ... | {"fn_name": "__init__", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5872a121056584c25400011d |
def __init__(self, seed):
|
4,910 | This kata is part one of precise fractions series (see pt. 2: http://www.codewars.com/kata/precise-fractions-pt-2-conversion).
When dealing with fractional values, there's always a problem with the precision of arithmetical operations. So lets fix it!
Your task is to implement class ```Fraction``` that takes care of ... | ["from fractions import Fraction\n\ndef to_string(self):\n n, d = self.numerator, self.denominator\n s, w, n = \"-\" if n < 0 else \"\", *divmod(abs(n), d)\n r = \" \".join((str(w) if w else \"\", f\"{n}/{d}\" if n else \"\")).strip()\n return f\"{s}{r}\"\n\nFraction.__str__ = to_string\nFraction.to_decimal... | {"fn_name": "to_string", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/54cf4fc26b85dc27bf000a6b |
def to_string(self):
|
4,911 | #Adding values of arrays in a shifted way
You have to write a method, that gets two parameter:
```markdown
1. An array of arrays with int-numbers
2. The shifting value
```
#The method should add the values of the arrays to one new array.
The arrays in the array will all have the same size and this size will always ... | ["from itertools import zip_longest as zl\n\ndef sum_arrays(arrays, shift):\n shifted = [[0] * shift * i + arr for i, arr in enumerate(arrays)]\n return [sum(t) for t in zl(*shifted, fillvalue=0)]", "from itertools import zip_longest\n\ndef sum_arrays(arrays, shift):\n shifted = [([0] * shift * i) + array for ... | {"fn_name": "sum_arrays", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/57c7231c484cf9e6ac000090 |
def sum_arrays(arrays, shift):
|
4,912 | # Task
You are implementing your own HTML editor. To make it more comfortable for developers you would like to add an auto-completion feature to it.
Given the starting HTML tag, find the appropriate end tag which your editor should propose.
# Example
For startTag = "<button type='button' disabled>", the output sh... | ["def html_end_tag_by_start_tag(start_tag):\n return \"</\" + start_tag[1:-1].split(\" \")[0] + \">\"", "def html_end_tag_by_start_tag(start_tag):\n return \"</{}>\".format(start_tag.strip(\"<>\").split(\" \")[0])\n", "import re\ndef html_end_tag_by_start_tag(start_tag):\n return re.sub('<(\\w+)(?:.*)>', r'</\\1... | {"fn_name": "html_end_tag_by_start_tag", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5886f3713a111b620f0000dc |
def html_end_tag_by_start_tag(start_tag):
|
4,913 | # Our Setup
Alice and Bob work in an office. When the workload is light and the boss isn't looking, they often play simple word games for fun. This is one of those days!
# This Game
Today Alice and Bob are playing what they like to call _Mutations_, where they take turns trying to "think up" a new four-letter word i... | ["import re\n\ndef genMask(w):\n x = list(w)\n for i in range(len(w)):\n x[i] = '.'\n yield ''.join(x)\n x[i] = w[i]\n\ndef mutations(alice, bob, word, first):\n players, seen = [alice,bob], {word}\n win, failed, i = -1, -1, first^1\n while 1:\n i ^= 1\n lst = pla... | {"fn_name": "mutations", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5cb5eb1f03c3ff4778402099 |
def mutations(alice, bob, word, first):
|
4,914 | When provided with a letter, return its position in the alphabet.
Input :: "a"
Ouput :: "Position of alphabet: 1"
`This kata is meant for beginners. Rank and upvote to bring it out of beta` | ["def position(alphabet):\n return \"Position of alphabet: {}\".format(ord(alphabet) - 96)", "def position(alphabet):\n return \"Position of alphabet: %s\" % (\"abcdefghijklmnopqrstuvwxyz\".find(alphabet) + 1)", "from string import ascii_lowercase\ndef position(char):\n return \"Position of alphabet: {0}\".for... | {"fn_name": "position", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5808e2006b65bff35500008f |
def position(alphabet):
|
4,915 | Help Suzuki rake his garden!
The monastery has a magnificent Zen garden made of white gravel and rocks and it is raked diligently everyday by the monks. Suzuki having a keen eye is always on the lookout for anything creeping into the garden that must be removed during the daily raking such as insects or moss.
You wi... | ["VALID = {'gravel', 'rock'}\n\n\ndef rake_garden(garden):\n return ' '.join(a if a in VALID else 'gravel' for a in garden.split())\n", "def rake_garden(garden):\n return \" \".join(w if w == \"rock\" else \"gravel\" for w in garden.split())\n", "import re\n\ndef rake_garden(garden):\n return re.sub(r'(?<!\\S)... | {"fn_name": "rake_garden", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/571c1e847beb0a8f8900153d |
def rake_garden(garden):
|
4,916 | Write a function generator that will generate the first `n` primes grouped in tuples of size `m`. If there are not enough primes for the last tuple it will have the remaining values as `None`.
## Examples
```python
For n = 11 and m = 2:
(2, 3), (5, 7), (11, 13), (17, 19), (23, 29), (31, None)
For n = 11 and m = 3:
(... | ["# generate primes up to limit\nLIMIT = 10**6\nsieve = [0]*2 + list(range(2, LIMIT))\nfor n in sieve:\n if n:\n for i in range(n*n, LIMIT, n):\n sieve[i] = 0\nPRIMES = list(n for n in sieve if n)\n\ndef get_primes(n, m=2):\n primes_ = PRIMES[:n] + [None] * m\n return ( tuple(primes_[i:i+m]) ... | {"fn_name": "get_primes", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/593e8d839335005b42000097 |
def get_primes(how_many, group_size=2):
|
4,917 | Write a function that takes a string of braces, and determines if the order of the braces is valid. It should return `true` if the string is valid, and `false` if it's invalid.
This Kata is similar to the [Valid Parentheses](https://www.codewars.com/kata/valid-parentheses) Kata, but introduces new characters: brackets... | ["def validBraces(string):\n braces = {\"(\": \")\", \"[\": \"]\", \"{\": \"}\"}\n stack = []\n for character in string:\n if character in braces.keys():\n stack.append(character)\n else:\n if len(stack) == 0 or braces[stack.pop()] != character:\n return False... | {"fn_name": "validBraces", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5277c8a221e209d3f6000b56 |
def validBraces(string):
|
4,918 | You have been tasked with converting a number from base i (sqrt of -1) to base 10.
Recall how bases are defined:
abcdef = a * 10^5 + b * 10^4 + c * 10^3 + d * 10^2 + e * 10^1 + f * 10^0
Base i follows then like this:
... i^4 + i^3 + i^2 + i^1 + i^0
The only numbers in any place will be 1 or 0
Examples:
... | ["def convert(n):\n ds = list(map(int, reversed(str(n))))\n return [sum(ds[::4]) - sum(ds[2::4]), sum(ds[1::4]) - sum(ds[3::4])]", "def convert(n):\n s = str(n)[::-1]\n return [sum(p * s[i - p::4].count(\"1\") for p in (1, -1)) for i in (1, 2)]\n", "def convert(n):\n result = sum(1j ** i for i, x in enum... | {"fn_name": "convert", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/583a47342fb0ba1418000060 |
def convert(n):
|
4,919 | You are given an n by n ( square ) grid of characters, for example:
```python
[['m', 'y', 'e'],
['x', 'a', 'm'],
['p', 'l', 'e']]
```
You are also given a list of integers as input, for example:
```python
[1, 3, 5, 8]
```
You have to find the characters in these indexes of the grid if you think of the indexes a... | ["def grid_index(grid, idxs):\n return ''.join(grid[x][y] for x,y in map(lambda n: divmod(n-1,len(grid)),idxs))", "def grid_index(grid, indexes):\n flat = sum(grid, [])\n return \"\".join( flat[i-1] for i in indexes )", "def grid_index(grid, indexes):\n flat = tuple(x for e in grid for x in e)\n return '... | {"fn_name": "grid_index", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5f5802bf4c2cc4001a6f859e |
def grid_index(grid, indexes):
|
4,920 | Given a certain array of integers, create a function that may give the minimum number that may be divisible for all the numbers of the array.
```python
min_special_mult([2, 3 ,4 ,5, 6, 7]) == 420
```
The array may have integers that occurs more than once:
```python
min_special_mult([18, 22, 4, 3, 21, 6, 3]) == 2772
``... | ["from fractions import gcd\nimport re\nfrom functools import reduce\n\ndef min_special_mult(arr):\n l = [e for e in arr if not re.match('(None)|([+-]?\\d+)', str(e))]\n if len(l) == 1:\n return 'There is 1 invalid entry: {}'.format(l[0])\n if len(l) > 1:\n return 'There are {} invalid entries: {... | {"fn_name": "min_special_mult", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/56f245a7e40b70f0e3000130 |
def min_special_mult(arr):
|
4,921 | In this kata, we're going to create the function `nato` that takes a `word` and returns a string that spells the word using the [NATO phonetic alphabet](https://en.wikipedia.org/wiki/NATO_phonetic_alphabet).
There should be a space between each word in the returned string, and the first letter of each word should be c... | ["letters = {\n \"A\": \"Alpha\", \"B\": \"Bravo\", \"C\": \"Charlie\",\n \"D\": \"Delta\", \"E\": \"Echo\", \"F\": \"Foxtrot\",\n \"G\": \"Golf\", \"H\": \"Hotel\", \"I\": \"India\",\n \"J\": \"Juliett\",\"K\": \"Kilo\", \"L\": \"Lima\",\n \"M\": \"Mike\", \"N\": \"November\",\"O\": \"O... | {"fn_name": "nato", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/54530f75699b53e558002076 |
def nato(word):
|
4,922 | Linked lists are data structures composed of nested or chained objects, each containing a single value and a reference to the next object.
Here's an example of a list:
```python
class LinkedList:
def __init__(self, value=0, next=None):
self.value = value
self.next = next
LinkedList(1, Li... | ["def list_to_array(lst):\n arr = []\n while lst != None:\n arr.append(lst.value)\n lst = lst.next\n return arr", "def list_to_array(lst):\n return ([lst.value] + list_to_array(lst.next)) if lst else []", "def list_to_array(ll):\n output = []\n while ll:\n output.append(ll.value)\... | {"fn_name": "list_to_array", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/557dd2a061f099504a000088 |
def list_to_array(lst):
|
4,923 | You have two arguments: ```string``` - a string of random letters(only lowercase) and ```array``` - an array of strings(feelings). Your task is to return how many specific feelings are in the ```array```.
For example:
```
string -> 'yliausoenvjw'
array -> ['anger', 'awe', 'joy', 'love', 'grief']
output -> '3 feelin... | ["from collections import Counter\n\ndef count_feelings(s, arr):\n total = sum(Counter(s) & Counter(w) == Counter(w) for w in arr)\n return '%s feeling%s.' % (total, '' if total == 1 else 's')", "from collections import Counter\n\n\ndef count_feelings(stg, lst):\n letters = Counter(stg)\n count = sum(1 for ... | {"fn_name": "count_feelings", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5a33ec23ee1aaebecf000130 |
def count_feelings(s, arr):
|
4,924 | Professor Oak has just begun learning Python and he wants to program his new Pokedex prototype with it.
For a starting point, he wants to instantiate each scanned Pokemon as an object that is stored at Pokedex's memory. He needs your help!
Your task is to:
1) Create a ```PokeScan``` class that takes in 3 arguments: ... | ["class PokeScan:\n def __init__(self, name, level, pkmntype):\n self.name = name\n self.level = level\n self.pkmntype = pkmntype\n\n def info(self):\n level_info = \"weak\" if self.level <= 20 else \"fair\" if self.level <= 50 else \"strong\"\n pkmntypes_info = {\"water\": \"we... | {"fn_name": "__init__", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/57520361f2dac757360018ce |
def __init__(self, name, level, pkmntype):
|
4,925 | ## Preface
A collatz sequence, starting with a positive integern, is found by repeatedly applying the following function to n until n == 1 :
`$f(n) =
\begin{cases}
n/2, \text{ if $n$ is even} \\
3n+1, \text{ if $n$ is odd}
\end{cases}$`
----
A more detailed description of the collatz conjecture may be found [on... | ["def collatz(n):\n l = [str(n)]\n while n > 1:\n n = 3 * n + 1 if n % 2 else n / 2\n l.append(str(n))\n return '->'.join(l)", "def collatz_step(n):\n if n % 2 == 0:\n return n//2\n else:\n return n*3 + 1\n\ndef collatz_seq(n):\n while n != 1:\n yield n\n n = ... | {"fn_name": "collatz", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5286b2e162056fd0cb000c20 |
def collatz(n):
|
4,926 | Given any number of boolean flags function should return true if and only if one of them is true while others are false. If function is called without arguments it should return false.
```python
only_one() == False
only_one(True, False, False) == True
only_one(True, False, False, True) == False
only_one(False,... | ["def only_one(*args):\n return sum(args) == 1", "def only_one(*args):\n return args.count(True)==1", "def only_one(*args):\n count = 0\n for item in args:\n if item:\n count += 1\n if count == 2:\n return False\n return True if count == 1 else False", "def only_one(*x... | {"fn_name": "only_one", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5734c38da41454b7f700106e |
def only_one(*args):
|
4,927 | Given an array `A` and an integer `x`, map each element in the array to `F(A[i],x)` then return the xor sum of the resulting array.
where F(n,x) is defined as follows:
F(n, x) = ^(x)Cx **+** ^(x+1)Cx **+** ^(x+2)Cx **+** ... **+** ^(n)Cx
and ^(n)Cx represents [Combination](https://en.m.wikipedia.org/wiki/Combination... | ["from functools import reduce\nfrom gmpy2 import comb\nfrom operator import xor\n\ndef transform(a, x):\n return reduce(xor, (comb(n + 1, x + 1) for n in a))", "def transform(A, x):\n c, i, f, r = 1, x, 0, None\n for n in sorted(A):\n while i <= n:\n c *= i\n c //= i-x or x\n ... | {"fn_name": "transform", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5bb9053a528b29a970000113 |
def transform(A, x):
|
4,928 | A startup office has an ongoing problem with its bin. Due to low budgets, they don't hire cleaners. As a result, the staff are left to voluntarily empty the bin. It has emerged that a voluntary system is not working and the bin is often overflowing. One staff member has suggested creating a rota system based upon the s... | ["def binRota(arr):\n return [name for i, row in enumerate(arr) for name in row[::-1 if i % 2 else 1]]", "def binRota(arr):\n rota = []\n for i, row in enumerate(arr):\n if i % 2: row = reversed(row)\n rota.extend(row)\n return rota", "def binRota(arr):\n res = []\n for i in range(len(ar... | {"fn_name": "binRota", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/578fdcfc75ffd1112c0001a1 |
def binRota(arr):
|
4,929 | ## Decode the diagonal.
Given a grid of characters. Output a decoded message as a string.
Input
```
H Z R R Q
D I F C A E A !
G H T E L A E
L M N H P R F
X Z R P E
```
Output
`HITHERE!` (diagonally down right `↘` and diagonally up right `↗` if you can't go further).
The message ends when there is n... | ["def get_diagonale_code(grid):\n grid = [line.split() for line in grid.split(\"\\n\")]\n i, j, d, word = 0, 0, 1, \"\"\n while 0 <= i < len(grid) and j < len(grid[i]):\n if 0 <= j < len(grid[i]):\n word += grid[i][j]\n i, j = i + d, j + 1\n else: i += d\n if i == 0 o... | {"fn_name": "get_diagonale_code", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/55af0d33f9b829d0a800008d |
def get_diagonale_code(grid:
|
4,930 | You are given an array of positive and negative integers and a number ```n``` and ```n > 1```. The array may have elements that occurs more than once.
Find all the combinations of n elements of the array that their sum are 0.
```python
arr = [1, -1, 2, 3, -2]
n = 3
find_zero_sum_groups(arr, n) == [-2, -1, 3] # -2 - 1 +... | ["from itertools import combinations\ndef find_zero_sum_groups(arr, n):\n combos = sorted(sorted(c) for c in combinations(set(arr), n) if sum(c) == 0)\n return combos if len(combos) > 1 else combos[0] if combos else \"No combinations\" if arr else \"No elements to combine\"", "from itertools import combinations a... | {"fn_name": "find_zero_sum_groups", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5711fc7c159cde6ac70003e2 |
def find_zero_sum_groups(arr, n):
|
4,931 | # Task
Given a rectangular matrix containing only digits, calculate the number of different `2 × 2` squares in it.
# Example
For
```
matrix = [[1, 2, 1],
[2, 2, 2],
[2, 2, 2],
[1, 2, 3],
[2, 2, 1]]
```
the output should be `6`.
Here are all 6 different 2 × 2 squares:
```... | ["def different_squares(matrix):\n s = set()\n rows, cols = len(matrix), len(matrix[0])\n for row in range(rows - 1):\n for col in range(cols - 1):\n s.add((matrix[row][col], matrix[row][col + 1], matrix[row + 1][col], matrix[row + 1][col + 1]))\n return len(s)", "def different_squares(mat... | {"fn_name": "different_squares", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/588805ca44c7e8c3a100013c |
def different_squares(matrix):
|
4,932 | # Toggling Grid
You are given a grid (2d array) of 0/1's. All 1's represents a solved puzzle. Your job is to come up with a sequence of toggle moves that will solve a scrambled grid.
Solved:
```
[ [1, 1, 1],
[1, 1, 1],
[1, 1, 1] ]
```
"0" (first row) toggle:
```
[ [0, 0, 0],
[1, 1, 1],
[1, 1, 1] ]
```
then... | ["def find_solution(m):\n return [j for j,r in enumerate(m) if r[0]^m[0][0]] + [len(m)+i for i,b in enumerate(m[0]) if not b]", "find_solution = lambda m: [n for n, r in enumerate(m) if r[0]] + [n for n, c in enumerate(m[0],len(m)) if not m[0][0] ^ c]", "def find_solution(puzzle):\n n, sol = len(puzzle), []\n ... | {"fn_name": "find_solution", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5bfc9bf3b20606b065000052 |
def find_solution(puzzle):
|
4,933 | Write a function that will randomly upper and lower characters in a string - `randomCase()` (`random_case()` for Python).
A few examples:
```
randomCase("Lorem ipsum dolor sit amet, consectetur adipiscing elit") == "lOReM ipSum DOloR SiT AmeT, cOnsEcTEtuR aDiPiSciNG eLIt"
randomCase("Donec eleifend cursus lobortis")... | ["import random\n\ndef random_case(x):\n return \"\".join([random.choice([c.lower(), c.upper()]) for c in x])", "In [20]: def random_case(x): return \"\".join([choice([c.lower(), c.upper()]) for c in x]) # That one \nIn [21]: %timeit random_case(s) ... | {"fn_name": "random_case", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/57073869924f34185100036d |
def random_case(x):
|
4,934 | Write a `sort` function that will sort a massive list of strings in caseless, lexographic order.
Example Input:
`['b', 'ba', 'ab', 'bb', 'c']`
Expected Output:
`['ab', 'b', 'ba', 'bb', 'c']`
* The argument for your function will be a generator that will return a new word for each call of next()
* Your function will ... | ["import heapq, itertools\n\ndef sort(iterable):\n heap = list(iterable)\n heapq.heapify(heap)\n return (heapq.heappop(heap) for i in range(len(heap)))", "def sort(words):\n from random import choice\n from itertools import chain\n words = list(words)\n if len(words) <= 1: return iter(words)\n p... | {"fn_name": "sort", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5820e17770ca28df760012d7 |
def sort(words):
|
4,935 | ⚠️ The world is in quarantine! There is a new pandemia that struggles mankind. Each continent is isolated from each other but infected people have spread before the warning. ⚠️
🗺️ You would be given a map of the world in a type of string:
string s = "01000000X000X011X0X"
'0' : uninfected
'1' : infected... | ["def infected(s):\n lands = s.split('X')\n total = sum(map(len, lands))\n infected = sum(len(x) for x in lands if '1' in x)\n return infected * 100 / (total or 1)", "def infected(s):\n total_population = s.split('X')\n total = 0\n infected = 0\n for population in total_population:\n if \... | {"fn_name": "infected", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5e2596a9ad937f002e510435 |
def infected(s):
|
4,936 | Write a function `reverse` which reverses a list (or in clojure's case, any list-like data structure)
(the dedicated builtin(s) functionalities are deactivated) | ["from collections import deque\n\ndef reverse(lst):\n q = deque()\n for x in lst:\n q.appendleft(x)\n return list(q)", "def reverse(lst):\n out = list()\n for i in range(len(lst)-1,-1,-1):\n out.append(lst[i])\n return out", "\ndef reverse(lst):\n empty_list = list() # use... | {"fn_name": "reverse", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5413759479ba273f8100003d |
def reverse(lst):
|
4,937 | You're in the casino, playing Roulette, going for the "1-18" bets only and desperate to beat the house and so you want to test how effective the [Martingale strategy](https://en.wikipedia.org/wiki/Martingale_(betting_system)) is.
You will be given a starting cash balance and an array of binary digits to represent a w... | ["def martingale(bank, outcomes):\n stake = 100\n for i in outcomes:\n if i == 0:\n bank -= stake\n stake *= 2\n else:\n bank += stake\n stake = 100\n return bank", "def martingale(bank, outcomes):\n bet=100\n for results in outcomes:\n if ... | {"fn_name": "martingale", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5eb34624fec7d10016de426e |
def martingale(bank, outcomes):
|
4,938 | The goal of this kata is to write a function that takes two inputs: a string and a character. The function will count the number of times that character appears in the string. The count is case insensitive.
For example:
```python
count_char("fizzbuzz","z") => 4
count_char("Fancy fifth fly aloof","f") => 5
```
The c... | ["def count_char(s,c):\n return s.lower().count(c.lower())", "def count_char(strng, c):\n return strng.lower().count(c.lower())", "def count_char(s, c):\n return s.upper().count(c.upper())", "from collections import Counter\n\ndef count_char(s, c):\n return Counter(s.lower())[c.lower()]", "def count_char(st... | {"fn_name": "count_char", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/577ad961ae2807182f000c29 |
def count_char(s, c):
|
4,939 | # Background
I drink too much coffee. Eventually it will probably kill me.
*Or will it..?*
Anyway, there's no way to know.
*Or is there...?*
# The Discovery of the Formula
I proudly announce my discovery of a formula for measuring the life-span of coffee drinkers!
For
* ```h``` is a health number assigned to ... | ["def coffee_limits(year, month, day):\n h = int(f'{year:04}{month:02}{day:02}')\n return [limit(h, 0xcafe), limit(h, 0xdecaf)]\n \ndef limit(h, c):\n for i in range(1, 5000):\n h += c\n if 'DEAD' in f'{h:X}':\n return i\n return 0\n\n", "def coffee_limits(year, month, day):\n ... | {"fn_name": "coffee_limits", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/57db78d3b43dfab59c001abe |
def coffee_limits(year, month, day):
|
4,940 | # Story
Old MacDingle had a farm...
...and on that farm he had
* horses
* chickens
* rabbits
* some apple trees
* a vegetable patch
Everything is idylic in the MacDingle farmyard **unless somebody leaves the gates open**
Depending which gate was left open then...
* horses might run away
* horses might eat the... | ["from itertools import groupby\ndef shut_the_gate(farm):\n who_eats_whom = {'H': ['A', 'V'], 'R': ['V'], 'C': []}\n runaway_back ,runaway_front, farm = [], [], [\"\".join(j) for k, j in groupby(farm)]\n def doSomeFarm(i=0):\n def do(j,s=False):\n while (j >= 0 if s else j<len(farm)) and farm... | {"fn_name": "shut_the_gate", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/59218bf66034acb9b7000040 |
def shut_the_gate(farm):
|
4,941 | Suzuki needs help lining up his students!
Today Suzuki will be interviewing his students to ensure they are progressing in their training. He decided to schedule the interviews based on the length of the students name in descending order. The students will line up and wait for their turn.
You will be given a string o... | ["lineup_students = lambda (s): sorted(s.split(), key=lambda x: (len(x), x), reverse=True)", "def lineup_students(s):\n return sorted(s.split(), key=lambda i:(len(i),i), reverse=True)\n", "def lineup_students(names):\n return sorted(names.split(), key=lambda s: (len(s), s), reverse=True)", "def lineup_students(na... | {"fn_name": "lineup_students", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5701800886306a876a001031 |
def lineup_students(s):
|
4,942 | You are given a list of directions in the form of a list:
goal = ["N", "S", "E", "W"]
Pretend that each direction counts for 1 step in that particular direction.
Your task is to create a function called directions, that will return a reduced list that will get you to the same point.The order of directions must be re... | ["def directions(goal):\n y = goal.count(\"N\") - goal.count(\"S\")\n x = goal.count(\"E\") - goal.count(\"W\")\n \n return [\"N\"] * y + [\"S\"] * (-y) + [\"E\"] * x + [\"W\"] * (-x)", "def directions(goal):\n count = lambda s: len([c for c in goal if c == s])\n ns = 1 * count(\"N\") - 1 * count(\"S\... | {"fn_name": "directions", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/56a14f18005af7002f00003f |
def directions(goal):
|
4,943 | Your task is to return how many times a string contains a given character.
The function takes a string(inputS) as a paremeter and a char(charS) which is the character that you will have to find and count.
For example, if you get an input string "Hello world" and the character to find is "o", return 2. | ["def string_counter(string, char):\n return string.count(char)", "string_counter = str.count ", "def string_counter(string, char):\n return sum(1 for i in string if char == i)", "def string_counter(strng, char):\n '''Return the frequency of a character in a string'''\n return strng.count(char)", "string... | {"fn_name": "string_counter", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/584466950d3bedb9b300001f |
def string_counter(string, char):
|
4,944 | Create a class Vector that has simple (3D) vector operators.
In your class, you should support the following operations, given Vector ```a``` and Vector ```b```:
```python
a + b # returns a new Vector that is the resultant of adding them
a - b # same, but with subtraction
a == b # returns true if they have the same m... | ["import math\n\n\nclass VectorInputCoordsValidationError(Exception):\n \"\"\"Custom exception class for invalid input args given to the Vector instantiation\"\"\"\n\n\nclass Vector:\n # https://www.mathsisfun.com/algebra/vectors.html\n\n def __init__(self, *args):\n try:\n self.x, self.y, se... | {"fn_name": "__init__", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/532a69ee484b0e27120000b6 |
def __init__(self, *args):
|
4,945 | A great flood has hit the land, and just as in Biblical times we need to get the animals to the ark in pairs. We are only interested in getting one pair of each animal, and not interested in any animals where there are less than 2....they need to mate to repopulate the planet after all!
You will be given a list of ani... | ["def two_by_two(animals):\n return {x:2 for x in animals if animals.count(x) > 1} if animals else False", "from collections import Counter\n\ndef two_by_two(animals):\n return bool(animals) and {key : 2 for key, value in Counter(animals).items() if value >= 2}", "def two_by_two(animals):\n return {animal: 2 f... | {"fn_name": "two_by_two", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/578de3801499359921000130 |
def two_by_two(animals):
|
4,946 | # Task
A boy is walking a long way from school to his home. To make the walk more fun he decides to add up all the numbers of the houses that he passes by during his walk. Unfortunately, not all of the houses have numbers written on them, and on top of that the boy is regularly taking turns to change streets, so the n... | ["def house_numbers_sum(inp):\n return sum(inp[:inp.index(0)])", "from itertools import takewhile; house_numbers_sum = lambda arr: sum(x for x in takewhile(lambda x: x!=0, arr))", "def house_numbers_sum(inp):\n total = 0\n for house_num in inp:\n if house_num == 0:\n return total\n els... | {"fn_name": "house_numbers_sum", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/58880c6e79a0a3e459000004 |
def house_numbers_sum(inp):
|
4,947 | Create a function ```sel_number()```, that will select numbers that fulfill the following constraints:
1) The numbers should have 2 digits at least.
2) They should have their respective digits in increasing order from left to right.
Examples: 789, 479, 12678, have these feature. But 617, 89927 are not of this type.
... | ["def sel_number(n, d):\n cnt = 0\n for a in range(12, n + 1):\n nums = list(map(int, str(a)))\n if nums == sorted(set(nums)) and \\\n all(c - b <= d for b, c in zip(nums[:-1], nums[1:])):\n cnt += 1\n return cnt\n", "sel_number=lambda n,d:sum(all(d>=int(b)-int(a)>0for a... | {"fn_name": "sel_number", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/55d8aa568dec9fb9e200004a |
def sel_number(n, d):
|
4,948 | Write the function `resistor_parallel` that receive an undefined number of resistances parallel resistors and return the total resistance.
You can assume that there will be no 0 as parameter.
Also there will be at least 2 arguments.
Formula:
`total = 1 / (1/r1 + 1/r2 + .. + 1/rn)`
Examples:
`resistor_parallel(... | ["def resistor_parallel(*rs):\n return 1 / sum(1.0 / r for r in rs)", "def resistor_parallel(*resistances):\n return 1 / sum(1.0 / r for r in resistances)", "def resistor_parallel(*xs):\n return 1 / sum(1 / x for x in map(float, xs))", "resistor_parallel = lambda *args: 1 / sum(1.0 / i for i in args)", "def re... | {"fn_name": "resistor_parallel", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5723b111101f5f905f0000a5 |
def resistor_parallel(*resistors):
|
4,949 | Robinson Crusoe decides to explore his isle. On a sheet of paper he plans the following process.
His hut has coordinates `origin = [0, 0]`. From that origin he walks a given distance `d` on a line
that has a given angle `ang` with the x-axis. He gets to a point A.
(Angles are measured with respect to the x-axis)
Fro... | ["from math import cos, sin, radians\n\ndef crusoe(n, d, ang, dist_mult, ang_mult):\n x, y, a = 0, 0, radians(ang)\n for i in range(n):\n x += d * cos(a)\n y += d * sin(a)\n d *= dist_mult\n a *= ang_mult\n return x, y", "from math import sin,cos,pi\ndef crusoe(n, d, ang, dis_tmult,... | {"fn_name": "crusoe", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5d95b7644a336600271f52ba |
def crusoe(n, d, ang, dist_mult, ang_mult):
|
4,950 | ### Task
Your main goal is to find two numbers(` >= 0 `), greatest common divisor of wich will be `divisor` and number of iterations, taken by Euclids algorithm will be `iterations`.
### Euclid's GCD
```CSharp
BigInteger FindGCD(BigInteger a, BigInteger b) {
// Swaping `a` and `b`
if (a < b) {
a += b;
b ... | ["def find_initial_numbers (divisor, iterations):\n a = divisor\n b = divisor if iterations != 0 else 0\n \n for _ in range(iterations):\n c = b\n b = a\n a = b + c\n \n return a, b", "def find_initial_numbers (divisor, iterations):\n a, b = divisor, 0\n for _ in range(itera... | {"fn_name": "find_initial_numbers ", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/58cd7f6914e656400100005a |
def find_initial_numbers (divisor, iterations):
|
4,951 | Take the following IPv4 address: 128.32.10.1
This address has 4 octets where each octet is a single byte (or 8 bits).
* 1st octet 128 has the binary representation: 10000000
* 2nd octet 32 has the binary representation: 00100000
* 3rd octet 10 has the binary representation: 00001010
* 4th octet 1 has the binary repre... | ["def ip_to_int32(ip):\n \"\"\"\n Take the following IPv4 address: 128.32.10.1 This address has 4 octets\n where each octet is a single byte (or 8 bits).\n\n 1st octet 128 has the binary representation: 10000000\n 2nd octet 32 has the binary representation: 00100000\n 3rd octet 10 has the binary repre... | {"fn_name": "ip_to_int32", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/52ea928a1ef5cfec800003ee |
def ip_to_int32(ip):
|
4,952 | **The Rub**
You need to make a function that takes an object as an argument, and returns a very similar object but with a special property. The returned object should allow a user to access values by providing only the beginning of the key for the value they want. For example if the given object has a key `idNumber`, ... | ["\ndef partial_keys(d):\n class Dct(dict):\n def __getitem__(self,pk):\n k = min((k for k in self if k.startswith(pk)), default=None)\n return k if k is None else super().__getitem__(k)\n return Dct(d)", "class PartialKeysDict(dict):\n\n def __init__(self, *args, **kwargs):\n ... | {"fn_name": "__getitem__", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5e602796017122002e5bc2ed |
def __getitem__(self, key):
|
4,953 | Lets play some Pong!

For those who don't know what Pong is, it is a simple arcade game where two players can move their paddles to hit a ball towards the opponent's side of the screen, gaining a point for each opponent's miss. You can read more a... | ["from itertools import cycle\n\nclass Pong:\n def __init__(self, max_score):\n self.max_score = max_score;\n self.scores = {1: 0, 2: 0}\n self.players = cycle((1, 2))\n\n def game_over(self):\n return any(score >= self.max_score for score in list(self.scores.values()))\n\n def play... | {"fn_name": "__init__", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5b432bdf82417e3f39000195 |
def __init__(self, max_score):
|
4,954 | Design a data structure that supports the following two operations:
* `addWord` (or `add_word`) which adds a word,
* `search` which searches a literal word or a regular expression string containing lowercase letters `"a-z"` or `"."` where `"."` can represent any letter
You may assume that all given words contain only... | ["import re\nclass WordDictionary:\n def __init__(self):\n self.data=[]\n \n def add_word(self,x):\n self.data.append(x)\n \n def search(self,x):\n for word in self.data:\n if re.match(x+\"\\Z\",word): return True\n return False", "class WordDictionary:\n def __init__(... | {"fn_name": "__init__", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5631ac5139795b281d00007d |
def __init__(self):
|
4,955 | It is a well-known fact that behind every good comet is a UFO. These UFOs often come to collect loyal supporters from here on Earth. Unfortunately, they only have room to pick up one group of followers on each trip. They do, however, let the groups know ahead of time which will be picked up for each comet by a clever s... | ["from operator import mul\n\ndef ride(group, comet):\n val = lambda name: reduce(mul, (ord(c)-64 for c in name))\n return 'GO' if val(comet) % 47 == val(group) % 47 else 'STAY'", "def ride(group,comet):\n n1 = 1\n n2 = 1\n for x in group:\n n1 *= ord(x.lower()) - 96\n for x in comet:\n ... | {"fn_name": "ride", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/55491e9e50f2fc92f3000074 |
def ride(group,comet):
|
4,956 | Our cells go through a process called protein synthesis to translate the instructions in DNA into an amino acid chain, or polypeptide.
Your job is to replicate this!
---
**Step 1: Transcription**
Your input will be a string of DNA that looks like this:
`"TACAGCTCGCTATGAATC"`
You then must transcribe it to mRNA. ... | ["import re\n\nTABLE = str.maketrans('ACGT','UGCA')\n\ndef protein_synthesis(dna):\n rna = re.findall(r'.{1,3}', dna.translate(TABLE))\n return ' '.join(rna), ' '.join(x for x in map(CODON_DICT.get, rna) if x)", "MRNA_TABLE = str.maketrans(\"ACGT\", \"UGCA\")\n\ndef protein_synthesis(dna):\n rna = dna.translat... | {"fn_name": "protein_synthesis", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/58df2d65808fbcdfc800004a |
def protein_synthesis(dna):
|
4,957 | Teach snoopy and scooby doo how to bark using object methods.
Currently only snoopy can bark and not scooby doo.
```python
snoopy.bark() #return "Woof"
scoobydoo.bark() #undefined
```
Use method prototypes to enable all Dogs to bark. | ["class Dog ():\n def __init__(self, breed):\n self.breed = breed\n def bark(self):\n return \"Woof\"\n\nsnoopy = Dog(\"Beagle\")\n\nscoobydoo = Dog(\"Great Dane\")", "class Dog ():\n def __init__(self, breed):\n self.breed = breed\n self.bark = lambda: \"Woof\"\n \nsnoopy = Dog(\"Beagle\")\n\nscoobyd... | {"fn_name": "__init__", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/54dba07f03e88a4cec000caf |
def __init__(self, breed):
|
4,958 | Complete the solution so that it returns a formatted string. The return value should equal "Value is VALUE" where value is a 5 digit padded number.
Example:
```python
solution(5) # should return "Value is 00005"
``` | ["def solution(value):\n return \"Value is %05d\" % value", "solution='Value is {:05d}'.format\n \n", "def solution(value):\n num = 5 - len(str(value))\n zeros = \"\"\n for i in range(num):\n zeros += \"0\"\n return(\"Value is {}\".format(zeros + str(value)))\n", "def solution(value):\n retu... | {"fn_name": "solution", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/51c89385ee245d7ddf000001 |
def solution(value):
|
4,959 | There are a **n** balls numbered from 0 to **n-1** (0,1,2,3,etc). Most of them have the same weight, but one is heavier. Your task is to find it.
Your function will receive two arguments - a `scales` object, and a ball count. The `scales` object has only one method:
```python
get_weight(left, right)
```
where `l... | ["def find_ball(scales, n):\n select = list(range(n))\n while len(select) > 1:\n left, right, unused = select[::3], select[1::3], select[2::3]\n if len(select) % 3 == 1: unused.append(left.pop())\n select = [left, unused, right][scales.get_weight(left, right) + 1]\n return select.pop()", "... | {"fn_name": "find_ball", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/545c4f7682e55d3c6e0011a1 |
def find_ball(scales, ball_count):
|
4,960 | [Harshad numbers](http://en.wikipedia.org/wiki/Harshad_number) (also called Niven numbers) are positive numbers that can be divided (without remainder) by the sum of their digits.
For example, the following numbers are Harshad numbers:
* 10, because 1 + 0 = 1 and 10 is divisible by 1
* 27, because 2 + 7 = 9 and 27 is... | ["from itertools import count, islice\n\n\nclass Harshad:\n @staticmethod\n def is_valid(number):\n return number % sum(map(int, str(number))) == 0\n \n @classmethod\n def get_next(cls, number):\n return next(i for i in count(number+1) if cls.is_valid(i))\n \n @classmethod\n def ge... | {"fn_name": "is_valid", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/54a0689443ab7271a90000c6 |
def is_valid(number):
|
4,961 | Everyday we go to different places to get our things done. Those places can be represented by specific location points `[ [, ], ... ]` on a map. I will be giving you an array of arrays that contain coordinates of the different places I had been on a particular day. Your task will be to find `peripheries (outermost edge... | ["def box(coords):\n lat, long = zip(*coords)\n return {\"nw\": [max(lat), min(long)], \"se\": [min(lat), max(long)]}", "def box(coords):\n return {\n 'nw': [max(x for x, _ in coords), min(y for _, y in coords)],\n 'se': [min(x for x, _ in coords), max(y for _, y in coords)],\n }", "def box(co... | {"fn_name": "box", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/58ed139326f519019a000053 |
def box(coords):
|
4,962 | Polly is 8 years old. She is eagerly awaiting Christmas as she has a bone to pick with Santa Claus. Last year she asked for a horse, and he brought her a dolls house. Understandably she is livid.
The days seem to drag and drag so Polly asks her friend to help her keep count of how long it is until Christmas, in days. ... | ["from datetime import date\n\n\ndef days_until_christmas(day):\n christmas = date(day.year, 12, 25)\n if day > christmas:\n christmas = date(day.year + 1, 12, 25)\n return (christmas - day).days\n", "from datetime import date, timedelta\n\ndef days_until_christmas(day):\n next = day + timedelta(days... | {"fn_name": "days_until_christmas", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/56f6b23c9400f5387d000d48 |
def days_until_christmas(day):
|
4,963 | Given a number return the closest number to it that is divisible by 10.
Example input:
```
22
25
37
```
Expected output:
```
20
30
40
``` | ["def closest_multiple_10(i):\n return round(i, -1)", "def closest_multiple_10(i):\n return round(i / 10) * 10", "def closest_multiple_10(i):\n r = i % 10\n return i - r if r < 5 else i - r + 10", "closest_multiple_10=lambda x:round(x,-1)", "def closest_multiple_10(x):\n return x - (x% 10) if x%10 < 5 el... | {"fn_name": "closest_multiple_10", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/58249d08b81f70a2fc0001a4 |
def closest_multiple_10(i):
|
4,964 | # Is the string uppercase?
## Task
```if-not:haskell,csharp,javascript,coffeescript,elixir,forth,go,dart,julia,cpp,reason,typescript,racket,ruby
Create a method `is_uppercase()` to see whether the string is ALL CAPS. For example:
```
```if:haskell,reason,typescript
Create a method `isUpperCase` to see whether the str... | ["def is_uppercase(inp):\n return inp.isupper()", "def is_uppercase(inp):\n return inp.upper()==inp", "is_uppercase = str.isupper", "def is_uppercase(inp):\n if inp.isupper():\n return True\n else:\n return False", "def is_uppercase(inp):\n return inp == inp.upper()", "def is_uppercase(inf)... | {"fn_name": "is_uppercase", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/56cd44e1aa4ac7879200010b |
def is_uppercase(inp):
|
4,965 | Your task in this kata is to implement a function that calculates the sum of the integers inside a string. For example, in the string "The30quick20brown10f0x1203jumps914ov3r1349the102l4zy dog", the sum of the integers is 3635.
*Note: only positive integers will be tested.* | ["import re\n\ndef sum_of_integers_in_string(s):\n return sum(int(x) for x in re.findall(r\"(\\d+)\", s))", "import re\n\ndef sum_of_integers_in_string(s):\n return sum(map(int, re.findall(\"\\d+\", s)))", "import re\n\ndef sum_of_integers_in_string(s):\n return sum(int(i) for i in re.findall('\\d+', s))\n", "de... | {"fn_name": "sum_of_integers_in_string", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/598f76a44f613e0e0b000026 |
def sum_of_integers_in_string(s):
|
4,966 | You and your friends have been battling it out with your Rock 'Em, Sock 'Em robots, but things have gotten a little boring. You've each decided to add some amazing new features to your robot and automate them to battle to the death.
Each robot will be represented by an object. You will be given two robot objects, and ... | ["from operator import itemgetter\n\ndef fight(r1, r2, tactics):\n \n i, bots = 0, sorted((r2,r1), key=itemgetter('speed')) # Get the bots in reversed order!\n for r in bots: r['tactics'] = r['tactics'][::-1] # Reverse the tactics to use pop()\n \n while 1:\n ... | {"fn_name": "fight", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/566b490c8b164e03f8000002 |
def fight(robot_1, robot_2, tactics):
|
4,967 | Imagine the following situations:
- A truck loading cargo
- A shopper on a budget
- A thief stealing from a house using a large bag
- A child eating candy very quickly
All of these are examples of ***The Knapsack Problem***, where there are more things that you ***want*** to take with you than you ***can*** take with... | ["def knapsack(capacity, items):\n ratios = [float(item[1]) / item[0] for item in items]\n collection = [0] * len(items)\n space = capacity\n while any(ratios):\n best_index = ratios.index(max(ratios))\n if items[best_index][0] <= space:\n collection[best_index] += 1\n sp... | {"fn_name": "knapsack", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/53ffbba24e9e1408ee0008fd |
def knapsack(capacity, items):
|
4,968 | Two numbers are **relatively prime** if their greatest common factor is 1; in other words: if they cannot be divided by any other common numbers than 1.
`13, 16, 9, 5, and 119` are all relatively prime because they share no common factors, except for 1. To see this, I will show their factorizations:
```python
13: 13
... | ["from fractions import gcd\n\ndef relatively_prime (n, l):\n return [x for x in l if gcd(n, x) == 1]\n", "from math import gcd\n\ndef relatively_prime (n, l):\n return [x for x in l if gcd(n, x) == 1]", "from math import gcd\n\ndef relatively_prime (n, lst):\n return [m for m in lst if gcd(m, n) == 1]", "def ... | {"fn_name": "relatively_prime ", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/56b0f5f84de0afafce00004e |
def relatively_prime (n, l):
|
4,969 | Build Tower Advanced
---
Build Tower by the following given arguments:
__number of floors__ (integer and always greater than 0)
__block size__ (width, height) (integer pair and always greater than (0, 0))
Tower block unit is represented as `*`
* Python: return a `list`;
* JavaScript: returns an `Array`;
Have fun!
*... | ["def tower_builder(n, (w, h)):\n return [str.center(\"*\" * (i*2-1)*w, (n*2-1)*w) for i in range(1, n+1) for _ in range(h)]", "def tower_builder(n_floors, block_size):\n w, h = block_size\n filled_block = '*' * w\n empty_block = ' ' * w\n tower = []\n for n in range(1,n_floors+1):\n for _ in r... | {"fn_name": "tower_builder", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/57675f3dedc6f728ee000256 |
def tower_builder(n_floors, block_size):
|
4,970 | ----
Vampire Numbers
----
Our loose definition of [Vampire Numbers](http://en.wikipedia.org/wiki/Vampire_number) can be described as follows:
```python
6 * 21 = 126
# 6 and 21 would be valid 'fangs' for a vampire number as the
# digits 6, 1, and 2 are present in both the product and multiplicands
10 * 11 = 110
# 11... | ["def vampire_test(x, y):\n return sorted(str(x * y)) == sorted(str(x) + str(y))", "def vampire_test(x, y):\n return sorted(list(str(x) + str(y))) == sorted(list(str(x*y)))", "from collections import Counter\n\ndef vampire_test(x, y):\n return Counter(str(x) + str(y)) == Counter(str(x * y))", "def vampire_test... | {"fn_name": "vampire_test", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/54d418bd099d650fa000032d |
def vampire_test(x, y):
|
4,971 | Linked Lists - Sorted Insert
Write a SortedInsert() function which inserts a node into the correct location of a pre-sorted linked list which is sorted in ascending order. SortedInsert takes the head of a linked list and data used to create a node as arguments. SortedInsert() should also return the head of the list.
... | ["class Node(object):\n def __init__(self, data, nxt = None):\n self.data = data\n self.next = nxt\n \ndef sorted_insert(head, data):\n if not head or data < head.data: return Node(data, head)\n else:\n head.next = sorted_insert(head.next, data)\n return head", "class Node(object):\n def __init__(s... | {"fn_name": "__init__", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/55cc33e97259667a08000044 |
def __init__(self, data):
|
4,972 | Linked Lists - Length & Count
Implement Length() to count the number of nodes in a linked list.
Implement Count() to count the occurrences of an integer in a linked list.
I've decided to bundle these two functions within the same Kata since they are both very similar.
The `push()`/`Push()` and `buildOneTwoThree()`/... | ["class Node(object):\n def __init__(self, data):\n self.data = data\n self.next = None\n \ndef length(node):\n leng = 0\n while node:\n leng += 1\n node = node.next\n return leng\n \ndef count(node, data):\n c = 0\n while node:\n if node.data==data:\n ... | {"fn_name": "__init__", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/55beec7dd347078289000021 |
def __init__(self, data):
|
4,973 | Given an array of integers (x), and a target (t), you must find out if any two consecutive numbers in the array sum to t. If so, remove the second number.
Example:
x = [1, 2, 3, 4, 5]
t = 3
1+2 = t, so remove 2. No other pairs = t, so rest of array remains:
[1, 3, 4, 5]
Work through the array from left to right.
... | ["def trouble(x, t):\n arr = [x[0]]\n for c in x[1:]:\n if c + arr[-1] != t:\n arr.append(c)\n return arr", "def trouble(array, target):\n i = 0\n while i < len(array) - 1:\n if array[i] + array[i+1] == target:\n del array[i+1]\n else:\n i += 1\n retur... | {"fn_name": "trouble", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/57f7796697d62fc93d0001b8 |
def trouble(x, t):
|
4,974 | You're putting together contact information for all the users of your website to ship them a small gift. You queried your database and got back a list of users, where each user is another list with up to two items: a string representing the user's name and their shipping zip code. Example data might look like:
```pyth... | ["def user_contacts(data):\n return {contact[0]: contact[1] if len(contact) > 1 else None\n for contact in data}\n", "def user_contacts(data):\n return {u[0]: (u[1] if len(u) > 1 else None) for u in data}", "def user_contacts(data):\n a = {}\n for i in data:\n a[i[0]] = i[1] if len(i) == 2... | {"fn_name": "user_contacts", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/586f61bdfd53c6cce50004ee |
def user_contacts(data):
|
4,975 | Create a function taking a positive integer as its parameter and returning a string containing the Roman Numeral representation of that integer.
Modern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals 1990 is... | ["def solution(n):\n roman_numerals = {1000:'M',\n 900: 'CM',\n 500: 'D',\n 400: 'CD',\n 100: 'C',\n 90: 'XC',\n 50: 'L',\n 40: 'XL',\n 10: 'X',\n ... | {"fn_name": "solution", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/51b62bf6a9c58071c600001b |
def solution(n):
|
4,976 | The function must return the sequence of titles that match the string passed as an argument.
```if:javascript
TITLES is a preloaded sequence of strings.
```
```python
titles = ['Rocky 1', 'Rocky 2', 'My Little Poney']
search(titles, 'ock') --> ['Rocky 1', 'Rocky 2']
```
But the function return some weird result an... | ["def search(titles, term): \n return list(filter(lambda title: term in title.lower(), titles))", "def search(titles, term): \n return [ title for title in titles if term in title.lower() ]", "search = lambda titles, term: list(filter(lambda title: term.lower() in title.lower(), titles))", "def search(titles, ter... | {"fn_name": "search", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/52cd53948d673a6e66000576 |
def search(titles, term):
|
4,977 | # Messi goals function
[Messi](https://en.wikipedia.org/wiki/Lionel_Messi) is a soccer player with goals in three leagues:
- LaLiga
- Copa del Rey
- Champions
Complete the function to return his total number of goals in all three leagues.
Note: the input will always be valid.
For example:
```
5, 10, 2 --> 17
`... | ["def goals(*a):\n return sum(a)", "def goals(*args):\n return sum(args)", "def goals(laLiga, copaDelRey, championsLeague):\n return laLiga+copaDelRey+championsLeague", "def goals(laLiga, copaDelRey, championsLeague):\n \n resultado = laLiga + copaDelRey + championsLeague\n \n return resultado\n ... | {"fn_name": "goals", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/55f73be6e12baaa5900000d4 |
def goals(laLiga, copaDelRey, championsLeague):
|
4,978 | In this kata, your task is to implement what I call **Iterative Rotation Cipher (IRC)**. To complete the task, you will create an object with two methods, `encode` and `decode`. (For non-JavaScript versions, you only need to write the two functions without the enclosing dict)
Input
The encode method will receive two a... | ["def shift(string, step):\n i = (step % len(string)) if string else 0\n return f\"{string[-i:]}{string[:-i]}\"\n\ndef encode(n, string):\n for _ in range(n):\n shifted = shift(string.replace(\" \", \"\"), n)\n l = [len(word) for word in string.split(\" \")]\n string = \" \".join(shift(shi... | {"fn_name": "encode", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5a3357ae8058425bde002674 |
def encode(n,strng):
|
4,979 | # Story
Those pesky rats have returned and this time they have taken over the Town Square.
The Pied Piper has been enlisted again to play his magical tune and coax all the rats towards him.
But some of the rats are deaf and are going the wrong way!
# Kata Task
How many deaf rats are there?
## Input Notes
* The T... | ["from math import hypot\n\nDIRS = {'\u2190': (0,-1), '\u2191': (-1,0), '\u2192': (0,1), '\u2193': (1,0),\n '\u2196': (-1,-1), '\u2197': (-1,1), '\u2198': (1,1), '\u2199': (1,-1)}\n\ndef count_deaf_rats(town):\n pipper = next( (x,y) for x,r in enumerate(town) for y,c in enumerate(r) if c=='P')\n return su... | {"fn_name": "count_deaf_rats", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5c1448e08a2d87eda400005f |
def count_deaf_rats(town_square):
|
4,980 | #Sort the columns of a csv-file
You get a string with the content of a csv-file. The columns are separated by semicolons.
The first line contains the names of the columns.
Write a method that sorts the columns by the names of the columns alphabetically and incasesensitive.
An example:
```
Before sorting:
As table (o... | ["def sort_csv_columns(csv_file_content, sep=';', end='\\n'):\n '''Sort a CSV file by column name.'''\n csv_columns = zip(*(row.split(sep) for row in csv_file_content.split(end)))\n sorted_columns = sorted(csv_columns, key=lambda col: col[0].lower())\n return end.join(sep.join(row) for row in zip(*sorted_co... | {"fn_name": "sort_csv_columns", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/57f7f71a7b992e699400013f |
def sort_csv_columns(csv_file_content):
|
4,981 | Many websites use weighted averages of various polls to make projections for elections. They’re weighted based on a variety of factors, such as historical accuracy of the polling firm, sample size, as well as date(s). The weights, in this kata, are already calculated for you. All you need to do is convert a set of poll... | ["def predict(candidates, polls):\n x = zip(*[list(map(lambda i: i * weight, poll)) for poll, weight in polls])\n x = list(map(round1, (map(lambda i: sum(i) / sum([i[1] for i in polls]), x))))\n return dict(zip(candidates,x))", "def predict(candidates, polls):\n weight = sum(w for _, w in polls)\n scores... | {"fn_name": "predict", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5827d31b86f3b0d9390001d4 |
def predict(candidates, polls):
|
4,982 | # Introduction
Dots and Boxes is a pencil-and-paper game for two players (sometimes more). It was first published in the 19th century by Édouard Lucas, who called it la pipopipette. It has gone by many other names, including the game of dots, boxes, dot to dot grid, and pigs in a pen.
Starting with an empty grid of ... | ["class Game():\n \n def __init__(self, n):\n k = 2 * n + 1\n self.board = {frozenset(k * r + 1 + c + d for d in (0, n, n + 1, k))\n for r in range(n) for c in range(n)}\n\n def play(self, lines):\n lines = set(lines)\n while 1:\n for cell in self.b... | {"fn_name": "__init__", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/58fdcc51b4f81a0b1e00003e |
def __init__(self, board):
|
4,983 | Your task is to implement a function that takes one or more dictionaries and combines them in one result dictionary.
The keys in the given dictionaries can overlap. In that case you should combine all source values in an array. Duplicate values should be preserved.
Here is an example:
```cs
var source1 = new Dictiona... | ["def merge(*dicts):\n result = {}\n for d in dicts:\n for key, value in d.items():\n result.setdefault(key, []).append(value)\n return result\n\nfrom itertools import groupby, chain", "from collections import defaultdict\n\ndef merge(*dicts):\n d = defaultdict(list)\n for dd in dicts:\... | {"fn_name": "merge", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5ae840b8783bb4ef79000094 |
def merge(*dicts):
|
4,984 | John has invited some friends. His list is:
```
s = "Fred:Corwill;Wilfred:Corwill;Barney:Tornbull;Betty:Tornbull;Bjon:Tornbull;Raphael:Corwill;Alfred:Corwill";
```
Could you make a program that
- makes this string uppercase
- gives it sorted in alphabetical order by last name.
When the last names are the same, sort... | ["def meeting(s):\n return ''.join(sorted('({1}, {0})'.format(*(x.split(':'))) for x in s.upper().split(';')))", "def meeting(s):\n s = s.upper()\n s = s.split(';')\n array = []\n string = \"\"\n for i in s:\n i = i.split(':')\n string = '('+i[1]+', '+i[0]+')'\n array.append(string)\n array.sort()\n ... | {"fn_name": "meeting", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/59df2f8f08c6cec835000012 |
def meeting(s):
|
4,985 | *You are a composer who just wrote an awesome piece of music. Now it's time to present it to a band that will perform your piece, but there's a problem! The singers vocal range doesn't stretch as your piece requires, and you have to transpose the whole piece.*
# Your task
Given a list of notes (represented as strings)... | ["def transpose(song, interval):\n altern = {\"Bb\": \"A#\", \"Db\": \"C#\", \"Eb\": \"D#\", \"Gb\": \"F#\", \"Ab\": \"G#\"}\n notes = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#']\n return [notes[(notes.index(altern.get(i, i)) + interval) % 12] for i in song]", "table = \"A Bb B C Db D Eb ... | {"fn_name": "transpose", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/55b6a3a3c776ce185c000021 |
def transpose(song, interval):
|
4,986 | # Write this function

`for i from 1 to n`, do `i % m` and return the `sum`
f(n=10, m=5) // returns 20 (1+2+3+4+0 + 1+2+3+4+0)
*You'll need to get a little clever with performance, since n can be a very large number* | ["def f(n, m):\n re, c = divmod(n,m) \n return m*(m-1)/2*re + (c+1)*c/2", "def f(n, m):\n # Function to return the sum of the remnainders when n is divided by m for all n from 1 to n\n # The remainders cycle from 0, 1, 2, 3,... m-1. This happens n // m times, with a final sequnce \n # up to n % m. The ... | {"fn_name": "f", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/54c2fc0552791928c9000517 |
def f(n, m):
|
4,987 | Write a function that receives two strings as parameter. This strings are in the following format of date: `YYYY/MM/DD`.
Your job is: Take the `years` and calculate the difference between them.
Examples:
```
'1997/10/10' and '2015/10/10' -> 2015 - 1997 = returns 18
'2015/10/10' and '1997/10/10' -> 2015 - 1997 = retur... | ["def how_many_years (date1,date2):\n return abs(int(date1.split('/')[0]) - int(date2.split('/')[0]))\n", "def how_many_years (date1,date2):\n return abs(int(date1[:4]) - int(date2[:4]))", "def how_many_years (date1,date2):\n year = lambda d: int(d[:4])\n return abs(year(date1) - year(date2))", "def how_many_... | {"fn_name": "how_many_years ", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/588f5a38ec641b411200005b |
def how_many_years (date1,date2):
|
4,988 | Now you have to write a function that takes an argument and returns the square of it. | ["def square(n):\n return n ** 2", "def square(n):\n return n*n", "square = lambda n: n*n", "def square(n):\n return pow(n, 2)", "def square(n):\n return n*n if isinstance(n,int) else None", "def mult(a, b):\n mv = 0\n for c in range(b):\n mv = sumVal(mv, a)\n return mv\n\ndef sumVal(a, b):\... | {"fn_name": "square", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/523b623152af8a30c6000027 |
def square(n):
|
4,989 | Create a function hollow_triangle(height) that returns a hollow triangle of the correct height. The height is passed through to the function and the function should return a list containing each line of the hollow triangle.
```
hollow_triangle(6) should return : ['_____#_____', '____#_#____', '___#___#___', '__#_____#... | ["def hollow_triangle(n):\n width = n * 2 - 1\n row = '{{:_^{}}}'.format(width).format\n return [row(mid(a)) for a in xrange(1, width, 2)] + [width * '#']\n\n\ndef mid(n):\n return '#' if n == 1 else '#{}#'.format('_' * (n - 2))", "def hollow_triangle(n):\n w, result = 2 * n - 1, [f\"{'_' * (2*i-1):#^{2*... | {"fn_name": "hollow_triangle", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/57819b700a8eb2d6b00002ab |
def hollow_triangle(n):
|
4,990 | Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
``` | ["def solution(string, ending):\n return string.endswith(ending)", "solution = str.endswith", "def solution(string, ending):\n return ending in string[-len(ending):]", "def solution(string, ending):\n # your code here...\n string1 = len(string) - len(ending)\n string2 = len(string) - string1\n string3... | {"fn_name": "solution", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/51f2d1cafc9c0f745c00037d |
def solution(string, ending):
|
4,991 | I will give you two strings. I want you to transform stringOne into stringTwo one letter at a time.
Example: | ["def mutate_my_strings(s1,s2):\n return '\\n'.join( [s1] + [s2[:i]+s1[i:] for i,(a,b) in enumerate(zip(s1,s2),1) if a != b ]) + '\\n'", "def mutate_my_strings(s1, s2):\n result = [s1]\n result.extend(f\"{s2[:i+1]}{s1[i+1:]}\" for i in range(len(s1)) if s1[i] != s2[i])\n result.append(\"\")\n return \"\\... | {"fn_name": "mutate_my_strings", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/59bc0059bf10a498a6000025 |
def mutate_my_strings(s1,s2):
|
4,992 | Given a random bingo card and an array of called numbers, determine if you have a bingo!
*Parameters*: `card` and `numbers` arrays.
*Example input*:
```
card = [
['B', 'I', 'N', 'G', 'O'],
[1, 16, 31, 46, 61],
[3, 18, 33, 48, 63],
[5, 20, 'FREE SPACE', 50, 65],
[7, 22, 37, 52, 67],
[9, 24, 39, 54, 69]
]
... | ["def bingo(card, numbers):\n \n rc, cc, dc = [0]*5, [0]*5, [1]*2 # rows count, columns count, diag counts\n rc[2] = cc[2] = 1 # preaffect 'FREE SPACE'\n s = set(numbers)\n \n for x,line in enumerate(card[1:]):\n for y,(c,n) in enumerate(zip(card[0], line)):... | {"fn_name": "bingo", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5af304892c5061951e0000ce |
def bingo(card, numbers):
|
4,993 | The description is rather long but you are given all needed formulas (almost:-)
John has bought a bike but before going moutain biking he wants us to do a few simulations.
He gathered information:
- His trip will consist of an ascent of `dTot` kilometers with an average slope of `slope` *percent*
- We suppose that:... | ["from math import sin, atan\n\ndef temps(v0, slope, d_tot):\n GRAVITY_ACC = 9.81 * 3.6 * 60.0 # gravity acceleration\n DRAG = 60.0 * 0.3 / 3.6 # force applied by air on the cyclist\n DELTA_T = 1.0/60.0 # in minutes\n D_WATTS = 0.5 ... | {"fn_name": "temps", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5879f95892074d769f000272 |
def temps(v0, slope, d_tot):
|
4,994 | A grammar is a set of rules that let us define a language. These are called **production rules** and can be derived into many different tools. One of them is **String Rewriting Systems** (also called Semi-Thue Systems or Markov Algorithms). Ignoring technical details, they are a set of rules that substitute ocurrences ... | ["def word_problem(rules: List[Tuple[str, str]], from_str: str, to_str: str, applications: int) -> bool:\n rec = lambda s,n: s == to_str or n and any(s[i:].startswith(x) and rec(s[:i] + y + s[i+len(x):], n-1) for i in range(len(s)) for x,y in rules)\n return rec(from_str, applications)", "def word_problem(rules, ... | {"fn_name": "word_problem", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5e453b6476551c0029e275db |
def word_problem(rules:
|
4,995 | Another rewarding day in the fast-paced world of WebDev. Man, you love your job! But as with any job, somtimes things can get a little tedious. Part of the website you're working on has a very repetitive structure, and writing all the HTML by hand is a bore. Time to automate! You want to write some functions that will ... | ["class HTMLGen:\n def __init__(self):\n self.a = lambda t: self.tag(\"a\", t)\n self.b = lambda t: self.tag(\"b\", t)\n self.p = lambda t: self.tag(\"p\", t)\n self.body = lambda t: self.tag(\"body\", t)\n self.div = lambda t: self.tag(\"div\", t)\n self.span = lambda t: se... | {"fn_name": "__init__", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/54eecc187f9142cc4600119e |
def __init__(self):
|
4,996 | ## **Instructions**
The goal of this kata is two-fold:
1.) You must produce a fibonacci sequence in the form of an array, containing a number of items equal to the input provided.
2.) You must replace all numbers in the sequence `divisible by 3` with `Fizz`, those `divisible by 5` with `Buzz`, and those `divisible... | ["def fibs_fizz_buzz(n):\n a, b, out = 0, 1, []\n\n for i in range(n):\n s = \"Fizz\"*(b % 3 == 0) + \"Buzz\"*(b % 5 == 0)\n out.append(s if s else b)\n a, b = b, a+b\n \n return out", "def fibs_fizz_buzz(n):\n a, b, f = 1, 1, []\n for _ in range(n):\n s = \"\"\n ... | {"fn_name": "fibs_fizz_buzz", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/57bf599f102a39bb1e000ae5 |
def fibs_fizz_buzz(n):
|
4,997 | The function sigma 1, σ1 in mathematics, is known as the one that gives the sum of the divisors of an integer number.
For example for the number 10,
```python
σ1(10) = 18 # because the divisors of 10 are: 1, 2, 5, 10
σ1(10) = 1 + 2 + 5 + 10 = 18
```
You can see the graph of this important function up to 250:
The n... | ["cache = {}\ndef sum_div(x):\n if x not in cache:\n cache[x] = sum(i for i in range(1, x+1) if x % i == 0)\n return cache[x]\n\ndef is_required(x):\n reversed = int(str(x)[::-1])\n return x != reversed and sum_div(x) == sum_div(reversed)\n\nrequired = [x for x in range(528, 10**4) if is_required(x)]... | {"fn_name": "sigma1", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/5619dbc22e69620e5a000010 |
def sigma1(n):
|
4,998 | The principal of a school likes to put challenges to the students related with finding words of certain features.
One day she said: "Dear students, the challenge for today is to find a word that has only one vowel and seven consonants but cannot have the letters "y" and "m". I'll give a special award for the first stud... | ["def wanted_words(vowels, consonants, forbidden):\n return [w for w in WORD_LIST\n if len(w) == vowels + consonants\n and sum(map(w.count, 'aeiou')) == vowels\n and not any(c in w for c in forbidden)]", "from collections import defaultdict\nWORD_INDEX = defaultdict(list)... | {"fn_name": "wanted_words", "inputs": [[1, 7, ["m", "y"]], [3, 7, ["m", "y"]], [3, 7, ["a", "s", "m", "y"]]], "outputs": [[["strength"]], [["afterwards", "background", "photograph", "successful", "understand"]], [[]]]} | introductory | https://www.codewars.com/kata/580be55ca671827cfd000043 |
def wanted_words(n, m, forbid_let):
|
4,999 | Complete the method that takes a sequence of objects with two keys each: country or state, and capital. Keys may be symbols or strings.
The method should return an array of sentences declaring the state or country and its capital.
## Examples
```python
[{'state': 'Maine', 'capital': 'Augusta'}] --> ["The capital of ... | ["def capital(capitals):\n return [f\"The capital of {c.get('state') or c['country']} is {c['capital']}\" for c in capitals]", "def capital(capitals): \n ans = []\n for each in capitals:\n a = each.get('state', '')\n b = each.get('country', '')\n c = each.get('capital')\n ans.append... | {"fn_name": "capital", "inputs": [], "outputs": []} | introductory | https://www.codewars.com/kata/53573877d5493b4d6e00050c |
def capital(capitals):
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.