problem_id
int64
80
5k
question
stringlengths
170
10.1k
solutions
stringlengths
0
675k
input_output
stringlengths
0
33.5k
difficulty
stringclasses
3 values
url
stringlengths
38
68
starter_code
stringlengths
0
315
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,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,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,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,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,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! ![](https://s-media-cache-ak0.pinimg.com/236x/1b/cf/f4/1bcff4f4621644461103576e40bde4ed.jpg) _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,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,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,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,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,279
Once upon a time, a CodeWarrior, after reading a [discussion on what can be the plural](http://www.codewars.com/kata/plural/discuss/javascript), took a look at [this page](http://en.wikipedia.org/wiki/Grammatical_number#Types_of_number ) and discovered that **more than 1** "kind of plural" may exist. For example [Sur...
["import re\n\ndef sursurungal(txt):\n txt=re.sub(r'\\b2\\s(\\S+)s', r'2 bu\\1', txt) \n txt=re.sub(r'\\b([3-9])\\s(\\S+)s', r'\\1 \\2zo', txt)\n return re.sub(r'(\\d+\\d)\\s(\\S+)s', r'\\1 ga\\2ga', txt)\n \n", "import re\n\ndef sursurungal(txt):\n txt = re.sub(r'\\b2\\s(\\S+)s', r'2 bu\\1', txt)\n t...
{"fn_name": "sursurungal", "inputs": [["1 tomato"], ["0 tomato"], ["1 ananas"], ["2 bananas"], ["3 bananas"], ["10 bananas"], ["111 bananas"], ["6 birds with 2 wings each = 12 legs"], ["\n3 pigs\nmet 1 wolf\n2 days ago"]], "outputs": [["1 tomato"], ["0 tomato"], ["1 ananas"], ["2 bubanana"], ["3 bananazo"], ["10 gabana...
introductory
https://www.codewars.com/kata/5536aba6e4609cc6a600003d
def sursurungal(txt):
3,283
Your aged grandfather is tragically optimistic about Team GB's chances in the upcoming World Cup, and has enlisted you to help him make [Union Jack](https://en.wikipedia.org/wiki/Union_Jack) flags to decorate his house with. ## Instructions * Write a function which takes as a parameter a number which represents the d...
["from math import ceil\n\ndef union_jack(n):\n if not isinstance(n, (int, float)):\n return False\n n = max(7, ceil(n))\n h, m = divmod(n-1, 2)\n flag = [[\"X\" if len({i, n-j-1, j, h, h+m}) < 4+m else \"-\" for i in range(n)] for j in range(n)] \n return \"\\n\".join(\"\".join(row) for row in fl...
{"fn_name": "union_jack", "inputs": [[4.5], [7.1], [19.00384], [109.1], [66.4], ["pippi"], [{}]], "outputs": [["X--X--X\n-X-X-X-\n--XXX--\nXXXXXXX\n--XXX--\n-X-X-X-\nX--X--X"], ["X--XX--X\n-X-XX-X-\n--XXXX--\nXXXXXXXX\nXXXXXXXX\n--XXXX--\n-X-XX-X-\nX--XX--X"], ["X--------XX--------X\n-X-------XX-------X-\n--X------XX--...
introductory
https://www.codewars.com/kata/5620281f0eeee479cd000020
def union_jack(n):
3,285
We all love the future president (or Führer or duce or sōtō as he could find them more fitting) donald trump, but we might fear that some of his many fans like John Miller or John Barron are not making him justice, sounding too much like their (and our as well, of course!) hero and thus risking to compromise him. For ...
["import re\ndef trump_detector(ts):\n x=re.findall(r'([aeiou])(\\1*)',ts,re.I)\n y=[len(i[1]) for i in x]\n return round(sum(y)/len(y),2)", "import re\n\ndef trump_detector(trump_speech):\n lst = [ len(tup[1]) for tup in re.findall(r'([aeiou])(\\1*)', trump_speech, re.I) ]\n return round(sum(lst)/len(ls...
{"fn_name": "trump_detector", "inputs": [["I will build a huge wall"], ["HUUUUUGEEEE WAAAAAALL"], ["MEXICAAAAAAAANS GOOOO HOOOMEEEE"], ["America NUUUUUKEEEE Oooobaaaamaaaaa"], ["listen migrants: IIII KIIIDD YOOOUUU NOOOOOOTTT"]], "outputs": [[0], [4], [2.5], [1.89], [1.56]]}
introductory
https://www.codewars.com/kata/57829376a1b8d576640000d6
def trump_detector(trump_speech):
3,288
In this Kata, you will be given a number in form of a string and an integer `k` and your task is to insert `k` commas into the string and determine which of the partitions is the largest. ``` For example: solve('1234',1) = 234 because ('1','234') or ('12','34') or ('123','4'). solve('1234',2) = 34 because ('1','2','3...
["def solve(st, k):\n length = len(st) - k\n return max(int(st[i:i + length]) for i in range(k + 1))", "def solve(st,k):\n c=len(st)-k\n return int(max(st[i:i+c] for i in range(k+1)))", "def solve(st,k):\n return max([int(st[i:i+len(st)-k]) for i in range(len(st))])", "def solve(st, k):\n n = len(st) ...
{"fn_name": "solve", "inputs": [["1234", 1], ["1234", 2], ["1234", 3], ["2020", 1]], "outputs": [[234], [34], [4], [202]]}
introductory
https://www.codewars.com/kata/5b83c1c44a6acac33400009a
def solve(st,k):
3,289
In genetics, a sequence’s motif is a nucleotides (or amino-acid) sequence pattern. Sequence motifs have a biological significance. For more information you can take a look [here](https://en.wikipedia.org/wiki/Sequence_motif). For this kata you need to complete the function `motif_locator`. This function receives 2 ar...
["def motif_locator(sequence, motif):\n res, i = [], 0\n while True:\n i = sequence.find(motif, i) + 1\n if not i: return res\n res.append(i)", "def motif_locator(sequence, motif):\n return [i+1 for i,c in enumerate(sequence) if sequence[i:i+len(motif)] == motif]", "def motif_locator(seq, ...
{"fn_name": "motif_locator", "inputs": [["TTCCGGAACC", "CC"], ["ACGTTACAACGTTAG", "ACGT"], ["ACGTACGTACGT", "AAA"], ["ACGT", "ACGTGAC"]], "outputs": [[[3, 9]], [[1, 9]], [[]], [[]]]}
introductory
https://www.codewars.com/kata/5760c1c7f2717b91e20001a4
def motif_locator(sequence, motif):
3,293
Rule 30 is a one-dimensional binary cellular automaton. You can have some information here: * [https://en.wikipedia.org/wiki/Rule_30](https://en.wikipedia.org/wiki/Rule_30) You have to write a function that takes as input an array of 0 and 1 and a positive integer that represents the number of iterations. This func...
["def rule30(a, n):\n for _ in range(n):\n a = [int(0 < 4*x + 2*y + z < 5) for x, y, z in\n zip([0, 0] + a, [0] + a + [0], a + [0, 0])]\n return a", "def rule30(li, n):\n for i in range(n):\n li = [0] + li + [0]\n li = [(li[k-1] if k else 0)^(l or (li[k+1] if k<len(li)-1 els...
{"fn_name": "rule30", "inputs": [[[1], 1], [[1], 2], [[1], 21], [[0], 5], [[0], 0], [[1, 1, 1], 0], [[0], 3], [[1], -3], [[1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1], 1], [[1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1], 75]], "outputs": [[[1, 1, 1]], [[1, 1, 0, 0, 1]], [[1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0,...
introductory
https://www.codewars.com/kata/5581e52ac76ffdea700000c1
def rule30(list_, n):
3,297
A stick is balanced horizontally on a support. Will it topple over or stay balanced? (This is a physics problem: imagine a real wooden stick balanced horizontally on someone's finger or on a narrow table, for example). The stick is represented as a list, where each entry shows the mass in that part of the stick. The...
["from math import ceil\n\ndef will_it_balance(stick, gnd):\n gravPt = sum(v*i for i,v in enumerate(stick)) / sum(stick)\n return gnd[int(gravPt)] == gnd[ceil(gravPt)] == 1", "def will_it_balance(stick, terrain):\n com = sum(i*w for i,w in enumerate(stick))/sum(stick)\n return terrain.index(1)<=com<=max(i f...
{"fn_name": "will_it_balance", "inputs": [[[2, 3, 2], [0, 1, 0]], [[5, 1, 1], [0, 1, 0]], [[3, 3, 4], [0, 1, 0]], [[9, 7, 1, 1], [1, 1, 0, 0]], [[9, 1, 1, 7], [1, 1, 0, 0]]], "outputs": [[true], [false], [false], [true], [false]]}
introductory
https://www.codewars.com/kata/5a8328fefd57777fa3000072
def will_it_balance(stick, terrain):
3,307
Freddy has a really fat left pinky finger, and every time Freddy tries to type an ```A```, he accidentally hits the CapsLock key! Given a string that Freddy wants to type, emulate the keyboard misses where each ```A``` supposedly pressed is replaced with CapsLock, and return the string that Freddy actually types. It d...
["def fat_fingers(s):\n if not s: return s\n swap = [False]\n return ''.join( c.swapcase() if swap[0] else c for c in s \n if c not in \"aA\" or swap.__setitem__(0, not swap[0]) )", "import re\n\ndef fat_fingers(string):\n return ''.join(w.swapcase() if i%2 else w for i, w in enumerate(re.s...
{"fn_name": "fat_fingers", "inputs": [["aAaaaaAaaaAAaAa"], ["The end of the institution, maintenance, and administration of government, is to secure the existence of the body politic, to protect it, and to furnish the individuals who compose it with the power of enjoying in safety and tranquillity their natural rights,...
introductory
https://www.codewars.com/kata/5aa99584fd5777ee9a0001f1
def fat_fingers(string):
3,308
In telecomunications we use information coding to detect and prevent errors while sending data. A parity bit is a bit added to a string of binary code that indicates whether the number of 1-bits in the string is even or odd. Parity bits are used as the simplest form of error detecting code, and can detect a 1 bit err...
["def parity_bit(binary):\n return ' '.join(byte[:-1] if byte.count('1') % 2 == 0 else 'error' for byte in binary.split())", "def parity_bit(binary):\n return \" \".join(\"error\" if byte.count(\"1\") & 1 else byte[:-1] for byte in binary.split())", "def decode(binary):\n *b, p = binary\n if '01'[b.count('1...
{"fn_name": "parity_bit", "inputs": [["01011001"], ["00110001"], ["11111111"], ["00000000"], ["11100111"], ["00111100 00111101"], ["00001111 11100001"], ["01011110 00011000"], ["11111111 11011100 11100011"], ["00111110 00110100 00111011"], ["01101110 01100000 01010110 10001111 01100011"], ["10100011 00111001 11001100 0...
introductory
https://www.codewars.com/kata/58409435258e102ae900030f
def parity_bit(binary):
3,313
# RoboScript #1 - Implement Syntax Highlighting ## Disclaimer The story presented in this Kata Series is purely fictional; any resemblance to actual programming languages, products, organisations or people should be treated as purely coincidental. ## About this Kata Series This Kata Series is based on a fictional s...
["import re\ndef highlight(code):\n code = re.sub(r\"(F+)\", '<span style=\"color: pink\">\\g<1></span>', code)\n code = re.sub(r\"(L+)\", '<span style=\"color: red\">\\g<1></span>', code)\n code = re.sub(r\"(R+)\", '<span style=\"color: green\">\\g<1></span>', code)\n code = re.sub(r\"(\\d+)\", '<span styl...
{"fn_name": "highlight", "inputs": [["F3RF5LF7"], ["FFFR345F2LL"], ["RRRRRF45L3F2"], ["RRRRR(F45L3)F2"], ["FF(LF6(RF3)2)3"]], "outputs": [["<span style=\"color: pink\">F</span><span style=\"color: orange\">3</span><span style=\"color: green\">R</span><span style=\"color: pink\">F</span><span style=\"color: orange\">5</...
introductory
https://www.codewars.com/kata/58708934a44cfccca60000c4
def highlight(code):
3,314
In this Kata, you will be given two numbers, `a` and `b`, and your task is to determine if the first number `a` is divisible by `all` the prime factors of the second number `b`. For example: `solve(15,12) = False` because `15` is not divisible by all the prime factors of `12` (which include`2`). See test cases for mor...
["import fractions\n\ndef solve(a, b):\n c = fractions.gcd(a, b)\n while c > 1:\n b //= c\n c = fractions.gcd(a, b)\n return b == 1", "from math import gcd\n\n\ndef solve(a, b):\n while 1 < gcd(a, b):\n b = b // gcd(a, b)\n return b == 1\n", "from math import gcd\n\ndef solve(a, b):\...
{"fn_name": "solve", "inputs": [[2, 256], [2, 253], [9, 243], [15, 12], [21, 2893401], [21, 2893406], [54, 2834352], [54, 2834359], [1000013, 7187761], [1000013, 7187762]], "outputs": [[true], [false], [true], [false], [true], [false], [true], [false], [true], [false]]}
introductory
https://www.codewars.com/kata/59ec2d112332430ce9000005
def solve(a,b):
3,320
###Introduction The [I Ching](https://en.wikipedia.org/wiki/I_Ching) (Yijing, or Book of Changes) is an ancient Chinese book of sixty-four hexagrams. A hexagram is a figure composed of six stacked horizontal lines, where each line is either Yang (an unbroken line) or Yin (a broken line): ``` --------- ---- ---- ...
["l = {'one': 5, 'two': 4, 'three': 3, 'four': 2, 'five': 1, 'six': 0}\ny = {'hhh': '----o----', 'hht': '---- ----', 'htt': '---------', 'ttt': '----x----'}\n\ndef oracle(arr):\n s = [''] * 6\n for x in arr: s[l[x[0]]] = y[''.join(sorted(x[1:]))]\n return '\\n'.join(s)", "ORDER = \"one two three four five six\...
{"fn_name": "oracle", "inputs": [[[["two", "h", "h", "t"], ["six", "t", "h", "t"], ["four", "t", "t", "t"], ["one", "h", "t", "h"], ["three", "h", "h", "h"], ["five", "t", "t", "h"]]], [[["six", "t", "t", "h"], ["one", "h", "h", "t"], ["three", "t", "h", "h"], ["two", "t", "t", "t"], ["five", "h", "h", "t"], ["four", "...
introductory
https://www.codewars.com/kata/56e60e54517a8c167e00154d
def oracle(arr):
3,322
# Number encrypting: cypher ## Part I of Number encrypting Katas *** ## Introduction Back then when the internet was coming up, most search functionalities simply looked for keywords in text to show relevant documents. Hackers weren't very keen on having their information displayed on websites, bulletin boards, newsgr...
["def cypher(s):\n return s.translate(str.maketrans('IREASGTBlzeasbtgoO','123456781234567900'))", "translation = str.maketrans(\"IREASGTBOlzeasbtgo\",\"123456780123456790\")\n\ndef cypher(s):\n return s.translate(translation)", "def cypher(string):\n D = {'I' :'1', 'l':'1', 'R':'2', 'z':'2', 'E':'3', 'e':'3',\...
{"fn_name": "cypher", "inputs": [["Hello World"], ["I am your father"], ["I do not know what else I can test. Be cool. Good luck"], ["IlRzEeAaSsGbTtBgOo"], [""]], "outputs": [["H3110 W0r1d"], ["1 4m y0ur f47h3r"], ["1 d0 n07 kn0w wh47 3153 1 c4n 7357. 83 c001. 600d 1uck"], ["112233445566778900"], [""]]}
introductory
https://www.codewars.com/kata/57aa3927e298a757820000a8
def cypher(string):
3,324
In JavaScript, ```if..else``` is the most basic condition statement, it consists of three parts:```condition, statement1, statement2```, like this: ```python if condition: statementa else: statementb ``` It means that if the condition is true, then execute the statementa, otherwise execute the statementb.If the...
["def sale_hotdogs(n):\n return n * (100 if n < 5 else 95 if n < 10 else 90)\n", "def sale_hotdogs(n):\n rate = 100 if n<5 else 95 if n<10 else 90\n return n * rate", "def sale_hotdogs(n):\n return n * [90, 95, 100][(n<10) + (n<5)]", "class Color(object):\n BLACK = 0\n RED = 1\n\n\nclass Node(object):...
{"fn_name": "sale_hotdogs", "inputs": [[0], [1], [2], [3], [4], [5], [9], [10], [11], [100]], "outputs": [[0], [100], [200], [300], [400], [475], [855], [900], [990], [9000]]}
introductory
https://www.codewars.com/kata/57202aefe8d6c514300001fd
def sale_hotdogs(n):
3,327
You're writing an excruciatingly detailed alternate history novel set in a world where [Daniel Gabriel Fahrenheit](https://en.wikipedia.org/wiki/Daniel_Gabriel_Fahrenheit) was never born. Since Fahrenheit never lived the world kept on using the [Rømer scale](https://en.wikipedia.org/wiki/R%C3%B8mer_scale), invented by...
["def celsius_to_romer(temp):\n # Converts temperature in degrees Celsius to degrees Romer\n return (temp * 21 / 40) + 7.5\n", "def celsius_to_romer(temp):\n return temp * 21 / 40 + 7.5\n", "def celsius_to_romer(c):\n return c * 21 / 40 + 7.5 ", "def celsius_to_romer(x):\n return x * 21 / 40 + 7.5", "def...
{"fn_name": "celsius_to_romer", "inputs": [[24], [8], [29]], "outputs": [[20.1], [11.7], [22.725]]}
introductory
https://www.codewars.com/kata/5862eeeae20244d5eb000005
def celsius_to_romer(temp):
3,339
No Story No Description Only by Thinking and Testing Look at the results of the testcases, and guess the code! --- ## Series: 01. [A and B?](http://www.codewars.com/kata/56d904db9963e9cf5000037d) 02. [Incomplete string](http://www.codewars.com/kata/56d9292cc11bcc3629000533) 03. [True or False](http://www.codewars...
["def mystery(n):\n return [i for i in range(1, n + 1, 2) if n % i == 0]", "def mystery(n):\n return [i for i in range(1, n + 1) if n%i == 0 and i%2]", "def mystery(n):\n if n < 1:\n return []\n d = {1, n}\n for k in range(2, int(n ** 0.5) + 1):\n if not n % k:\n d.add(k)\n ...
{"fn_name": "mystery", "inputs": [[-1], [0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10]], "outputs": [[[]], [[]], [[1]], [[1]], [[1, 3]], [[1]], [[1, 5]], [[1, 3]], [[1, 7]], [[1]], [[1, 3, 9]], [[1, 5]]]}
introductory
https://www.codewars.com/kata/56ee0448588cbb60740013b9
def mystery(n):
3,340
The [Sharkovsky's Theorem](https://en.wikipedia.org/wiki/Sharkovskii%27s_theorem) involves the following ordering of the natural numbers: ```math 3≺5≺7≺9≺ ...\\ ≺2·3≺2·5≺2·7≺2·9≺...\\ ≺2^n·3≺2^n·5≺2^n·7≺2^n·9≺...\\ ≺2^{(n+1)}·3≺2^{(n+1)}·5≺2^{(n+1)}·7≺2^{(n+1)}·9≺...\\ ≺2^n≺2^{(n-1)}≺...\\ ≺4≺2≺1\\ ``` Your task is t...
["def sharkovsky(a, b): return f(a)<f(b)\n\ndef f(n,p=0):\n while n%2==0:\n n>>=1\n p+=1\n return n==1, p*(-1)**(n==1), n", "def analyse(x):\n n = (b := bin(x)).rstrip(\"0\")\n p = len(b) - len(n)\n return (n := int(n, 2)) == 1, p * (-1)**(n == 1), n\n\n\ndef sharkovsky(a, b):\n return ...
{"fn_name": "sharkovsky", "inputs": [[18, 12], [3, 9], [10, 16], [1, 22], [32, 1024], [17, 17]], "outputs": [[true], [true], [true], [false], [false], [false]]}
introductory
https://www.codewars.com/kata/5f579a3b34d5ad002819eb9e
def sharkovsky(a, b):
3,342
## Task: You have to write a function `pattern` which returns the following Pattern(See Pattern & Examples) upto `n` number of rows. * Note:`Returning` the pattern is not the same as `Printing` the pattern. #### Rules/Note: * If `n < 1` then it should return "" i.e. empty string. * There are `no whitespaces` in the ...
["def pattern(n):\n return \"\\n\".join([x * str(x) for x in range(1, n + 1)])", "def pattern(n):\n result = ''\n for i in range(1, n + 1):\n result += str(i) * i + '\\n'\n return result[:-1]", "def pattern(n):\n return '\\n'.join(str(i)*i for i in range(1, n + 1))", "pattern=lambda n: \"\\n\".joi...
{"fn_name": "pattern", "inputs": [[1], [2], [5], [0], [-25]], "outputs": [["1"], ["1\n22"], ["1\n22\n333\n4444\n55555"], [""], [""]]}
introductory
https://www.codewars.com/kata/5572f7c346eb58ae9c000047
def pattern(n):
3,343
**Background** You most probably know, that the *kilo* used by IT-People differs from the *kilo* used by the rest of the world. Whereas *kilo* in kB is (mostly) intrepreted as 1024 Bytes (especially by operating systems) the non-IT *kilo* denotes the factor 1000 (as in "1 kg is 1000g"). The same goes for the prefixe...
["def memorysize_conversion(memorysize):\n [value, unit] = memorysize.split(\" \")\n kibis = [\"KiB\", \"MiB\", \"GiB\", \"TiB\"]\n kilos = [\"kB\", \"MB\", \"GB\", \"TB\"]\n if unit in kibis:\n return (str(round(float(value)*pow(1.024, kibis.index(unit)+1), 3))+\" \"+kilos[kibis.index(unit)])\n e...
{"fn_name": "memorysize_conversion", "inputs": [["1 KiB"]], "outputs": [["1.024 kB"]]}
introductory
https://www.codewars.com/kata/5a115ff080171f9651000046
def memorysize_conversion(memorysize):
3,345
There is an array of strings. All strings contains similar _letters_ except one. Try to find it! ```python find_uniq([ 'Aa', 'aaa', 'aaaaa', 'BbBb', 'Aaaa', 'AaAaAa', 'a' ]) # => 'BbBb' find_uniq([ 'abc', 'acb', 'bac', 'foo', 'bca', 'cab', 'cba' ]) # => 'foo' ``` Strings may contain spaces. Spaces is not significant,...
["from collections import defaultdict\n\ndef find_uniq(a):\n d = {}\n c = defaultdict(int)\n for e in a:\n t = frozenset(e.strip().lower())\n d[t] = e\n c[t] += 1\n \n return d[next(filter(lambda k: c[k] == 1, c))]", "def find_uniq(arr):\n if set(arr[0].lower()) == set(arr[1].lowe...
{"fn_name": "find_uniq", "inputs": [[["Aa", "aaa", "aaaaa", "BbBb", "Aaaa", "AaAaAa", "a"]], [["abc", "acb", "bac", "foo", "bca", "cab", "cba"]], [["silvia", "vasili", "victor"]], [["Tom Marvolo Riddle", "I am Lord Voldemort", "Harry Potter"]], [["", "", "", "a", "", ""]], [[" ", " ", " ", "a", " ", ""]], [["foobar...
introductory
https://www.codewars.com/kata/585d8c8a28bc7403ea0000c3
def find_uniq(arr):
3,346
The prime numbers are not regularly spaced. For example from `2` to `3` the gap is `1`. From `3` to `5` the gap is `2`. From `7` to `11` it is `4`. Between 2 and 50 we have the following pairs of 2-gaps primes: `3-5, 5-7, 11-13, 17-19, 29-31, 41-43` A prime gap of length n is a run of n-1 consecutive composite numbers...
["def gap(g, m, n):\n previous_prime = n\n for i in range(m, n + 1):\n if is_prime(i):\n if i - previous_prime == g: \n return [previous_prime, i]\n previous_prime = i\n return None\n \n \ndef is_prime(n):\n for i in range(2, int(n**.5 + 1)):\n ...
{"fn_name": "gap", "inputs": [[2, 3, 10], [3, 3, 10], [2, 100, 110], [4, 100, 110], [6, 100, 110], [8, 300, 400], [10, 300, 400], [4, 30000, 100000], [6, 30000, 100000], [8, 30000, 100000], [11, 30000, 100000], [2, 10000000, 11000000]], "outputs": [[[3, 5]], [null], [[101, 103]], [[103, 107]], [null], [[359, 367]], [[3...
introductory
https://www.codewars.com/kata/561e9c843a2ef5a40c0000a4
def gap(g, m, n):
3,353
*** Nova polynomial subtract*** This kata is from a series on polynomial handling. ( [#1](http://www.codewars.com/kata/nova-polynomial-1-add-1) [#2](http://www.codewars.com/kata/570eb07e127ad107270005fe) [#3](http://www.codewars.com/kata/5714041e8807940ff3001140 ) [#4](http://www.codewars.com/kata/571a2e2df24bdf...
["from itertools import zip_longest\n\ndef poly_subtract(p1, p2):\n return [x - y for x, y in zip_longest(p1, p2, fillvalue=0)]\n", "from itertools import zip_longest\n\ndef poly_subtract(a, b):\n return [x - y for x, y in zip_longest(a, b, fillvalue=0)]", "def poly_subtract(p1, p2):\n p1length = len(p1)\n ...
{"fn_name": "poly_subtract", "inputs": [[[], []], [[1, 2, 3, 4, 5, 6], []], [[], [1, 2, 3, 4, 5, 6]]], "outputs": [[[]], [[1, 2, 3, 4, 5, 6]], [[-1, -2, -3, -4, -5, -6]]]}
introductory
https://www.codewars.com/kata/5714041e8807940ff3001140
def poly_subtract(p1, p2):
3,365
You have a collection of lovely poems. Unfortuantely they aren't formatted very well. They're all on one line, like this: ``` Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. ``` What you want is to present each sentence on a new line, ...
["def format_poem(poem):\n return \".\\n\".join(poem.split(\". \"))", "def format_poem(poem):\n return poem.replace(\". \", \".\\n\")\n", "def format_poem(poem):\n lines = poem.split('. ')\n return '.\\n'.join(lines)\n \n \n \n \n \n", "from re import sub\n\n# Try to solve this challenge with...
{"fn_name": "format_poem", "inputs": [["Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated."], ["Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules."], ["Altho...
introductory
https://www.codewars.com/kata/585af8f645376cda59000200
def format_poem(poem):
3,368
_Based on [Project Euler problem 35](https://projecteuler.net/problem=35)_ A circular prime is a prime in which every circular permutation of that number is also prime. Circular permutations are created by rotating the digits of the number, for example: `197, 971, 719`. One-digit primes are circular primes by definiti...
["def circular_permutations(n):\n n = str(n)\n return [int(n[i:] + n[:i]) for i in range(len(n))]\n\ndef is_prime(n):\n return n > 1 and all(n % i != 0 for i in range(2, int(n**0.5)+1))\n\ndef circular_prime(n):\n return all(is_prime(x) for x in circular_permutations(n))\n", "def circular_prime(n):\n ret...
{"fn_name": "circular_prime", "inputs": [[197], [179], [971], [222], [9377], [7], [213], [35], [1]], "outputs": [[true], [false], [true], [false], [true], [true], [false], [false], [false]]}
introductory
https://www.codewars.com/kata/56b2333e2542c2aadb000079
def circular_prime(n):
3,370
In this kata the function returns an array/list of numbers without its last element. The function is already written for you and the basic tests pass, but random tests fail. Your task is to figure out why and fix it. Good luck! Hint: watch out for side effects. ~~~if:javascript Some good reading: [MDN Docs about arr...
["def without_last(lst):\n return lst[:-1]", "def without_last(lst):\n lst_copy = list(lst) # creates a shallow copy\n lst_copy.pop()\n return lst_copy\n\n# There are several other ways to solve this\n# like returning lst[:-1] directly or creating a new list iteratively with all the elements of lst minus th...
{"fn_name": "without_last", "inputs": [[[1, 2, 3, 4, 5]], [[9, 7, 6, 9]]], "outputs": [[[1, 2, 3, 4]], [[9, 7, 6]]]}
introductory
https://www.codewars.com/kata/5a4ff3c5fd56cbaf9800003e
def without_last(lst):
3,373
Write a function that accepts two square (`NxN`) matrices (two dimensional arrays), and returns the product of the two. Only square matrices will be given. How to multiply two square matrices: We are given two matrices, A and B, of size 2x2 (note: tests are not limited to 2x2). Matrix C, the solution, will be equal ...
["from numpy import matrix\n\ndef matrix_mult(a, b):\n return ( matrix(a) * matrix(b) ).tolist()", "def matrix_mult(a, b):\n return [[sum(a[i][k]*b[k][j] for k in range(len(a))) for j in range(len(a))] for i in range(len(a))]", "import numpy as np\ndef matrix_mult(a, b):\n return np.dot(a,b).tolist()", "def matrix_m...
{"fn_name": "matrix_mult", "inputs": [[[[1, 2], [3, 2]], [[3, 2], [1, 1]]], [[[9, 7], [0, 1]], [[1, 1], [4, 12]]], [[[1, 2, 3], [3, 2, 1], [2, 1, 3]], [[4, 5, 6], [6, 5, 4], [4, 6, 5]]]], "outputs": [[[[5, 4], [11, 8]]], [[[37, 93], [4, 12]]], [[[28, 33, 29], [28, 31, 31], [26, 33, 31]]]]}
introductory
https://www.codewars.com/kata/5263a84ffcadb968b6000513
def matrix_mult(a, b):
3,381
Americans are odd people: in their buildings, the first floor is actually the ground floor and there is no 13th floor (due to superstition). Write a function that given a floor in the american system returns the floor in the european system. With the 1st floor being replaced by the ground floor and the 13th floor bei...
["def get_real_floor(n):\n if n <= 0: return n\n if n < 13: return n-1\n if n > 13: return n-2", "def get_real_floor(n):\n return n if n < 1 else n - 1 if n < 13 else n - 2", "def get_real_floor(n):\n return n - (1 if n < 13 else 2) if n > 0 else n", "def get_real_floor(n):\n return n - (n > 0) - (n >...
{"fn_name": "get_real_floor", "inputs": [[1], [0], [5], [10], [12], [14], [15], [37], [200], [-2], [-5]], "outputs": [[0], [0], [4], [9], [11], [12], [13], [35], [198], [-2], [-5]]}
introductory
https://www.codewars.com/kata/574b3b1599d8f897470018f6
def get_real_floor(n):
3,384
General primality test are often computationally expensive, so in the biggest prime number race the idea is to study special sub-families of prime number and develop more effective tests for them. [Mersenne Primes](https://en.wikipedia.org/wiki/Mersenne_prime) are prime numbers of the form: Mn = 2^(n) - 1. So far, 49...
["def lucas_lehmer(n):\n return n in [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279,\n 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701,\n 23209, 44497, 86243, 110503, 132049, 216091, 756839, 859433,\n 1257787, 1398269, 2976221, 3021377, 697...
{"fn_name": "lucas_lehmer", "inputs": [[2], [3], [4], [5], [7], [10], [33], [101], [11213], [11215]], "outputs": [[true], [true], [false], [true], [true], [false], [false], [false], [true], [false]]}
introductory
https://www.codewars.com/kata/5416fac7932c1dcc4f0006b4
def lucas_lehmer(n):
3,386
Hi there! You have to implement the `String get_column_title(int num) // syntax depends on programming language` function that takes an integer number (index of the Excel column) and returns the string represents the title of this column. #Intro In the MS Excel lines are numbered by decimals, columns - by sets of ...
["from string import ascii_uppercase as u\n\ndef get_column_title(n):\n assert isinstance(n, int) and n > 0\n col = []\n while n:\n n, r = divmod(n-1, 26)\n col.append(u[r])\n return ''.join(reversed(col))", "upper = __import__(\"string\").ascii_uppercase.__getitem__\n\ndef get_column_title(nu...
{"fn_name": "get_column_title", "inputs": [[1], [26], [52], [53], [702]], "outputs": [["A"], ["Z"], ["AZ"], ["BA"], ["ZZ"]]}
introductory
https://www.codewars.com/kata/56d082c24f60457198000e77
def get_column_title(num):
3,389
Write a function that when given a URL as a string, parses out just the domain name and returns it as a string. For example: ```python domain_name("http://github.com/carbonfive/raygun") == "github" domain_name("http://www.zombie-bites.com") == "zombie-bites" domain_name("https://www.cnet.com") == "cnet" ```
["def domain_name(url):\n return url.split(\"//\")[-1].split(\"www.\")[-1].split(\".\")[0]", "import re\ndef domain_name(url):\n return re.search('(https?://)?(www\\d?\\.)?(?P<name>[\\w-]+)\\.', url).group('name')\n", "def domain_name(url):\n url = url.replace('www.','')\n url = url.replace('https://','')\n...
{"fn_name": "domain_name", "inputs": [["http://google.com"], ["http://google.co.jp"], ["https://123.net"], ["https://hyphen-site.org"], ["http://codewars.com"], ["www.xakep.ru"], ["https://youtube.com"], ["http://www.codewars.com/kata/"], ["icann.org"]], "outputs": [["google"], ["google"], ["123"], ["hyphen-site"], ["c...
introductory
https://www.codewars.com/kata/514a024011ea4fb54200004b
def domain_name(url):
3,390
A [Narcissistic Number](https://en.wikipedia.org/wiki/Narcissistic_number) is a positive number which is the sum of its own digits, each raised to the power of the number of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10). For example, take 153 (3 digits): ``` 1^3 + 5^3 + 3^3 ...
["def narcissistic(value):\n return value == sum(int(x) ** len(str(value)) for x in str(value))", "def narcissistic( value ):\n value = str(value)\n size = len(value)\n sum = 0\n for i in value:\n sum += int(i) ** size\n return sum == int(value)", "def narcissistic(value):\n return bool(valu...
{"fn_name": "narcissistic", "inputs": [[1], [5], [7], [153], [370], [371], [1634]], "outputs": [[true], [true], [true], [true], [true], [true], [true]]}
introductory
https://www.codewars.com/kata/5287e858c6b5a9678200083c
def narcissistic( value ):
3,394
The Collatz Conjecture states that for any natural number n, if n is even, divide it by 2. If n is odd, multiply it by 3 and add 1. If you repeat the process continuously for n, n will eventually reach 1. For example, if n = 20, the resulting sequence will be: [20, 10, 5, 16, 8, 4, 2, 1] Write a program that will o...
["def collatz(n):\n step = 1\n while n!= 1:\n n = [n//2, (n*3)+1][n%2]\n step += 1\n return step\n\n\n", "from itertools import count\n\ndef collatz(n):\n for iteration in count(1):\n if n == 1:\n return iteration\n elif n % 2 == 0:\n n //= 2\n else:\n n...
{"fn_name": "collatz", "inputs": [[100], [10], [500], [73567465519280238573], [1000000000], [1000000000000000]], "outputs": [[26], [7], [111], [362], [101], [276]]}
introductory
https://www.codewars.com/kata/54fb963d3fe32351f2000102
def collatz(n):
3,397
# Introduction A grille cipher was a technique for encrypting a plaintext by writing it onto a sheet of paper through a pierced sheet (of paper or cardboard or similar). The earliest known description is due to the polymath Girolamo Cardano in 1550. His proposal was for a rectangular stencil allowing single letters, ...
["def grille(msg, code):\n return ''.join(msg[-1-i] for i,c in enumerate(bin(code)[::-1]) if c == '1' and i < len(msg))[::-1]", "def grille(message, code):\n binary = bin(code)[2:][-len(message):].zfill(len(message))\n return ''.join(char for char, code in zip(message, binary) if code == '1')", "def grille(m, ...
{"fn_name": "grille", "inputs": [["abcdef", 5], ["", 5], ["abcd", 1], ["0abc", 2], ["ab", 255], ["ab", 256], ["abcde", 32], ["tcddoadepwweasresd", 77098]], "outputs": [["df"], [""], ["d"], ["b"], ["ab"], [""], [""], ["codewars"]]}
introductory
https://www.codewars.com/kata/595b3f0ad26b2d817400002a
def grille(message, code):
3,402
**Debug** a function called calculate that takes 3 values. The first and third values are numbers. The second value is a character. If the character is "+" , "-", "\*", or "/", the function will return the result of the corresponding mathematical function on the two numbers. If the string is not one of the specified ch...
["from operator import add, sub, mul, truediv\nD = {'+':add, '-':sub, '*':mul, '/':truediv}\n\ndef calculate(a, o, b):\n try: return D[o](a, b)\n except: pass", "def calculate(a, o, b):\n result = 0\n if(o == \"+\"):\n return a + b\n elif(o == \"-\"):\n return a - b\n elif(o == \"/\" and...
{"fn_name": "calculate", "inputs": [[2, "+", 4], [6, "-", 1.5], [-4, "*", 8], [49, "/", -7], [8, "m", 2], [4, "/", 0], [3.2, "+", 8], [3.2, "-", 8], [3.2, "/", 8], [3.2, "*", 8], [-3, "+", 0], [-3, "-", 0], [-3, "/", 0], [-2, "/", -2], [-2, "codewars", -2], [-3, "*", 0], [0, "*", 0], [0, "**", 0], [-3, "w", 0], [0, "/"...
introductory
https://www.codewars.com/kata/56368f37d464c0a43c00007f
def calculate(a, o, b):
3,403
This kata focuses on the Numpy python package and you can read up on the Numpy array manipulation functions here: https://docs.scipy.org/doc/numpy-1.13.0/reference/routines.array-manipulation.html You will get two integers `N` and `M`. You must return an array with two sub-arrays with numbers in ranges `[0, N / 2)` an...
["import numpy as np\n\n\ndef reorder(a, b):\n return np.roll(np.arange(a).reshape(2, -1), b, 1).tolist()\n", "from collections import deque\n\n\ndef reorder(n, m):\n a, b = deque(range(n // 2)), deque(range(n // 2, n))\n a.rotate(m)\n b.rotate(m)\n return [list(a), list(b)]", "# Numpy?\n# https://media....
{"fn_name": "reorder", "inputs": [[10, 1], [10, 3], [10, 97]], "outputs": [[[[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]], [[[2, 3, 4, 0, 1], [7, 8, 9, 5, 6]]], [[[3, 4, 0, 1, 2], [8, 9, 5, 6, 7]]]]}
introductory
https://www.codewars.com/kata/5a48fab7bdb9b5b3690009b6
def reorder(a, b):
3,404
In this Kata, you will be given a string and two indexes (`a` and `b`). Your task is to reverse the portion of that string between those two indices inclusive. ~~~if-not:fortran ``` solve("codewars",1,5) = "cawedors" -- elements at index 1 to 5 inclusive are "odewa". So we reverse them. solve("cODEWArs", 1,5) = "cAWE...
["def solve(s,a,b):\n return s[:a]+s[a:b+1][::-1]+s[b+1:]", "def solve(st,a,b):\n return st[:a]+st[a:b+1][::-1]+ st[b+1:]", "def solve(st,a,b):\n return f'{st[:a]}{st[a : b + 1][::-1]}{st[b + 1 :]}'", "def solve(st,a,b):\n sub, rev = st[a:b+1], st[a:b+1][::-1]\n return st.replace(sub, rev)", "def solve(s...
{"fn_name": "solve", "inputs": [["codewars", 1, 5], ["codingIsFun", 2, 100], ["FunctionalProgramming", 2, 15], ["abcefghijklmnopqrstuvwxyz", 0, 20], ["abcefghijklmnopqrstuvwxyz", 5, 20]], "outputs": [["cawedors"], ["conuFsIgnid"], ["FuargorPlanoitcnmming"], ["vutsrqponmlkjihgfecbawxyz"], ["abcefvutsrqponmlkjihgwxyz"]]}
introductory
https://www.codewars.com/kata/5a8d1c82373c2e099d0000ac
def solve(st,a,b):
3,406
Mutual Recursion allows us to take the fun of regular recursion (where a function calls itself until a terminating condition) and apply it to multiple functions calling each other! Let's use the Hofstadter Female and Male sequences to demonstrate this technique. You'll want to create two functions `F` and `M` such th...
["def f(n): return n - m(f(n-1)) if n else 1\n\ndef m(n): return n - f(m(n-1)) if n else 0", "def f(n):\n if n == 0:\n return 1\n return n - m(f(n - 1))\n\ndef m(n):\n if n == 0:\n return 0\n return n - f(m(n - 1))", "df={0:1}\ndm={0:0}\ndef f(n):\n if n in df: \n return df[n]\n e...
{"fn_name": "f", "inputs": [[0], [5], [10], [15], [25]], "outputs": [[1], [3], [6], [9], [16]]}
introductory
https://www.codewars.com/kata/53a1eac7e0afd3ad3300008b
def f(n):
3,419
Write a function that will encrypt a given sentence into International Morse Code, both the input and out puts will be strings. Characters should be separated by a single space. Words should be separated by a triple space. For example, "HELLO WORLD" should return -> ".... . .-.. .-.. --- .-- --- .-. .-.. -.." To f...
["#CHAR_TO_MORSE preloaded to convert characters into Morse code\nCODE = {'A': '.-', 'B': '-...', 'C': '-.-.', \n 'D': '-..', 'E': '.', 'F': '..-.',\n 'G': '--.', 'H': '....', 'I': '..',\n 'J': '.---', 'K': '-.-', 'L': '.-..',\n 'M': '--', 'N': '-.', 'O': '---...
{"fn_name": "encryption", "inputs": [["HELLO WORLD"], ["SOS"], ["1836"], ["THE QUICK BROWN FOX"], ["JUMPED OVER THE"], ["LAZY DOG"], ["WOLFRAM ALPHA 1"], ["CodeWars Rocks"], [""], ["Final basic test"]], "outputs": [[".... . .-.. .-.. --- .-- --- .-. .-.. -.."], ["... --- ..."], [".---- ---.. ...-- -...."], ["- .... ....
introductory
https://www.codewars.com/kata/55b8c0276a7930249e00003c
def encryption(string):
3,423
In this Kata, you will be given an array of numbers and a number `n`, and your task will be to determine if `any` array elements, when summed (or taken individually), are divisible by `n`. For example: * `solve([1,3,4,7,6],9) == true`, because `3 + 6` is divisible by `9` * `solve([1,2,3,4,5],10) == true` for sim...
["from itertools import combinations\n\ndef solve(a, n):\n return any(sum(c) % n == 0 for i in range(len(a)) for c in combinations(a, i+1))", "def solve(xs, n):\n rs = set()\n for x in xs:\n for r in list(rs):\n rs.add((r + x) % n)\n rs.add(x % n)\n return 0 in rs", "from itertools ...
{"fn_name": "solve", "inputs": [[[1, 2, 3, 4, 5], 8], [[7, 2, 8, 5], 16], [[1, 2, 3, 4, 5], 10], [[3, 1, 5, 7], 14], [[1, 2, 3, 4, 5], 15], [[8, 5, 3, 9], 7], [[8, 5, 3], 7]], "outputs": [[true], [false], [true], [false], [true], [true], [false]]}
introductory
https://www.codewars.com/kata/59eb64cba954273cd4000099
def solve(arr,n):
3,425
A [Word Square](https://en.wikipedia.org/wiki/Word_square) is a set of words written out in a square grid, such that the same words can be read both horizontally and vertically. The number of words, equal to the number of letters in each word, is known as the *order* of the square. For example, this is an *order* `5` ...
["from collections import Counter\ndef word_square(ls):\n n = int(len(ls)**0.5)\n return n*n==len(ls) and sum(i%2 for i in list(Counter(ls).values())) <= n\n", "def word_square(letters):\n root = int(len(letters)**0.5)\n return len(letters)**0.5 == root and sum([ letters.count(i)%2 for i in set(letters) ]) ...
{"fn_name": "word_square", "inputs": [["SATORAREPOTENETOPERAROTAS"], ["NOTSQUARE"], ["BITICETEN"], ["CARDAREAREARDART"], ["CODEWARS"], ["AAAAACEEELLRRRTT"], ["AAACCEEEEHHHMMTT"], ["AAACCEEEEHHHMMTTXXX"], ["ABCD"], ["GHBEAEFGCIIDFHGG"], ["AAHHFDKIHHFCXZBFDERRRTXXAA"], ["AABBCCDDEEFFGGGG"], ["ABCABCABC"], ["FRACTUREOUTLI...
introductory
https://www.codewars.com/kata/578e07d590f2bb8d3300001d
def word_square(letters):
3,427
There is an array with some numbers. All numbers are equal except for one. Try to find it! ```python find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2 find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55 ``` It’s guaranteed that array contains at least 3 numbers. The tests contain some very huge arrays, so think about performance. This is t...
["def find_uniq(arr):\n a, b = set(arr)\n return a if arr.count(a) == 1 else b", "def find_uniq(arr):\n if (arr[0]==arr[1]):\n return([x for x in arr[2:] if x!=arr[0] ][0])\n return(arr[0] if arr[1]==arr[2] else arr[1])\n", "def find_uniq(arr):\n s = set(arr)\n for e in s:\n if arr.coun...
{"fn_name": "find_uniq", "inputs": [[[1, 1, 1, 2, 1, 1]], [[0, 0, 0.55, 0, 0]], [[4, 4, 4, 3, 4, 4, 4, 4]], [[5, 5, 5, 5, 4, 5, 5, 5]], [[6, 6, 6, 6, 6, 5, 6, 6]], [[7, 7, 7, 7, 7, 7, 6, 7]], [[8, 8, 8, 8, 8, 8, 8, 7]], [[3, 3, 3, 3, 3, 3, 3, 2]], [[2, 2, 2, 2, 2, 2, 2, 1]], [[0, 1, 1, 1, 1, 1, 1, 1]]], "outputs": [[2]...
introductory
https://www.codewars.com/kata/585d7d5adb20cf33cb000235
def find_uniq(arr):
3,442
In genetics 2 differents DNAs sequences can code for the same protein. This is due to the redundancy of the genetic code, in fact 2 different tri-nucleotide can code for the same amino-acid. For example the tri-nucleotide 'TTT' and the tri-nucleotide 'TTC' both code for the amino-acid 'F'. For more information you ca...
["def code_for_same_protein(seq1,seq2):\n if seq1 == seq2:\n return True\n lista = [['GCT','GCC','GCA','GCG'],['CGT','CGC','CGA','CGG','AGA','AGG'],['AAT','AAC'],['GAT','GAC'],['AAT','AAC','GAT','GAC'],['TGT','TGC'],['CAA','CAG'],['GAA','GAG'],['CAA','CAG','GAA','GAG'],['GGT','GGC','GGA','GGG'],['CAT','CAC...
{"fn_name": "code_for_same_protein", "inputs": [["ATGTCGTCAATTTAA", "ATGTCGTCAATTTAA"], ["ATGTTTTAA", "ATGTTCTAA"], ["ATGTTTTAA", "ATGATATAA"], ["ATGTTTGGGAATAATTAAGGGTAA", "ATGTTCGGGAATAATGGGAGGTAA"]], "outputs": [[true], [true], [false], [false]]}
introductory
https://www.codewars.com/kata/57cbb9e240e3024aae000b26
def code_for_same_protein(seq1,seq2):
3,443
A system is transmitting messages in binary, however it is not a perfect transmission, and sometimes errors will occur which result in a single bit flipping from 0 to 1, or from 1 to 0. To resolve this, A 2-dimensional Parity Bit Code is used: https://en.wikipedia.org/wiki/Multidimensional_parity-check_code In this s...
["def correct(m, n, bits):\n l = m*n\n row = next((i for i in range(m) if f\"{bits[i*n:(i+1)*n]}{bits[l+i]}\".count(\"1\") % 2), None)\n col = next((i for i in range(n) if f\"{bits[i:l:n]}{bits[l+m+i]}\".count(\"1\") % 2), None)\n if row is col is None:\n return bits\n err = (l + row) if col is No...
{"fn_name": "correct", "inputs": [[1, 1, "111"], [1, 1, "011"], [1, 1, "101"], [1, 1, "110"], [2, 3, "11111010001"], [2, 3, "11011010001"], [2, 3, "11111011001"], [2, 3, "11111010011"]], "outputs": [["111"], ["111"], ["111"], ["111"], ["11111010001"], ["11111010001"], ["11111010001"], ["11111010001"]]}
introductory
https://www.codewars.com/kata/5d870ff1dc2362000ddff90b
def correct(m, n, bits):
3,446
#### Task: Your job here is to implement a method, `approx_root` in Ruby/Python/Crystal and `approxRoot` in JavaScript/CoffeeScript, that takes one argument, `n`, and returns the approximate square root of that number, rounded to the nearest hundredth and computed in the following manner. 1. Start with `n = 213`...
["def approx_root(n):\n base = int(n**0.5)\n return round( base + (n - base**2) / ((base + 1)**2 - base**2) , 2)", "def approx_root(n):\n m = n**0.5\n a, b = [int(x) for x in [m, m + 1]]\n c = a**2\n return round(a + ((n - c) / (b**2 - c)), 2)", "def approx_root(n):\n b = int(n ** 0.5)\n diff_gn...
{"fn_name": "approx_root", "inputs": [[400], [401], [2], [4], [5], [6], [7], [8], [9], [100], [120], [106], [111], [121], [168]], "outputs": [[20], [20.02], [1.33], [2], [2.2], [2.4], [2.6], [2.8], [3], [10], [10.95], [10.29], [10.52], [11], [12.96]]}
introductory
https://www.codewars.com/kata/58475cce273e5560f40000fa
def approx_root(n):
3,449
As a member of the editorial board of the prestigous scientific Journal _Proceedings of the National Academy of Sciences_, you've decided to go back and review how well old articles you've published stand up to modern publication best practices. Specifically, you'd like to re-evaluate old findings in light of recent li...
["def categorize_study(p_value, requirements):\n study_value = p_value * (2**(6-requirements))\n \n if study_value < 0.05 and requirements != 0:\n return \"Fine\"\n elif study_value < 0.05 and requirements == 0:\n return \"Needs review\"\n elif study_value > 0.05 and study_value < 0.15:\n ...
{"fn_name": "categorize_study", "inputs": [[0.01, 3], [0.04, 6], [0.0001, 0], [0.012, 0]], "outputs": [["Needs review"], ["Fine"], ["Needs review"], ["Pants on fire"]]}
introductory
https://www.codewars.com/kata/5864af6739c5ab26e80000bf
def categorize_study(p_value, requirements):
3,450
This is a spin off of my first [kata](http://www.codewars.com/kata/56bc28ad5bdaeb48760009b0). You are given a list of character sequences as a comma separated string. Write a function which returns another string containing all the character sequences except the first and the last ones, separated by spaces. If the inpu...
["def array(strng):\n return ' '.join(strng.split(',')[1:-1]) or None\n", "def array(s):\n r = ' '.join(s.split(',')[1:-1])\n return r if r else None", "def array(string):\n res = ' '.join(string.split(',')[1:-1])\n return res if len(res) > 0 else None", "def array(string):\n if len(string) <5:\n ret...
{"fn_name": "array", "inputs": [[""], ["1"], ["1, 3"], ["1,2,3"], ["1,2,3,4"]], "outputs": [[null], [null], [null], ["2"], ["2 3"]]}
introductory
https://www.codewars.com/kata/570597e258b58f6edc00230d
def array(string):
3,451
If you finish this kata, you can try [Insane Coloured Triangles](http://www.codewars.com/kata/insane-coloured-triangles) by Bubbler, which is a ***much*** harder version of this one. A coloured triangle is created from a row of colours, each of which is red, green or blue. Successive rows, each containing one fewer co...
["COLORS = set(\"RGB\")\n\ndef triangle(row):\n while len(row)>1:\n row = ''.join( a if a==b else (COLORS-{a,b}).pop() for a,b in zip(row, row[1:]))\n return row", "def triangle(row):\n dicts = {'GG':'G', 'BB':'B', 'RR':'R', 'BR':'G', 'BG':'R', 'GB':'R', 'GR':'B', 'RG':'B', 'RB':'G'}\n if len(row) > ...
{"fn_name": "triangle", "inputs": [["GB"], ["RRR"], ["RGBG"], ["RBRGBRB"], ["RBRGBRBGGRRRBGBBBGG"], ["B"]], "outputs": [["R"], ["R"], ["B"], ["G"], ["G"], ["B"]]}
introductory
https://www.codewars.com/kata/5a25ac6ac5e284cfbe000111
def triangle(row):
3,455
# Definition **_Disarium number_** is the number that *The sum of its digits powered with their respective positions is equal to the number itself*. ____ # Task **_Given_** a number, **_Find if it is Disarium or not_** . ____ # Warm-up (Highly recommended) # [Playing With Numbers Series](https://www.codewars.com...
["def disarium_number(n):\n return \"Disarium !!\" if n == sum(int(d)**i for i, d in enumerate(str(n), 1)) else \"Not !!\"", "def disarium_number(number):\n a=0\n for j,i in enumerate(str(number)):\n a+=int(i)**(j+1)\n return 'Disarium !!' if a==number else 'Not !!'\n", "def disarium_number(num):\n ...
{"fn_name": "disarium_number", "inputs": [[1024], [1306], [1999], [2427], [1048576], [2646798]], "outputs": [["Not !!"], ["Disarium !!"], ["Not !!"], ["Disarium !!"], ["Not !!"], ["Disarium !!"]]}
introductory
https://www.codewars.com/kata/5a53a17bfd56cb9c14000003
def disarium_number(number):
3,456
This challenge extends the previous [repeater()](https://www.codewars.com/kata/thinkful-string-drills-repeater) challenge. Just like last time, your job is to write a function that accepts a string and a number as arguments. This time, however, you should format the string you return like this: ```python >>> repeater('...
["def repeater(string, n):\n return '\"{}\" repeated {} times is: \"{}\"'.format(string, n, string * n)\n", "def repeater(string, n):\n return '\"{0}\" repeated {1} times is: \"{2}\"'.format(string, n, string * n)\n", "def repeater(s, n):\n return '\"{}\" repeated {} times is: \"{}\"'.format(s, n, s * n)", "def ...
{"fn_name": "repeater", "inputs": [["yo", 3], ["WuB", 6], ["code, eat, code, sleep... ", 2]], "outputs": [["\"yo\" repeated 3 times is: \"yoyoyo\""], ["\"WuB\" repeated 6 times is: \"WuBWuBWuBWuBWuBWuB\""], ["\"code, eat, code, sleep... \" repeated 2 times is: \"code, eat, code, sleep... code, eat, code, sleep... \""]]...
introductory
https://www.codewars.com/kata/585a1f0945376c112a00019a
def repeater(string, n):
3,465
# Description Write a function that checks whether a credit card number is correct or not, using the Luhn algorithm. The algorithm is as follows: * From the rightmost digit, which is the check digit, moving left, double the value of every second digit; if the product of this doubling operation is greater than 9 (e.g....
["def valid_card(card):\n s = list(map(int, str(card.replace(' ', ''))))\n s[0::2] = [d * 2 - 9 if d * 2 > 9 else d * 2 for d in s[0::2]]\n return sum(s) % 10 == 0", "def valid_card(card_number):\n total = 0\n for i, a in enumerate(reversed(card_number.replace(' ', ''))):\n if i % 2:\n ...
{"fn_name": "valid_card", "inputs": [["5457 6238 9823 4311"], ["8895 6238 9323 4311"], ["5457 6238 5568 4311"], ["5457 6238 9323 4311"], ["2222 2222 2222 2224"], ["5457 1125 9323 4311"], ["1252 6238 9323 4311"], ["9999 9999 9999 9995"], ["0000 0300 0000 0000"], ["4444 4444 4444 4448"], ["5457 6238 9323 1252"], ["5457 6...
introductory
https://www.codewars.com/kata/56d55dcdc87df58c81000605
def valid_card(card):
3,467
Create a function that finds the [integral](https://en.wikipedia.org/wiki/Integral) of the expression passed. In order to find the integral all you need to do is add one to the `exponent` (the second argument), and divide the `coefficient` (the first argument) by that new number. For example for `3x^2`, the integral ...
["def integrate(coef, exp):\n exp = exp + 1\n coef = coef / exp if coef % exp else coef // exp\n return f\"{coef}x^{exp}\"", "def integrate(coefficient, exponent):\n return (str(coefficient // (exponent + 1)) + 'x^' + str(exponent + 1)) ", "def integrate(coefficient, exponent):\n return f'{coefficient /...
{"fn_name": "integrate", "inputs": [[3, 2], [12, 5], [20, 1], [40, 3], [90, 2]], "outputs": [["1x^3"], ["2x^6"], ["10x^2"], ["10x^4"], ["30x^3"]]}
introductory
https://www.codewars.com/kata/59811fd8a070625d4c000013
def integrate(coefficient, exponent):
3,470
The goal is to write a pair of functions the first of which will take a string of binary along with a specification of bits, which will return a numeric, signed complement in two's complement format. The second will do the reverse. It will take in an integer along with a number of bits, and return a binary string. ht...
["def to_twos_complement(binary, bits):\n return int(binary.replace(' ', ''), 2) - 2 ** bits * int(binary[0])\n\ndef from_twos_complement(n, bits):\n return '{:0{}b}'.format(n & 2 ** bits - 1, bits)", "def to_twos_complement(b, bits):\n b = b.replace(\" \",\"\")\n return int(b,2) if int(b,2) < 2**(bits-1) e...
{"fn_name": "to_twos_complement", "inputs": [["00000001", 8], ["00000010", 8], ["01111110", 8], ["01111111", 8], ["11111111", 8], ["11111110", 8], ["10000010", 8], ["1000 0000", 8], ["1010 1010 0010 0010 1110 1010 0010 1110", 32], ["1000 0000 1110 1111 0011 0100 1100 1010", 32], ["10110001000100000101100011111000", 32]...
introductory
https://www.codewars.com/kata/58d4785a2285e7795c00013b
def to_twos_complement(binary, bits):
3,482
# Definition **_Extra perfect number_** *is the number that* **_first_** and **_last_** *bits* are **_set bits_**. ____ # Task **_Given_** *a positive integer* `N` , **_Return_** the **_extra perfect numbers_** *in range from* `1` to `N` . ____ # Warm-up (Highly recommended) # [Playing With Numbers Series]...
["def extra_perfect(n):\n return list(range(1,n+1,2))", "def extra_perfect(n):\n return list(range(1, n + 1, 2))\n", "def extra_perfect(n):\n return [i for i in range(n+1) if i % 2 != 0] ", "def extra_perfect(n):\n return [i for i in range(1,n+1) if bin(i)[2]=='1' and bin(i)[-1]=='1']", "def extra_perfect(n...
{"fn_name": "extra_perfect", "inputs": [[3], [5], [7], [28], [39]], "outputs": [[[1, 3]], [[1, 3, 5]], [[1, 3, 5, 7]], [[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27]], [[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39]]]}
introductory
https://www.codewars.com/kata/5a662a02e626c54e87000123
def extra_perfect(n):
3,496
In this kata you will be given a sequence of the dimensions of rectangles ( sequence with width and length ) and circles ( radius - just a number ). Your task is to return a new sequence of dimensions, sorted ascending by area. For example, ```python seq = [ (4.23, 6.43), 1.23, 3.444, (1.342, 3.212) ] # [ rectangle...
["def sort_by_area(seq): \n def func(x):\n if isinstance(x, tuple):\n return x[0] * x[1]\n else:\n return 3.14 * x * x\n return sorted(seq, key=func)", "from math import pi as PI\n\ndef circle(r): return r*r*PI\ndef rect(a,b): return a*b\ndef getArea(r): ...
{"fn_name": "sort_by_area", "inputs": [[[]]], "outputs": [[[]]]}
introductory
https://www.codewars.com/kata/5a1ebc2480171f29cf0000e5
def sort_by_area(seq):
3,497
A [perfect power](https://en.wikipedia.org/wiki/Perfect_power) is a classification of positive integers: > In mathematics, a **perfect power** is a positive integer that can be expressed as an integer power of another positive integer. More formally, n is a perfect power if there exist natural numbers m > 1, and k > 1...
["from math import ceil, log, sqrt\n\ndef isPP(n):\n for b in range(2, int(sqrt(n)) + 1):\n e = int(round(log(n, b)))\n if b ** e == n:\n return [b, e]\n return None\n", "def isPP(n):\n for i in range(2, int(n**.5) + 1):\n number = n\n times = 0\n while number % i ...
{"fn_name": "isPP", "inputs": [[4], [9], [5]], "outputs": [[[2, 2]], [[3, 2]], [null]]}
introductory
https://www.codewars.com/kata/54d4c8b08776e4ad92000835
def isPP(n):
3,509
Scientists working internationally use metric units almost exclusively. Unless that is, they wish to crash multimillion dollars worth of equipment on Mars. Your task is to write a simple function that takes a number of meters, and outputs it using metric prefixes. In practice, meters are only measured in "mm" (thousa...
["def meters(x):\n #your code here\n arr = ['','k','M','G','T','P','E','Z','Y']\n count=0\n while x>=1000 :\n x /=1000.00 \n count+=1\n if int(x)==x:\n x=int(x) \n return str(x)+arr[count]+'m'\n", "PREFIXES = (\n (10 ** 24, 'Y'),\n (10 ** 21, 'Z'),\n ...
{"fn_name": "meters", "inputs": [[1], [999], [123456], [12300000], [9000000000.0], [9000000000000.0], [9000000000000000.0], [9e+18], [9e+21], [9e+24]], "outputs": [["1m"], ["999m"], ["123.456km"], ["12.3Mm"], ["9Gm"], ["9Tm"], ["9Pm"], ["9Em"], ["9Zm"], ["9Ym"]]}
introductory
https://www.codewars.com/kata/5264f5685fda8ed370000265
def meters(x):
3,512
Just like in the ["father" kata](http://www.codewars.com/kata/find-fibonacci-last-digit/), you will have to return the last digit of the nth element in the Fibonacci sequence (starting with 1,1, to be extra clear, not with 0,1 or other numbers). You will just get much bigger numbers, so good luck bruteforcing your way...
["def last_fib_digit(n):\n return [0,1,1,2,3,5,8,3,1,4,5,9,4,3,7,0,7,7,4,1,5,6,1,7,8,5,3,8,1,9,0,9,9,8,7,5,2,7,9,6,5,1,6,7,3,0,3,3,6,9,5,4,9,3,2,5,7,2,9,1][n%60]", "def last_fib_digit(n):\n \"\"\" well, it is periodic on 60 \"\"\"\n a = 0\n b = 1\n for _ in range(n%60):\n a, b = b, (a+b)%10\n r...
{"fn_name": "last_fib_digit", "inputs": [[1], [21], [302], [4003], [50004], [600005], [7000006], [80000007], [900000008], [1000000009]], "outputs": [[1], [6], [1], [7], [8], [5], [3], [8], [1], [9]]}
introductory
https://www.codewars.com/kata/56b7771481290cc283000f28
def last_fib_digit(n):
3,518
On Unix system type files can be identified with the ls -l command which displays the type of the file in the first alphabetic letter of the file system permissions field. You can find more information about file type on Unix system on the [wikipedia page](https://en.wikipedia.org/wiki/Unix_file_types). - '-' A regula...
["dict = {'-':\"file\",'d':\"directory\",'l':\"symlink\",'c':\"character_file\",'b':\"block_file\",'p':\"pipe\",'s':\"socket\",'D':\"door\"}\ndef linux_type(file_attribute):\n return dict[file_attribute[0]]", "def linux_type(s):\n return {x: y for x, y in zip(\"-dlcbpsD\", \"file directory symlink character_file ...
{"fn_name": "linux_type", "inputs": [["-rwxrwxrwx"], ["Drwxr-xr-x"], ["lrwxrw-rw-"], ["srwxrwxrwx"]], "outputs": [["file"], ["door"], ["symlink"], ["socket"]]}
introductory
https://www.codewars.com/kata/5822b65bb81f702016000026
def linux_type(file_attribute):
3,522
# Introduction and Warm-up (Highly recommended) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) ___ # Task **_Given_** an *array/list [] of integers* , **_Find_** **_The maximum difference_** *between the successive elements in its sorted form*. ___ # Note...
["def max_gap(numbers):\n lst = sorted(numbers)\n return max(b-a for a,b in zip(lst, lst[1:]))", "import numpy\n\ndef max_gap(numbers):\n return max(numpy.diff(sorted(numbers)))", "def max_gap(numbers):\n A = sorted(numbers)\n return max([abs(A[i] - A[i+1]) for i in range(len(A)-1)])", "def max_gap(n):\n...
{"fn_name": "max_gap", "inputs": [[[13, 10, 2, 9, 5]], [[13, 3, 5]], [[24, 299, 131, 14, 26, 25]], [[-3, -27, -4, -2]], [[-7, -42, -809, -14, -12]], [[12, -5, -7, 0, 290]], [[-54, 37, 0, 64, -15, 640, 0]], [[130, 30, 50]], [[1, 1, 1]], [[-1, -1, -1]]], "outputs": [[4], [8], [168], [23], [767], [278], [576], [80], [0], ...
introductory
https://www.codewars.com/kata/5a7893ef0025e9eb50000013
def max_gap(numbers):
3,526
Check your arrows You have a quiver of arrows, but some have been damaged. The quiver contains arrows with an optional range information (different types of targets are positioned at different ranges), so each item is an arrow. You need to verify that you have some good ones left, in order to prepare for battle: ```py...
["def any_arrows(arrows):\n return any(not i.get(\"damaged\", False) for i in arrows)\n", "def any_arrows(arrows):\n return any(not arrow.get('damaged', False) for arrow in arrows)\n", "def any_arrows(arrows):\n return any([True for a in arrows if 'damaged' not in a or a['damaged'] == False])", "def any_arrows...
{"fn_name": "any_arrows", "inputs": [[[]], [[{"range": 5, "damaged": false}]], [[{"range": 5, "damaged": false}, {"range": 15, "damaged": true}]], [[{"range": 5}, {"range": 10, "damaged": true}, {"damaged": true}]], [[{"range": 10, "damaged": true}, {"damaged": true}]]], "outputs": [[false], [true], [true], [true], [fa...
introductory
https://www.codewars.com/kata/559f860f8c0d6c7784000119
def any_arrows(arrows):
3,531
A [Mersenne prime](https://en.wikipedia.org/wiki/Mersenne_prime) is a prime number that can be represented as: Mn = 2^(n) - 1. Therefore, every Mersenne prime is one less than a power of two. Write a function that will return whether the given integer `n` will produce a Mersenne prime or not. The tests will check ra...
["def valid_mersenne(n):\n return n in {2,3,5,7,13,17,19,31,61,89,107,127,521,607,1279}", "def valid_mersenne(n):\n '''Currently using the Lucas-Lehmer test.'''\n \n if n < 2:\n return False\n \n if n == 2:\n return True\n \n mersenne = 2**n - 1\n \n residue = 4\n for _ in...
{"fn_name": "valid_mersenne", "inputs": [[2], [3], [5], [7], [11], [13], [17], [19], [21], [23], [31], [49], [61], [89], [107], [127], [221], [521], [607], [1279]], "outputs": [[true], [true], [true], [true], [false], [true], [true], [true], [false], [false], [true], [false], [true], [true], [true], [true], [false], [t...
introductory
https://www.codewars.com/kata/56af6e4198909ab73200013f
def valid_mersenne(n):
3,533
# Task Write a function `deNico`/`de_nico()` that accepts two parameters: - `key`/`$key` - string consists of unique letters and digits - `message`/`$message` - string with encoded message and decodes the `message` using the `key`. First create a numeric key basing on the provided `key` by assigning each letter p...
["def de_nico(key, msg):\n ll, order, s = len(key), [sorted(key).index(c) for c in key], ''\n while msg:\n s, msg = s + ''.join(msg[i] for i in order if i < len(msg)), msg[ll:]\n return s.strip()", "def de_nico(key,msg):\n \n decoder = []\n \n # assign key letters numbers according to alphab...
{"fn_name": "de_nico", "inputs": [["crazy", "cseerntiofarmit on "], ["crazy", "cseerntiofarmit on"], ["abc", "abcd"], ["ba", "2143658709"], ["a", "message"], ["key", "eky"]], "outputs": [["secretinformation"], ["secretinformation"], ["abcd"], ["1234567890"], ["message"], ["key"]]}
introductory
https://www.codewars.com/kata/596f610441372ee0de00006e
def de_nico(key,msg):
3,538
## Story > "You have serious coding skillz? You wannabe a [scener](https://en.wikipedia.org/wiki/Demoscene)? Complete this mission and u can get in teh crew!" You have read a similar message on your favourite [diskmag](https://en.wikipedia.org/wiki/Disk_magazine) back in the early 90s, and got really excited. You con...
["from math import pi, sin\n\ndef scroller(text, amp, period):\n return '\\n'.join(' ' * (amp + int(round(sin(i * 2 * pi / period) * amp))) + c for i, c in enumerate(text))\n", "import math\ndef scroller(text, amp, period):\n l = lambda i, c: ' '*(amp+i) + c + \"\\n\"\n return (''.join([l(round(amp * math.sin(...
{"fn_name": "scroller", "inputs": [["Hello World!", 3, 10], ["I'm a Codewars warrior lately...", 5, 18]], "outputs": [[" H\n e\n l\n l\n o\n \n W\no\nr\n l\n d\n !"], [" I\n '\n m\n \n a\n \n C\n o\n d\n e\n w\n a\n r\...
introductory
https://www.codewars.com/kata/59cabf6baeb28482b8000017
def scroller(text, amp, period):
3,540
According to ISO 8601, the first calendar week (1) starts with the week containing the first thursday in january. Every year contains of 52 (53 for leap years) calendar weeks. **Your task is** to calculate the calendar week (1-53) from a given date. For example, the calendar week for the date `2019-01-01` (string) sho...
["from datetime import datetime\n\n\ndef get_calendar_week(date_string):\n return datetime.strptime(date_string, \"%Y-%m-%d\").isocalendar()[1] ", "from datetime import date\n\ndef get_calendar_week(s):\n return date(*map(int, s.split(\"-\"))).isocalendar()[1]", "import datetime\nget_calendar_week=lambda d:dat...
{"fn_name": "get_calendar_week", "inputs": [["2017-01-01"], ["2018-12-24"], ["2018-12-31"], ["2019-01-01"], ["2016-02-29"], ["2015-12-29"], ["2024-12-31"], ["2025-01-05"], ["2025-01-06"], ["1995-12-31"], ["1996-01-01"], ["1999-12-31"], ["2000-01-02"], ["2000-01-03"], ["2016-12-25"], ["2016-12-26"], ["2017-01-02"], ["20...
introductory
https://www.codewars.com/kata/5c2bedd7eb9aa95abe14d0ed
def get_calendar_week(date_string):
3,542
This is related to my other Kata about cats and dogs. # Kata Task I have a cat and a dog which I got as kitten / puppy. I forget when that was, but I do know their current ages as `catYears` and `dogYears`. Find how long I have owned each of my pets and return as a list [`ownedCat`, `ownedDog`] NOTES: * Results ar...
["def owned_cat_and_dog(cy, dy):\n cat = 0 if cy < 15 else 1 if cy < 24 else 2 + (cy - 24) // 4\n dog = 0 if dy < 15 else 1 if dy < 24 else 2 + (dy - 24) // 5\n return [cat, dog]", "def owned_cat_and_dog(cat_years, dog_years):\n i = cat_years\n k = dog_years\n if i < 24:\n cat_years = 1\n if k...
{"fn_name": "owned_cat_and_dog", "inputs": [[9, 7], [15, 15], [18, 21], [19, 17], [24, 24], [25, 25], [26, 26], [27, 27], [56, 64]], "outputs": [[[0, 0]], [[1, 1]], [[1, 1]], [[1, 1]], [[2, 2]], [[2, 2]], [[2, 2]], [[2, 2]], [[10, 10]]]}
introductory
https://www.codewars.com/kata/5a6d3bd238f80014a2000187
def owned_cat_and_dog(cat_years, dog_years):
3,554
Zonk is addictive dice game. In each round player rolls 6 dice. Then (s)he composes combinations from them. Each combination gives certain points. Then player can take one or more dice combinations to his hand and re-roll remaining dice or save his score. Dice in player's hand won't be taken into account in subsequen...
["def get_score(dice):\n if all(i in dice for i in range(1, 7)):\n return 1000\n if len(dice) == 6 and all(dice.count(d) == 2 for d in set(dice)):\n return 750\n score = 0\n score += sum((dice.count(d)==n) * d * (n-2) * (1000 if d==1 else 100) for d in set(dice) for n in range(3, 7))\n scor...
{"fn_name": "get_score", "inputs": [[[1]], [[5]], [[1, 1]], [[5, 5]], [[5, 1]], [[5, 6]], [[1, 1, 1]], [[2, 2, 2]], [[3, 3, 3]], [[4, 4, 4]], [[5, 5, 5]], [[6, 6, 6]], [[1, 2, 1]], [[1, 1, 5]], [[5, 5, 6]], [[1, 5, 5]], [[1, 1, 1, 1]], [[2, 2, 2, 2]], [[3, 3, 3, 3]], [[4, 4, 4, 4]], [[5, 5, 5, 5]], [[6, 6, 6, 6]], [[1,...
introductory
https://www.codewars.com/kata/53837b8c94c170e55f000811
def get_score(dice):
3,555
Given the number n, return a string which shows the minimum number of moves to complete the tower of Hanoi consisting of n layers. Tower of Hanoi : https://en.wikipedia.org/wiki/Tower_of_Hanoi Example - 2 layered Tower of Hanoi Input: n=2 Start [[2, 1], [], []] Goal [[], [], [2, 1]] Expected Output : '[[2, 1], []...
["def hanoiArray(n):\n A, B, C = list(range(n, 0, -1)), [], []\n res = [str([A, C, B])]\n def rec(n, X, Y, Z):\n if not n: return\n rec(n-1, X, Z, Y)\n Y.append(X.pop())\n res.append(str([A, C, B]))\n rec(n-1, Z, Y, X) \n rec(n, A, B, C)\n return '\\n'.join(res)"...
{"fn_name": "hanoiArray", "inputs": [[2], [3]], "outputs": [["[[2, 1], [], []]\n[[2], [1], []]\n[[], [1], [2]]\n[[], [], [2, 1]]"], ["[[3, 2, 1], [], []]\n[[3, 2], [], [1]]\n[[3], [2], [1]]\n[[3], [2, 1], []]\n[[], [2, 1], [3]]\n[[1], [2], [3]]\n[[1], [], [3, 2]]\n[[], [], [3, 2, 1]]"]]}
introductory
https://www.codewars.com/kata/5a02a758ffe75f8da5000030
def hanoiArray(n):
3,556
Base on the fairy tale [Diamonds and Toads](https://en.wikipedia.org/wiki/Diamonds_and_Toads) from Charles Perrault. In this kata you will have to complete a function that take 2 arguments: - A string, that correspond to what the daugther says. - A string, that tell you wich fairy the girl have met, this one can be `...
["from collections import Counter\n\ndef diamonds_and_toads(sentence, fairy):\n c = Counter(sentence)\n d = {'good':['ruby', 'crystal'], 'evil':['python', 'squirrel']}\n\n return {s:c[s[0]] + 2*c[s[0].upper()] for s in d[fairy]}", "def diamonds_and_toads(sentence,fairy):\n items = {\"ruby\":0, \"crystal\":0...
{"fn_name": "diamonds_and_toads", "inputs": [["Ruby and Crystal", "good"], ["This string contain some Ruby and some Crystal in it", "good"], ["Python and Squirrel", "evil"], ["This string contain some Python and some Squirrel in it", "evil"]], "outputs": [[{"ruby": 3, "crystal": 2}], [{"ruby": 4, "crystal": 3}], [{"pyt...
introductory
https://www.codewars.com/kata/57fa537f8b0760c7da000407
def diamonds_and_toads(sentence,fairy):
3,560
You are a skier (marked below by the `X`). You have made it to the Olympics! Well done. ``` \_\_\_X\_ \*\*\*\*\*\ \*\*\*\*\*\*\ \*\*\*\*\*\*\*\ \*\*\*\*\*\*\*\*\ \*\*\*\*\*\*\*\*\*\\.\_\_\_\_/ ``` Your job in this kata is to calculate the maximum speed you will achieve during your downhill run. The speed is dictated ...
["def ski_jump(mountain):\n height = len(mountain)\n speed = height * 1.5\n jump_length = height * speed * 9 / 10\n return (\n f\"{jump_length:.2f} metres: He's crap!\" if jump_length < 10 else\n f\"{jump_length:.2f} metres: He's ok!\" if jump_length < 25 else\n f\"{jump_length:.2f} me...
{"fn_name": "ski_jump", "inputs": [[["*"]], [["*", "**", "***"]], [["*", "**", "***", "****", "*****", "******"]], [["*", "**", "***", "****", "*****", "******", "*******", "********"]]], "outputs": [["1.35 metres: He's crap!"], ["12.15 metres: He's ok!"], ["48.60 metres: He's flying!"], ["86.40 metres: Gold!!"]]}
introductory
https://www.codewars.com/kata/57ed7214f670e99f7a000c73
def ski_jump(mountain):
3,562
In computer science and discrete mathematics, an [inversion](https://en.wikipedia.org/wiki/Inversion_%28discrete_mathematics%29) is a pair of places in a sequence where the elements in these places are out of their natural order. So, if we use ascending order for a group of numbers, then an inversion is when larger num...
["def count_inversion(nums):\n return sum(a > b for i, a in enumerate(nums) for b in nums[i + 1:])\n", "def count_inversion(s):\n return sum(s[i] > s[j]\n for i in range(len(s) - 1)\n for j in range(i + 1, len(s)))", "def count_inversion(sequence):\n def rec(arr):\n if len(ar...
{"fn_name": "count_inversion", "inputs": [[[1, 2, 3]], [[-3, -2, -1]], [[-20, 0, 20]], [[-13, 4, 8]], [[1, 3, 2]], [[-2, -3, -1]], [[-20, 20, 0]], [[-13, 9, 8]], [[3, 6, 2]], [[3, 6, 2, 7, 3]], [[26, 32, -21, 45, 21]], [[14, 12, 17, 124, 1, -12, 21, -24]], [[]], [[25, 12, 7, 4, 2, -7, -12, -22]], [[324, 123, 36, 4, -1,...
introductory
https://www.codewars.com/kata/5728a1bc0838ffea270018b2
def count_inversion(sequence):
3,563
Final kata of the series (highly recommended to compute [layers](https://www.codewars.com/kata/progressive-spiral-number-position/) and [branch](https://www.codewars.com/kata/progressive-spiral-number-branch/) first to get a good idea), this is a blatant ripoff of [the one offered on AoC](http://adventofcode.com/2017/d...
["def distance(n):\n if n == 1: return 0\n r = 0 - (1 - n ** .5) // 2\n d, m = divmod(n - (2*r - 1) ** 2 - 1, 2*r)\n z = (r * (1 + 1j) - m - 1) * 1j ** d\n return abs(z.real) + abs(z.imag)", "from itertools import count\n\ndef pos(n):\n for i in count(1, 2):\n if i*i >= n:\n break\n ...
{"fn_name": "distance", "inputs": [[1], [5], [25], [30], [96], [50], [66], [306], [307], [308]], "outputs": [[0], [2], [4], [5], [5], [7], [7], [17], [18], [17]]}
introductory
https://www.codewars.com/kata/5a27e3438882f334a10000e3
def distance(n):
3,565
In this Kata, you will be given a lower case string and your task will be to remove `k` characters from that string using the following rule: ```Python - first remove all letter 'a', followed by letter 'b', then 'c', etc... - remove the leftmost character first. ``` ```Python For example: solve('abracadabra', 1) = 'b...
["def solve(st,k): \n for l in sorted(st)[:k]:\n st=st.replace(l,'',1)\n return st", "solve = lambda s, k: ''.join(t[1] for t in sorted(sorted(enumerate(s), key=lambda x:x[1])[k:]))", "from collections import Counter\nfrom itertools import accumulate\nfrom operator import add\nfrom string import ascii_lowe...
{"fn_name": "solve", "inputs": [["abracadabra", 0], ["abracadabra", 1], ["abracadabra", 2], ["abracadabra", 6], ["abracadabra", 8], ["abracadabra", 50], ["hxehmvkybeklnj", 5], ["cccaabababaccbc", 3], ["cccaabababaccbc", 9], ["u", 1], ["back", 3]], "outputs": [["abracadabra"], ["bracadabra"], ["brcadabra"], ["rcdbr"], [...
introductory
https://www.codewars.com/kata/5b728f801db5cec7320000c7
def solve(st,k):
3,571
You're laying out a rad pixel art mural to paint on your living room wall in homage to [Paul Robertson](http://68.media.tumblr.com/0f55f7f3789a354cfcda7c2a64f501d1/tumblr_o7eq3biK9s1qhccbco1_500.png), your favorite pixel artist. You want your work to be perfect down to the millimeter. You haven't decided on the dimens...
["def is_divisible(wall_length, pixel_size):\n return wall_length % pixel_size == 0", "def is_divisible(wall_length, pixel_size):\n return not wall_length % pixel_size", "def is_divisible(a, b):\n return a % b == 0", "def is_divisible(wall_length, pixel_size):\n return divmod(wall_length,pixel_size)[1] == 0...
{"fn_name": "is_divisible", "inputs": [[4050, 27], [4066, 27], [10000, 20], [10005, 20]], "outputs": [[true], [false], [true], [false]]}
introductory
https://www.codewars.com/kata/58630e2ae88af44d2b0000ea
def is_divisible(wall_length, pixel_size):
3,579
You may be familiar with the concept of combinations: for example, if you take 5 cards from a 52 cards deck as you would playing poker, you can have a certain number (2,598,960, would you say?) of different combinations. In mathematics the number of *k* combinations you can have taking from a set of *n* elements is ca...
["from math import factorial\n\ndef choose(n, k):\n return factorial(n) / ( factorial(k) * factorial(n-k) ) if k <=n else 0", "import sys\nimport functools\nsys.setrecursionlimit(1_000_000)\n\n# lru_cache is a python shortcut for memoization\n# memoization is a technique to avoid repeatedly calculating\n# something ...
{"fn_name": "choose", "inputs": [[1, 1], [5, 4], [10, 5], [10, 20], [52, 5], [100, 10], [500, 4], [1000, 3], [200, 8], [300, 6]], "outputs": [[1], [5], [252], [0], [2598960], [17310309456440], [2573031125], [166167000], [55098996177225], [962822846700]]}
introductory
https://www.codewars.com/kata/55b22ef242ad87345c0000b2
def choose(n,k):
3,590
Given two arrays of strings, return the number of times each string of the second array appears in the first array. #### Example ```python array1 = ['abc', 'abc', 'xyz', 'cde', 'uvw'] array2 = ['abc', 'cde', 'uap'] ``` How many times do the elements in `array2` appear in `array1`? * `'abc'` appears twice in the fi...
["def solve(a,b):\n return [a.count(e) for e in b]", "from collections import Counter\n\ndef solve(a,b):\n c = Counter(a)\n return [c[s] for s in b]", "def solve(a,b):\n return [a.count(x) for x in b]", "def solve(a,b):\n return list(map(a.count, b))", "def solve(haystack, needles):\n return [haystack...
{"fn_name": "solve", "inputs": [[["abc", "abc", "xyz", "abcd", "cde"], ["abc", "cde", "uap"]], [["abc", "xyz", "abc", "xyz", "cde"], ["abc", "cde", "xyz"]], [["quick", "brown", "fox", "is", "quick"], ["quick", "abc", "fox"]]], "outputs": [[[2, 1, 0]], [[2, 1, 2]], [[2, 0, 1]]]}
introductory
https://www.codewars.com/kata/59ca8e8e1a68b7de740001f4
def solve(a,b):
3,591
In the morning all the doors in the school are closed. The school is quite big: there are **N** doors. Then pupils start coming. It might be hard to believe, but all of them want to study! Also, there are exactly **N** children studying in this school, and they come one by one. When these strange children pass by some...
["def doors(n):\n return int(n ** .5)", "def doors(n):\n doors = [False] * n\n for i in range(0, n):\n for j in range(i, n, i + 1):\n doors[j] = not doors[j]\n return doors.count(True)", "def doors(n):\n return int(n**0.5)", "def doors(n):\n from math import sqrt\n return int(sqrt...
{"fn_name": "doors", "inputs": [[5], [10], [100]], "outputs": [[2], [3], [10]]}
introductory
https://www.codewars.com/kata/57c15d314677bb2bd4000017
def doors(n):
3,592
Given an `x` and `y` find the smallest and greatest numbers **above** and **below** a given `n` that are divisible by both `x` and `y`. ### Examples ```python greatest(2, 3, 20) => 18 # 18 is the greatest number under 20 that is divisible by both 2 and 3 smallest(2, 3, 20) => 24 # 24 is the smallest number above 2...
["from math import gcd\n\n\ndef greatest(x, y, n):\n z = x * y // gcd(x, y)\n return (n - 1) // z * z\n \ndef smallest(x, y, n):\n z = x * y // gcd(x, y)\n return (n + z) // z * z\n", "from fractions import gcd\n\ndef near(x, y, n):\n lcm = x * y // gcd(x, y)\n return n // lcm * lcm, lcm\n\ndef gre...
{"fn_name": "greatest", "inputs": [[2, 3, 20], [13, 17, 100], [10, 100, 100], [1000000007, 1000000009, 10000000000000000000]], "outputs": [[18], [0], [0], [9000000144000000567]]}
introductory
https://www.codewars.com/kata/55f2a1c2cb3c95af75000045
def greatest(x, y, n):
3,593
Given a string and an array of integers representing indices, capitalize all letters at the given indices. For example: * `capitalize("abcdef",[1,2,5]) = "aBCdeF"` * `capitalize("abcdef",[1,2,5,100]) = "aBCdeF"`. There is no index 100. The input will be a lowercase string with no spaces and an array of digits. Goo...
["def capitalize(s,ind):\n ind = set(ind)\n return ''.join(c.upper() if i in ind else c for i,c in enumerate(s))", "def capitalize(s, ind):\n result = list(s)\n for index in ind:\n try:\n result[index] = result[index].upper()\n except IndexError:\n break # assumes the in...
{"fn_name": "capitalize", "inputs": [["abcdef", [1, 2, 5]], ["abcdef", [1, 2, 5, 100]], ["codewars", [1, 3, 5, 50]], ["abracadabra", [2, 6, 9, 10]], ["codewarriors", [5]], ["indexinglessons", [0]]], "outputs": [["aBCdeF"], ["aBCdeF"], ["cOdEwArs"], ["abRacaDabRA"], ["codewArriors"], ["Indexinglessons"]]}
introductory
https://www.codewars.com/kata/59cfc09a86a6fdf6df0000f1
def capitalize(s,ind):
3,594
**An [isogram](https://en.wikipedia.org/wiki/Isogram)** (also known as a "nonpattern word") is a logological term for a word or phrase without a repeating letter. It is also used by some to mean a word or phrase in which each letter appears the same number of times, not necessarily just once. You task is to write a me...
["from collections import Counter\nimport re\n\ndef is_isogram(word):\n if type(word) is not str or not word: return False\n return len(set( Counter(re.sub(r'[^a-z]', \"\", word.lower())).values() )) == 1", "from collections import Counter\n\ndef is_isogram(word):\n try:\n return len(set(Counter(filter(...
{"fn_name": "is_isogram", "inputs": [[null], [3], ["Dermatoglyphics"], ["isogram"], ["eleven"], ["moOse"], ["isIsogram"], [""], ["-.-"], ["subdermatoglyphic"], ["Alphabet"], ["thumbscrew-japingly"], ["Hjelmqvist-Gryb-Zock-Pfund-Wax"], ["Emily Jung Schwartzkopf"], ["aabbccddeeffgg"]], "outputs": [[false], [false], [true...
introductory
https://www.codewars.com/kata/586d79182e8d9cfaba0000f1
def is_isogram(word):
3,602
> [Run-length encoding](https://en.wikipedia.org/w/index.php?title=Run-length_encoding) (RLE) is a very simple form of data compression in which runs of data (that is, sequences in which the same data value occurs in many consecutive data elements) are stored as a single data value and count, rather than as the origina...
["from itertools import groupby\n\ndef run_length_encoding(s):\n return [[sum(1 for _ in g), c] for c, g in groupby(s)]", "from itertools import groupby\ndef run_length_encoding(s):\n return [[len(list(b)), a] for a,b in groupby(s)]", "def run_length_encoding(s):\n count, prev, lst = 1, '', []\n for c in s:\n ...
{"fn_name": "run_length_encoding", "inputs": [[""], ["abc"], ["aab"], ["hello world!"], ["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbb"]], "outputs": [[[]], [[[1, "a"], [1, "b"], [1, "c"]]], [[[2, "a"], [1, "b"]]], [[[1, "h"], [1, "e"], [2, "l"], [1, "o"], [1, " "], [1, "w"], [1, "o"], [1, "r"], [1, "l"], [1, "d"], [1, "!"]]]...
introductory
https://www.codewars.com/kata/546dba39fa8da224e8000467
def run_length_encoding(s):
3,604
This kata is based on a [variation](https://www.codewars.com/kata/happy-numbers-5) of *Happy Numbers* by TySlothrop. It is advisable to complete it first to grasp the idea and then move on to this one. ___ Hello, my dear friend, and welcome to another *Happy Numbers* kata! What? You're not interested in them anymore?...
["sum_dig = lambda n, D={str(d): d*d for d in range(10)}: sum(map(D.get, str(n)))\nis_happy = lambda n: n > 4 and is_happy(sum_dig(n)) or n == 1\n\nhappy_set = set(filter(is_happy, range(100)))\nfor n in range(100, 3 * 10 ** 5):\n if sum_dig(n) in happy_set: happy_set.add(n)\n\nfrom bisect import bisect\ndef perform...
{"fn_name": "performant_numbers", "inputs": [[10], [50], [100]], "outputs": [[[1, 7, 10]], [[1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49]], [[1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100]]]}
introductory
https://www.codewars.com/kata/5adf5b6a2f10c6c4bc000200
def performant_numbers(n, happy_list=sorted(happy_set)):
3,605
In the drawing below we have a part of the Pascal's triangle, lines are numbered from **zero** (top). The left diagonal in pale blue with only numbers equal to 1 is diagonal **zero**, then in dark green (1, 2, 3, 4, 5, 6, 7) is diagonal 1, then in pale green (1, 3, 6, 10, 15, 21) is diagonal 2 and so on. We want to c...
["def diagonal(n, p):\n # your code\n res = 0\n for base in range(p, max(n,p) + 1):\n value = 1\n for i in range(base-p+1,base+1):\n value *= i\n for i in range(1,p+1):\n value //= i\n res += int(value)\n return res\n", "import math\n\ndef diagonal(n, p):\n ...
{"fn_name": "diagonal", "inputs": [[20, 3], [20, 4], [20, 5], [20, 15], [100, 0], [1291, 5], [1291, 56], [1291, 1234], [12910, 15], [129100, 5]], "outputs": [[5985], [20349], [54264], [20349], [101], [6385476296235036], [154789835867995789816056814507354264440830262370837552235265352527754232996260833330144856388410192...
introductory
https://www.codewars.com/kata/559b8e46fa060b2c6a0000bf
def diagonal(n, p):
3,610
## Fixed xor Write a function that takes two hex strings as input and XORs them against each other. If the strings are different lengths the output should be the length of the shortest string. Hint: The strings would first need to be converted to binary to be XOR'd. ## Note: If the two strings are of different leng...
["def fixed_xor(a, b):\n return \"\".join(f\"{int(x, 16)^int(y, 16):x}\" for x, y in zip(a, b))", "def fixed_xor(a, b):\n\n m = min(len(a), len(b)) \n \n return f\"{int(a[:m], 16) ^ int(b[:m], 16):0{m}x}\" if m else \"\"\n", "def fixed_xor(a, b):\n return \"\".join(format(int(x, 16) ^ int(y, 16), \"x...
{"fn_name": "fixed_xor", "inputs": [["1c0111001f010100061a024b53535009181c", "686974207468652062756c6c277320657965"], ["aadf", "bce2"], ["ab3f", "ac"], ["", ""], ["c611d9bdd9de38b9eb", "23a0745505d4d25494"], ["7d1e875da9d5e89b54c7eaf", "3541599be591709795cebd5"], ["785a6677b3e52f0e7", "a8d97da7441"], ["6cbd75511e7f750c...
introductory
https://www.codewars.com/kata/580f1220df91273ee90001e7
def fixed_xor(a, b):
3,614
NOTE: It is recommended you complete [Introduction to Esolangs](https://www.codewars.com/kata/esolang-interpreters-number-1-introduction-to-esolangs-and-my-first-interpreter-ministringfuck/) or [MiniBitFlip](https://www.codewars.com/kata/esolang-minibitflip/) before solving this one. Task: Make an interpreter for an es...
["def interpreter(tape):\n memory, ptr, output = {0: 0}, 0, \"\"\n \n for command in tape:\n if command == \">\": ptr += 1\n elif command == \"<\": ptr -= 1\n elif command == \"!\": memory[len(memory)] = 0\n elif command == \"*\": output += chr(memory.get(ptr, 0) % 256) \n ...
{"fn_name": "interpreter", "inputs": [["++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++...
introductory
https://www.codewars.com/kata/5876e24130b45aaa0c00001d
def interpreter(tape):
3,628
> **Note**: This kata is a translation of this (Java) one: http://www.codewars.com/kata/rotate-array. I have not translated this first one as usual because I did not solved it, and I fear not being able to solve it (Java is **not** my cup of... tea). @cjmcgraw, if you want to use my translation on your kata feel free ...
["def rotate(arr, n):\n # ...\n n = n % len(arr)\n return arr[-n:] + arr[:-n]", "from collections import deque\n\n\ndef rotate(arr, n):\n \"\"\"Return a given array, rotated by n spaces.\"\"\"\n rotator = deque(arr)\n rotator.rotate(n)\n return list(rotator)\n", "def rotate(arr, n):\n dex = -(n ...
{"fn_name": "rotate", "inputs": [[["a", "b", "c"], 1], [[1.0, 2.0, 3.0], 1], [[true, true, false], 1]], "outputs": [[["c", "a", "b"]], [[3.0, 1.0, 2.0]], [[false, true, true]]]}
introductory
https://www.codewars.com/kata/54f8b0c7a58bce9db6000dc4
def rotate(arr, n):