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 |
|---|---|---|---|---|---|---|---|
Define a function that takes in two non-negative integers `$a$` and `$b$` and returns the last decimal digit of `$a^b$`. Note that `$a$` and `$b$` may be very large!
For example, the last decimal digit of `$9^7$` is `$9$`, since `$9^7 = 4782969$`. The last decimal digit of `$({2^{200}})^{2^{300}}$`, which has over `$... | algorithms | def last_digit(n1, n2):
return pow(n1, n2, 10)
| Last digit of a large number | 5511b2f550906349a70004e1 | [
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/5511b2f550906349a70004e1 | 5 kyu |
With a friend we used to play the following game on a chessboard
(8, rows, 8 columns).
On the first row at the *bottom* we put numbers:
`1/2, 2/3, 3/4, 4/5, 5/6, 6/7, 7/8, 8/9`
On row 2 (2nd row from the bottom) we have:
`1/3, 2/4, 3/5, 4/6, 5/7, 6/8, 7/9, 8/10`
On row 3:
`1/4, 2/5, 3/6, 4/7, 5/8, 6/9, 7/10, 8/11`... | reference | '''
n t(i) n-1 (n + i + 1) * (n - i)
s(n) = Σ ----- + Σ ---------------------
i=1 i + 1 i=1 2 * (n + i + 1)
n i n-1 n - i
= Σ --- + Σ -----
i=1 2 i=1 2
n i n-1 i
= Σ --- + Σ ---
i=1 2 i=1 2
n n-1
= --- + Σ i
2 i=1
n n * (n - 1)
= --- + -----------
2 2
= n^2 / 2
'''
def game(n):
r... | Playing on a chessboard | 55ab4f980f2d576c070000f4 | [
"Puzzles",
"Fundamentals"
] | https://www.codewars.com/kata/55ab4f980f2d576c070000f4 | 6 kyu |
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said
# Description:
```if:javascript
Given an array `arr` that contains some integers(positive, negative or 0), and a `range` list such as `[[start1,end1],[start2,end2],...]`,... | reference | def max_sum(arr, ranges):
return max(sum(arr[start: stop + 1]) for start, stop in ranges)
| The maximum sum value of ranges -- Simple version | 583d10c03f02f41462000137 | [
"Fundamentals"
] | https://www.codewars.com/kata/583d10c03f02f41462000137 | 6 kyu |
Complete the function that calculates the area of the red square, when the length of the circular arc `A` is given as the input. Return the result rounded to two decimals.

Note: use the π value provided in your language (`Math::PI`, `M_PI`, `math.pi`, etc) | reference | from math import pi
def square_area(A):
return round((2 * A / pi) * * 2, 2)
| Area of a Square | 5748838ce2fab90b86001b1a | [
"Fundamentals",
"Mathematics",
"Geometry"
] | https://www.codewars.com/kata/5748838ce2fab90b86001b1a | 8 kyu |
A triangle is called an equable triangle if its area equals its perimeter. Return `true`, if it is an equable triangle, else return `false`. You will be provided with the length of sides of the triangle. Happy Coding! | reference | def equable_triangle(a, b, c):
p = a + b + c
ph = p / 2
return p * p == ph * (ph - a) * (ph - b) * (ph - c)
| Check if a triangle is an equable triangle! | 57d0089e05c186ccb600035e | [
"Fundamentals",
"Geometry"
] | https://www.codewars.com/kata/57d0089e05c186ccb600035e | 7 kyu |
Find the area of a rectangle when provided with one diagonal and one side of the rectangle. If the input diagonal is less than or equal to the length of the side, return "Not a rectangle". If the resultant area has decimals round it to two places.
`This kata is meant for beginners. Rank and upvote to bring it out of b... | reference | def area(d, l):
return "Not a rectangle" if d <= l else round(l * (d * d - l * l) * * .5, 2)
| Find the area of the rectangle! | 580a0347430590220e000091 | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/580a0347430590220e000091 | 7 kyu |
Complete the function which will return the area of a circle with the given `radius`.
Returned value is expected to be accurate up to tolerance of 0.01.
~~~if:coffeescript,javascript,typescript
If the `radius` is not positive, throw `Error`.
~~~
~~~if:csharp
If the `radius` is not positive, throw `ArgumentException`... | reference | def circle_area(r):
if r > 0:
return r ** 2 * 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234... | Area of a Circle | 537baa6f8f4b300b5900106c | [
"Fundamentals",
"Algorithms",
"Geometry",
"Mathematics"
] | https://www.codewars.com/kata/537baa6f8f4b300b5900106c | 7 kyu |
We'd like to know the area of an arbitrary shape. The only information of the shape is that it is bounded within the square area of four points: (0, 0), (1, 0), (1, 1) and (0, 1).
Given a function `f(x, y)` which returns a boolean representing whether the point `(x, y)` is inside the shape, determine the area of the s... | algorithms | from random import random as rand
def area_of_the_shape(f, n=10000):
return sum(f(rand(), rand()) for _ in range(n)) / n
| Area of a Shape | 5474be18b2bc28ff92000fbd | [
"Statistics",
"Algorithms"
] | https://www.codewars.com/kata/5474be18b2bc28ff92000fbd | 6 kyu |
In geometry, a cube is a three-dimensional solid object bounded by six square faces, facets or sides, with three meeting at each vertex.The cube is the only regular hexahedron and is one of the five Platonic solids. It has 12 edges, 6 faces and 8 vertices.The cube is also a square parallelepiped, an equilateral cuboid ... | reference | def you_are_a_cube(cube):
return round(cube * * (1 / 3)) * * 3 == cube
| You are a Cube! | 57da5365a82a1998440000a9 | [
"Geometry",
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/57da5365a82a1998440000a9 | 7 kyu |
Write function heron which calculates the area of a triangle with sides a, b, and c (x, y, z in COBOL).
Heron's formula:
```math
\sqrt{s * (s - a) * (s - b) * (s - c)}
```
where
```math
s = \frac{a + b + c} 2
```
Output should have 2 digits precision.
| reference | def heron(a, b, c):
s = (a + b + c) / 2
return round((s * (s - a) * (s - b) * (s - c)) * * 0.5, 2)
| Heron's formula | 57aa218e72292d98d500240f | [
"Fundamentals"
] | https://www.codewars.com/kata/57aa218e72292d98d500240f | 7 kyu |
Determine the **area** of the largest square that can fit inside a circle with radius *r*. | algorithms | def area_largest_square(r):
return 2 * r * * 2
| Largest Square Inside A Circle | 5887a6fe0cfe64850800161c | [
"Geometry",
"Algorithms"
] | https://www.codewars.com/kata/5887a6fe0cfe64850800161c | 7 kyu |
`1, 246, 2, 123, 3, 82, 6, 41` are the divisors of number `246`. Squaring these divisors we get: `1, 60516, 4, 15129, 9, 6724, 36, 1681`. The sum of these squares is `84100` which is `290 * 290`.
#### Task
Find all integers between `m` and `n` (m and n integers with 1 <= m <= n) such that the sum of their squared divi... | reference | CACHE = {}
def squared_cache(number):
if number not in CACHE:
divisors = [x for x in range(1, number + 1) if number % x == 0]
CACHE[number] = sum([x * x for x in divisors])
return CACHE[number]
return CACHE[number]
def list_squared(m, n):
ret = []
for number in range(m... | Integers: Recreation One | 55aa075506463dac6600010d | [
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/55aa075506463dac6600010d | 5 kyu |
Prior to having fancy iPhones, teenagers would wear out their thumbs sending SMS
messages on candybar-shaped feature phones with 3x4 numeric keypads.
------- ------- -------
| | | ABC | | DEF |
| 1 | | 2 | | 3 |
------- ------- -------
------- ------- -------
| GHI | | JKL | | MNO |
... | reference | BUTTONS = ['1', 'abc2', 'def3',
'ghi4', 'jkl5', 'mno6',
'pqrs7', 'tuv8', 'wxyz9',
'*', ' 0', '#']
def presses(phrase):
return sum(1 + button . find(c) for c in phrase . lower() for button in BUTTONS if c in button)
| Multi-tap Keypad Text Entry on an Old Mobile Phone | 54a2e93b22d236498400134b | [
"Fundamentals"
] | https://www.codewars.com/kata/54a2e93b22d236498400134b | 6 kyu |
Number is a palindrome if it is equal to the number with digits in reversed order.
For example, `5`, `44`, `171`, `4884` are palindromes, and `43`, `194`, `4773` are not.
Write a function which takes a positive integer and returns the number of special steps needed to obtain a palindrome. The special step is: "reverse... | algorithms | def palindrome_chain_length(n):
steps = 0
while str(n) != str(n)[:: - 1]:
n = n + int(str(n)[:: - 1])
steps += 1
return steps
| Palindrome chain length | 525f039017c7cd0e1a000a26 | [
"Algorithms"
] | https://www.codewars.com/kata/525f039017c7cd0e1a000a26 | 7 kyu |
Create a function named `divisors`/`Divisors` that takes an integer `n > 1` and returns an array with all of the integer's divisors(except for 1 and the number itself), from smallest to largest. If the number is prime return the string '(integer) is prime' (`null` in C#, empty table in COBOL) (use `Either String a` in ... | algorithms | def divisors(num):
l = [a for a in range(2, num) if num % a == 0]
if len(l) == 0:
return str(num) + " is prime"
return l
| Find the divisors! | 544aed4c4a30184e960010f4 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/544aed4c4a30184e960010f4 | 7 kyu |
The Fibonacci numbers are the numbers in the following integer sequence (Fn):
>0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ...
such as
>F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1.
Given a number, say prod (for product), we search two Fibonacci numbers F(n) and F(n+1) verifying
>F(n) * F(n+1) = prod.
... | reference | def productFib(prod):
a, b = 0, 1
while prod > a * b:
a, b = b, a + b
return [a, b, prod == a * b]
| Product of consecutive Fib numbers | 5541f58a944b85ce6d00006a | [
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/5541f58a944b85ce6d00006a | 5 kyu |
### Description:
Replace all vowel to exclamation mark in the sentence. `aeiouAEIOU` is vowel.
### Examples
```
replace("Hi!") === "H!!"
replace("!Hi! Hi!") === "!H!! H!!"
replace("aeiou") === "!!!!!"
replace("ABCDE") === "!BCD!"
``` | reference | def replace_exclamation(s):
return '' . join('!' if c in 'aeiouAEIOU' else c for c in s)
| Exclamation marks series #11: Replace all vowel to exclamation mark in the sentence | 57fb09ef2b5314a8a90001ed | [
"Fundamentals"
] | https://www.codewars.com/kata/57fb09ef2b5314a8a90001ed | 8 kyu |
### Description:
Remove all exclamation marks from the end of sentence.
### Examples
```
"Hi!" ---> "Hi"
"Hi!!!" ---> "Hi"
"!Hi" ---> "!Hi"
"!Hi!" ---> "!Hi"
"Hi! Hi!" ---> "Hi! Hi"
"Hi" ---> "Hi"
```
| reference | def remove(s):
return s . rstrip("!")
| Exclamation marks series #2: Remove all exclamation marks from the end of sentence | 57faece99610ced690000165 | [
"Fundamentals"
] | https://www.codewars.com/kata/57faece99610ced690000165 | 8 kyu |
In a genetic algorithm, a population is a collection of candidates that may evolve toward a better solution.
We determine how close a chromosome is to a ideal solution by calculating its fitness.
https://www.codewars.com/kata/567b468357ed7411be00004a/train
You are given two parameters, the `population` containing all ... | algorithms | def mapPopulationFit(population, fitness):
return [ChromosomeWrap(c, fitness(c)) for c in population]
| Genetic Algorithm Series - #4 Get population and fitnesses | 567b468357ed7411be00004a | [
"Algorithms",
"Genetic Algorithms",
"Arrays"
] | https://www.codewars.com/kata/567b468357ed7411be00004a | 7 kyu |
In genetic algorithms, crossover is a genetic operator used to vary the programming of chromosomes from one generation to the next.
The one-point crossover consists in swapping one's cromosome part with another in a specific given point. The image bellow shows the crossover being applied on chromosomes `1011011001111`... | algorithms | def crossover(chromosome1, chromosome2, index):
return [chromosome1[: index] + chromosome2[index:], chromosome2[: index] + chromosome1[index:]]
| Genetic Algorithm Series - #3 Crossover | 567d71b93f8a50f461000019 | [
"Strings",
"Algorithms",
"Genetic Algorithms"
] | https://www.codewars.com/kata/567d71b93f8a50f461000019 | 7 kyu |
Mutation is a genetic operator used to maintain genetic diversity from one generation of a population of genetic algorithm chromosomes to the next.

A mutation here may happen on zero or more positions in a chromosome. It is going to check every position and by a given proba... | algorithms | from random import random
def mutate(chromosome, p):
res = ''
for s in chromosome:
res += str(1 - int(s)) if random() < p else s
return res
| Genetic Algorithm Series - #2 Mutation | 567b39b27d0a4606a5000057 | [
"Algorithms",
"Genetic Algorithms",
"Strings"
] | https://www.codewars.com/kata/567b39b27d0a4606a5000057 | 7 kyu |
A genetic algorithm is based in groups of chromosomes, called populations. To start our population of chromosomes we need to generate random binary strings with a specified length.
In this kata you have to implement a function `generate` that receives a `length` and has to return a random binary strign with `length` c... | algorithms | import random
def generate(length):
return ('{:0{}b}' . format(random . getrandbits(length), length)
if length > 0
else '')
| Genetic Algorithm Series - #1 Generate | 567d609f1c16d7369c000008 | [
"Strings",
"Fundamentals",
"Genetic Algorithms",
"Algorithms"
] | https://www.codewars.com/kata/567d609f1c16d7369c000008 | 7 kyu |
Your task is to write function ```findSum```.
Upto and including ```n```, this function will return the sum of all multiples of 3 and 5.
For example:
```findSum(5)``` should return 8 (3 + 5)
```findSum(10)``` should return 33 (3 + 5 + 6 + 9 + 10) | reference | def find(n):
return sum(e for e in range(1, n + 1) if e % 3 == 0 or e % 5 == 0)
| Sum of all the multiples of 3 or 5 | 57f36495c0bb25ecf50000e7 | [
"Fundamentals"
] | https://www.codewars.com/kata/57f36495c0bb25ecf50000e7 | 7 kyu |
Sexy primes are pairs of two primes that are `6` apart. In this kata, your job is to complete the function which returns `true` if `x` & `y` are *sexy*, `false` otherwise.
### Examples
```
5, 11 --> true
61, 67 --> true
7, 13 --> true
5, 7 --> false
1, 7 --> false (1 is not a prime)
```
Note: `x` & ... | reference | def sexy_prime(x, y):
return abs(x - y) == 6 and is_prime(x) and is_prime(y)
# A bit overkill for this kata, but excellent efficiency!
def is_prime(n):
factors = 0
for k in (2, 3):
while n % k == 0:
n / /= k
factors += 1
k = 5
step = 2
while k * k <= n:
if... | Sexy Primes <3 | 56b58d11e3a3a7cade000792 | [
"Fundamentals"
] | https://www.codewars.com/kata/56b58d11e3a3a7cade000792 | 7 kyu |
Error Handling is very important in coding and seems to be overlooked or not implemented properly.
#Task
Your task is to implement a function which takes a string as input and return an object containing the properties
vowels and consonants. The vowels property must contain the total count of vowels {a,e,i,o,u}, and ... | reference | def get_count(words=""):
if not isinstance(words, str):
return {'vowels': 0, 'consonants': 0}
letter = "" . join([c . lower() for c in words if c . isalpha()])
vowel = "" . join([c for c in letter if c in 'aeiou'])
consonant = "" . join([c for c in letter if c not in 'aeiou'])
return {'vow... | Invalid Input - Error Handling #1 | 55e6125ad777b540d9000042 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/55e6125ad777b540d9000042 | 7 kyu |
# Area of an arrow
An arrow is formed in a rectangle with sides `a` and `b` by joining the bottom corners to the midpoint of the top edge and the centre of the rectangle.
:
return a * b / 4.0
| Area of an arrow | 589478160c0f8a40870000bc | [
"Mathematics"
] | https://www.codewars.com/kata/589478160c0f8a40870000bc | 7 kyu |
## 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 ... | games | def pattern(n):
return '\n' . join(str(i) * i for i in xrange(1, n + 1))
| Complete The Pattern #1 | 5572f7c346eb58ae9c000047 | [
"Strings",
"ASCII Art",
"Puzzles"
] | https://www.codewars.com/kata/5572f7c346eb58ae9c000047 | 7 kyu |
In John's car the GPS records every `s` seconds the distance travelled from an origin (distances are measured in an arbitrary but consistent unit).
For example, below is part of a record with `s = 15`:
x = [0.0, 0.19, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25]
The sections are:
0.0-0.19, 0.19-0.5, 0.5-0.75, ... | reference | def gps(s, x):
if len(x) < 2:
return 0
a = max(x[i] - x[i - 1] for i in range(1, len(x)))
return a * 3600.0 / s
| Speed Control | 56484848ba95170a8000004d | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/56484848ba95170a8000004d | 7 kyu |
## 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... | games | def pattern(n):
return "\n" . join(["" . join([str(y) for y in range(n, x, - 1)]) for x in range(n)])
| Complete The Pattern #2 | 55733d3ef7c43f8b0700007c | [
"ASCII Art",
"Puzzles"
] | https://www.codewars.com/kata/55733d3ef7c43f8b0700007c | 7 kyu |
This program tests the life of an evaporator containing a gas.
We know the content of the evaporator (content in ml),
the percentage of foam or gas lost every day (evap_per_day) and the threshold (threshold) in percentage beyond which the evaporator is no longer useful.
All numbers are strictly positive.
The program... | reference | def evaporator(content, evap_per_day, threshold):
n = 0
current = 100
percent = 1 - evap_per_day / 100.0
while current > threshold:
current *= percent
n += 1
return n
| Deodorant Evaporator | 5506b230a11c0aeab3000c1f | [
"Fundamentals"
] | https://www.codewars.com/kata/5506b230a11c0aeab3000c1f | 7 kyu |
## Terminal game bug squashing
You are creating a text-based terminal version of your favorite board game. In the board game, each turn has six steps that must happen in this order: roll the dice, move, combat, get coins, buy more health, and print status.
---
You are using a library that already has the functions b... | reference | from preloaded import *
health = 100
position = 0
coins = 0
def main():
roll_dice()
move()
combat()
get_coins()
buy_health()
print_status()
| Grasshopper - Bug Squashing | 56214b6864fe8813f1000019 | [
"Fundamentals"
] | https://www.codewars.com/kata/56214b6864fe8813f1000019 | 8 kyu |
Oh no! Timmy hasn't followed instructions very carefully and forgot how to use the new String Template feature, Help Timmy with his string template so it works as he expects!
<div>
<a href="http://www.codewars.com/kata/55c7f90ac8025ebee1000062" style="text-decoration: none; font-size: 20px; font-family: monospace;">◄... | bug_fixes | def build_string(* args):
return "I like {}!" . format(", " . join(args))
| String Templates - Bug Fixing #5 | 55c90cad4b0fe31a7200001f | [
"Strings",
"Debugging"
] | https://www.codewars.com/kata/55c90cad4b0fe31a7200001f | 8 kyu |
<b>[Wilson primes](https://en.wikipedia.org/wiki/Wilson_prime)</b> satisfy the following condition.
Let ```P``` represent a prime number.
Then,
```
((P-1)! + 1) / (P * P)
```
should give a whole number.
Your task is to create a function that returns ```true``` if the given number is a <b>Wilson prime</b>.
~~~if... | reference | def am_i_wilson(n):
return n in (5, 13, 563)
| Wilson primes | 55dc4520094bbaf50e0000cb | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/55dc4520094bbaf50e0000cb | 8 kyu |
Let's build a matchmaking system that helps discover jobs for developers based on a number of factors.
One of the simplest, yet most important factors is compensation. As developers we know how much money we need to support our lifestyle, so we generally have a rough idea of the minimum salary we would be satisfied wi... | algorithms | def match(candidate, job):
return candidate['min_salary'] * 0.9 <= job['max_salary']
| Job Matching #1 | 56c22c5ae8b139416c00175d | [
"Algorithms"
] | https://www.codewars.com/kata/56c22c5ae8b139416c00175d | 8 kyu |
Create a method that accepts a list and an item, and returns `true` if the item belongs to the list, otherwise `false`.
~~~if:ruby
If you need help, here's some reference material: http://www.rubycuts.com/enum-include
~~~ | reference | def include(arr, item):
return item in arr
| Enumerable Magic - Does My List Include This? | 545991b4cbae2a5fda000158 | [
"Fundamentals"
] | https://www.codewars.com/kata/545991b4cbae2a5fda000158 | 8 kyu |
## Task
Create a method **all** which takes two params:
* a sequence
* a function (function pointer in C)
and returns **true** if the function in the params returns true for every element in the sequence. Otherwise, it should return false. If the sequence is empty, it should return true, since technically nothing fa... | reference | def _all(seq, fun):
return all(map(fun, seq))
| Enumerable Magic #1 - True for All? | 54598d1fcbae2ae05200112c | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/54598d1fcbae2ae05200112c | 8 kyu |
The male gametes or sperm cells in humans and other mammals are heterogametic and contain one of two types of sex chromosomes. They are either X or Y. The female gametes or eggs however, contain only the X sex chromosome and are homogametic.
The sperm cell determines the sex of an individual in this case. If a sperm c... | reference | def chromosome_check(sperm):
return 'Congratulations! You\'re going to have a {}.' . format('son' if 'Y' in sperm else 'daughter')
| Determine offspring sex based on genes XX and XY chromosomes | 56530b444e831334c0000020 | [
"Fundamentals"
] | https://www.codewars.com/kata/56530b444e831334c0000020 | 8 kyu |
<a href="http://imgur.com/hpDQY8o"><img src="http://i.imgur.com/hpDQY8o.png?1" title="source: imgur.com" /></a>
The medians of a triangle are the segments that unit the vertices with the midpoint of their opposite sides.
The three medians of a triangle intersect at the same point, called the barycenter or the centroid... | reference | def bar_triang(a, b, c):
return [round(sum(x) / 3.0, 4) for x in zip(a, b, c)]
| Localize The Barycenter of a Triangle | 5601c5f6ba804403c7000004 | [
"Fundamentals",
"Mathematics",
"Geometry"
] | https://www.codewars.com/kata/5601c5f6ba804403c7000004 | 8 kyu |
```if-not:julia,racket,elixir
Write a function that returns the total surface area and volume of a box as an array: `[area, volume]`
```
```if:julia
Write a function that returns the total surface area and volume of a box as a tuple: `(area, volume)`
```
```if:racket
Write a function that returns the total surface area... | reference | def get_size(w, h, d):
area = 2 * (w * h + h * d + w * d)
volume = w * h * d
return [area, volume]
| Surface Area and Volume of a Box | 565f5825379664a26b00007c | [
"Geometry",
"Fundamentals"
] | https://www.codewars.com/kata/565f5825379664a26b00007c | 8 kyu |
Complete the function which converts a binary number (given as a string) to a decimal number. | reference | def bin_to_decimal(inp):
return int(inp, 2)
| Bin to Decimal | 57a5c31ce298a7e6b7000334 | [
"Binary",
"Fundamentals"
] | https://www.codewars.com/kata/57a5c31ce298a7e6b7000334 | 8 kyu |
Basic regex tasks. Write a function that takes in a numeric code of any length. The function should check if the code begins with 1, 2, or 3 and return `true` if so. Return `false` otherwise.
You can assume the input will always be a number. | reference | def validate_code(code):
return str(code). startswith(('1', '2', '3'))
| validate code with simple regex | 56a25ba95df27b7743000016 | [
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/56a25ba95df27b7743000016 | 8 kyu |
#Description
Everybody has probably heard of the animal heads and legs problem from the earlier years at school. It goes:
```“A farm contains chickens and cows. There are x heads and y legs. How many chickens and cows are there?” ```
Where x <= 1000 and y <=1000
#Task
Assuming there are no other types of animals, ... | algorithms | def animals(heads, legs):
chickens, cows = 2 * heads - legs / 2, legs / 2 - heads
if chickens < 0 or cows < 0 or not chickens == int(chickens) or not cows == int(cows):
return "No solutions"
return chickens, cows
| Heads and Legs | 574c5075d27783851800169e | [
"Algebra",
"Logic",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/574c5075d27783851800169e | 8 kyu |
## Your Task
Given an array of Boolean values and a logical operator, return a Boolean result based on sequentially applying the operator to the values in the array.
## Examples
1) booleans = `[True, True, False]`, operator = `"AND"`
* `True` `AND` `True` -> `True`
* `True` `AND` `False` -> `False`
* return `Fal... | reference | def logical_calc(array, op):
res = array[0]
for x in array[1:]:
if op == "AND":
res &= x
elif op == "OR":
res |= x
else:
res ^= x
return res # boolean
| Logical calculator | 57096af70dad013aa200007b | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/57096af70dad013aa200007b | 8 kyu |
Write a simple regex to validate a username. Allowed characters are:
- lowercase letters,
- numbers,
- underscore
Length should be between 4 and 16 characters (both included). | reference | import re
def validate_usr(un):
return re . match('^[a-z0-9_]{4,16}$', un) != None
| Simple validation of a username with regex | 56a3f08aa9a6cc9b75000023 | [
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/56a3f08aa9a6cc9b75000023 | 8 kyu |
Sometimes, I want to quickly be able to convert miles per imperial gallon (`mpg`) into kilometers per liter (`kpl`).
Create an application that will display the number of kilometers per liter (output) based on the number of miles per imperial gallon (input).
```if-not:swift
Make sure to round off the result to two de... | algorithms | def converter(mpg):
# your code here
return round(mpg / 4.54609188 * 1.609344, 2)
| Miles per gallon to kilometers per liter | 557b5e0bddf29d861400005d | [
"Algorithms"
] | https://www.codewars.com/kata/557b5e0bddf29d861400005d | 8 kyu |
Given an array of 4 integers
```[a,b,c,d]``` representing two points ```(a, b)``` and ```(c, d)```, return a string representation of the slope of the line joining these two points.
For an undefined slope (division by 0), return ```undefined``` . Note that the "undefined" is case-sensitive.
```
a:x1
b:y1
... | reference | def find_slope(points):
x1, y1, x2, y2 = points
if x2 - x1 == 0:
return "undefined"
return str((y2 - y1) / / (x2 - x1))
| Find the Slope | 55a75e2d0803fea18f00009d | [
"Mathematics",
"Fundamentals",
"Algebra"
] | https://www.codewars.com/kata/55a75e2d0803fea18f00009d | 8 kyu |
Upon arriving at an interview, you are presented with a solid blue cube. The cube is then dipped in red paint, coating the entire surface of the cube. The interviewer then proceeds to cut through the cube in all three dimensions a certain number of times.
Your function takes as parameter the number of times the cube h... | games | ''' PROOF:
number of cuts = x
The total number of cubes = (x+1)^3
the number of all blue cubes = (x-1)^3
Number of cubes with one or more red squares:
= (x+1)^3 - (x-1)^3
= (x+1)(x+1)(x+1) - (x-1)(x-1)(x-1)
= x^3 + 3x^2 + 3x + 1 - (x^3 - 3x^2 + 3x -1 )
= 6x^2 + 2
'''
def count_squares(x):
return... | Count the number of cubes with paint on | 5763bb0af716cad8fb000580 | [
"Puzzles"
] | https://www.codewars.com/kata/5763bb0af716cad8fb000580 | 8 kyu |
# Subtract the sum
<span style="color:red">_NOTE! This kata can be more difficult than regular 8-kyu katas (lets say 7 or 6 kyu)_</span>
Complete the function which get an input number `n` such that `n >= 10` and `n < 10000`, then:
1. Sum all the digits of `n`.
2. Subtract the sum from `n`, and it is your n... | games | fruit = {1: 'kiwi', 2: 'pear', 3: 'kiwi', 4: 'banana', 5: 'melon', 6: 'banana', 7: 'melon',
8: 'pineapple', 9: 'apple', 10: 'pineapple', 11: 'cucumber', 12: 'pineapple',
13: 'cucumber', 14: 'orange', 15: 'grape', 16: 'orange', 17: 'grape', 18: 'apple',
19: 'grape', 20: 'cherry', 21: 'pear'... | Never visit a . . . !? | 56c5847f27be2c3db20009c3 | [
"Puzzles",
"Strings",
"Number Theory",
"Mathematics"
] | https://www.codewars.com/kata/56c5847f27be2c3db20009c3 | 8 kyu |
For a pole vaulter, it is very important to begin the approach run at the best possible starting mark. This is affected by numerous factors and requires fine-tuning in practice. But there is a guideline that will help a beginning vaulter start at approximately the right location for the so-called "three-step approach,"... | reference | def starting_mark(height):
return round(9.45 + (10.67 - 9.45) / (1.83 - 1.52) * (height - 1.52), 2)
| Pole Vault Starting Marks | 5786f8404c4709148f0006bf | [
"Fundamentals",
"Mathematics",
"Puzzles"
] | https://www.codewars.com/kata/5786f8404c4709148f0006bf | 8 kyu |
Given an array of numbers, check if any of the numbers are the character codes for lower case vowels (`a, e, i, o, u`).
If they are, change the array value to a string of that vowel.
Return the resulting array. | reference | def is_vow(inp):
return [chr(n) if chr(n) in "aeiou" else n for n in inp]
| Is there a vowel in there? | 57cff961eca260b71900008f | [
"Fundamentals",
"Strings",
"Arrays"
] | https://www.codewars.com/kata/57cff961eca260b71900008f | 8 kyu |
Finish the uefaEuro2016() function so it return string just like in the examples below:
```javascript
uefaEuro2016(['Germany', 'Ukraine'],[2, 0]) // "At match Germany - Ukraine, Germany won!"
uefaEuro2016(['Belgium', 'Italy'],[0, 2]) // "At match Belgium - Italy, Italy won!"
uefaEuro2016(['Portugal', 'Iceland'],[1, 1])... | reference | def uefa_euro_2016(teams, scores):
return f"At match { teams [ 0 ]} - { teams [ 1 ]} , { 'teams played draw.' if scores [ 0 ] == scores [ 1 ] else teams [ scores . index ( max ( scores ))] + ' won!' } "
| UEFA EURO 2016 | 57613fb1033d766171000d60 | [
"Strings",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/57613fb1033d766171000d60 | 8 kyu |
```if:python,php
In this kata you will have to write a function that takes `litres` and `price_per_litre` (**in dollar**) as arguments.
```
```if:csharp,java,javascript
In this kata you will have to write a function that takes `litres` and `pricePerLitre` (**in dollar**) as arguments.
```
Purchases of 2 or more litr... | reference | def fuel_price(litres, price_per_liter):
discount = int(min(litres, 10) / 2) * 5 / 100
return round((price_per_liter - discount) * litres, 2)
| Fuel Calculator: Total Cost | 57b58827d2a31c57720012e8 | [
"Mathematics",
"Fundamentals",
"Logic"
] | https://www.codewars.com/kata/57b58827d2a31c57720012e8 | 8 kyu |
Hey awesome programmer!
You've got much data to manage and of course you use zero-based and non-negative ID's to make each data item unique!
Therefore you need a method, which returns the <b>smallest unused ID</b> for your next new data item...
Note: The given array of used IDs may be unsorted. For test reasons ther... | algorithms | def next_id(arr):
t = 0
while t in arr:
t += 1
return t
| Smallest unused ID | 55eea63119278d571d00006a | [
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/55eea63119278d571d00006a | 8 kyu |
# Palindrome strings
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward. This includes capital letters, punctuation, and word dividers.
Implement a function that checks if something is a palindrome. If the input is a number, convert it to string first.
#... | reference | def is_palindrome(string):
return str(string)[:: - 1] == str(string)
| Palindrome Strings | 57a5015d72292ddeb8000b31 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/57a5015d72292ddeb8000b31 | 8 kyu |
Input: Array of elements
["h","o","l","a"]
Output: String with comma delimited elements of the array in th same order.
"h,o,l,a"
Note: if this seems too simple for you try [the next level](https://www.codewars.com/kata/5711d95f159cde99e0000249)
Note2: the input data can be: boolean array, array of objects, array o... | reference | def print_array(arr):
return ',' . join(map(str, arr))
| Printing Array elements with Comma delimiters | 56e2f59fb2ed128081001328 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/56e2f59fb2ed128081001328 | 8 kyu |
### Combine strings function
```if:coffeescript,haskell,javascript
Create a function named `combineNames` that accepts two parameters (first and last name). The function should return the full name.
```
```if:python,ruby
Create a function named (`combine_names`) that accepts two parameters (first and last name). The fu... | reference | def combine_names(first, last):
return first + " " + last
| Grasshopper - Combine strings | 55f73f66d160f1f1db000059 | [
"Fundamentals"
] | https://www.codewars.com/kata/55f73f66d160f1f1db000059 | 8 kyu |
Write a function which removes from string all non-digit characters and parse the remaining to number. E.g: "hell5o wor6ld" -> 56
Function:
```javascript
getNumberFromString(s)
```
```ruby
get_number_from_string(s)
```
```csharp
GetNumberFromString(string s)
``` | reference | def get_number_from_string(string):
return int('' . join(x for x in string if x . isdigit()))
| Get number from string | 57a37f3cbb99449513000cd8 | [
"Strings",
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/57a37f3cbb99449513000cd8 | 8 kyu |
Implement `String#digit?` (in Java `StringUtils.isDigit(String)`), which should return `true` if given object is a digit (0-9), `false` otherwise. | reference | def is_digit(n):
return n . isdigit() and len(n) == 1
| Regexp Basics - is it a digit? | 567bf4f7ee34510f69000032 | [
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/567bf4f7ee34510f69000032 | 8 kyu |
Your task is simply to count the total number of lowercase letters in a string.
## Examples
```
"abc" ===> 3
"abcABC123" ===> 3
"abcABC123!@€£#$%^&*()_-+=}{[]|\':;?/>.<,~" ===> 3
"" ===> 0;
"ABC123!@€£#$%^&*()_-+=}{[]|\':;?/>.<,~" ===> 0
"abcdefghijklmnopqrstuvwxyz" ===> 26
```
| reference | def lowercase_count(strng):
return sum(a . islower() for a in strng)
| Regex count lowercase letters | 56a946cd7bd95ccab2000055 | [
"Fundamentals",
"Regular Expressions",
"Algorithms"
] | https://www.codewars.com/kata/56a946cd7bd95ccab2000055 | 8 kyu |
There's a **"3 for 2"** (or **"2+1"** if you like) offer on mangoes. For a given quantity and price (per mango), calculate the total cost of the mangoes.
### Examples
```python
mango(2, 3) ==> 6 # 2 mangoes for $3 per unit = $6; no mango for free
mango(3, 3) ==> 6 # 2 mangoes for $3 per unit = $6; +1 mango for f... | reference | def mango(quantity, price):
return (quantity - quantity / / 3) * price
| Price of Mangoes | 57a77726bb9944d000000b06 | [
"Fundamentals"
] | https://www.codewars.com/kata/57a77726bb9944d000000b06 | 8 kyu |
Although shapes can be very different by nature, they can be sorted by the size of their area.
<b style='font-size:16px'>Task:</b>
<ul>
<li>Create different shapes that can be part of a sortable list. The sort order is based on the size of their respective areas:
<ul>
<li>The area of a <i><b style="color:lightgreen... | reference | from math import pi
class Shape:
def __init__(self, area): self . area = area
def __lt__(self, rhs): return self . area < rhs . area
class Rectangle (Shape):
def __init__(self, w, h): super(). __init__(w * h)
class Square (Rectangle):
def __init__(self, s): super(). __init__(s, s)
... | Sortable Shapes | 586669a8442e3fc307000048 | [
"Sorting",
"Fundamentals",
"Mathematics",
"Design Patterns",
"Arrays",
"Geometry"
] | https://www.codewars.com/kata/586669a8442e3fc307000048 | 6 kyu |
### Color Ghost
Create a class Ghost
Ghost objects are instantiated without any arguments.
Ghost objects are given a random color attribute of "white" or "yellow" or "purple" or "red" when instantiated
```javascript
ghost = new Ghost();
ghost.color //=> "white" or "yellow" or "purple" or "red"
```
```coffeescript
gh... | reference | import random
class Ghost (object):
def __init__(self):
self . color = random . choice(["white", "yellow", "purple", "red"])
| Color Ghost | 53f1015fa9fe02cbda00111a | [
"Object-oriented Programming",
"Fundamentals"
] | https://www.codewars.com/kata/53f1015fa9fe02cbda00111a | 8 kyu |
# back·ro·nym
> An acronym deliberately formed from a phrase whose initial letters spell out a particular word or words, either to create a memorable name or as a fanciful explanation of a word's origin.
>
> "Biodiversity Serving Our Nation", or BISON
*(from https://en.oxforddictionaries.com/definition/backronym)*
... | reference | def make_backronym(acronym):
return ' ' . join(dictionary[char . upper()] for char in acronym)
| makeBackronym | 55805ab490c73741b7000064 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/55805ab490c73741b7000064 | 7 kyu |
<h1>Template Strings</h1>
Template Strings, this kata is mainly aimed at the new JS ES6 Update introducing Template Strings
<h3>Task</h3>
Your task is to return the correct string using the Template String Feature.
<h3>Input</h3>
Two Strings, no validation is needed.
<h3>Output</h3>
You must output a string containi... | reference | def temple_strings(obj, feature):
return f" { obj } are { feature } "
| Template Strings | 55a14f75ceda999ced000048 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/55a14f75ceda999ced000048 | 8 kyu |
Imagine you are creating a game where the user has to guess the correct number. But there is a limit of how many guesses the user can do.
- If the user tries to guess more than the limit, the function should throw an error.
- If the user guess is right it should return true.
- If the user guess is wrong it should retu... | reference | class Guesser:
def __init__(self, number, lives):
self . number = number
self . lives = lives
def guess(self, n):
if self . lives < 1:
raise "Too many guesses!"
if self . number == n:
return True
self . lives -= 1
return False
| Finish Guess the Number Game | 568018a64f35f0c613000054 | [
"Fundamentals",
"Object-oriented Programming"
] | https://www.codewars.com/kata/568018a64f35f0c613000054 | 8 kyu |
Hey Codewarrior!
You already implemented a <b>Cube</b> class, but now we need your help again! I'm talking about constructors. We don't have one. Let's code two: One taking an integer and one handling no given arguments!
Also we got a problem with negative values. Correct the code so negative values will be switche... | reference | class Cube:
def __init__(self, side=0):
self . _side = abs(side)
def get_side(self):
"""Return the side of the Cube"""
return self . _side
def set_side ( self , new_side ):
"""Set the value of the Cube's side."""
self . _side = abs ( new_side ) | Playing with cubes II | 55c0ac142326fdf18d0000af | [
"Fundamentals",
"Object-oriented Programming"
] | https://www.codewars.com/kata/55c0ac142326fdf18d0000af | 8 kyu |
## Fix the function
I created this function to add five to any number that was passed in to it and return the new value.
It doesn't throw any errors but it returns the wrong number.
Can you help me fix the function? | reference | def add_five(num):
return num + 5
| Grasshopper - Basic Function Fixer | 56200d610758762fb0000002 | [
"Fundamentals"
] | https://www.codewars.com/kata/56200d610758762fb0000002 | 8 kyu |
You will be given a list of strings. You must sort it alphabetically (case-sensitive, and based on the ASCII values of the chars) and then return the first value.
The returned value must be a string, and have `"***"` between each of its letters.
You should not remove or add elements from/to the array. | reference | def two_sort(lst):
return '***' . join(min(lst))
| Sort and Star | 57cfdf34902f6ba3d300001e | [
"Fundamentals",
"Strings",
"Arrays",
"Sorting"
] | https://www.codewars.com/kata/57cfdf34902f6ba3d300001e | 8 kyu |
This is the first step to understanding FizzBuzz.
Your inputs:
a positive integer, n, greater than or equal to one.
n is provided, you have NO CONTROL over its value.
Your expected output is an array of positive integers from 1 to n (inclusive).
Your job is to write an algorithm that gets you from the input to the... | reference | def pre_fizz(n):
# your code here
return list(range(1, n + 1))
| Pre-FizzBuzz Workout #1 | 569e09850a8e371ab200000b | [
"Fundamentals"
] | https://www.codewars.com/kata/569e09850a8e371ab200000b | 8 kyu |
A startup office has an ongoing problem with its bin. Due to low budgets, they don't hire cleaners. As a result, the staff are left to voluntarily empty the bin. It has emerged that a voluntary system is not working and the bin is often overflowing. One staff member has suggested creating a rota system based upon the s... | reference | def bin_rota(arr):
return [name for i, row in enumerate(arr) for name in (reversed(row) if i & 1 else row)]
| The Lazy Startup Office | 578fdcfc75ffd1112c0001a1 | [
"Arrays",
"Matrix",
"Fundamentals"
] | https://www.codewars.com/kata/578fdcfc75ffd1112c0001a1 | 7 kyu |
```if-not:rust
Your task is to write a function `toLeetSpeak` that converts a regular english sentence to Leetspeak.
```
```if:rust
Your task is to write a function `to_leet_speak` that converts a regular english sentence to Leetspeak.
```
More about LeetSpeak You can read at wiki -> https://en.wikipedia.org/wiki/Leet... | reference | def to_leet_speak(str):
return str . translate(str . maketrans("ABCEGHILOSTZ", "@8(36#!10$72"))
| ToLeetSpeak | 57c1ab3949324c321600013f | [
"Fundamentals"
] | https://www.codewars.com/kata/57c1ab3949324c321600013f | 7 kyu |
Each number should be formatted that it is rounded to two decimal places. You don't need to check whether the input is a valid number because only valid numbers are used in the tests.
```
Example:
5.5589 is rounded 5.56
3.3424 is rounded 3.34
``` | reference | def two_decimal_places(n):
return round(n, 2)
| Formatting decimal places #0 | 5641a03210e973055a00000d | [
"Fundamentals"
] | https://www.codewars.com/kata/5641a03210e973055a00000d | 8 kyu |
Write a function `partlist` that gives all the ways to divide a list (an array) of at least two elements into two non-empty parts.
- Each two non empty parts will be in a pair (or an array for languages without tuples or a `struct`in C - C: see Examples test Cases - )
- Each part will be in a string
- Elements of a p... | reference | def partlist(arr):
return [(' ' . join(arr[: i]), ' ' . join(arr[i:])) for i in range(1, len(arr))]
| Parts of a list | 56f3a1e899b386da78000732 | [
"Arrays",
"Lists",
"Data Structures",
"Algorithms"
] | https://www.codewars.com/kata/56f3a1e899b386da78000732 | 7 kyu |
#Get the averages of these numbers
Write a method, that gets an array of integer-numbers and return an array of the averages of each integer-number and his follower, if there is one.
Example:
```
Input: [ 1, 3, 5, 1, -10]
Output: [ 2, 4, 3, -4.5]
```
If the array has 0 or 1 values or is null, your method should ret... | algorithms | def averages(arr):
return [(arr[x] + arr[x + 1]) / 2 for x in range(len(arr or []) - 1)]
| Averages of numbers | 57d2807295497e652b000139 | [
"Fundamentals",
"Logic",
"Algorithms"
] | https://www.codewars.com/kata/57d2807295497e652b000139 | 7 kyu |
# Instructions
Write a function that takes a single non-empty string of only lowercase and uppercase ascii letters (`word`) as its argument, and returns an ordered list containing the indices of all capital (uppercase) letters in the string.
# Example (Input --> Output)
```
"CodEWaRs" --> [0,3,4,6]
``` | reference | def capitals(word):
return [i for (i, c) in enumerate(word) if c . isupper()]
| Find the capitals | 539ee3b6757843632d00026b | [
"Strings",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/539ee3b6757843632d00026b | 7 kyu |
Two tortoises named ***A*** and ***B*** must run a race. ***A*** starts with an average speed of ```720 feet per hour```.
Young ***B*** knows she runs faster than ***A***, and furthermore has not finished her cabbage.
When she starts, at last, she can see that ***A*** has a `70 feet lead` but ***B***'s speed is `850 f... | reference | from datetime import datetime, timedelta
def race(v1, v2, g):
if v1 >= v2:
return None
else:
sec = timedelta(seconds=int((g * 3600 / (v2 - v1))))
d = datetime(1, 1, 1) + sec
return [d . hour, d . minute, d . second]
| Tortoise racing | 55e2adece53b4cdcb900006c | [
"Fundamentals",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/55e2adece53b4cdcb900006c | 6 kyu |
You are given two arrays `a1` and `a2` of strings. Each string is composed with letters from `a` to `z`.
Let `x` be any string in the first array and `y` be any string in the second array.
`Find max(abs(length(x) − length(y)))`
If `a1` and/or `a2` are empty return `-1` in each language
except in Haskell (F#) where... | reference | def mxdiflg(a1, a2):
if a1 and a2:
return max(
len(max(a1, key=len)) - len(min(a2, key=len)),
len(max(a2, key=len)) - len(min(a1, key=len)))
return - 1
| Maximum Length Difference | 5663f5305102699bad000056 | [
"Fundamentals"
] | https://www.codewars.com/kata/5663f5305102699bad000056 | 7 kyu |
You have a positive number `n` consisting of digits.
You can do **at most** one operation:
Choosing the index of a digit in the number, remove this digit at that index and insert it back to another or at the same place in the number in order to find the smallest number you can get.
#### Task:
Return an array or a tu... | reference | def smallest(n):
s = str(n)
min1, from1, to1 = n, 0, 0
for i in range ( len ( s )):
removed = s [: i ] + s [ i + 1 :]
for j in range ( len ( removed ) + 1 ):
num = int ( removed [: j ] + s [ i ] + removed [ j :])
if ( num < min1 ):
min1 , from1 , to1 = num , i , j
return [ min1 , from... | Find the smallest | 573992c724fc289553000e95 | [
"Fundamentals"
] | https://www.codewars.com/kata/573992c724fc289553000e95 | 5 kyu |
Take an integer `n (n >= 0)` and a digit `d (0 <= d <= 9)` as an integer.
Square all numbers `k (0 <= k <= n)` between 0 and n.
Count the numbers of digits `d` used in the writing of all the `k**2`.
Implement the function taking `n` and `d` as parameters and returning this count.
#### Examples:
```
n = 10, d = 1... | reference | def nb_dig(n, d):
return sum(str(i * i). count(str(d)) for i in range(n + 1))
| Count the Digit | 566fc12495810954b1000030 | [
"Fundamentals"
] | https://www.codewars.com/kata/566fc12495810954b1000030 | 7 kyu |
You are given a list/array which contains only integers (positive and negative). Your job is to sum only the numbers that are the same and consecutive. The result should be one list.
Extra credit if you solve it in one line. You can assume there is never an empty list/array and there will always be an integer.
Same ... | algorithms | from itertools import groupby
def sum_consecutives(s):
return [sum(group) for c, group in groupby(s)]
| Sum consecutives | 55eeddff3f64c954c2000059 | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/55eeddff3f64c954c2000059 | 6 kyu |
Let us begin with an example:
Take a number: `56789`. Rotate left, you get `67895`.
Keep the first digit in place and rotate left the other digits: `68957`.
Keep the first two digits in place and rotate the other ones: `68579`.
Keep the first three digits and rotate left the rest:
`68597`.
Now it is over since ... | reference | def max_rot(n):
s, arr = str(n), [n]
for i in range(len(s)):
s = s[: i] + s[i + 1:] + s[i]
arr . append(int(s))
return max(arr)
| Rotate for a Max | 56a4872cbb65f3a610000026 | [
"Algorithms"
] | https://www.codewars.com/kata/56a4872cbb65f3a610000026 | 7 kyu |
----
Vampire Numbers
----
Our loose definition of [Vampire Numbers](http://en.wikipedia.org/wiki/Vampire_number) can be described as follows:
```python
6 * 21 = 126
# 6 and 21 would be valid 'fangs' for a vampire number as the
# digits 6, 1, and 2 are present in both the product and multiplicands
10 * 11 = 110
# 11... | reference | def vampire_test(x, y):
return sorted(str(x * y)) == sorted(str(x) + str(y))
| Vampire Numbers | 54d418bd099d650fa000032d | [
"Fundamentals"
] | https://www.codewars.com/kata/54d418bd099d650fa000032d | 7 kyu |
The word `i18n` is a common abbreviation of `internationalization` in the developer community, used instead of typing the whole word and trying to spell it correctly. Similarly, `a11y` is an abbreviation of `accessibility`.
Write a function that takes a string and turns any and all "words" (see below) within that stri... | reference | import re
regex = re . compile('[a-z]{4,}', re . IGNORECASE)
def replace(match):
word = match . group(0)
return word[0] + str(len(word) - 2) + word[- 1]
def abbreviate(s):
return regex . sub(replace, s)
| Word a10n (abbreviation) | 5375f921003bf62192000746 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5375f921003bf62192000746 | 6 kyu |
Implement a pseudo-encryption algorithm which given a string `S` and an integer `N` concatenates all the odd-indexed characters of `S` with all the even-indexed characters of `S`, this process should be repeated `N` times.
Examples:
```
encrypt("012345", 1) => "135024"
encrypt("012345", 2) => "135024" -> "30415... | reference | def decrypt(text, n):
if text in ("", None):
return text
ndx = len(text) / / 2
for i in range(n):
a = text[: ndx]
b = text[ndx:]
text = "" . join(b[i: i + 1] + a[i: i + 1] for i in range(ndx + 1))
return text
def encrypt(text, n):
for i in range(n):
text = text[1::... | Simple Encryption #1 - Alternating Split | 57814d79a56c88e3e0000786 | [
"Cryptography",
"Algorithms",
"Strings",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/57814d79a56c88e3e0000786 | 6 kyu |
In English and programming, groups can be made using symbols such as `()` and `{}` that change meaning. However, these groups must be closed in the correct order to maintain correct syntax.
Your job in this kata will be to make a program that checks a string for correct grouping. For instance, the following groups are... | algorithms | BRACES = {'(': ')', '[': ']', '{': '}'}
def group_check(s):
stack = []
for b in s:
c = BRACES . get(b)
if c:
stack . append(c)
elif not stack or stack . pop() != b:
return False
return not stack
| Checking Groups | 54b80308488cb6cd31000161 | [
"Algorithms",
"Data Structures",
"Strings",
"Data Types"
] | https://www.codewars.com/kata/54b80308488cb6cd31000161 | 6 kyu |
### Count the number of Duplicates
Write a function that will return the count of **distinct case-insensitive** alphabetic characters and numeric digits that occur more than
once in the input string.
The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits.
### Ex... | reference | def duplicate_count(s):
return len([c for c in set(s . lower()) if s . lower(). count(c) > 1])
| Counting Duplicates | 54bf1c2cd5b56cc47f0007a1 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/54bf1c2cd5b56cc47f0007a1 | 6 kyu |
There is a bus moving in the city which takes and drops some people at each bus stop.
You are provided with a list (or array) of integer pairs. Elements of each pair represent the number of people that get on the bus (the first item) and the number of people that get off the bus (the second item) at a bus stop.
Your ... | reference | def number(bus_stops):
return sum([stop[0] - stop[1] for stop in bus_stops])
| Number of People in the Bus | 5648b12ce68d9daa6b000099 | [
"Fundamentals"
] | https://www.codewars.com/kata/5648b12ce68d9daa6b000099 | 7 kyu |
My little sister came back home from school with the following task:
given a squared sheet of paper she has to cut it in pieces
which, when assembled, give squares the sides of which form
an increasing sequence of numbers.
At the beginning it was lot of fun but little by little we were tired of seeing the pile of torn ... | reference | def decompose(n, a=None):
if a == None:
a = n * n
if a == 0:
return []
for m in range(min(n - 1, int(a * * .5)), 0, - 1):
sub = decompose(m, a - m * m)
if sub != None:
return sub + [m]
| Square into Squares. Protect trees! | 54eb33e5bc1a25440d000891 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/54eb33e5bc1a25440d000891 | 4 kyu |
You are given a string containing 0's, 1's and one or more '?', where `?` is a wildcard that can be `0` or `1`.
Return an array containing all the possibilities you can reach substituing the `?` for a value.
## Examples
```
'101?' -> ['1010', '1011']
'1?1?' -> ['1010', '1110', '1011', '1111']
```
Notes:
* Don't wo... | games | from itertools import product
def possibilities(pattern):
pattern_format = pattern . replace('?', '{}')
return [pattern_format . format(* values) for values in product('10', repeat=pattern . count('?'))]
| 1's, 0's and wildcards | 588f3e0dfa74475a2600002a | [
"Combinatorics",
"Strings",
"Permutations",
"Puzzles"
] | https://www.codewars.com/kata/588f3e0dfa74475a2600002a | 5 kyu |
Given an array (arr) as an argument complete the function `countSmileys` that should return the total number of smiling faces.
Rules for a smiling face:
- Each smiley face must contain a valid pair of eyes. Eyes can be marked as `:` or `;`
- A smiley face can have a nose but it does not have to. Valid characters for... | reference | from re import findall
def count_smileys(arr):
return len(list(findall(r"[:;][-~]?[)D]", " " . join(arr))))
| Count the smiley faces! | 583203e6eb35d7980400002a | [
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/583203e6eb35d7980400002a | 6 kyu |
Every now and then people in the office moves teams or departments. Depending what people are doing with their time they can become more or less boring. Time to assess the current team.
```if-not:java
You will be provided with an object(staff) containing the staff names as keys, and the department they work in as valu... | reference | def boredom(staff):
lookup = {
"accounts": 1,
"finance": 2,
"canteen": 10,
"regulation": 3,
"trading": 6,
"change": 6,
"IS": 8,
"retail": 5,
"cleaning": 4,
"pissing about": 25
}
n = sum(lookup[s] for s in staff . va... | The Office II - Boredom Score | 57ed4cef7b45ef8774000014 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/57ed4cef7b45ef8774000014 | 7 kyu |
Your task is to write a function which returns the sum of a sequence of integers.
The sequence is defined by 3 non-negative values: **begin**, **end**, **step**.
If **begin** value is greater than the **end**, your function should return **0**.
If **end** is not the result of an integer number of steps, then don't ad... | reference | def sequence_sum(start, end, step):
return sum(range(start, end + 1, step))
| Sum of a sequence | 586f6741c66d18c22800010a | [
"Fundamentals",
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/586f6741c66d18c22800010a | 7 kyu |
I need to save some money to buy a gift. I think I can do something like that:
First week (W0) I save nothing on Sunday, 1 on Monday, 2 on Tuesday... 6 on Saturday,
second week (W1) 2 on Monday... 7 on Saturday and so on according to the table below where the days are numbered from 0 to 6.
Can you tell me how much I ... | algorithms | def finance(n):
return n * (n + 1) * (n + 2) / 2
| Financing Plan on Planet XY140Z-n | 559ce00b70041bc7b600013d | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/559ce00b70041bc7b600013d | 6 kyu |
> "7777...*8?!??!*", exclaimed Bob, "I missed it again! Argh!" Every time there's an interesting number coming up, he notices and then promptly forgets. Who *doesn't* like catching those one-off interesting mileage numbers?
Let's make it so Bob **never** misses another interesting number. We've hacked into his car... | algorithms | def is_incrementing(number): return str(number) in '1234567890'
def is_decrementing(number): return str(number) in '9876543210'
def is_palindrome(number): return str(number) == str(number)[:: - 1]
def is_round(number): return set(str(number)[1:]) == set('0')
def is_interesting(number, awesome_phrase... | Catching Car Mileage Numbers | 52c4dd683bfd3b434c000292 | [
"Algorithms"
] | https://www.codewars.com/kata/52c4dd683bfd3b434c000292 | 4 kyu |
# Story
Your online store likes to give out coupons for special occasions. Some customers try to cheat the system by entering invalid codes or using expired coupons.
# Task
Your mission:
Write a function called `checkCoupon` which verifies that a coupon code is valid and not expired.
A coupon is no more valid on ... | reference | import datetime
def check_coupon(entered_code, correct_code, current_date, expiration_date):
if entered_code is correct_code:
return (datetime . datetime . strptime(current_date, '%B %d, %Y') <= datetime . datetime . strptime(expiration_date, '%B %d, %Y'))
return False
| The Coupon Code | 539de388a540db7fec000642 | [
"Date Time",
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/539de388a540db7fec000642 | 7 kyu |
Create a function with two arguments that will return an array of the first `n` multiples of `x`.
Assume both the given number and the number of times to count will be positive numbers greater than `0`.
Return the results as an array or list ( depending on language ).
### Examples
```cpp
countBy(1,10) should ret... | reference | def count_by(x, n):
return [i * x for i in range(1, n + 1)]
| Count by X | 5513795bd3fafb56c200049e | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/5513795bd3fafb56c200049e | 8 kyu |
## Task
Your task is to write a function which returns the `n`-th term of the following series, which is the sum of the first `n` terms of the sequence (`n` is the input parameter).
```math
\mathrm{Series:}\quad 1 + \frac14 + \frac17 + \frac1{10} + \frac1{13} + \frac1{16} + \dots
```
You will need to figure out the ... | reference | def series_sum(n):
return '{:.2f}' . format(sum(1.0 / (3 * i + 1) for i in range(n)))
| Sum of the first nth term of Series | 555eded1ad94b00403000071 | [
"Fundamentals"
] | https://www.codewars.com/kata/555eded1ad94b00403000071 | 7 kyu |
<h1>Switch/Case - Bug Fixing #6</h1>
<p>
Oh no! Timmy's evalObject function doesn't work. He uses Switch/Cases to evaluate the given properties of an object, can you fix timmy's function?
</p>
<!--
<br><br><br><br>
<select id="collectionSelect"/>
<iframe style="visibility:hidden;display:none;" onload="
(function(e){
v... | bug_fixes | def eval_object(v):
return {"+": v['a'] + v['b'],
"-": v['a'] - v['b'],
"/": v['a'] / v['b'],
"*": v['a'] * v['b'],
"%": v['a'] % v['b'],
"**": v['a'] * * v['b'], }. get(v['operation'])
| Switch/Case - Bug Fixing #6 | 55c933c115a8c426ac000082 | [
"Debugging"
] | https://www.codewars.com/kata/55c933c115a8c426ac000082 | 8 kyu |
<h1>Failed Filter - Bug Fixing #3</h1>
Oh no, Timmy's filter doesn't seem to be working? Your task is to fix the FilterNumber function to remove all the numbers from the string.
| bug_fixes | def filter_numbers(string):
return "" . join(x for x in string if not x . isdigit())
| Failed Filter - Bug Fixing #3 | 55c606e6babfc5b2c500007c | [
"Strings",
"Debugging"
] | https://www.codewars.com/kata/55c606e6babfc5b2c500007c | 7 kyu |
**Problem Description:**
Oh no, Timmy's received some hate mail recently but he knows better. Help Timmy fix his regex filter so he can be awesome again!
**Task:**
You are given a string `phrase` containing some potentially offensive words such as "bad," "mean," "ugly," "horrible," and "hideous." Timmy wants to repl... | bug_fixes | import re
def filter_words(phrase):
return re . sub("(bad|mean|ugly|horrible|hideous)", "awesome",
phrase, flags=re . IGNORECASE)
| Regex Failure - Bug Fixing #2 | 55c423ecf847fbcba100002b | [
"Debugging"
] | https://www.codewars.com/kata/55c423ecf847fbcba100002b | 7 kyu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.