description stringlengths 38 154k | category stringclasses 5
values | solutions stringlengths 13 289k | name stringlengths 3 179 | id stringlengths 24 24 | tags listlengths 0 13 | url stringlengths 54 54 | rank_name stringclasses 8
values |
|---|---|---|---|---|---|---|---|
### Description
Let's play the game "Whac-A-Mole". Give you an 2D array:
```
[
[1,1,2,2],
[3,3,4,4],
[4,8,8,8]
]
```
The meaning of numbers in the array is that the mole will disappear after n seconds(0 means no mole). You are holding a big hammer and every second can hit two moles. Please calculate the maximum numbe... | reference | def whac_a_mole(a):
b = []
for x in a:
b . extend(x)
b . sort()
n = r = h = 0
for x in b:
if x - n > 0:
r += 1
h ^= 1
n += not h
return r
| I guess this is a 6kyu kata #5: Whac-A-Mole | 57d250e55dc38e288c000081 | [
"Puzzles",
"Fundamentals"
] | https://www.codewars.com/kata/57d250e55dc38e288c000081 | 6 kyu |
Jon and Joe have received equal marks in the school examination. But, they won't reconcile in peace when equated with each other. To prove his might, Jon challenges Joe to write a program to find all possible number combos that sum to a given number. While unsure whether he would be able to accomplish this feat or not,... | algorithms | def combos(n):
if n == 1:
return [[1]]
if n == 2:
return [[1, 1], [2]]
if n == 3:
return [[1, 1, 1], [1, 2], [3]]
if n == 4:
return [[1, 1, 1, 1], [1, 1, 2], [1, 3], [2, 2], [4]]
if n == 5:
return [[1, 1, 1, 1, 1], [1, 1, 1, 2], [1, 1, 3], [1, 2, 2],... | Find all possible number combos that sum to a number | 555b1890a75b930e63000023 | [
"Fundamentals",
"Mathematics",
"Recursion",
"Algorithms"
] | https://www.codewars.com/kata/555b1890a75b930e63000023 | 4 kyu |
Remember the game 2048? http://gabrielecirulli.github.io/2048/
The main part of this game is merging identical tiles in a row.
* Implement a function that models the process of merging all of the tile values in a single row.
* This function takes the array line as a parameter and returns a new array with the tile ... | algorithms | from itertools import groupby
def merge(line):
merged = []
for k, g in groupby(v for v in line if v):
g = list(g)
n, r = divmod(len(g), 2)
if n:
merged . extend([k * 2] * n)
if r:
merged . append(k)
return merged + [0] * (len(line) - len(merged))
| Merge in 2048 | 55e1990978c60e5052000011 | [
"Games",
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/55e1990978c60e5052000011 | 6 kyu |
Create a function `isAlt()` that accepts a string as an argument and validates whether the vowels (a, e, i, o, u) and consonants are in alternate order.
```javascript
isAlt("amazon")
// true
isAlt("apple")
// false
isAlt("banana")
// true
```
```haskell
isAlt "amazon" -> True
isAlt "apple" -> False
isAlt "banana" -> ... | algorithms | import re
def is_alt(s):
return not re . search('[aeiou]{2}|[^aeiou]{2}', s)
| Are we alternate? | 59325dc15dbb44b2440000af | [
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/59325dc15dbb44b2440000af | 6 kyu |
In mathematics, an n<sup>th</sup> root of a number `x`, where `n` is usually assumed to be a positive integer, is a number `r` which, when raised to the power `n`, yields `x`:
```
r^n=x,
```
Given number `n`, such that `n > 1`, find if its 2<sup>nd</sup> root, 4<sup>th</sup> root and 8<sup>th</sup> root are all integer... | algorithms | def perfect_roots(n):
return (n * * 0.125) % 1 == 0
| number with 3 roots. | 5932c94f6aa4d1d786000028 | [
"Algorithms"
] | https://www.codewars.com/kata/5932c94f6aa4d1d786000028 | 7 kyu |
A core idea of several left-wing ideologies is that the wealthiest should *support* the poorest, no matter what and that is exactly what you are called to do using this kata (which, on a side note, was born out of the necessity to redistribute the width of `div`s into a given container).
You will be given two paramete... | algorithms | def socialist_distribution(population, minimum):
if minimum > sum(population) / / len(population):
return []
while min(population) < minimum:
population[population . index(min(population))] += 1
population[population . index(max(population))] -= 1
return population
| Socialist distribution | 58cfa5bd1c694fe474000146 | [
"Arrays",
"Lists",
"Statistics",
"Algorithms"
] | https://www.codewars.com/kata/58cfa5bd1c694fe474000146 | 6 kyu |
# Task
The number is considered to be `unlucky` if it does not have digits `4` and `7` and is divisible by `13`. Please count all unlucky numbers not greater than `n`.
# Example
For `n = 20`, the result should be `2` (numbers `0 and 13`).
For `n = 100`, the result should be `7` (numbers `0, 13, 26, 39, 52, 65, a... | games | def unlucky_number(n):
return sum(not ('4' in s or '7' in s) for s in map(str, range(0, n + 1, 13)))
| Simple Fun #174: Unlucky Number | 58b65c5e8b98b2e4fa000034 | [
"Puzzles"
] | https://www.codewars.com/kata/58b65c5e8b98b2e4fa000034 | 6 kyu |
Your task is to write a function which cuts cancer cells from the body.
### Cancer cells are divided into two types:
* <span style="color:red">Advance</span> stage,described as letter <span style="color:red">C</span>
* <span style="color:Tomato">Initial</span> stage,described as letter <span style="color:Tomato">c... | reference | import re
reg = re . compile(r"c|[a-z]?C[a-z]?")
def cut_cancer_cells(s):
return reg . sub("", s)
| Cancer cells | 5931614bb2f657c18c0001c3 | [
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/5931614bb2f657c18c0001c3 | 6 kyu |
*** No Loops Allowed ***
You will be given an array `a` and a value `x`. All you need to do is check whether the provided array contains the value, without using a loop.
Array can contain numbers or strings. `x` can be either. Return `true` if the array contains the value, `false` if not. With strings you will need t... | reference | def check(a, x):
return x in a
| No Loops 2 - You only need one | 57cc40b2f8392dbf2a0003ce | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/57cc40b2f8392dbf2a0003ce | 8 kyu |
# Introduction
Digital Cypher assigns a unique number to each letter of the alphabet:
```
a b c d e f g h i j k l m n o p q r s t u v w x y z
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
```
In the encrypted word we write the corresponding numbers instead o... | reference | def find_the_key(message, code):
diffs = "" . join(str(c - ord(m) + 96) for c, m in zip(code, message))
for size in range(1, len(code) + 1):
key = diffs[: size]
if (key * len(code))[: len(code)] == diffs:
return int(key)
| Digital cypher vol 3 - missing key | 5930d8a4b8c2d9e11500002a | [
"Fundamentals",
"Ciphers",
"Cryptography"
] | https://www.codewars.com/kata/5930d8a4b8c2d9e11500002a | 6 kyu |
```if:java
___Note for Java users:___ Due to type checking in Java, inputs and outputs are formated quite differently in this language. See the footnotes of the description.
<hr>
```
You have the following lattice points with their corresponding coordinates and each one with an specific colour.
```
Point [x , y]... | reference | from itertools import combinations
def count_col_triang(a):
p, r = {}, {}
for xy, col in a:
p[col] = p . get(col, []) + [xy]
for k in p:
r[k] = sum(1 for c in combinations(p[k], 3) if triangle(* c))
mx = max(r . values())
return [len(a), len(p), sum(r . values()), sorted(k for k ... | Coloured Lattice Points Forming Coloured Triangles | 57cebf1472f98327760003cd | [
"Fundamentals",
"Data Structures",
"Algorithms",
"Geometry",
"Mathematics",
"Logic",
"Strings"
] | https://www.codewars.com/kata/57cebf1472f98327760003cd | 4 kyu |
# Covfefe
Your are given a string. You must replace any occurence of the sequence `coverage` by `covfefe`, however, if you don't find the word `coverage` in the string, you must add `covfefe` at the end of the string with a leading space.
For the languages where the string is mutable (such as ruby), don't modify the... | games | def covfefe(s):
return s . replace("coverage", "covfefe") if "coverage" in s else s + " covfefe"
| Covfefe | 592fd8f752ee71ac7e00008a | [
"Strings"
] | https://www.codewars.com/kata/592fd8f752ee71ac7e00008a | 7 kyu |
# Introduction
<pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">
Dots and Boxes is a pencil-and-paper game for two players (sometimes more). It was first published in the 19th century by Édouard Lucas, who called it la pipopipette. It ... | reference | class Game ():
def __init__(self, n):
k = 2 * n + 1
self . board = {frozenset(k * r + 1 + c + d for d in (0, n, n + 1, k))
for r in range(n) for c in range(n)}
def play(self, lines):
lines = set(lines)
while 1:
for cell in self . board:
stick = cell - lin... | Pigs in a Pen | 58fdcc51b4f81a0b1e00003e | [
"Puzzles",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/58fdcc51b4f81a0b1e00003e | 5 kyu |
You will receive an uncertain amount of integers in a certain order ```k1, k2, ..., kn```.
You form a new number of n digits in the following way:
you take one of the possible digits of the first given number, ```k1```, then the same with the given number ```k2```, repeating the same process up to ```kn``` and you con... | reference | from itertools import product
def proc_seq(* args):
nums = set(int('' . join(l))
for l in product(* (str(a) for a in args)) if l[0] != '0')
if len(nums) == 1:
return [1, nums . pop()]
return [len(nums), min(nums), max(nums), sum(nums)]
| Building a Sequence Cocatenating Digits with a Given Order. | 5717924a1c2734e78f000430 | [
"Fundamentals",
"Data Structures",
"Algorithms",
"Mathematics",
"Logic",
"Strings"
] | https://www.codewars.com/kata/5717924a1c2734e78f000430 | 5 kyu |
<p>This is the second part of this kata series. First part is <a href="https://www.codewars.com/kata/adding-words-part-i/">here</a> and the third is <a href="https://www.codewars.com/kata/adding-words-part-iii/">here</a></p>
<p>Add two English words together!</p>
<p>Implement a class <code>Arith</code> such that</p>
`... | reference | class Arith (object):
# Constant names and associated ranges for natural numbers
zero_nine = ("zero,one,two,three,four,five,six,seven,eight,nine", 0, 10, 1)
ten_nineteen = (
"ten,eleven,twelve,thirteen,fourteen,fifteen,sixteen,seventeen,eighteen,nineteen", 10, 20, 1)
tens = ("twenty,thirty,... | Adding words - Part II | 592eccf7d6a5403edf000aa1 | [
"Mathematics"
] | https://www.codewars.com/kata/592eccf7d6a5403edf000aa1 | 5 kyu |
From wikipedia <https://en.wikipedia.org/wiki/Partition_(number_theory)>
In number theory and combinatorics, a partition of a positive integer n, also called an integer partition,
is a way of writing n as a sum of positive integers.
Two sums that differ only in the order of their summands are considered the **same*... | reference | def prod(n):
ret = [{1.}]
for i in range(1, n + 1):
ret . append({(i - x) * j for x, s in enumerate(ret) for j in s})
return ret[- 1]
def part(n):
p = sorted(prod(n))
return "Range: %d Average: %.2f Median: %.2f" % \
(p[- 1] - p[0], sum(p) / len(p), (p[len(p) / / 2] + p[~ l... | Getting along with Integer Partitions | 55cf3b567fc0e02b0b00000b | [
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/55cf3b567fc0e02b0b00000b | 4 kyu |
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/1c/Sydney_-_Newcastle_freeway_north_bound_at_Berowra.jpg/500px-Sydney_-_Newcastle_freeway_north_bound_at_Berowra.jpg">
# Back-Story
Every day I travel on the freeway.
When I am more bored than usual I sometimes like to play the following counting game... | algorithms | def freeway_game(km, kph, cars):
t = km / kph
c = 0
for dt, speed in cars:
d = km - (t - dt / 60) * speed
if dt <= 0:
c += d > 0
else:
c -= d < 0
return c
| The Freeway Game | 59279aea8270cc30080000df | [
"Algorithms"
] | https://www.codewars.com/kata/59279aea8270cc30080000df | 6 kyu |
In this Kata, we use the Euler method for integrating a function (see [wiki](https://en.wikipedia.org/wiki/Euler_method)).
Remember that integrating a function basically means 'calculating the area under a curve'. One way to approximate the area is to chop it up into rectangles (whose area is just height * width) and ... | algorithms | def euler(stop, step_size):
def f(x): return 5 + 2 * x + 3 * x * * 2
n = int(stop / / step_size)
prev = 0
for i in range(n + 1):
prev += step_size * f(step_size * i)
return prev
| Euler method for numerical integration | 587c0d396d360f3cc600003f | [
"Algorithms"
] | https://www.codewars.com/kata/587c0d396d360f3cc600003f | 6 kyu |
<a href="http://imgur.com/RTBtOMl"><img src="http://i.imgur.com/RTBtOMl.jpg" title="source: imgur.com" /></a>
In this kata we will see a method, not so accurate but a different one to estimate number Pi. You will be given a list of random points contained in a cube of side of length 2l. The center of the cube coincide... | reference | import math
def mCarlo3D_pi(lst):
R = max(abs(r) for pt in lst for r in pt)
inPts = sum(sum(r * * 2 for r in pt) <= R * * 2 for pt in lst)
approxPi = 6.0 * inPts / len(lst)
relError = abs(approxPi - math . pi) / math . pi * 100
return [len(lst), R, inPts, round(approxPi, 4), "{}%" . format... | MONTE CARLO 3D | 55f9ee4d8f3bbabf2200000c | [
"Fundamentals",
"Mathematics",
"Data Structures"
] | https://www.codewars.com/kata/55f9ee4d8f3bbabf2200000c | 5 kyu |
# Introduction
Digital Cypher assigns to each letter of the alphabet unique number. For example:
```
a b c d e f g h i j k l m
1 2 3 4 5 6 7 8 9 10 11 12 13
n o p q r s t u v w x y z
14 15 16 17 18 19 20 21 22 23 24 25 26
```
Instead of letters in encrypted word we write the corre... | reference | from itertools import cycle
from string import ascii_lowercase
def decode(code, key):
keys = cycle(map(int, str(key)))
return '' . join(ascii_lowercase[n - next(keys) - 1] for n in code)
| Digital cypher vol 2 | 592edfda5be407b9640000b2 | [
"Fundamentals",
"Ciphers",
"Cryptography"
] | https://www.codewars.com/kata/592edfda5be407b9640000b2 | 7 kyu |
Learning to code around your full time job is taking over your life. You realise that in order to make significant steps quickly, it would help to go to a coding bootcamp in London.
Problem is, many of them cost a fortune, and those that don't still involve a significant amount of time off work - who will pay your mor... | reference | def sabb(stg, value, happiness):
sabbatical = (value + happiness +
sum(1 for c in stg if c in "sabbatical")) > 22
return "Sabbatical! Boom!" if sabbatical else "Back to your desk, boy."
| The Office VI - Sabbatical | 57fe50d000d05166720000b1 | [
"Fundamentals",
"Strings",
"Arrays",
"Mathematics"
] | https://www.codewars.com/kata/57fe50d000d05166720000b1 | 7 kyu |
<p>This is the first part of this kata series. Second part is <a href="https://www.codewars.com/kata/adding-words-part-ii/">here</a> and third part is <a href="https://www.codewars.com/kata/adding-words-part-iii/">here</a></p>
<p>Add two English words together!</p>
<p>Implement a class <code>Arith</code> (struct <code>... | reference | class Arith ():
def __init__(self, first):
self . NUMS = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven",
"twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty"]
self . first = first
d... | Adding words - Part I | 592eaf848c91f248ca000012 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/592eaf848c91f248ca000012 | 7 kyu |
# Introduction
Digital Cypher assigns to each letter of the alphabet unique number. For example:
```
a b c d e f g h i j k l m
1 2 3 4 5 6 7 8 9 10 11 12 13
n o p q r s t u v w x y z
14 15 16 17 18 19 20 21 22 23 24 25 26
```
Instead of letters in encrypted word we write the corre... | reference | from itertools import cycle
def encode(message, key):
return [ord(a) - 96 + int(b) for a, b in zip(message, cycle(str(key)))]
| Digital cypher | 592e830e043b99888600002d | [
"Fundamentals",
"Ciphers",
"Cryptography"
] | https://www.codewars.com/kata/592e830e043b99888600002d | 7 kyu |
[comment]: # (Hello Contributors, the following guidelines in order of importance should help you write new translations and squash any pesky unintended bugs.)
[//]: # (The epsilon of all floating point test case comparisons is 0.01.)
[//]: # (Each test case shall pass if the statement "a^2 + b^2 = c^2" is true of the ... | reference | def how_to_find_them(rt):
return {d: rt[d] if d in rt
else (rt["a"] * * 2 + rt["b"] * * 2) * * .5 if d == "c"
else (rt["c"] * * 2 - rt[(set("ab") - {d}). pop()] * * 2) * * .5 for d in "abc"}
| Markings to White Triangles and How to Find Them | 592dcbfedc403be22f00018f | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/592dcbfedc403be22f00018f | 6 kyu |
# Task
Given an integer array `arr`. Your task is to remove one element, maximize the product of elements.
The result is the element which should be removed. If more than one valid results exist, return the smallest one.
# Input/Output
`[input]` integer array `arr`
non-empty unsorted integer array. It contains p... | reference | from operator import mul
from functools import reduce
def maximum_product(arr):
prod_dct = {x: reduce(mul, arr[: i] + arr[i + 1:], 1)
for i, x in enumerate(arr)}
return max(arr, key=lambda x: (prod_dct[x], - x))
| Simple Fun #312: Maximum Product | 592e2446dc403b132d0000be | [
"Fundamentals"
] | https://www.codewars.com/kata/592e2446dc403b132d0000be | 7 kyu |
The special score(ssc) of an array of integers will be the sum of each integer multiplied by its corresponding index plus one in the array.
E.g.: with the array ```[6, 12, -1]```
```
arr = [6, 12, -1 ]
ssc = 1*6 + 2*12 + 3*(-1) = 6 + 24 - 3 = 27
```
The array given in the example has six(6) permuta... | reference | from itertools import permutations
def ssc_forperm(arr):
perms = set(p for p in permutations(arr))
values = [sum((x + 1) * y for x, y in enumerate(i)) for i in perms]
return [{"total perm": len(perms)}, {"total ssc": sum(values)}, {"max ssc": max(values)}, {"min ssc": min(values)}]
| Permutations Of An Array And Associated Values | 562c5ea7b5fe27d303000054 | [
"Fundamentals",
"Mathematics",
"Data Structures",
"Permutations",
"Algorithms"
] | https://www.codewars.com/kata/562c5ea7b5fe27d303000054 | 6 kyu |
If we have an integer of n digits, ```d1d2d3d4d5....dn```, we define the following scores:
score_prod = 1d<sub>1</sub> + 2d<sub>2</sub> + 3d<sub>3</sub> + 4d<sub>4</sub> + 5d<sub>5</sub> + .... + nd<sub>n</sub>
score_pow = 1<sup>d1</sup> + 2<sup>d2</sup> + 3<sup>d3</sup> + 4<sup>d4</sup> + 5<sup>d5</sup> + .... + n<s... | reference | from functools import lru_cache
def score_pow(n):
return sum(i * * int(d) for i, d in enumerate(str(n), 1))
def score_prod(n):
return sum(i * int(d) for i, d in enumerate(str(n), 1))
@ lru_cache(None)
def div_sum(n):
total = 0
for div in range(1, n / / 2 + 1):
if n % div... | Check a Curious Divisibility. (Brute force version) | 5681e4ff81ba1b0cdb000031 | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/5681e4ff81ba1b0cdb000031 | 6 kyu |
<p>Bleatrix Trotter the sheep has devised a strategy that helps her fall asleep faster. First, she picks a number <code>N</code>. Then she starts naming <code>N</code>, <code>2 × N</code>, <code>3 × N</code>, and so on.</p>
<p>Whenever she names a number, she thinks about all of the digits in that number. She keeps tra... | reference | def trotter(n):
i, numStr, numList = 0, '', [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
if n == 0:
return ('INSOMNIA')
while all([i in numStr for i in numList]) != True:
i += 1
numStr = numStr + str(n * i)
return (i * n)
| Bleatrix Trotter (The Counting Sheep) | 59245b3c794d54b06600002a | [
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/59245b3c794d54b06600002a | 6 kyu |
A carpet shop sells carpets in different varieties. Each carpet can come in a different roll width and can have a different price per square meter.
Write a function `cost_of_carpet` which calculates the cost (rounded to 2 decimal places) of carpeting a room, following these constraints:
* The carpeting has to be don... | algorithms | def cost_of_carpet(l, w, r, c):
w, l = sorted((w, l))
return "error" if r < w or w == 0 else round((l if r < l else w) * r * c, 2)
| Carpet shop | 592c6d71d2c6d91643000009 | [
"Algorithms"
] | https://www.codewars.com/kata/592c6d71d2c6d91643000009 | 6 kyu |
<p>We have 3 equations with 3 unknowns <code>x, y, and z</code> and we are to solve for these unknowns.</p>
<p>Equations <code>4x -3y +z = -10</code>, <code>2x +y +3z = 0</code>, and <code>-x +2y -5z = 17</code> will be passed in as an array of <code>[[4, -3, 1, -10], [2, 1, 3, 0], [-1, 2, -5, 17]]</code> and the resul... | reference | import numpy as np
def solve_eq(eq):
a = np . array([arr[: 3] for arr in eq])
b = np . array([arr[- 1] for arr in eq])
return [round(x) for x in np . linalg . solve(a, b)]
| Simultaneous Equations - Three Variables | 59280c056d6c5a74ca000149 | [
"Mathematics"
] | https://www.codewars.com/kata/59280c056d6c5a74ca000149 | 5 kyu |
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... | games | def to_twos_complement(binary, bits):
return int(binary . replace(' ', ''), 2) - 2 * * bits * int(binary[0])
def from_twos_complement(n, bits):
return '{:0{}b}' . format(n & 2 * * bits - 1, bits)
| Two's Complement | 58d4785a2285e7795c00013b | [
"Binary",
"Puzzles"
] | https://www.codewars.com/kata/58d4785a2285e7795c00013b | 6 kyu |
Here's another staple for the functional programmer. You have a sequence of values and some predicate for those values. You want to get the longest prefix of elements such that the predicate is true for each element. We'll call this the `takeWhile` function. It accepts two arguments. The first is the sequence of values... | algorithms | from itertools import takewhile
def take_while(arr, pred_fun):
return list(takewhile(pred_fun, arr))
| The takeWhile Function | 54f9173aa58bce9031001548 | [
"Functional Programming",
"Arrays",
"Algorithms",
"Lists",
"Data Structures"
] | https://www.codewars.com/kata/54f9173aa58bce9031001548 | 6 kyu |
The integer `64` is the first integer that has all of its digits even and furthermore, is a perfect square.
The second one is `400` and the third one `484`.
Give the numbers of this sequence that are in the range `[a,b]` (both values inclusive)
Examples:
```
Even digit squares between 100 to 1000: [400, 484] (the... | reference | def is_even(x):
return all(int(i) % 2 == 0 for i in str(x))
def even_digit_squares(a, b):
first = int(a * * (1 / 2)) + 1
last = int(b * * (1 / 2)) + 1
return sorted([x * x for x in range(first, last) if is_even(x * x)])
| #1 Sequences: Pure Even Digit Perfect Squares (P.E.D.P.S) | 59290e641a640c53d000002c | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/59290e641a640c53d000002c | 6 kyu |
You will be given an array of positive integers. The array should be sorted by the amount of distinct perfect squares and reversed, that can be generated from each number permuting its digits.
E.g.: ```arr = [715, 112, 136, 169, 144]```
```
Number Perfect Squares w/ its Digits Amount
715 - ... | reference | from collections import defaultdict
SQUARES = [x * * 2 for x in range(1, 3163)]
DIGITS = defaultdict(int)
for sqr in SQUARES:
DIGITS['' . join(sorted(str(sqr)))] += 1
def sort_by_perfsq(arr):
return sorted(arr, key=lambda n: (- DIGITS['' . join(sorted(str(n)))], n))
| Sorting Arrays by the Amount of Perfect Squares that Each Element May Generate | 582fdcc039f654905400001e | [
"Algorithms",
"Mathematics",
"Number Theory",
"Permutations"
] | https://www.codewars.com/kata/582fdcc039f654905400001e | 5 kyu |
<h2>Christmas Present Calculator</h2>
After we find out if <a href="https://www.codewars.com/kata/5857e8bb9948644aa1000246">Santa can save Christmas</a> there is another task to face.
<br>
<br>
Santa's little helper aren't sick anymore. They are ready to give away presents again. But some of them are still weak.
<br>... | reference | def count_presents(prod, presents):
time = sum(prod . values()) * 24
pres_count = 0
for i in sorted(presents):
t = int(i[: 2]) + (int(i[3: 5]) / 60) + (int(i[6:]) / 3600)
if t <= time:
pres_count += 1
time -= t
return pres_count
| Christmas Present Calculator | 585b989c45376c73e30000d1 | [
"Date Time",
"Fundamentals"
] | https://www.codewars.com/kata/585b989c45376c73e30000d1 | 6 kyu |
<h2> Introduction </h2>
The GADERYPOLUKI is a simple substitution cypher used in scouting to encrypt messages. The encryption is based on short, easy to remember key. The key is written as paired letters, which are in the cipher simple replacement.
The most frequently used key is "GA-DE-RY-PO-LU-KI".
```
g => a
a ... | reference | def find_the_key(messages, secrets):
return '' . join(sorted({a + b for a, b in map(sorted, zip('' . join(messages), '' . join(secrets))) if a != b}))
| GA-DE-RY-PO-LU-KI cypher vol 3 - Missing key | 592bdf59912f2209710000e9 | [
"Fundamentals",
"Ciphers",
"Cryptography"
] | https://www.codewars.com/kata/592bdf59912f2209710000e9 | 6 kyu |
## Funny Dots
You will get two integers `n` (width) and `m` (height) and your task is to draw the following pattern. Each line is seperated with a newline (`\n`)
Both integers are equal or greater than 1; no need to check for invalid parameters.
## Examples
<pre>
<code>
... | algorithms | def dot(n, m):
sep = '+---' * n + '+'
dot = '| o ' * n + '|'
return '\n' . join([sep, dot] * m + [sep])
| ASCII Fun #2: Funny Dots | 59098c39d8d24d12b6000020 | [
"ASCII Art"
] | https://www.codewars.com/kata/59098c39d8d24d12b6000020 | 6 kyu |
<h2> Introduction </h2>
Mr. Safety loves numeric locks and his Nokia 3310. He locked almost everything in his house. He is so smart and he doesn't need to remember the combinations. He has an algorithm to generate new passcodes on his Nokia cell phone.
<br/>
<img src='https://i.postimg.cc/2yCH2WhV/Nokia-3310.jpg' bor... | games | def unlock(message): return message . lower(). translate(
message . maketrans("abcdefghijklmnopqrstuvwxyz", "22233344455566677778889999"))
| Mr. Safety's treasures | 592c1dfb912f22055b000099 | [
"Puzzles"
] | https://www.codewars.com/kata/592c1dfb912f22055b000099 | 6 kyu |
I want to honor the movie "X plus Y" reproducing here one of his mathematical problems. Although I can not pose the problem with the fidelity it deserves I have implemented it so that it can be properly tested.
#### Original problem
##### There are N cards in a row and they can be face up or face down. A turn consist... | reference | from itertools import accumulate
from operator import xor
def x_plus_y(s):
return sum(accumulate(map(int, s), xor))
| X plus Y Card problem | 59269e371a640c0e98000085 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/59269e371a640c0e98000085 | 6 kyu |
Consider the following class:
```csharp
public class Animal
{
public string Name { get; set; }
public int NumberOfLegs { get; set; }
}
```
```javascript
var Animal = {
name: "Cat",
numberOfLegs: 4
}
```
```python
class Animal:
def __init__(self, name, number_of_legs):
self.name = n... | reference | def sort_animals(input):
return sorted(input, key=lambda x: (x . number_of_legs, x . name))
| Sort My Animals | 58ff1c8b13b001a5a50005b4 | [
"Lists",
"Sorting",
"Fundamentals"
] | https://www.codewars.com/kata/58ff1c8b13b001a5a50005b4 | 6 kyu |
<h2> Introduction </h2>
The GADERYPOLUKI is a simple substitution cypher used in scouting to encrypt messages. The encryption is based on short, easy to remember key. The key is written as paired letters, which are in the cipher simple replacement.
The most frequently used key is "GA-DE-RY-PO-LU-KI".
```
G => A
g ... | reference | def encode(str, key):
key = key . lower() + key . upper()
dict = {char: key[i - 1] if i % 2 else key[i + 1]
for i, char in enumerate(key)}
return '' . join(dict . get(char, char) for char in str)
decode = encode
| GA-DE-RY-PO-LU-KI cypher vol 2 | 592b7b16281da94068000107 | [
"Fundamentals",
"Ciphers",
"Cryptography"
] | https://www.codewars.com/kata/592b7b16281da94068000107 | 6 kyu |
<h2> Introduction </h2>
The GADERYPOLUKI is a simple substitution cypher used in scouting to encrypt messages. The encryption is based on short, easy to remember key. The key is written as paired letters, which are in the cipher simple replacement.
The most frequently used key is "GA-DE-RY-PO-LU-KI".
```
G => A
g ... | reference | dict = {i[0]: i[1] for i in ['GA', 'DE', 'RY', 'PO', 'LU', 'KI', 'AG', 'ED', 'YR', 'OP',
'UL', 'IK', 'ga', 'de', 'ry', 'po', 'lu', 'ki', 'ag', 'ed', 'yr', 'op', 'ul', 'ik']}
def encode(s):
return '' . join([dict[i] if i in dict else i for i in s])
def decode(s):
retur... | GA-DE-RY-PO-LU-KI cypher | 592a6ad46d6c5a62b600003f | [
"Fundamentals",
"Ciphers",
"Cryptography"
] | https://www.codewars.com/kata/592a6ad46d6c5a62b600003f | 7 kyu |
<h2>Is the number even?</h2>
If the numbers is even return `true`. If it's odd, return `false`.
<br><br><br><br><br>
Oh yeah... the following symbols/commands have been disabled!
- use of `%`
- use of `.even?` in Ruby
- use of `mod` in Python
| reference | def is_even(n):
return not n & 1
| isEven? - Bitwise Series | 592a33e549fe9840a8000ba1 | [
"Restricted",
"Fundamentals"
] | https://www.codewars.com/kata/592a33e549fe9840a8000ba1 | 7 kyu |
Write a function that accepts two numbers `a` and `b` and returns whether `a` is smaller than, bigger than, or equal to `b`, as a string.
```
(5, 4) ---> "5 is greater than 4"
(-4, -7) ---> "-4 is greater than -7"
(2, 2) ---> "2 is equal to 2"
```
There is only one problem...
You cannot use `if` statements, and ... | reference | def no_ifs_no_buts(a, b):
d = {a < b: 'smaller than', a == b: 'equal to', a > b: 'greater than'}
return f' { a } is { d [ True ]} { b } '
| No ifs no buts | 592915cc1fad49252f000006 | [
"Restricted",
"Fundamentals"
] | https://www.codewars.com/kata/592915cc1fad49252f000006 | 7 kyu |
Write a function `filterLucky`/`filter_lucky()` that accepts a list of integers and filters the list to only include the elements that contain the digit 7.
For example,
```
ghci> filterLucky [1,2,3,4,5,6,7,68,69,70,15,17]
[7,70,17]
```
Don't worry about bad input, you will always receive a finite list of integers. | reference | def filter_lucky(lst): return [n for n in lst if '7' in str(n)]
| Find the lucky numbers | 580435ab150cca22650001fb | [
"Fundamentals"
] | https://www.codewars.com/kata/580435ab150cca22650001fb | 7 kyu |
# Task
Some light bulbs are placed in a circle (clockwise direction). Each one is either `on (1)` or `off (0)`.
Every turn, the light bulbs change their states. If a light bulb was `on` at the `previous turn`, the light bulb to the `right of it` changes its state, i.e. if `lights[0]` is `on`. then, if `lights[1]` was... | algorithms | def light_bulbs(lights, n):
return lights if not n else light_bulbs([b ^ lights[i - 1] for i, b in enumerate(lights)], n - 1)
| Simple Fun #219: Light Bulbs | 5901555b63bf404a66000029 | [
"Puzzles",
"Algorithms"
] | https://www.codewars.com/kata/5901555b63bf404a66000029 | 6 kyu |
# Task
Amin and Sam are playing a game in which Amin gives Sam two binary numbers `a` and `b`, written as strings, and asks him to calculate the minimum number of right rotate of string `a` that minimize the `Hamming distance` between `a` and `b`. Help Sam answer this question for the given `a` and `b`.
A Hamming dist... | algorithms | def hamming_rotate(a, b):
def hamming_dist(i):
return sum(d != b[(j + i) % len(a)] for j, d in enumerate(a))
return min(range(len(a)), key=hamming_dist)
| Simple Fun #308: Hamming Rotate | 592786effb1f93349b0000b2 | [
"Algorithms"
] | https://www.codewars.com/kata/592786effb1f93349b0000b2 | 6 kyu |
# Task
John is a typist. He has a habit of typing: he never use the `Shift` key to switch case, just using only `Caps Lock`.
Given a string `s`. Your task is to count how many times the keyboard has been tapped by John.
You can assume that, at the beginning the `Caps Lock` light is not lit.
# Input/Output
`[input... | reference | def typist(s):
up = False
t = len(s)
for c in s:
if c . isupper() and not up:
up = True
t += 1
elif c . islower() and up:
up = False
t += 1
return t
| Simple Fun #305: Typist | 592645498270ccd7950000b4 | [
"Fundamentals"
] | https://www.codewars.com/kata/592645498270ccd7950000b4 | 6 kyu |
It's Friday the 13th, and Jason is ready for his first killing spree!
Create a function, killcount, that accepts two arguments: an array of array pairs (the conselor's name and intelligence - ["Chad", 2]) and an integer representing Jason's intellegence.
Ruby, Python, Crystal:
```ruby
counselors = [["Chad", 2], ["To... | reference | def kill_count(counselors, jason):
return [x for x, y in counselors if y < jason]
| Friday the 13th Part 1 | 5925acf31a9825d616000e74 | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/5925acf31a9825d616000e74 | 7 kyu |
Write a function taking in a string like `WOW this is REALLY amazing` and returning `Wow this is really amazing`. String should be capitalized and properly spaced. Using `re` and `string` is not allowed.
Examples:
```python
filter_words('HELLO CAN YOU HEAR ME') #=> Hello can you hear me
filter_words('now THI... | reference | def filter_words(st):
return ' ' . join(st . capitalize(). split())
| No yelling! | 587a75dbcaf9670c32000292 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/587a75dbcaf9670c32000292 | 7 kyu |
# Task
```
+----+----+----+
| a1 | a2 | a3 |
+----+----+----+
```
As shown above. There are three grids. Each grid fill in a number(let's call `a1, a2 and a3`). Such that `0 ≤ a1, a2, a3 ≤ n`, where `n` is given, and meet the following rules:
```
- a1 + a2 is a multiple of 2;
- a2 + a3 is a multiple of 3;
- a1 + a2 + ... | games | LOOP = (0, 0, 5, 5, 10, 10, 15, 15, 20, 25, 25, 30, 30, 35, 40)
def find_max_sum(n):
q, r = divmod(n, 15)
return 45 * q + LOOP[r]
| Simple Fun #302: Find The Max Sum | 59252121fb1f93fc8200013a | [
"Puzzles"
] | https://www.codewars.com/kata/59252121fb1f93fc8200013a | 6 kyu |
We want to know the index of the vowels in a given word, for example, there are two vowels in the word super (the second and fourth letters).
So given a string "super", we should return a list of `[2, 4]`.
Some examples:
Mmmm => []
Super => [2,4]
Apple => [1,5]
YoMama -> [1,2,4,6]
### NOTES
* Vowels in this ... | reference | def vowel_indices(word):
return [i for i, x in enumerate(word, 1) if x . lower() in 'aeiouy']
| Find the vowels | 5680781b6b7c2be860000036 | [
"Fundamentals"
] | https://www.codewars.com/kata/5680781b6b7c2be860000036 | 7 kyu |
Write a function that generate the sequence of numbers which starts from the "From" number, then adds to each next term the "Step" number until the "To" number. For example:
```python
generator(10, 20, 10) = [10, 20] # "From" = 10, "Step" = 10, "To" = 20
generator(10, 20, 1) = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ... | reference | def generator(start, stop, step):
if step == 0:
return []
if stop < start:
return list(range(start, stop - 1, - step))
return list(range(start, stop + 1, step))
| From-To-Step Sequence Generator | 56459c0df289d97bd7000083 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/56459c0df289d97bd7000083 | 7 kyu |
# Task
We know that some numbers can be split into two primes. ie. `5 = 2 + 3, 10 = 3 + 7`. But some numbers are not. ie. `17, 27, 35`, etc..
Given a positive integer `n`. Determine whether it can be split into two primes. If yes, return the maximum product of two primes. If not, return `0` instead.
# Input/Output
... | reference | def isPrime(n):
return n == 2 or n > 2 and n & 1 and all(n % p for p in range(3, int(n * * .5 + 1), 2))
def prime_product(n):
return next((x * (n - x) for x in range(n >> 1, 1, - 1) if isPrime(x) and isPrime(n - x)), 0)
| Simple Fun #303: Prime Product | 592538b3071ba54511000219 | [
"Fundamentals"
] | https://www.codewars.com/kata/592538b3071ba54511000219 | 6 kyu |
# Task
Some children are playing rope skipping game. Children skip the rope at roughly the same speed: `once per second`. If the child fails during the jump, he needs to tidy up the rope and continue. This will take `3 seconds`.
You are given an array sorted in ascending order, where each element is a jump count after... | games | def tiaosheng(failed_counter):
count = 0
jumps = 0
while count < 60:
count += 1
jumps += 1
if jumps in failed_counter:
count += 3
return jumps
| Simple Fun #301: Rope Skipping Game | 5925138effaed0de490000cf | [
"Puzzles"
] | https://www.codewars.com/kata/5925138effaed0de490000cf | 6 kyu |
Find the second-to-last element of a list.
The input list will always contain at least two elements.
Example:
```rust
penultimate([1,2,3,4]) // -> 3
penultimate([4,3,2,1]) // -> 2
```
```haskell
penultimate [1,2,3,4] -- => 3
penultimate ['a'..'z'] -- => 'y'
```
```clojure
(penultimate [1,2,3,4... | reference | def penultimate(a):
return a[- 2]
| Penultimate | 54162d1333c02486a700011d | [
"Lists",
"Fundamentals"
] | https://www.codewars.com/kata/54162d1333c02486a700011d | 7 kyu |
###Lucky number
Write a function to find if a number is lucky or not. If the sum of all digits is 0 or multiple of 9 then the number is lucky.
`1892376 => 1+8+9+2+3+7+6 = 36`. 36 is divisible by 9, hence number is lucky.
Function will return `true` for lucky numbers and `false` for others.
| reference | def is_lucky(n):
return n % 9 == 0
| lucky number | 55afed09237df73343000042 | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/55afed09237df73343000042 | 7 kyu |
Count the number of occurrences of each character and return it as a (list of tuples) in order of appearance. For empty output return (an empty list).
Consult the solution set-up for the exact data structure implementation depending on your language.
Example:
```python
ordered_count("abracadabra") == [('a', 5), ('b',... | reference | from collections import Counter
def ordered_count(input):
return list(Counter(input). items())
| Ordered Count of Characters | 57a6633153ba33189e000074 | [
"Fundamentals"
] | https://www.codewars.com/kata/57a6633153ba33189e000074 | 7 kyu |
Write a function that doubles every second integer in a list, starting from the left.
Example:
For input array/list :
```javascript
[1,2,3,4]
```
the function should return :
```javascript
[1,4,3,8]
```
| reference | def double_every_other(l):
return [x * 2 if i % 2 else x for i, x in enumerate(l)]
| Double Every Other | 5809c661f15835266900010a | [
"Fundamentals",
"Lists",
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/5809c661f15835266900010a | 7 kyu |
Write a function, `isItLetter` or `is_it_letter` or `IsItLetter`, which tells us if a given character is a letter or not. | reference | def is_it_letter(s):
return s . isalpha()
| Is it a letter? | 57a06b07cf1fa58b2b000252 | [
"Fundamentals"
] | https://www.codewars.com/kata/57a06b07cf1fa58b2b000252 | 7 kyu |
Implement a function that returns the minimal and the maximal value of a list (in this order). | reference | def get_min_max(seq):
return min(seq), max(seq)
| Find min and max | 57a1ae8c7cb1f31e4e000130 | [
"Fundamentals"
] | https://www.codewars.com/kata/57a1ae8c7cb1f31e4e000130 | 7 kyu |
Bob is a lazy man.
He needs you to create a method that can determine how many ```letters``` (both uppercase and lowercase **ASCII** letters) and ```digits``` are in a given string.
Example:
"hel2!lo" --> 6
"wicked .. !" --> 6
"!?..A" --> 1 | reference | def count_letters_and_digits(s):
return sum(map(str . isalnum, s))
| Help Bob count letters and digits. | 5738f5ea9545204cec000155 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5738f5ea9545204cec000155 | 7 kyu |
You will be given two ASCII strings, `a` and `b`. Your task is write a function to determine which one of these strings is "worth" more, and return it.
A string's worth is determined by the sum of its ASCII codepoint indexes. So, for example, the string `HELLO` has a value of 372: H is codepoint 72, E 69, L 76, and O ... | games | def highest_value(a, b):
return max(a, b, key=lambda s: sum(map(ord, s)))
| Which string is worth more? | 5840586b5225616069000001 | [
"Algorithms",
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5840586b5225616069000001 | 7 kyu |
Write a function `getNumberOfSquares` (C, F#, Haskell) / `get_number_of_squares` (Python, Ruby) that will return how many integer (starting from 1, 2...) numbers raised to power of 2 and then summed up are less than some number given as a parameter.
E.g 1: For n = 6 result should be 2 because 1^2 + 2^2 = 1 + 4 = 5 an... | reference | def get_number_of_squares(n):
s, i = 0, 0
while s < n:
i += 1
s += i * * 2
return i - 1
| Sum of squares less than some number | 57b71a89b69bfc92c7000170 | [
"Fundamentals"
] | https://www.codewars.com/kata/57b71a89b69bfc92c7000170 | 7 kyu |
The look and say sequence is a sequence in which each number is the result of a "look and say" operation on the previous element.
Considering for example the classical version startin with `"1"`: `["1", "11", "21, "1211", "111221", ...]`. You can see that the second element describes the first as `"1(times number)1"`,... | reference | from re import sub
def look_and_say_sequence(s, n):
for _ in range(1, n):
s = sub(r'(.)\1*', lambda m: str(len(m . group(0))) + m . group(1), s)
return s
| Look and say sequence generator | 592421cb7312c23a990000cf | [
"Strings",
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/592421cb7312c23a990000cf | 6 kyu |
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... | algorithms | from math import gcd
def greatest(x, y, n):
lcm = (x * y) / / gcd(x, y)
return (n / / lcm) * lcm if (n / / lcm) * lcm < n else 0
def smallest(x, y, n):
lcm = (x * y) / / gcd(x, y)
return lcm + (n / / lcm) * (lcm)
| When greatest is less than smallest | 55f2a1c2cb3c95af75000045 | [
"Mathematics",
"Logic",
"Algorithms"
] | https://www.codewars.com/kata/55f2a1c2cb3c95af75000045 | 6 kyu |
Your task here is the find the GCF (Greatest Common Factor) of any two numbers passed into a method, which will return one integer answer as an output.
Examples:
```java
findGCF(4, 6); // Should return 2
findGCF(93, 186); // Should return 93
findGCF(20, 5); // Should return 5
```
```python
find_GCF(4, 6) # Should ret... | algorithms | from fractions import gcd as find_GCF
| Find the GCF of Two Numbers | 579e3476cf1fa55592000045 | [
"Algorithms",
"Logic",
"Numbers",
"Data Types",
"Mathematics"
] | https://www.codewars.com/kata/579e3476cf1fa55592000045 | 7 kyu |
Consider a game, wherein the player has to guess a target word. All the player knows is the length of the target word.
To help them in their goal, the game will accept guesses, and return the number of letters that are in the correct position.
Write a method that, given the correct word and the player's guess, return... | games | def count_correct_characters(s, t):
assert len(s) == len(t)
return sum(a == b for a, b in zip(s, t))
| Guess the Word: Count Matching Letters | 5912ded3f9f87fd271000120 | [
"Strings",
"Games",
"Puzzles"
] | https://www.codewars.com/kata/5912ded3f9f87fd271000120 | 7 kyu |
# Task
Get the digits sum of `n`<sub>th</sub> number from the [Look-and-Say sequence](http://en.wikipedia.org/wiki/Look-and-say_sequence)(1-based).
`1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, ...`
# Input/Output
`[input]` integer `n`
`n`<sub>th</sub> number in the sequence to get where `1 <= n <= 55` a... | games | def look_and_say_and_sum(N):
l = [1]
for n in range(N - 1):
result = [1, l[0]]
for i in range(1, len(l)):
if l[i] == result[- 1]:
result[- 2] += 1
else:
result += [1, l[i]]
l = result
return sum(l)
| Simple Fun #299: Look And Say And Sum | 5922828c80a27c049c000078 | [
"Puzzles"
] | https://www.codewars.com/kata/5922828c80a27c049c000078 | 5 kyu |
*** No Loops Allowed ***
You will be given an array (a) and a limit value (limit). You must check that all values in the array are below or equal to the limit value. If they are, return true. Else, return false.
You can assume all values in the array are numbers.
Do not use loops. Do not modify input array.
Looking... | reference | def small_enough(a, limit):
return max(a) <= limit
| No Loops 1 - Small enough? | 57cc4853fa9fc57a6a0002c2 | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/57cc4853fa9fc57a6a0002c2 | 7 kyu |
A series or sequence of numbers is usually the product of a function and can either be infinite or finite.
In this kata we will only consider finite series and you are required to return a code according to the type of sequence:
|Code|Type|Example|
|-|-|-|
|`0`|`unordered`|`[3,5,8,1,14,3]`|
|`1`|`strictly increasing`... | algorithms | def sequence_classifier(arr):
if all(arr[i] == arr[i + 1] for i in range(len(arr) - 1)):
return 5
if all(arr[i] < arr[i + 1] for i in range(len(arr) - 1)):
return 1
if all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1)):
return 2
if all(arr[i] > arr[i + 1] for i in range(len(a... | Sequence classifier | 5921c0bc6b8f072e840000c0 | [
"Algorithms"
] | https://www.codewars.com/kata/5921c0bc6b8f072e840000c0 | 6 kyu |
# RoboScript #3 - Implement the RS2 Specification
## 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... | algorithms | from collections import deque
import re
TOKENIZER = re . compile(r'(R+|F+|L+|\)|\()(\d*)')
def parseCode(code):
cmds = [[]]
for cmd, n in TOKENIZER . findall(code):
s, r = cmd[0], int(n or '1') + len(cmd) - 1
if cmd == '(':
cmds . append([])
elif cmd == ')':
lst = cmds ... | RoboScript #3 - Implement the RS2 Specification | 58738d518ec3b4bf95000192 | [
"Esoteric Languages",
"Interpreters",
"Regular Expressions",
"Algorithms"
] | https://www.codewars.com/kata/58738d518ec3b4bf95000192 | 4 kyu |
# Task
Given two numbers `x` and `y`. You have to convert `x` to `y` using minimum number of operations.
There are two valid operation on the number `x`:
```
Multiply x by some prime p
Divide x by some prime p
```
Your task is to find the minimum number of operations.
Note that integer division is NOT allowed. Tha... | games | from collections import Counter
def factors(n):
for i in [2] + list(range(3, int(n * * 0.5) + 1, 2)):
while not n % i:
yield i
n = n / / i
if n > 2:
yield n
def prime_operations(x, y):
C = Counter(factors(x))
C . subtract(Counter(factors(y)))
return sum(map(a... | Simple Fun #127: Prime Operations | 58a3e2978bdda5a0d9000187 | [
"Puzzles"
] | https://www.codewars.com/kata/58a3e2978bdda5a0d9000187 | 5 kyu |
## Task
Given a string consisting of lowercase English letters, find the largest square number which can be obtained by reordering its characters and replacing them with digits (leading zeros are not allowed) where same characters always map to the same digits and different characters always map to different digits.
... | games | from collections import Counter
from math import isqrt
def mask(x):
return sorted(Counter(str(x)). values())
def construct_square(s):
m, r = mask(s), range(isqrt(10 * * ~ - len(s)), isqrt(10 * * len(s)) + 1)
return (m := mask(s)) and max((n * n for n in r if mask(n * n) == m), default=- 1)
| Simple Fun #33: Construct Square | 58870c87c81516bbdb0000d8 | [
"Puzzles"
] | https://www.codewars.com/kata/58870c87c81516bbdb0000d8 | 6 kyu |
## Task
Last night you had to study, but decided to party instead. Now there is a black and white photo of you that is about to go viral. You cannot let this ruin your reputation, so you want to apply box blur algorithm to the photo to hide its content.
The algorithm works as follows: each pixel x in the resulting i... | games | from scipy . ndimage import convolve
def box_blur(image):
return (convolve(image, [[1, 1, 1]] * 3)[1: - 1, 1: - 1] / / 9). tolist()
| Simple Fun #84: Box Blur | 5895326bcc949f496b00003e | [
"Puzzles"
] | https://www.codewars.com/kata/5895326bcc949f496b00003e | 6 kyu |
### Background
I was reading a [book](http://www.amazon.co.uk/Things-Make-Do-Fourth-Dimension/dp/1846147646/) recently, "Things to Make and Do in the Fourth Dimension" by comedian and mathematician Matt Parker, and in the first chapter of the book Matt talks about problems he likes to solve in his head to take his min... | algorithms | CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
def from10(n, b):
if b == 10: return n
new = ''
while n:
new += str(CHARS[n % b])
n / /= b
return new[:: - 1]
def to10(n, b):
num = 0
for i, d in enumerate(str(n)[:: - 1]):
num += int(CHARS . index(d)) * (b * * i)
... | Polydivisible Numbers | 556206664efbe6376700005c | [
"Number Theory",
"Algorithms"
] | https://www.codewars.com/kata/556206664efbe6376700005c | 4 kyu |
In this kata, your task is to create a regular expression capable of evaluating binary strings (strings with only `1`s and `0`s) and determining whether the given string represents a number divisible by 3.
Take into account that:
* An empty string *might* be evaluated to true (it's not going to be tested, so you don'... | games | PATTERN = re . compile(r'^(0|1(01*0)*1)*$')
| Binary multiple of 3 | 54de279df565808f8b00126a | [
"Regular Expressions",
"Algorithms",
"Puzzles",
"Number Theory"
] | https://www.codewars.com/kata/54de279df565808f8b00126a | 4 kyu |
## Introduction
<pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">A multi-storey car park (also called a parking garage, parking structure, parking ramp, parkade, parking building, parking deck or indoor parking) is a building designed ... | reference | def escape(carpark):
car, stairs, start, moves, x = - 1, - 1, - 1, [], 0
while x < len(carpark):
# Use string to avoid troubles with absence of 1 or 2
line = '' . join(map(str, carpark[x]))
stairs = line . find("1") # Search for stairs
if start == - 1:
# Do this only while the car ... | Car Park Escape | 591eab1d192fe0435e000014 | [
"Arrays",
"Games",
"Fundamentals"
] | https://www.codewars.com/kata/591eab1d192fe0435e000014 | 5 kyu |
# Task
Amin and Haji are playing a simple game: Haji thinks of a number `x` in range `[1..n]`, and Amin tries to guess the number by asking variations of the following question: `"Is your number divisible by number y?"`.
The game is played according to the following rules: first Amin asks all the questions that inter... | algorithms | from math import log
def find_divs(mx=10 * * 3):
def is_prime(n): return n == 2 or all(n % k for k in [2] + [* range(3, int(n * * .5) + 1, 2)])
marg = int(mx * * .5)
res = {k for k in range(2, mx + 1) if is_prime(k)}
res = res | {d * * pw for d in res if d <= marg for pw in range(2, int(log(m... | Simple Fun #295: Guess Number | 591e62eef99b994288000057 | [
"Mathematics",
"Number Theory"
] | https://www.codewars.com/kata/591e62eef99b994288000057 | 6 kyu |
## Task
Ram lives in a house which is round in shape. The house has `n` entrances numbered from `1` to `n`. For each `i` in range `1..n-1` entrances `i` and `i + 1` are adjacent; entrances `1` and `n` are also adjacent.
Ram's flat is located at entrance `a`. Each evening he goes for a walk around the house, counting ... | games | def round_and_round(n, a, b):
return (a + b) % n or n
| Simple Fun #296: Round And Round | 591e8c715b1d254f9e00005e | [
"Puzzles"
] | https://www.codewars.com/kata/591e8c715b1d254f9e00005e | 7 kyu |
Given a certain square matrix ```A```, of dimension ```n x n```, that has negative and positive values (many of them may be 0).
We need the following values rounded to the closest integer:
- the average of all the positive numbers and zeros that are in the principal diagonal and in the columns with odd index, **avg1*... | reference | def avg_diags(m):
a1, a2, l, l1, l2 = 0, 0, len(m), 0, 0
for i in range(0, l):
if i & 1:
if m[i][i] >= 0:
a1 += m[i][i]
l1 += 1
else:
if m[l - i - 1][i] < 0:
a2 += m[len(m) - i - 1][i]
l2 += 1
return [round(a1 / l1) if l1 > 0 else - 1, round(abs(a2)... | #4 Matrices: Process for a Square Matrix | 58fef91f184b6dcc07000179 | [
"Mathematics",
"Data Structures",
"Matrix",
"Linear Algebra",
"Fundamentals"
] | https://www.codewars.com/kata/58fef91f184b6dcc07000179 | 6 kyu |
Two numbers are **relatively prime** if their greatest common factor is 1; in other words: if they cannot be divided by any other common numbers than 1.
`13, 16, 9, 5, and 119` are all relatively prime because they share no common factors, except for 1. To see this, I will show their factorizations:
```python
13: 13
... | algorithms | from fractions import gcd
def relatively_prime(n, l):
return [x for x in l if gcd(n, x) == 1]
| Relatively Prime Numbers | 56b0f5f84de0afafce00004e | [
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/56b0f5f84de0afafce00004e | 7 kyu |
Create a function that takes a number as an argument and returns a grade based on that number.
Score | Grade
-----------------------------------------|-----
Anything greater than 1 or less than 0.6 | "F"
0.9 or greater | "A"
0.8 or greater ... | reference | def grader(x):
if 0.9 <= x <= 1:
return "A"
elif 0.8 <= x < 0.9:
return "B"
elif 0.7 <= x < 0.8:
return "C"
elif 0.6 <= x < 0.7:
return "D"
else:
return "F"
| Grader | 53d16bd82578b1fb5b00128c | [
"Fundamentals"
] | https://www.codewars.com/kata/53d16bd82578b1fb5b00128c | 8 kyu |
# Task
Given a number `n`, return a string representing it as a sum of distinct powers of three, or return `"Impossible"` if that's not possible to achieve.
# Input/Output
`[input]` integer `n`
A positive integer n.
`1 ≤ n ≤ 10^16`.
`[output]` a string
A string representing the sum of powers of three which ad... | algorithms | import numpy as np
def sum_of_threes(n):
s = np . base_repr(n, 3)
if '2' in s:
return 'Impossible'
return '+' . join(['3^{}' . format(i) for i, d in enumerate(s[:: - 1]) if d == '1'][:: - 1])
| Simple Fun #290: Sum Of Threes | 591d3375e51f4a0940000052 | [
"Algorithms"
] | https://www.codewars.com/kata/591d3375e51f4a0940000052 | 6 kyu |
Every natural number, ```n```, may have a prime factorization like:
<a href="http://imgur.com/1M2nwjh"><img src="http://i.imgur.com/1M2nwjh.png?1" title="source: imgur.com" /></a>
We define the **geometric derivative of n**, as a number with the following value:
<a href="http://imgur.com/dMNPsIx"><img src="http://i.... | reference | def f(n):
res = 1
i = 2
while n != 1:
k = 0
while n % i == 0:
k += 1
n / /= i
if k != 0:
res *= k * i * * (k - 1)
i += 1
return res
| Transformation of a Number Through Prime Factorization | 572caa2672a38ba648001dcd | [
"Fundamentals",
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/572caa2672a38ba648001dcd | 5 kyu |
# Task
There's a wolf who lives in the plane forest, which is located on the `Cartesian coordinate system`. When going on the hunt, the wolf starts at point `(0, 0)` and goes `spirally` as shown in the picture below:

The wolf finally found something to eat... | games | def turns_on_road(x, y):
if [x, y] == [0, 0]:
return 0
if x > 0 and - x + 1 < y <= x:
return 4 * x - 3
if x < 0 and x <= y < - x:
return 4 * (- x) - 1
if y > 0 and - y <= x < y:
return 4 * y - 2
if y < 0 and y < x <= - y + 1:
return 4 * (- y)
| Simple Fun #288: Turns On Road | 591c075a94414c1617000063 | [
"Puzzles"
] | https://www.codewars.com/kata/591c075a94414c1617000063 | 6 kyu |
<img src="https://i.imgur.com/ta6gv1i.png?1" title="source: imgur.com" />
<!-- Weekly Kata Challenge 4/Feb/2022 -->
<span style='color:#cc3300;'>
<i>
> "What is your name" said Tim. <br>"My name" said the mouse "Is Dinglemouse".
<br><br>
> "What were you before the witch turned you into a mouse" said Rose. <br>"I was... | algorithms | import itertools
def bananas(s):
result = set()
for comb in itertools . combinations(range(len(s)), len(s) - 6):
arr = list(s)
for i in comb:
arr[i] = '-'
candidate = '' . join(arr)
if candidate . replace('-', '') == 'banana':
result . add(candidate)
return resu... | Bananas | 5917fbed9f4056205a00001e | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5917fbed9f4056205a00001e | 5 kyu |
In this simple exercise, you will build a program that takes a value, `integer `, and returns a list of its multiples up to another value, `limit `. If `limit` is a multiple of ```integer```, it should be included as well. There will only ever be positive integers passed into the function, not consisting of 0. The limi... | reference | def find_multiples(integer, limit):
return list(range(integer, limit + 1, integer))
| Find Multiples of a Number | 58ca658cc0d6401f2700045f | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/58ca658cc0d6401f2700045f | 8 kyu |
# Task
You are given a `chessboard` with several `rooks` and `bishops` placed on some of its squares. How many unoccupied squares are there that are not under attack of any chess piece?
Here, the standard rules are applied: a square is under attack of a rook or a bishop only if all squares between the piece and the ... | games | PIECES_MOVES = {1: [(1, 0), (- 1, 0), (0, 1), (0, - 1)],
- 1: [(1, 1), (- 1, - 1), (- 1, 1), (1, - 1)]}
def bishops_and_rooks(chessboard):
def theRootOfAllEvil(r, c):
evilIsHere . add((r, c))
for dr, dc in PIECES_MOVES[chessboard[r][c]]:
for i in range(1, 8):
x, y = r + ... | Chess Fun #9: Bishops And Rooks | 58a3b28b2f949e21b3000001 | [
"Puzzles"
] | https://www.codewars.com/kata/58a3b28b2f949e21b3000001 | 5 kyu |
Given a positive integer `n`, return first n dgits of Thue-Morse sequence, as a string (see examples).
Thue-Morse sequence is a binary sequence with 0 as the first element. The rest of the sequece is obtained by adding the Boolean (binary) complement of a group obtained so far.
```
For example:
0
01
0110
01101001
an... | algorithms | def thue_morse(n):
out = "0"
while len ( out ) < n :
out += out . replace ( '1' , '2' ). replace ( '0' , '1' ). replace ( '2' , '0' )
return out [: n ] | Thue-Morse Sequence | 591aa1752afcb02fa300002a | [
"Strings",
"Binary",
"Algorithms"
] | https://www.codewars.com/kata/591aa1752afcb02fa300002a | 6 kyu |
You are given a matrix ```M```, of positive and negative integers. It should be sorted in an up and down column way, starting always with the lowest element placed at the top left position finishing with the highest depending on ```n``` value: at the bottom right position if the number of columns,```n```, is odd, or p... | reference | def up_down_col_sort(m):
f = []
for i in m:
for j in i:
f += [j]
f = sorted(f)
a = len(m)
d = 0
g = []
for i in range(0, len(f), a):
if d == 0:
g += [f[i: i + a]]
d += 1
else:
g += [f[i: i + a][:: - 1]]
d = 0
return [list(i) for i in zip(* ... | #8 Matrices: Up and Down Sorting For Each Column | 590b8d5cee471472f40000aa | [
"Fundamentals",
"Algorithms",
"Data Structures",
"Mathematics",
"Matrix",
"Sorting"
] | https://www.codewars.com/kata/590b8d5cee471472f40000aa | 6 kyu |
# Task
`Codewars Weekly` has gained popularity in the past months and is receiving lots of fan letters. Unfortunately, some of the readers use offensive words and the editor wants to keep the magazine family friendly.
To manage this, you have been asked to implement a censorship algorithm. You will be given the fan le... | reference | def censor_this(text, forbidden_words):
return ' ' . join([w if w . lower() not in forbidden_words else '*' * len(w) for w in text . split()])
| Simple Fun #283: Censor The Forbidden Words | 591a86bfe76dc98f24000030 | [
"Fundamentals"
] | https://www.codewars.com/kata/591a86bfe76dc98f24000030 | 6 kyu |
We have a square matrix ```M``` of dimension ```n x n``` that has positive and negative numbers in the ranges ```[-9,-1]``` and ```[0,9]```,( the value ```0``` is excluded).
We want to add up all the products of the elements of the diagonals ```UP-LEFT to DOWN-BOTTOM```, that is the value of```sum1```; and the element... | reference | def sum_prod_diags(m):
s, n = 0, len(m)
for d in 0, - 1:
for x in range(n):
h = v = 1
for u in range(n - x):
h *= m[u ^ d][x + u]
if x:
v *= m[(x + u) ^ d][u]
s += (d | 1) * (h + v)
return s
| #9 Matrices: Adding diagonal products | 590bb735517888ae6b000012 | [
"Matrix",
"Algorithms",
"Fundamentals"
] | https://www.codewars.com/kata/590bb735517888ae6b000012 | 5 kyu |
# The Problem
Dan, president of a Large company could use your help. He wants to implement a system that will switch all his devices into offline mode depending on his meeting schedule. When he's at a meeting and somebody texts him, he wants to send an automatic message informing that he's currently unavailable and th... | algorithms | def check_availability(schedule, current_time):
for tb, te in schedule:
if tb <= current_time < te:
return te
return True
| Are you available? | 5603002927a683441f0000cb | [
"Algorithms"
] | https://www.codewars.com/kata/5603002927a683441f0000cb | 6 kyu |
This series of katas will introduce you to basics of doing geometry with computers.
Write the function `circleArea`/`CircleArea` which takes in a `Circle` object and calculates the area of that circle.</br>
The `Circle` class can be seen below:
```javascript
// Represents a Circle where center is a Point and radius is... | reference | from math import pi
def circle_area(circle):
return pi * circle . radius * * 2
| Geometry Basics: Circle Area in 2D | 58e3f824a33b52c1dc0001c0 | [
"Geometry",
"Fundamentals"
] | https://www.codewars.com/kata/58e3f824a33b52c1dc0001c0 | 8 kyu |
# Task
Given an array `arr`, find the maximal value of `k` such `a[i] mod k` = `a[j] mod k` for all valid values of i and j.
If it's impossible to find such number (there's an infinite number of `k`s), return `-1` instead.
# Input/Output
`[input]` integer array `arr`
A non-empty array of positive integer.
`2 <= a... | algorithms | def finding_k(arr):
for n in range(max(arr) - 1, 0, - 1):
if len({x % n for x in arr}) == 1:
return n
return - 1
| Simple Fun #279: Finding K | 5919427e5ffc30804900005f | [
"Algorithms"
] | https://www.codewars.com/kata/5919427e5ffc30804900005f | 6 kyu |
You are a *khm*mad*khm* scientist and you decided to play with electron distribution among atom's shells.
You know that basic idea of electron distribution is that electrons should fill a shell untill it's holding the maximum number of electrons.
---
Rules:
- Maximum number of electrons in a shell is distribute... | algorithms | def atomic_number(electrons):
result = []
i = 1
while electrons > 0:
result . append(min(2 * (i * * 2), electrons))
electrons -= result[- 1]
i += 1
return result
| Ideal electron distribution | 59175441e76dc9f9bc00000f | [
"Arrays",
"Lists",
"Algorithms"
] | https://www.codewars.com/kata/59175441e76dc9f9bc00000f | 6 kyu |
# Description:
Replace the pair of exclamation marks and question marks to spaces(from the left to the right). A pair of exclamation marks and question marks must has the same number of "!" and "?".
That is: "!" and "?" is a pair; "!!" and "??" is a pair; "!!!" and "???" is a pair; and so on..
# Examples
```
re... | reference | import re
def replace(s):
dic = {'!': '?', '?': '!'}
r = re . findall(r'[!]+|[/?]+', s)
for i in r[:]:
ii = dic[i[0]] * len(i)
if ii in r:
r[r . index(ii)] = ' ' * len(i)
return '' . join(r)
| Exclamation marks series #15: Replace the pair of exclamation marks and question marks to spaces | 57fb2c822b5314e2bb000027 | [
"Fundamentals"
] | https://www.codewars.com/kata/57fb2c822b5314e2bb000027 | 6 kyu |
# Task
Businesses like to have memorable telephone numbers. One way to make a telephone number memorable is to have it spell a memorable word or phrase.
For example, you can call the University of Waterloo by dialing the memorable `TUT-GLOP`. Sometimes only part of the number is used to spell a word. When you get ... | algorithms | def find_duplicate_phone_numbers(phone_numbers):
stan = [a . upper(). translate(str . maketrans('ABCDEFGHIJKLMNOPRSTUVWXY',
'222333444555666777888999')). replace('-', '') for a in phone_numbers]
return sorted(['{}-{}:{}' . format(a[: 3], a[3:], stan . count(... | Simple Fun #186: Duplicate Phone Numbers | 58bf67eb68d8469e3c000041 | [
"Algorithms"
] | https://www.codewars.com/kata/58bf67eb68d8469e3c000041 | 6 kyu |
# Task
Given a `sequence` of integers, check whether it is possible to obtain a strictly increasing sequence by erasing no more than one element from it.
# Example
For `sequence = [1, 3, 2, 1]`, the output should be `false`;
For `sequence = [1, 3, 2]`, the output should be `true`.
# Input/Output
- `[input]` ... | games | def almost_increasing_sequence(sequence):
save, first = - float('inf'), True
for i, x in enumerate(sequence):
if x > save:
save = x
elif first:
if i == 1 or x > sequence[i - 2]:
save = x
first = False
else:
return False
return True
| Simple Fun #64: Almost Increasing Sequence | 5893e7578afa367a61000036 | [
"Puzzles"
] | https://www.codewars.com/kata/5893e7578afa367a61000036 | 6 kyu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.