description
stringlengths 38
154k
| category
stringclasses 5
values | solutions
stringlengths 13
289k
| name
stringlengths 3
179
| id
stringlengths 24
24
| tags
sequencelengths 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 `$10^{92}$` decimal digits, is `$6$`. Also, please take `$0^0$` to be `$1$`.
You may assume that the input will always be valid.
## Examples
```haskell
lastDigit 4 1 `shouldBe` 4
lastDigit 4 2 `shouldBe` 6
lastDigit 9 7 `shouldBe` 9
lastDigit 10 (10^10) `shouldBe` 0
lastDigit (2^200) (2^300) `shouldBe` 6
```
```javascript
lastDigit(4n, 1n) // returns 4n
lastDigit(4n, 2n) // returns 6n
lastDigit(9n, 7n) // returns 9n
lastDigit(10n,10000000000n) // returns 0n
```
```python
last_digit(4, 1) # returns 4
last_digit(4, 2) # returns 6
last_digit(9, 7) # returns 9
last_digit(10, 10 ** 10) # returns 0
last_digit(2 ** 200, 2 ** 300) # returns 6
```
```kotlin
lastDigit(4, 1) # returns 4
lastDigit(4, 2) # returns 6
lastDigit(9, 7) # returns 9
lastDigit(10, 10 ** 10) # returns 0
lastDigit(2 ** 200, 2 ** 300) # returns 6
```
```ruby
last_digit(4, 1) # returns 4
last_digit(4, 2) # returns 6
last_digit(9, 7) # returns 9
last_digit(10, 10 ** 10) # returns 0
last_digit(2 ** 200, 2 ** 300) # returns 6
```
```c
last_digit("4", "1") /* returns 4 */
last_digit("4", "2") /* returns 6 */
last_digit("9", "7") /* returns 9 */
last_digit("10","10000000000") /* returns 0 */
```
```nasm
.x: db `4\0`
.y: db `1\0`
mov rdi, .x
mov rsi, .y
call last_digit ; EAX <- 4
.x: db `4\0`
.y: db `2\0`
mov rdi, .x
mov rsi, .y
call last_digit ; EAX <- 6
.x: db `9\0`
.y: db `7\0`
mov rdi, .x
mov rsi, .y
call last_digit ; EAX <- 9
.x: db `10\0`
.y: db `10000000000\0`
mov rdi, .x
mov rsi, .y
call last_digit ; EAX <- 0
```
```cpp
last_digit("4", "1") // returns 4
last_digit("4", "2") // returns 6
last_digit("9", "7") // returns 9
last_digit("10","10000000000") // returns 0
```
```r
last_digit("4", "1") # returns 4
last_digit("4", "2") # returns 6
last_digit("9", "7") # returns 9
last_digit("10","10000000000") # returns 0
```
```rust
last_digit("4", "1") // returns 4
last_digit("4", "2") // returns 6
last_digit("9", "7") // returns 9
last_digit("10","10000000000") // returns 0
```
```purescript
lastDigit "4" "1" -- => 4
lastDigit "4" "2" -- => 6
lastDigit "9" "7" -- => 9
lastDigit "10" "10000000000" -- => 0
```
```cobol
LastDigit("4", "1") -- => 4
LastDigit("4", "2") -- => 6
LastDigit("9", "7") -- => 9
LastDigit("10", "10000000000") -- => 0
```
```csharp
GetLastDigit(4, 1) // returns 4
GetLastDigit(4, 2) // returns 6
GetLastDigit(9, 7) // returns 9
GetLastDigit(10, 10000000000) // returns 0
```
```java
lastDigit(new BigInteger("4"), new BigInteger("1")) // returns 4
lastDigit(new BigInteger("4"), new BigInteger("2")) // returns 6
lastDigit(new BigInteger("9"), new BigInteger("7")) // returns 9
lastDigit(new BigInteger("10"), new BigInteger("10000000000")) // returns 0
```
___
## Remarks
### C++, R, PureScript, COBOL | 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`
until last row:
`1/9, 2/10, 3/11, 4/12, 5/13, 6/14, 7/15, 8/16`
When all numbers are on the chessboard each in turn we toss a coin. The one who get "head" wins and
the other gives him, in dollars, the **sum of the numbers on the chessboard**.
We play for fun, the dollars come from a monopoly game!
#### Task
How much can I (or my friend) win or loses for each game if the chessboard has n rows and n columns? Add all of the fractional values on an n by n sized board and give the answer as a simplified fraction.
#### See Sample Tests for each language
- *Ruby, Python, JS, Coffee, Clojure, PHP, Elixir, Crystal, Typescript, Go:*
The function called 'game' with parameter n (integer >= 0) returns as result an irreducible fraction written as an array of integers: [numerator, denominator].
If the denominator is 1 return [numerator].
- *Haskell, Elm:*
'game' returns either a "Left Integer" if denominator is 1 otherwise
"Right (Integer, Integer)"
- *Prolog, COBOL:*
'game' returns an irreducible fraction written as an array of integers: [numerator, denominator].
If the denominator is 1 return [numerator, 1].
- *Java, C#, C++, F#, Swift, Reason, Kotlin, Pascal, Perl:*
'game' returns a string that mimicks the array returned in Ruby, Python, JS, etc...
- *Fortran, Bash: 'game' returns a string*
- *Forth:*
return on the stack the numerator and the denominator (even if the denominator is 1)
- In Fortran - as in any other language - the returned string is not permitted to contain any redundant trailing whitespace: you can use dynamically allocated character strings.
| 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):
return [n * * 2, 2] if n % 2 else [n * * 2 / / 2]
| 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],...]`, start and end are the index of `arr` and start always less than end. Your task is to calculate the sum value of each range (start index and end index are both inclusive), and return the maximum sum value.
```
```if:ruby
Given an array (`arr`) of integers and an array (`ranges`) of ranges (e.g. `[[1, 32], [16, 24],...]`), which represent an index range of `arr`, calculate the sum of each range (start index and end index are both inclusive) of `arr`, and return the maximum sum.
```
```if:php
Given an array `$a` that contains some integers and a `$range` list such as `[[$start1, $end1], [$start2, $end2], ... ]` where `$start(n)` and `$end(n)` are valid keys of the non-associative array `$a` and `$start(n)` is always guaranteed to be strictly less than `$end(n)`. Your task is to calculate the sum value of each range (start index and end index are both inclusive) and return the maximum sum value.
```
```if:haskell
Given a list `arr` that contains some integers(positive, negative or 0), and a `range` list such as `[(start1,end1),(start2,end2),...]`, start and end are the index of `arr` and start always less than end. Your task is to calculate the sum value of each range (start index and end index are both inclusive), and return the maximum sum value.
```
For example:
```javascript
Given arr = [1,-2,3,4,-5,-4,3,2,1],
range = [[1,3],[0,4],[6,8]]
should return 6
calculation process:
range[1,3] = arr[1]+arr[2]+arr[3] = 5
range[0,4] = arr[0]+arr[1]+arr[2]+arr[3]+arr[4] = 1
range[6,8] = arr[6]+arr[7]+arr[8] = 6
So the maximum sum value is 6
```
```ruby
arr = [1,-2,3,4,-5,-4,3,2,1]
ranges = [[1,3],[0,4],[6,8]]
max_sum(arr,ranges) should return 6
Process:
range[1,3] = arr[1] + arr[2] + arr[3] = 5
range[0,4] = arr[0] + arr[1] + arr[2] + arr[3] + arr[4] = 1
range[6,8] = arr[6] + arr[7] + arr[8] = 6
Result: Maximum range sum is 6
```
```php
Given arr = [1,-2,3,4,-5,-4,3,2,1],
range = [[1,3],[0,4],[6,8]]
should return 6
calculation process:
range[1,3] = arr[1]+arr[2]+arr[3] = 5
range[0,4] = arr[0]+arr[1]+arr[2]+arr[3]+arr[4] = 1
range[6,8] = arr[6]+arr[7]+arr[8] = 6
So the maximum sum value is 6
```
```haskell
Given arr = [1,-2,3,4,-5,-4,3,2,1],
range = [(1,3),(0,4),(6,8)]
should return 6
calculation process:
range(1,3) = arr[1]+arr[2]+arr[3] = 5
range(0,4) = arr[0]+arr[1]+arr[2]+arr[3]+arr[4] = 1
range(6,8) = arr[6]+arr[7]+arr[8] = 6
So the maximum sum value is 6
```
# Note:
- `arr`/`$a` always has at least 5 elements;
- `range`/`$range`/`ranges` always has at least 1 element;
- All inputs are valid;
- This is a simple version, if you want some challenge, please [try the challenge version](https://www.codewars.com/kata/the-maximum-sum-value-of-ranges-challenge-version/).
# Some Examples
```javascript
maxSum([1,-2,3,4,-5,-4,3,2,1],[[1,3],[0,4],[6,8]]) === 6
maxSum([1,-2,3,4,-5,-4,3,2,1],[[1,3]]) === 5
maxSum([1,-2,3,4,-5,-4,3,2,1],[[1,4],[2,5]]) === 0
```
```php
max_sum([1, -2, 3, 4, -5, -4, 3, 2, 1], [[1, 3], [0, 4], [6, 8]]); // => 6
max_sum([1, -2, 3, 4, -5, -4, 3, 2, 1], [[1, 3]]); // => 5
max_sum([1, -2, 3, 4, -5, -4, 3, 2, 1], [[1, 4], [2, 5]]); // => 0
```
```haskell
maxSum [1,-2,3,4,-5,-4,3,2,1] [(1,3),(0,4),(6,8)] == 6
maxSum [1,-2,3,4,-5,-4,3,2,1] [(1,3)] == 5
maxSum [1,-2,3,4,-5,-4,3,2,1] [(1,4),(2,5)] == 0
```
```ruby
max_sum([1,-2,3,4,-5,-4,3,2,1], [[1,3]]) == 5
max_sum([1,-2,3,4,-5,-4,3,2,1], [[1,4],[2,5]]) == 0
max_sum([1,-2,3,4,-5,-4,3,2,1], [ [1,3], [0,4], [6,8] ]) == 6
max_sum([11,-22,31,34,-45,-46,35,32,21], [[1,4],[0,3],[6,8],[0,8]]) == 88
``` | 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.
![Graph](http://i.imgur.com/nJrae8n.png)
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 beta!` | 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`.
~~~
~~~if:haskell
If the radius is positive, return `Just area`. Otherwise, return `Nothing`.
~~~
~~~if:java
If the `radius` is not positive, throw `IllegalArgumentException`.
~~~
~~~if:python
If the `radius` is not positive, raise `ValueError`.
~~~
~~~if:ruby
If the `radius` is not positive, raise `ArgumentError`.
~~~
Example:
```coffeescript
circleArea 43.2673 # returns 5881.248 (± 0.01)
circleArea 68 # returns 14526.724 (± 0.01)
circleArea 0 # throws Error
circleArea -1 # throws Error
```
```csharp
Kata.CalculateAreaOfCircle(43.2673); // returns 5881.248 (± 0.01)
Kata.CalculateAreaOfCircle(68); // returns 14526.724 (± 0.01)
Kata.CalculateAreaOfCircle(0.0); // throws ArgumentException
Kata.CalculateAreaOfCircle(-1.0); // throws ArgumentException
```
```haskell
circleArea 43.2673 -- returns Just ( 5881.248 ± 0.01)
circleArea 68 -- returns Just (14526.724 ± 0.01)
circleArea 0 -- returns Nothing
circleArea (-1) -- returns Nothing
```
```java
Circle.area(43.2673); // returns 5881.248 (± 0.01)
Circle.area(68); // returns 14526.724 (± 0.01)
Circle.area(0); // throws IllegalArgumentException
Circle.area(-1); // throws IllegalArgumentException
```
```javascript
circleArea(43.2673); // returns 5881.248 (± 0.01)
circleArea(68); // returns 14526.724 (± 0.01)
circleArea(0); // throws Error
circleArea(-1); // throws Error
```
```python
circle_area(43.2673) # returns 5881.248 (± 0.01)
circle_area(68) # returns 14526.724 (± 0.01)
circle_area(0) # raises ValueError
circle_area(-1) # raises ValueError
```
```ruby
circle_area(43.2673) # returns 5881.248 (± 0.01)
circle_area(68) # returns 14526.724 (± 0.01)
circle_area(0) # raises ArgumentError
circle_area(-1) # raises ArgumentError
```
```typescript
circleArea(43.2673); // returns 5881.248 (± 0.01)
circleArea(68); // returns 14526.724 (± 0.01)
circleArea(0); // throws Error
circleArea(-1); // throws Error
``` | reference | def circle_area(r):
if r > 0:
return r ** 2 * 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989
else:
raise ValueError
| 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 shape. Your answer is allowed to differ from the true answer by at most 0.01.
Hint: http://bit.ly/1vJJt61 | 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 and a right rhombohedron. It is a regular square prism in three orientations, and a trigonal trapezohedron in four orientations.
You are given a task of finding a if the provided value is a perfect cube! | 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 divisors is itself a square.
We will return an array of subarrays or of tuples (in C an array of Pair) or a string.
The subarrays (or tuples or Pairs) will have two elements: first the number the squared divisors of which is a square and then the sum of the squared divisors.
#### Example:
```
list_squared(1, 250) --> [[1, 1], [42, 2500], [246, 84100]]
list_squared(42, 250) --> [[42, 2500], [246, 84100]]
```
The form of the examples may change according to the language, see "Sample Tests".
#### Note
In Fortran - as in any other language - the returned string is not permitted to contain any redundant trailing whitespace: you can use dynamically allocated character strings.
| 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, n + 1):
divisors_sum = squared_cache(number)
if (divisors_sum * * 0.5). is_integer():
ret . append([number, divisors_sum])
return ret
| 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 |
| 4 | | 5 | | 6 |
------- ------- -------
------- ------- -------
|PQRS | | TUV | | WXYZ|
| 7 | | 8 | | 9 |
------- ------- -------
------- ------- -------
| * | |space| | # |
| | | 0 | | |
------- ------- -------
Prior to the development of T9 systems (predictive text entry), the method to type words was called "multi-tap" and involved pressing a button repeatedly to cycle through all its possible values, in order. For example:
* Pressing the button `7` repeatedly will cycle through the letters `P -> Q -> R -> S -> 7 -> P -> ...`.
* Pressing the button `0` is cycling through `SPACE -> 0 -> SPACE -> 0 -> ...`.
* Buttons with a single symbol on it just type this symbol.
A character is "locked in" and inserted into the message once the user presses a different key or pauses for a short period of time (thus, no extra button presses are required beyond what is needed for each letter individually). For example:
* To type a letter `"R"` you would press the `7` key three times (as the screen display for the current character cycles through `P->Q->R->S->7`).
* To type in a digit `3`, you would press the button `3` four times.
* To type in the message `"ABC"`, you would press the button `2` once, wait a second, then press the button `2` twice to enter the letter `B`, then pause for another second, and press the button `2` three times, to enter the letter `C`. You would have to press the button `2` six times in total.
In order to send the message `"WHERE DO U WANT 2 MEET L8R"` a teen would have to actually do 47 button presses. No wonder they abbreviated...
For this assignment, write code that can calculate the amount of button presses required for any phrase, with the following requirements:
- Punctuation can be ignored for this exercise.
- Likewise, the phone doesn't distinguish between upper and lowercase characters (but you should allow your module to accept input in either form, for convenience).
- Tested phrases contain letters (`A-Z` and `a-z`), digits (`0-9`), and special characters `#` and `*`.
| 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 the digits, and add to the original number". If the resulting number is not a palindrome, repeat the procedure with the sum until the resulting number is a palindrome.
If the input number is already a palindrome, the number of steps is `0`.
~~~if:java
All inputs are guaranteed to have a final palindrome which does not overflow `long`.
~~~
~~~if:javascript
All inputs are guaranteed to have a final palindrome which does not overflow `MAX_SAFE_INTEGER`.
~~~
~~~if:python
All inputs are guaranteed to have a final palindrome smaller than `$ 2^63 $`.
~~~
~~~if:pascal
All inputs are guaranteed to have a final palindrome which does not overflow `integer`.
~~~
### Example
For example, start with `87`:
```
87 + 78 = 165 - step 1, not a palindrome
165 + 561 = 726 - step 2, not a palindrome
726 + 627 = 1353 - step 3, not a palindrome
1353 + 3531 = 4884 - step 4, palindrome!
```
`4884` is a palindrome and we needed `4` steps to obtain it, so answer for `87` is `4`.
### Additional info
Some interesting information on the problem can be found in this Wikipedia article on [Lychrel numbers](https://en.wikipedia.org/wiki/Lychrel_number). | 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 Haskell and `Result<Vec<u32>, String>` in Rust).
#### Example:
```c
divisors(12); // results in {2, 3, 4, 6}
divisors(25); // results in {5}
divisors(13); // results in NULL
```
```javascript
divisors(12); // should return [2,3,4,6]
divisors(25); // should return [5]
divisors(13); // should return "13 is prime"
```
```elixir
divisors(12) # should return [2,3,4,6]
divisors(25) # should return [5]
divisors(13) # should return "13 is prime"
```
```coffeescript
divisors(12); # should return [2,3,4,6]
divisors(25); # should return [5]
divisors(13); # should return "13 is prime"
```
```haskell
divisors 12 -- should return Right [2,3,4,6]
divisors 25 -- should return Right [5]
divisors 13 -- should return Left "13 is prime"
```
```python
divisors(12); #should return [2,3,4,6]
divisors(25); #should return [5]
divisors(13); #should return "13 is prime"
```
```ruby
divisors(12) # should return [2,3,4,6]
divisors(25) # should return [5]
divisors(13) # should return "13 is prime"
```
```rust
divisors(12); // should return Ok(vec![2,3,4,6])
divisors(25); // should return Ok(vec![5])
divisors(13); // should return Err("13 is prime")
```
```csharp
Kata.Divisors(12) => new int[] {2, 3, 4, 6};
Kata.Divisors(25) => new int[] {5};
Kata.Divisors(13) => null;
```
```php
divisors(12); // => [2, 3, 4, 6]
divisors(25); // => [5]
divisors(13); // => '13 is prime'
```
```cobol
Divisors num = 12 => result = [2, 3, 4, 6]
Divisors num = 25 => result = [5]
Divisors num = 13 => result = []
``` | 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.
Your function productFib takes an integer (prod) and returns
an array:
```
[F(n), F(n+1), true] or {F(n), F(n+1), 1} or (F(n), F(n+1), True)
```
depending on the language if F(n) * F(n+1) = prod.
If you don't find two consecutive F(n) verifying `F(n) * F(n+1) = prod`you will return
```
[F(n), F(n+1), false] or {F(n), F(n+1), 0} or (F(n), F(n+1), False)
```
F(n) being the smallest one such as `F(n) * F(n+1) > prod`.
#### Some Examples of Return:
(depend on the language)
```
productFib(714) # should return (21, 34, true),
# since F(8) = 21, F(9) = 34 and 714 = 21 * 34
productFib(800) # should return (34, 55, false),
# since F(8) = 21, F(9) = 34, F(10) = 55 and 21 * 34 < 800 < 34 * 55
-----
productFib(714) # should return [21, 34, true],
productFib(800) # should return [34, 55, false],
-----
productFib(714) # should return {21, 34, 1},
productFib(800) # should return {34, 55, 0},
-----
productFib(714) # should return {21, 34, true},
productFib(800) # should return {34, 55, false},
```
#### Note:
- You can see examples for your language in "Sample Tests".
| 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 individuals and a function `fitness` that determines how close to the solution a chromosome is.
Your task is to return a collection containing an object with the chromosome and the calculated fitness.
```
[
{ chromosome: c, fitness: f },
{ chromosome: c, fitness: f },
...
]
```
~~~if:csharp
Note: you have a pre-loaded class `ChromosomeWrap` and you should return a collection of it instead.
```csharp
public class ChromosomeWrap
{
public string Chromosome { get; set; }
public double Fitness { get; set; }
}
```
~~~
~~~if:python
Note: you have a pre-loaded namedtuple `ChromosomeWrap` and you should return a collection of it instead.
```python
ChromosomeWrap = namedtuple("ChromosomeWrap", ["chromosome", "fitness"])
```
~~~
~~~if:php
Note: you have to return **an array of associative arrays** instead:
```php
// E.g.
array(
array("chromosome" => $c, "fitness" => $f),
array("chromosome" => $c, "fitness" => $f),
// ...
array("chromosome" => $c, "fitness" => $f)
);
```
~~~
# See other katas from this series
- [Genetic Algorithm Series - #1 Generate](http://www.codewars.com/kata/genetic-algorithm-series-number-1-generate)
- [Genetic Algorithm Series - #2 Mutation](http://www.codewars.com/kata/genetic-algorithm-series-number-2-mutation)
- [Genetic Algorithm Series - #3 Crossover](http://www.codewars.com/kata/genetic-algorithm-series-number-3-crossover)
- **Genetic Algorithm Series - #4 Get population and fitnesses**
- [Genetic Algorithm Series - #5 Roulette wheel selection](http://www.codewars.com/kata/genetic-algorithm-series-number-5-roulette-wheel-selection)
*This kata is a piece of [Binary Genetic Algorithm](http://www.codewars.com/kata/526f35b9c103314662000007)* | 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` and `1011100100110` with the cut point (index) `4`:
![](http://i.imgur.com/nZ4hgnS.gif)
In this kata you have to implement a function `crossover` that receives two chromosomes `chromosome1`, `chromosome2` and a zero-based `index` and it has to return an array with the crossover result on both chromosomes `[chromosome1, chromosome2]`.
# Example:
`crossover('111000', '000110', 3)` should return `['111110', 000000']`
# See other katas from this series
- [Genetic Algorithm Series - #1 Generate](http://www.codewars.com/kata/genetic-algorithm-series-number-1-generate)
- [Genetic Algorithm Series - #2 Mutation](http://www.codewars.com/kata/genetic-algorithm-series-number-2-mutation)
- **Genetic Algorithm Series - #3 Crossover**
- [Genetic Algorithm Series - #4 Get population and fitnesses](http://www.codewars.com/kata/genetic-algorithm-series-number-4-get-population-and-fitnesses)
- [Genetic Algorithm Series - #5 Roulette wheel selection](http://www.codewars.com/kata/genetic-algorithm-series-number-5-roulette-wheel-selection)
*This kata is a piece of ![2 kyu](http://i.imgur.com/CGlQhDW.png) [Binary Genetic Algorithm](http://www.codewars.com/kata/526f35b9c103314662000007)*
| 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.
![Mutation](http://i.imgur.com/HngmxNN.gif)
A mutation here may happen on zero or more positions in a chromosome. It is going to check every position and by a given probability it will decide if a mutation will occur.
A mutation is the change from `0` to `1` or from `1` to `0`.
***Note:*** *Some tests are random. If you think your algorithm is correct but the result fails, trying again should work.*
# See other katas from this series
- [Genetic Algorithm Series - #1 Generate](http://www.codewars.com/kata/genetic-algorithm-series-number-1-generate)
- **Genetic Algorithm Series - #2 Mutation**
- [Genetic Algorithm Series - #3 Crossover](http://www.codewars.com/kata/genetic-algorithm-series-number-3-crossover)
- [Genetic Algorithm Series - #4 Get population and fitnesses](http://www.codewars.com/kata/genetic-algorithm-series-number-4-get-population-and-fitnesses)
- [Genetic Algorithm Series - #5 Roulette wheel selection](http://www.codewars.com/kata/genetic-algorithm-series-number-5-roulette-wheel-selection) | 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` characters.
![](http://i.imgur.com/XW7Ys4n.gif)
# Example:
Generate a chromosome with length of 4 `generate(4)` could return the chromosome `0010`, `1110`, `1111`... or any of `2^4` possibilities.
***Note:*** *Some tests are random. If you think your algorithm is correct but the result fails, trying again should work.*
# See other katas from this series
- **Genetic Algorithm Series - #1 Generate**
- [Genetic Algorithm Series - #2 Mutation](http://www.codewars.com/kata/genetic-algorithm-series-number-2-mutation)
- [Genetic Algorithm Series - #3 Crossover](http://www.codewars.com/kata/genetic-algorithm-series-number-3-crossover)
- [Genetic Algorithm Series - #4 Get population and fitnesses](http://www.codewars.com/kata/genetic-algorithm-series-number-4-get-population-and-fitnesses)
- [Genetic Algorithm Series - #5 Roulette wheel selection](http://www.codewars.com/kata/genetic-algorithm-series-number-5-roulette-wheel-selection)
*This kata is a piece of [Binary Genetic Algorithm](http://www.codewars.com/kata/526f35b9c103314662000007)* | 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` & `y` are always positive integers, but they are not always in order of precendence... For example you can be given either `(5, 11)` or `(11, 5)` - both are valid. | 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 n % k:
k += step
step = 6 - step
else:
n / /= k
factors += 1
if n > 1:
factors += 1
return factors == 1
| 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 the total count of consonants {a,..,z} - {a,e,i,o,u}. Handle invalid input and don't forget to return valid ones.
#Input
The input is any random string. You must then discern what are vowels and what are consonants and sum for each category their total occurrences in an object. However you could also receive inputs that are not strings. If this happens then you must return an object with a vowels and consonants total of 0 because the input was NOT a string. Refer to the Example section for a more visual representation of which inputs you could receive and the outputs expected. :)
<h2>Example:</h2>
```javascript
Input: getCount('test')
Output: {vowels:1,consonants:3}
Input: getCount('tEst')
Output: {vowels:1,consonants:3}
Input getCount(' ')
Output: {vowels:0,consonants:0}
Input getCount()
Output: {vowels:0,consonants:0}
```
```python
Input: get_count('test')
Output: {vowels:1,consonants:3}
Input: get_count('tEst')
Output: {vowels:1,consonants:3}
Input get_count(' ')
Output: {vowels:0,consonants:0}
Input get_count()
Output: {vowels:0,consonants:0}
```
```ruby
Input: get_count('test')
Output: {vowels=>1,consonants=>3}
Input: get_count('tEst')
Output: {vowels=>1,consonants=>3}
Input get_count(' ')
Output: {vowels=>0,consonants=>0}
Input get_count()
Output: {vowels=>0,consonants=>0}
```
<h2>C#</h2>
<p>
A Counter class has been put in the preloaded section taking two parameters Vowels and Consonants this must be the Object you return!
</p>
```csharp
public class Counter {
public int Vowels { get; set; }
public int Consonants { get; set; }
public Counter(int vowels, int consonants)
{
Vowels = vowels;
Consonants = consonants;
}
}
```
| 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 {'vowels': len(vowel), 'consonants': len(consonant)}
| 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.
![arrow](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAAEsCAYAAADtt+XCAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAABJwSURBVHhe7d0LsFVV/cDxhSCP0NBKTS1MDVPHNBnLNDRNLKPRCjNfaEU1ppWZlmNqoKZFD1PHfGSpkRlU09PsXU5WVCpiZJgvMh/ZQ5BEA0S8f37rvy+CD4Qfj3vOPZ/PDHPvPus2Nbd77/fsvfZeq0/XYgUAVtI6zUcAWCkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkBKn67Fms87ypw5c8rcuXObI4Cn169fv7LRRhvVjyyrYwOyxx57lMcff7wMHjy4fgR4soEDB5arr766zJ49u2y44YbNq3Tr6IBcc8013lUAyzVy5MgyadKkehbCsjp6DuTBBx9sPgN4egsWLGg+48lMogOQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAApAgIACkCAkCKgACQIiAAPWzs2LFl0aJFzVH7EBCAHnb55ZeXrq6u5qh9CAhAC/jf//5Xjj322HL++ec3r7Q+AQFoARtvvHHZddddy5VXXlle8IIXNK+2NgEBaAF33313Ofzww8sf/vCHMmvWrDJlypRmpHUJCEALiDOQbqNGjSozZsxojlqXgAC0mHvvvbcMHjy4OWpdAgKNiRMnlj59+pQjjjiieQXWnrPOOqt+fOCBB8r06dPLoYceWo9bmYDQ8S699NIajhtvvLHeShm/uHF82GGHNV8Ba0f83G200UZtMf8RBISOdckll9Rf2JtvvrmG47zzzquvx/XnOB4zZkwdP/jgg+vrsKbEz9spp5xSP8a/3XbbrRlpbQJCx7noootqGG699db6y3rOOec0I8vqDsm73vWu+vUHHXRQMwIEAaFjfOELX6ghmDlzZg3D2Wef3Yws33777Ve//r3vfW/p27dvOfDAA5sR6GwCQq8Xl6YiHHFnS4Tgs5/9bDOycl7/+tfX9YqOPvro0q9fvzJ69OhmBDqTgNBrff7zn6/h+Oc//1nDMWHChGZk1YwcObI89thj5QMf+EBZd911ywEHHNCMQGcREHqdOMOIcMTTvBGOT33qU83I6vW6172uLFy4sBx//PGlf//+Zf/9929GoDMICL3Gpz/96RqOuXPn1nB031e/pu21117l0UcfLR/96EdrSN70pjc1I9C7CQht75Of/GQNx7x582o4zjjjjGZk7dpzzz1rSD72sY+VgQMH1sl36M0EhLYVZxgRjriMFOE47bTTmpGeNWLEiDJ//vwybty4MmjQoDr5Dr2RgNB2PvGJT9RwRDTi3/jx45uR1rL77rvXs6I4I3rOc55T9t133/q/F3oLAaFtnH766TUc8SxG/CE+9dRTm5HW9upXv7puFhRnTOutt17ZZ5992nL7UngyAaHlxaWgCMeAAQNqOE4++eRmpL286lWvKo888kid7B8yZEh57WtfW28HhnYlILSsj3/84zUc8a49wnHSSSc1I+1tl112KQ8//HBdQuV5z3tenTOJyXdoNwJCy4lF5SIcG2ywQQ3HiSee2Iz0LsOHDy8PPfRQXWIltjCNOZMFCxY0o9D6BISWEWcYEY5YzjrCccIJJzQjvdsrXvGKGpKLL764bLLJJvVSV0y+Q6sTEHpcnGFEODbbbLMajuOOO64Z6Sw77rhjmTNnTrnsssvq9yIudcWcCbQqAaHHfOQjH6nh2GKLLWo4jj322Gaks+2www7lwQcfLFdccUV58YtfXHbeeef6dD20GgFhrfvwhz9cwzFs2LAajve///3NCEvbbrvtyuzZs8vkyZPLS17yknqG8t///rcZhZ4nIKw1H/rQh2o4tt9++xqOo446qhlheV72spfVhSG//e1vl6233rp+/+JSF/Q0AWGN++AHP1jDsdNOO9VwxMZMrLw4Y3vggQfKVVddVbbZZpsaljhDgZ4iIKwxsV9GhCMmgyMcY8eObUZYFXEW8u9//7v85Cc/Kdtuu+2SsMDaJiCsdu973/tqOGIJjwjHO97xjmaE1WnLLbesIfnFL35RJ9632mqregxri4Cw2sScRoQjluiIcIwZM6YZYU2Ku9hi18Vf//rX9Y6tmHCPY1jTBIRVFnMaEY7YoS/CceihhzYjrE1xy+99991Xfve739XLhkOHDi3/+Mc/mlFY/QSEtJjTiHDEfhcRjoMPPrgZoSdtvvnm5d577y1//OMfy2677bbkGFY3AWGlvfOd76zhiK1bIxwHHXRQM0Ir2XTTTcvf//73cuONN9YFG+Pp9nvuuacZhVUnIKywmAyPcLz5zW+u4TjwwAObEVpZrK911113lT/96U91//buY1hVAsKzOuKII2o4Ro8eXcPx1re+tRmhncQilXfeeWf5y1/+Ui87RkhmzpzZjMLKExCe0WGHHVbD8fa3v72GI848aH+xdPxtt91WbrnlljJq1KgaljvuuKMZhRUnIDzFIYccUsNx+OGH13Dsv//+zQi9SWxm9de//rXcfvvt5S1vecuSsMCKEhCWiLuoIhwx1xHhiElyer/YuOvmm2+ul7Pe9ra3lec///k1LPBsBIQ6Gb7OOuvU23IjHG984xubETrJc5/73DJ9+vR651Y8yxNnKDNmzGhG4akEpIPFpHi/fv3q0iOPP/54ecMb3tCM0MliD/pp06bVW36PPPLIsuGGG9YzFHgyAelAcb07whH7cDz22GNl3333bUbgCYMHDy433HBDfZr93e9+dxkyZEg9Q4FuAtJBDjjggLLuuuvWfTkiHPvss08zAs9s0KBB9an2WKjx6KOPriGJMxQQkA4Qk+H9+/cvJ5xwQlm4cGHZe++9mxFYcQMGDKjrbMXS8bH98Prrr1+fcqdzCUgvFvf4Dxw4sJx00knl0UcfravkdpJJkyaV97znPeWMM85oXinlpptuKj/72c/KBRdcUMaPH18frOs+Pvnkk5uvKuXMM8+sc0MxoRziOYlzzz23fh5id8BvfOMbzVGp/x2dsidHnMX+5je/qfu2x5uSmDO5/vrrm1E6iYD0Qvvtt1+97HDKKaeU+fPnlz322KMZ6RxxxhVRiIhee+219fbkEE9hx80CEYYXvvCFdXK4+zgeqAvxtXG5Jla0jaXRr7jiivLSl7607uXeLdYDiwctu0WM4jmKThLzaNdcc0156KGH6puUmDO57rrrmlE6QleHGjFiRNfiPxLNUe8wcuTIrsVnHF1TpkxpXulc48aNaz77f90/6pMnT+7aYIMN6ufhyiuvXOZ4zJgxXUceeWRz1NU1a9asJf/ZzTbbrGvatGn180033XTJ6xMnTuzaa6+96uedrjf+DPbGvxWrizOQNhe338ZkeLz7i8su8+bNq0t4d7pTTz21PtcSZxHdZx9h8c/8MmcK8f1b+jguzSz95H08C9EtLmktDk756U9/WlcgfuUrX1mmTp1az1Bi+15K+fnPf15/Bk877bR6FhxzJvReAtKmFi1aVCfDYyJzwoQJ5ZFHHim77rprM9rZ4g9YXMKKeMQ8SERjaRGNpS19HE9hz5kzpzla1vHHH1+++tWvlu985zt1fbDF77brvuSxpayViZcVkY3/H84666w6+R5hpvcRkDYTd1HtueeedfmJs88+u4Yj3gnzhFgkMBxzzDFl2LBh5cILL6zHK+LEE0+sOyx2O+644+pOfyHO8v7zn/+USy65pLzmNa+pqxTHmY7v/zP70Y9+VBYsWFDf5ERIYttdeg8BaRPxSxh/tOId8nnnnVfmzp1bhg8f3oyytPi+xAZKcekq/t1///319ZhAj3fFS+8X/vDDDy9zHOuBRRS6/7PxB/Duu+9uRkt9oK7bdtttVz8uPZnO07v66qvrz/DnPve5ehdXTL7T/vrEREjzeUeJO5PiUkT3nTetKv7gxSZAt956a72baMcdd2xGoH3Fagg//OEP66WuVn+gtV3+VvQEZyAtqvvSVGxD+uUvf7lelxcPeovvfe97dTWEuNU6bgeOeSTaj4C0mLiksvPOO9fr7hMnTqwPa7385S9vRqF3iXf2EZKLLrqorggdZyS0DwFpEfEw1k477VS22GKLeufQ7Nmzy/bbb9+MQu8WT/bH3XCXXnppnXv68Y9/3IzQygSkh8WlqR122KFstdVW5Vvf+laZNWtW2XbbbZtR6Czf/OY3623XcfYdIYnJd1qXgPSQOMOIUMRtpnE9ONZR2mabbZpR6GyTJ0+uIYkHNyMkV111VTNCKxGQtaw7FBGPuEU0niuIdZaAp/r6179eQxJBiZB8//vfb0ZoBQKylkQott5663q5KlZ/jcX64rIV8OziTCRCEpPuEZLvfve7zQg9SUDWsH/9619lyy23rBPk8fBUPLQWK7wCKy/mRiIkcSYSIYnJd3qOgKwh8fRz3FEVT0XHOkCxLejQoUObUWBVfOUrX6khiUn2CEncgMLaJyCr2X333Vde9KIX1YUNf//73y85Bla/yy67rIYkLgtHSJbe5Is1T0BWk3vuuadsvvnmZffddy833HBDXT8pniIH1rwvfelLNSS/+tWvakjiWSrWPAFZRd0728V2sdOmTVtyDKx9X/ziF2tIYtXfCMnXvva1ZoQ1QUCS/va3v5VNNtmk7gkR26LOnDmzbLzxxs0o0JMuvvjiGpIpU6bUkMQ+Lqx+ArKS7rzzzhqK2Hc89p24/fbbO24vbGgXsRdMhOT666+vIbn88subEVYHAVlBEYpYzjm2O73tttvq8upLb3cKtK7zzz+/huSmm26qIYk5E1adgDyLCEVs4jR69Ohyxx13lBkzZtTdAIH2E5uxRUji9zhCEnMm5AnIM4jLU3GGccghh5S77rqr/PnPfy5DhgxpRoF2ds4559SQxJWFCMnKbHvMEwTkSWJCPMIxZsyYemtu3Fm1/vrrN6NAbxJb7EZI4k1ihCQudbHiBKQxffr0emlq7Nix9eG/qVOnlsGDBzejQG/2mc98poYkfvcjJOeee24zwvJ0dEBiUjye24iVcc8888y6N8d1111XBg0a1HwF0EkmTJhQQzJgwICy3nrrlR/84Af1ikREhafqs/ib1dV83lH23nvv8tvf/rZupwmwPHPnzq1BYVkdG5AFCxYseaexaNGi5lWAJ8Q+7bHVbpyB9O3bt3mVbh0bEABWjUl0AFIEBIAUAQEgRUAASBEQAFIEBIAUAQEgRUAASBEQAFIEBIAUAQEgRUAASBEQAFIEBIAUAQEgRUAASBEQAFIEBIAUAQEgRUAASOnTtVjzOXSsSZMmlV/+8pdl6NChZdy4cc2rwPI4A6Hj9e/fv1xwwQVl1KhR5dprry19+vRpRoDlcQZCxxs/fnw5/fTTm6PFvxSLA+LXAp6dgNDxFi5cWI466qgyffr0MnXq1Pra/Pnzy4ABA+rnwNNzCYuONm/evHoJa5dddqnzIN3vp1zGgmcnIHS0W265pX485phjyrBhw8qFF15Yj/v27Vs/As9MQOhow4cPLyNGjKhnHPHv/vvvr693X8oCnpk5EABSnIEAkCIgAKQICAApAgJAioAAkCIgAKQICAApAgJAioAAkCIgAKQICAApAgJAioAAkCIgAKQICAApAgJAioAAkCIgAKQICAApAgJAioAAkCIgAKQICAApAgJAioAAkCIgAKQICAApAgJAioAAkCIgAKQICAApAgJAioAAkCIgAKQICAApAgJAioAAkCIgAKQICAApAgJAioAAkCIgAKQICAApAgJAioAAkCIgAKQICAApAgJAioAAkCIgAKQICAApAgJAioAAkCIgAKQICAApAgJAioAAkCIgAKQICAApAgJAQin/B5NMkL2nLn1tAAAAAElFTkSuQmCC)
`a` and `b` are `integers` and `> 0`
Write a function which returns the area of the arrow. | games | def arrow_area(a, b):
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 pattern.
### Pattern:
1
22
333
....
.....
nnnnnn
### Examples:
+ pattern(5):
1
22
333
4444
55555
* pattern(11):
1
22
333
4444
55555
666666
7777777
88888888
999999999
10101010101010101010
1111111111111111111111
```if-not:cfml
* Hint: Use \n in string to jump to next line
```
```if:cfml
* Hint: Use Chr(10) in string to jump to next line
```
[List of all my katas]('http://www.codewars.com/users/curious_db97/authored')
| 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, 0.75-1.0, 1.0-1.25, 1.25-1.50, 1.5-1.75, 1.75-2.0, 2.0-2.25
We can calculate John's average hourly speed on every section and we get:
[45.6, 74.4, 60.0, 60.0, 60.0, 60.0, 60.0, 60.0, 60.0]
Given `s` and `x` the task is to return as an integer the `*floor*` of the maximum average speed per hour obtained on the sections of `x`.
If x length is less than or equal to 1 return `0` since the car didn't move.
#### Example:
With the above data your function `gps(s, x)` should return `74`
#### Note
With floats it can happen that results depends on the operations order. To calculate hourly speed you can use:
` (3600 * delta_distance) / s`.
Happy coding!
| 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 pattern.
### Pattern:
(n)(n-1)(n-2)...4321
(n)(n-1)(n-2)...432
(n)(n-1)(n-2)...43
(n)(n-1)(n-2)...4
...............
..............
(n)(n-1)(n-2)
(n)(n-1)
(n)
### Examples:
* pattern(4):
4321
432
43
4
* pattern(11):
1110987654321
111098765432
11109876543
1110987654
111098765
11109876
1110987
111098
11109
1110
11
~~~if-not:cfml
* Hint: Use \n in string to jump to next line
~~~
~~~if:cfml
* Hint: Use chr(10) in string to jump to next line
~~~
[List of all my katas]("http://www.codewars.com/users/curious_db97/authored") | 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 reports the nth day (as an integer)
on which the evaporator will be out of use.
#### Example:
```
evaporator(10, 10, 5) -> 29
```
#### Note:
Content is in fact not necessary in the body of the function "evaporator", you can use it or not use it, as you wish. Some people might prefer to reason with content, some other with percentages only. It's up to you but you must keep it as a parameter because the tests have it as an argument. | 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 below. Create a function named `main` that calls the functions in the proper order.
```javascript
- combat
- buyHealth
- getCoins
- printStatus
- rollDice
- move
```
```ruby
- `combat`
- `buy_health`
- `get_coins`
- `print_status`
- `roll_dice`
- `move`
```
```python
- `combat`
- `buy_health`
- `get_coins`
- `print_status`
- `roll_dice`
- `move`
```
```csharp
- `Combat`
- `BuyHealth`
- `GetCoins`
- `PrintStatus`
- `RollDice`
- `Move`
```
| 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;">◄PREVIOUS KATA</a>
<a href="http://www.codewars.com/kata/55c933c115a8c426ac000082" style="text-decoration: none; font-size: 20px; font-family: monospace;float:right;">NEXT KATA►</a>
</div>
| 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:lambdacalc
- Purity: `LetRec`
- Number Encoding: `Scott`
- Boolean Encoding: your output should be extensionally equal to a Church boolean (`True = \ x _ . x`, `False = \ _ x . x`)
~~~
| 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 with.
Let's give this a try. We'll create a function `match` (`job_matching` in Python) which takes a `candidate` and a `job`, which will return a Boolean indicating whether the job is a valid match for the candidate.
A candidate will have a minimum salary, so it will look like this:
```javascript
let candidate = {
minSalary: 120000
}
```
```ruby
candidate = {
'min_salary': 120000
}
```
```python
candidate = {
'min_salary': 120000
}
```
```csharp
Candidate candidate =
new Candidate(MinSalary: 120000);
```
A job will have a maximum salary, so it will look like this:
```javascript
let job = {
maxSalary: 140000
}
```
```ruby
job = {
'max_salary': 140000
}
```
```python
job = {
'max_salary': 140000
}
```
```csharp
Job job =
new Job(MaxSalary: 140000);
```
If either the candidate's minimum salary or the job's maximum salary is not present, throw an error.
For a valid match, the candidate's minimum salary must be less than or equal to the job's maximum salary. However, let's also include 10% wiggle room (deducted from the candidate's minimum salary) in case the candidate is a rockstar who enjoys programming on Codewars in their spare time. The company offering the job may be able to work something out.
---
Continue on with Kata:
- [Job Matching #2][3]
- [Job Matching #3][2]
[3]:https://www.codewars.com/kata/56c2578be8b139bd5c001bd8
[2]:https://www.codewars.com/kata/56c2a067585d9ac8280003c9 | 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 failed the test.
## Example
```
all((1, 2, 3, 4, 5), greater_than_9) -> false
all((1, 2, 3, 4, 5), less_than_9) -> True
```
## Help
Here's a (Ruby) resource if you get stuck:
http://www.rubycuts.com/enum-all
| 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 cell containing an X chromosome fertilizes an egg, the resulting zygote will be XX or female. If the sperm cell contains a Y chromosome, then the resulting zygote will be XY or male.
Determine if the sex of the offspring will be male or female based on the X or Y chromosome present in the male's sperm.
If the sperm contains the X chromosome, return "Congratulations! You're going to have a daughter.";
If the sperm contains the Y chromosome, return "Congratulations! You're going to have a son.";
| 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.
Given a triangle, defined by the cartesian coordinates of its vertices we need to localize its barycenter or centroid.
The function ```bar_triang() or barTriang or bar-triang```, receives the coordinates of the three vertices ```A, B and C ``` as three different arguments and outputs the coordinates of the barycenter ```O``` in an array ```[xO, yO]```
This is how our asked function should work:
the result of the coordinates should be expressed up to four decimals, (rounded result).
You know that the coordinates of the barycenter are given by the following formulas.
<a href="http://imgur.com/B0tjxUG"><img src="http://i.imgur.com/B0tjxUG.jpg?1" title="source: imgur.com" /></a>
For additional information about this important point of a triangle see at: (https://en.wikipedia.org/wiki/Centroid)
Let's see some cases:
```python
bar_triang([4, 6], [12, 4], [10, 10]) ------> [8.6667, 6.6667]
bar_triang([4, 2], [12, 2], [6, 10] ------> [7.3333, 4.6667]
```
```ruby
bar_triang([4, 6], [12, 4], [10, 10]) ------> [8.6667, 6.6667]
bar_triang([4, 2], [12, 2], [6, 10] ------> [7.3333, 4.6667]
```
```javascript
barTriang([4, 6], [12, 4], [10, 10]) ------> [8.6667, 6.6667]
barTriang([4, 2], [12, 2], [6, 10]) ------> [7.3333, 4.6667]
```
```clojure
bar-triang([4, 6], [12, 4], [10, 10]) ------> [8.6667, 6.6667]
bar-triang([4, 2], [12, 2], [6, 10] ------> [7.3333, 4.6667]
(bar-triang [0, 0], [1, 6], [8, -6]) ------> [3.0, 0.0]
```
```haskell
barTriang (4, 6) (12, 4) (10, 10) ------> (8.6667, 6.6667])
barTriang (4, 2) (12, 2) (6, 10) ------> (7.3333, 4.6667)
```
```java
barTriang([4, 6], [12, 4], [10, 10]) ------> {8.6667, 6.6667}
barTriang([4, 2], [12, 2], [6, 10] ------> {7.3333, 4.6667}
```
```elixir
bar_triang({4, 6}, {12, 4}, {10, 10}) ------> {8.6667, 6.6667}
bar_triang({4, 2}, {12, 2}, {6, 10}) ------> {7.3333, 4.6667}
```
The given points form a real or a degenerate triangle but in each case the above formulas can be used.
Enjoy it and happy coding!!
| 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 and volume of a box as a list: `(area, volume)`
```
```if:elixir
Write a function that returns the total surface area and volume of a box as a list: `{area, volume}`
```
| 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, work out how many of each animal are there.
```Return a tuple in Python - (chickens, cows) and an array list - [chickens, cows]/{chickens, cows} in all other languages```
If either the heads & legs is negative, the result of your calculation is negative or the calculation is a float return "No solutions" (no valid cases), or [-1, -1] in COBOL.
In the form:
```python
(Heads, Legs) = (72, 200)
VALID - (72, 200) => (44 , 28)
(Chickens, Cows)
INVALID - (72, 201) => "No solutions"
```
```javascript
[Heads, Legs] = [72, 200]
VALID - [72, 200] => [44 , 28]
[Chickens, Cows]
INVALID - [72, 201] => "No solutions"
```
```ruby
[Heads, Legs] = [72, 200]
VALID - [72, 200] => [44 , 28]
[Chickens, Cows]
INVALID - [72, 201] => "No solutions"
```
```cobol
Heads = 72
Legs = 200
=>
Chickens = 44
Cows = 28
Heads = 72
Legs = 201
=>
Chickens = -1
Cows = -1
```
However, ```if 0 heads and 0 legs are given always return [0, 0]``` since zero heads must give zero animals.
There are many different ways to solve this, but they all give the same answer.
You will only be given integers types - however negative values (edge cases) will be given.
Happy coding! | 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 `False`
2) booleans = `[True, True, False]`, operator = `"OR"`
* `True` `OR` `True` -> `True`
* `True` `OR` `False` -> `True`
* return `True`
3) booleans = `[True, True, False]`, operator = `"XOR"`
* `True` `XOR` `True` -> `False`
* `False` `XOR` `False` -> `False`
* return `False`
## Input
1) an array of Boolean values `(1 <= array_length <= 50)`
2) a string specifying a logical operator: `"AND"`, `"OR"`, `"XOR"`
## Output
A Boolean value (`True` or `False`). | 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 decimal points.
```
```if:swift
Your answer should be accurate within 0.01 kpl.
```
Some useful associations relevant to this kata:
- 1 Imperial Gallon = 4.54609188 litres
- 1 Mile = 1.609344 kilometres | 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
c:x2
d:y2
```
Assume that ```[a,b,c,d]``` and the answer are all integers
(no floating numbers!).
Slope: <https://en.wikipedia.org/wiki/Slope>
| 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 has been cut.
You must return the number of smaller cubes created by the cuts that have at least one red face.
To make it clearer, the picture below represents the cube after (from left to right) 0, 1 and 2 cuts have been made.
<img src=https://i.imgur.com/36x8Fkv.png>
```
Examples:
If we cut the cube 2 times, the function should return 26
If we cut the cube 4 times, the function should return 98
``` | 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 6 * x * * 2 + 2
| 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 new `n`.
3. If the new `n` is in the list below return the associated fruit, otherwise return back to task 1.
### Example
n = `325`
sum = `3+2+5` = `10`
n = `325-10` = `315` (not in the list)
sum = `3+1+5` = `9`
n = `315-9` = `306` (not in the list)
sum = `3+0+6` = `9`
n =`306-9` = `297` (not in the list)
.
.
.
...until you find the first n in the list below.
There is no preloaded code to help you.
_This is not about coding skills; think before you code_
```
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
22-cherry
23-pear
24-kiwi
25-banana
26-kiwi
27-apple
28-melon
29-banana
30-melon
31-pineapple
32-melon
33-pineapple
34-cucumber
35-orange
36-apple
37-orange
38-grape
39-orange
40-grape
41-cherry
42-pear
43-cherry
44-pear
45-apple
46-pear
47-kiwi
48-banana
49-kiwi
50-banana
51-melon
52-pineapple
53-melon
54-apple
55-cucumber
56-pineapple
57-cucumber
58-orange
59-cucumber
60-orange
61-grape
62-cherry
63-apple
64-cherry
65-pear
66-cherry
67-pear
68-kiwi
69-pear
70-kiwi
71-banana
72-apple
73-banana
74-melon
75-pineapple
76-melon
77-pineapple
78-cucumber
79-pineapple
80-cucumber
81-apple
82-grape
83-orange
84-grape
85-cherry
86-grape
87-cherry
88-pear
89-cherry
90-apple
91-kiwi
92-banana
93-kiwi
94-banana
95-melon
96-banana
97-melon
98-pineapple
99-apple
100-pineapple
```
| 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', 22: 'cherry', 23: 'pear', 24: 'kiwi',
25: 'banana', 26: 'kiwi', 27: 'apple', 28: 'melon', 29: 'banana', 30: 'melon',
31: 'pineapple', 32: 'melon', 33: 'pineapple', 34: 'cucumber', 35: 'orange',
36: 'apple', 37: 'orange', 38: 'grape', 39: 'orange', 40: 'grape', 41: 'cherry',
42: 'pear', 43: 'cherry', 44: 'pear', 45: 'apple', 46: 'pear', 47: 'kiwi',
48: 'banana', 49: 'kiwi', 50: 'banana', 51: 'melon', 52: 'pineapple', 53: 'melon',
54: 'apple', 55: 'cucumber', 56: 'pineapple', 57: 'cucumber', 58: 'orange',
59: 'cucumber', 60: 'orange', 61: 'grape', 62: 'cherry', 63: 'apple',
64: 'cherry', 65: 'pear', 66: 'cherry', 67: 'pear', 68: 'kiwi', 69: 'pear',
70: 'kiwi', 71: 'banana', 72: 'apple', 73: 'banana', 74: 'melon',
75: 'pineapple', 76: 'melon', 77: 'pineapple', 78: 'cucumber', 79: 'pineapple',
80: 'cucumber', 81: 'apple', 82: 'grape', 83: 'orange', 84: 'grape', 85: 'cherry',
86: 'grape', 87: 'cherry', 88: 'pear', 89: 'cherry', 90: 'apple', 91: 'kiwi',
92: 'banana', 93: 'kiwi', 94: 'banana', 95: 'melon', 96: 'banana', 97: 'melon',
98: 'pineapple', 99: 'apple', 100: 'pineapple'}
def subtract_sum(n):
n -= (sum([int(i) for i in str(n)]))
while not n in fruit:
n -= (sum([int(i) for i in str(n)]))
return fruit[n]
| 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," based on the vaulter's body height.
This guideline was taught to me in feet and inches, but due to the international nature of Codewars, I am creating this kata to use metric units instead.
You are given the following two guidelines to begin with:
(1) A vaulter with a height of 1.52 meters should start at 9.45 meters on the runway.
(2) A vaulter with a height of 1.83 meters should start at 10.67 meters on the runway.
You will receive a vaulter's height in meters (which will always lie in a range between a minimum of 1.22 meters and a maximum of 2.13 meters). Your job is to return the best starting mark in meters, rounded to two decimal places.
Hint: Based on the two guidelines given above, you will want to account for the change in starting mark per change in body height. This involves a linear relationship. (If you're not clear on that, search online for "linear equation.") But there is also a constant offset involved. If you can determine the rate of change described above, you should be able to determine that constant offset. | 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]) // "At match Portugal - Iceland, teams played draw."
```
```python
uefa_euro_2016(['Germany', 'Ukraine'],[2, 0]) # "At match Germany - Ukraine, Germany won!"
uefa_euro_2016(['Belgium', 'Italy'],[0, 2]) # "At match Belgium - Italy, Italy won!"
uefa_euro_2016(['Portugal', 'Iceland'],[1, 1]) # "At match Portugal - Iceland, teams played draw."
```
```ruby
uefa_euro_2016(['Germany', 'Ukraine'],[2, 0]) # "At match Germany - Ukraine, Germany won!"
uefa_euro_2016(['Belgium', 'Italy'],[0, 2]) # "At match Belgium - Italy, Italy won!"
uefa_euro_2016(['Portugal', 'Iceland'],[1, 1]) # "At match Portugal - Iceland, teams played draw."
```
| 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 litres get a discount of 5 cents per litre, purchases of 4 or more litres get a discount of 10 cents per litre, and so on every two litres, up to a maximum discount of 25 cents per litre. But total discount per litre cannot be more than 25 cents. Return the total cost rounded to 2 decimal places. Also you can guess that there will not be negative or non-numeric inputs.
Good Luck!
## Note
1 Dollar = 100 Cents | 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 there may be duplicate IDs, but you don't have to find or remove them!
Go on and code some pure awesomeness! | 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.
## Examples(Input ==> Output)
```
"anna" ==> true
"walter" ==> false
12321 ==> true
123456 ==> false
``` | 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 of string arrays, array of number arrays... 😕 | 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 function should return the full name.
```
```if:csharp
Create a function named (`Combine_names`) that accepts two parameters (first and last name). The function should return the full name.
```
Example:
```javascript
combineNames('James', 'Stevens')
```
```coffeescript
combineNames 'James', 'Stevens'
```
```python
combine_names('James', 'Stevens')
```
```ruby
combine_names('James', 'Stevens')
```
```haskell
combineNames "James" "Stevens"
```
```csharp
CombineNames("James", "Stevens")
```
returns:
```javascript
'James Stevens'
```
```coffeescript
'James Stevens'
```
```python
'James Stevens'
```
```ruby
'James Stevens'
```
```haskell
"James Stevens"
```
```csharp
"James Stevens"
```
| 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 free
mango(5, 3) ==> 12 # 4 mangoes for $3 per unit = $12; +1 mango for free
mango(9, 5) ==> 30 # 6 mangoes for $5 per unit = $30; +3 mangoes for free
``` | 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">Square</b></i> is the square of its <i><b>side</b></i></li>
<li>The area of a <i><b style="color:lightgreen">Rectangle</b></i> is <i><b>width</b></i> multiplied by <i><b>height</b></i></li>
<li>The area of a <i><b style="color:lightgreen">Triangle</b></i> is <i><b>base</b></i> multiplied by <i><b>height</b></i> divided by 2</li>
<li>The area of a <i><b style="color:lightgreen">Circle</b></i> is the square of its <i><b>radius</b></i> multiplied by π</li>
<li>The <i><b>area</b></i> of a <i><b style="color:lightgreen">CustomShape</b></i> is given</li>
</ul>
</li>
<br>
<li>The default sort order of a list of shapes is ascending on area size:</li>
```python
side = 1.1234
radius = 1.1234
base = 5
height = 2
# All classes must be subclasses of the Shape class
shapes: List[Shape] = [Square(side), Circle(radius), Triangle(base, height)]
shapes.sort()
```
```csharp
var side = 1.1234D;
var radius = 1.1234D;
var base = 5D;
var height = 2D;
var shapes = new List<Shape>{ new Square(side),
new Circle(radius),
new Triangle(base, height) };
shapes.Sort();
```
```fsharp
let side = 1.1234
let radius = 1.1234
let base = 5.
let height = 2.
let shapes = [ Square(side);
Circle(radius),
Triangle(base, height) ]
let sorted = Seq.sort shapes
```
```java
double side = 1.1234;
double radius = 1.1234;
double base = 5;
double height = 2;
ArrayList<Shape> shapes = new ArrayList<Shape>();
shapes.add(new Square(side));
shapes.add(new Circle(radius));
shapes.add(new Triangle(base, height));
Collections.sort(shapes);
```
```haskell
-- use record syntax
Square { side :: Double }
Rectangle { width :: Double, height :: Double }
Triangle { base :: Double, height :: Double }
Circle { radius :: Double }
CustomShape { area :: Double }
-- your types have to implement Show
shapes :: [Shape]
shapes = [Square 1.1234, Circle 1.1234, Triangle 5 2]
```
```javascript
let side = 1.1234;
let radius = 1.1234;
let base = 5;
let height = 2;
let shapes = [ new Square(side)
, new Circle(radius)
, new Triangle(base, height)
];
shapes.sort( (a,b) => Number(a>b)-Number(a<b) ); // instead of the default lexicographical sort, natural sort will be used
```
<li>Use the correct π constant for your circle area calculations:</li>
```python
math.pi
```
```csharp
System.Math.PI
```
```fsharp
System.Math.PI
```
```java
Math.PI
```
```haskell
pi from Prelude
```
```javascript
Math.PI
```
</ul>
<br> | 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)
class Triangle (Shape):
def __init__(self, b, h): super(). __init__(b * h / 2)
class Circle (Shape):
def __init__(self, r): super(). __init__(pi * r * * 2)
CustomShape = Shape
| 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
ghost = new Ghost()
ghost.color #=> "white" or "yellow" or "purple" or "red"
```
```ruby
ghost = Ghost.new
ghost.color #=> "white" or "yellow" or "purple" or "red"
```
```python
ghost = Ghost()
ghost.color #=> "white" or "yellow" or "purple" or "red"
```
```java
Ghost ghost = new Ghost();
ghost.getColor(); //=> "white" or "yellow" or "purple" or "red"
```
```c#
Ghost ghost = new Gost();
ghost.GetColor(); // => "white" or "yellow" or "purple" or "red"
```
| 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)*
Complete the function to create backronyms. Transform the given string (without spaces) to a backronym, using the preloaded dictionary and return a string of words, separated with a single space (but no trailing spaces).
The keys of the preloaded dictionary are **uppercase** letters `A-Z` and the values are predetermined words, for example:
```javascript
dict["P"] == "perfect"
```
```python
dictionary["P"] == "perfect"
```
```ruby
$dict["P"] == "perfect"
```
```csharp
dict['P'] == "perfect"
```
```java
dictionary.get("P") == "perfect"
```
```haskell
dict 'P' == "perfect"
```
## Examples
```
"dgm" ==> "disturbing gregarious mustache"
"lkj" ==> "literal klingon joke"
``` | 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 containing the two strings with the word ```' are '```
Reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/template_strings | 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 return false and lose a life.
Can you finish the game so all the rules are met? | 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 switched to positive ones!
The constructor taking no arguments should assign 0 to Cube's Side property.
| 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 output.
| 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 staff seating plan.
Create a function `binRota` that accepts a 2D array of names. The function will return a single array containing staff names in the order that they should empty the bin.
Adding to the problem, the office has some temporary staff. This means that the seating plan changes every month. Both staff members' names and the number of rows of seats may change. Ensure that the function `binRota` works when tested with these changes.
**Notes:**
- All the rows will always be the same length as each other.
- There will be no empty spaces in the seating plan.
- There will be no empty arrays.
- Each row will be at least one seat long.
An example seating plan is as follows:
![](http://i.imgur.com/aka6lh0l.png)
Or as an array:
```
[ ["Stefan", "Raj", "Marie"],
["Alexa", "Amy", "Edward"],
["Liz", "Claire", "Juan"],
["Dee", "Luke", "Katie"] ]
```
The rota should start with Stefan and end with Dee, taking the left-right zigzag path as illustrated by the red line:
<img src="http://i.imgur.com/JKlcPKxl.jpg">
As an output you would expect in this case:
```
["Stefan", "Raj", "Marie", "Edward", "Amy", "Alexa", "Liz", "Claire", "Juan", "Katie", "Luke", "Dee"])
``` | 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
Consider only uppercase letters (no lowercase letters, no numbers) and spaces.
For example:
```if-not:rust
~~~
toLeetSpeak("LEET") returns "1337"
~~~
```
```if:rust
~~~
to_leet_speak("LEET") returns "1337"
~~~
```
In this kata we use a simple LeetSpeak dialect. Use this alphabet:
```
{
A : '@',
B : '8',
C : '(',
D : 'D',
E : '3',
F : 'F',
G : '6',
H : '#',
I : '!',
J : 'J',
K : 'K',
L : '1',
M : 'M',
N : 'N',
O : '0',
P : 'P',
Q : 'Q',
R : 'R',
S : '$',
T : '7',
U : 'U',
V : 'V',
W : 'W',
X : 'X',
Y : 'Y',
Z : '2'
}
``` | 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 pair must be in the same order as in the original array.
#### Examples of returns in different languages:
```
a = ["az", "toto", "picaro", "zone", "kiwi"] -->
[["az", "toto picaro zone kiwi"], ["az toto", "picaro zone kiwi"], ["az toto picaro", "zone kiwi"], ["az toto picaro zone", "kiwi"]]
or
a = {"az", "toto", "picaro", "zone", "kiwi"} -->
{{"az", "toto picaro zone kiwi"}, {"az toto", "picaro zone kiwi"}, {"az toto picaro", "zone kiwi"}, {"az toto picaro zone", "kiwi"}}
or
a = ["az", "toto", "picaro", "zone", "kiwi"] -->
[("az", "toto picaro zone kiwi"), ("az toto", "picaro zone kiwi"), ("az toto picaro", "zone kiwi"), ("az toto picaro zone", "kiwi")]
or
a = [|"az", "toto", "picaro", "zone", "kiwi"|] -->
[("az", "toto picaro zone kiwi"), ("az toto", "picaro zone kiwi"), ("az toto picaro", "zone kiwi"), ("az toto picaro zone", "kiwi")]
or
a = ["az", "toto", "picaro", "zone", "kiwi"] -->
"(az, toto picaro zone kiwi)(az toto, picaro zone kiwi)(az toto picaro, zone kiwi)(az toto picaro zone, kiwi)"
```
#### Note
You can see other examples for each language in "Your test cases"
| 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 return an empty array.
Have fun coding it and please don't forget to vote and rank this kata! :-)
| 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 feet per hour`.
How long will it take ***B*** to catch ***A***?
More generally:
given two speeds `v1` (***A***'s speed, integer > 0) and `v2` (***B***'s speed, integer > 0) and a lead `g` (integer > 0)
how long will it take ***B*** to catch ***A***?
The result will be an array ```[hour, min, sec]``` which is the time needed in hours, minutes and seconds (round down to the nearest second)
or a string in some languages.
If `v1 >= v2` then return `nil`, `nothing`, `null`, `None` or `{-1, -1, -1}` for C++, C, Go, Nim, Pascal, COBOL, Erlang, `[-1, -1, -1]` for Perl,`[]` for Kotlin or "-1 -1 -1" for others.
#### Examples:
(form of the result depends on the language)
```
race(720, 850, 70) => [0, 32, 18] or "0 32 18"
race(80, 91, 37) => [3, 21, 49] or "3 21 49"
```
#### Note:
- See other examples in "Your test cases".
- In Fortran - as in any other language - the returned string is not permitted to contain any redundant trailing whitespace: you can use dynamically allocated character strings.
** Hints for people who don't know how to convert to hours, minutes, seconds:
- Tortoises don't care about fractions of seconds
- Think of calculation by hand using only integers (in your code use or simulate integer division)
- or Google: "convert decimal time to hours minutes seconds"
| 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 you will return `Nothing` (None).
#### Example:
```
a1 = ["hoqq", "bbllkw", "oox", "ejjuyyy", "plmiis", "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz", "qqquuhii", "dvvvwz"]
a2 = ["cccooommaaqqoxii", "gggqaffhhh", "tttoowwwmmww"]
mxdiflg(a1, a2) --> 13
```
#### Bash note:
- input : 2 strings with substrings separated by `,`
- output: number as a string | 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 tuple or a string depending on the language (see "Sample Tests")
with
- 1) the smallest number you got
- 2) the index `i` of the digit `d` you took, `i` as small as possible
- 3) the index `j` (as small as possible) where you insert this digit `d` to have the smallest number.
#### Examples:
```
smallest(261235) --> [126235, 2, 0] or (126235, 2, 0) or "126235, 2, 0"
```
`126235` is the smallest number gotten by taking `1` at index `2` and putting it at index `0`
```
smallest(209917) --> [29917, 0, 1] or ...
[29917, 1, 0] could be a solution too but index `i` in [29917, 1, 0] is greater than
index `i` in [29917, 0, 1].
```
`29917` is the smallest number gotten by taking `2` at index `0` and putting it at index `1`
which gave `029917` which is the number `29917`.
```
smallest(1000000) --> [1, 0, 6] or ...
```
#### Note
Have a look at "Sample Tests" to see the input and output in each language | 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 , from1 , to1 ] | 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
the k*k are 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
We are using the digit 1 in: 1, 16, 81, 100. The total count is then 4.
The function, when given n = 25 and d = 1 as argument, should return 11 since
the k*k that contain the digit 1 are:
1, 16, 81, 100, 121, 144, 169, 196, 361, 441.
So there are 11 digits 1 for the squares of numbers between 0 and 25.
```
Note that `121` has twice the digit 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 meaning: 1 == 1
1 != -1
#Examples:
```
[1,4,4,4,0,4,3,3,1] # should return [1,12,0,4,6,1]
"""So as you can see sum of consecutives 1 is 1
sum of 3 consecutives 4 is 12
sum of 0... and sum of 2
consecutives 3 is 6 ..."""
[1,1,7,7,3] # should return [2,14,3]
[-5,-5,7,7,12,0] # should return [-10,14,12,0]
``` | 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 keeping the first four it remains only one digit which
rotated is itself.
You have the following sequence of numbers:
`56789 -> 67895 -> 68957 -> 68579 -> 68597`
and you must return the greatest: `68957`.
#### Task
~~~if-not:factor
Write `function max_rot(n)` which given a positive integer `n` returns the maximum number you got doing rotations similar to the above example.
So `max_rot` (or `maxRot` or ... depending on the language) is such as:
- `max_rot(56789) should return 68957`
- `max_rot(38458215) should return 85821534`
~~~
~~~if:factor
Write a word `max-rot ( n -- max )` which given a positive integer `n` returns the maximum number you got doing rotations similar to the above example.
Here are a few example inputs:
- `56789 max-rot` should return `68957`
- `38458215 max-rot` should return `85821534`
~~~ | 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
# 110 is not a vampire number since there are three 1's in the
# multiplicands, but only two 1's in the product
```
Create a function that can receive two 'fangs' and determine if the product of the two is a valid vampire number.
| 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 string of **length 4 or greater** into an abbreviation, following these rules:
* A "word" is a sequence of alphabetical characters. By this definition, any other character like a space or hyphen (eg. "elephant-ride") will split up a series of letters into two words (eg. "elephant" and "ride").
* The abbreviated version of the word should have the first letter, then the number of removed characters, then the last letter (eg. "elephant ride" => "e6t r2e").
## Example
```javascript
abbreviate("elephant-rides are really fun!")
// ^^^^^^^^*^^^^^*^^^*^^^^^^*^^^*
// words (^): "elephant" "rides" "are" "really" "fun"
// 123456 123 1 1234 1
// ignore short words: X X
// abbreviate: "e6t" "r3s" "are" "r4y" "fun"
// all non-word characters (*) remain in place
// "-" " " " " " " "!"
=== "e6t-r3s are r4y fun!"
``` | 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" -> "304152"
encrypt("012345", 3) => "135024" -> "304152" -> "012345"
encrypt("01234", 1) => "13024"
encrypt("01234", 2) => "13024" -> "32104"
encrypt("01234", 3) => "13024" -> "32104" -> "20314"
```
Together with the encryption function, you should also implement a decryption function which reverses the process.
If the string `S` is an empty value or the integer `N` is not positive, return the first argument without changes.
___
This kata is part of the Simple Encryption Series:
* [Simple Encryption #1 - Alternating Split](https://www.codewars.com/kata/simple-encryption-number-1-alternating-split)
* [Simple Encryption #2 - Index-Difference](https://www.codewars.com/kata/simple-encryption-number-2-index-difference)
* [Simple Encryption #3 - Turn The Bits Around](https://www.codewars.com/kata/simple-encryption-number-3-turn-the-bits-around)
* [Simple Encryption #4 - Qwerty](https://www.codewars.com/kata/simple-encryption-number-4-qwerty)
Have fun coding it and please don't forget to vote and rank this kata! :-) | 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:: 2] + text[:: 2]
return text
| 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 done correctly:
```
({})
[[]()]
[{()}]
```
The next are done incorrectly:
```
{(})
([]
[])
```
A correct string cannot close groups in the wrong order, open a group but fail to close it, or close a group before it is opened.
Your function will take an input string that may contain any of the symbols `()`, `{}` or `[]` to create groups.
It should return `True` if the string is empty or otherwise grouped correctly, or `False` if it is grouped incorrectly. | 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.
### Example
"abcde" -> 0 `# no characters repeats more than once`
"aabbcde" -> 2 `# 'a' and 'b'`
"aabBcde" -> 2 ``# 'a' occurs twice and 'b' twice (`b` and `B`)``
"indivisibility" -> 1 `# 'i' occurs six times`
"Indivisibilities" -> 2 `# 'i' occurs seven times and 's' occurs twice`
"aA11" -> 2 `# 'a' and '1'`
"ABBA" -> 2 `# 'A' and 'B' each occur twice`
| 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 task is to return the number of people who are still on the bus after the last bus stop (after the last array). Even though it is the last bus stop, the bus might not be empty and some people might still be inside the bus, they are probably sleeping there :D
Take a look on the test cases.
Please keep in mind that the test cases ensure that the number of people in the bus is always >= 0. So the returned integer can't be negative.
The second value in the first pair in the array is 0, since the bus is empty in the first bus stop.
| 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 paper.
So we decided to write a program that could help us and protects trees.
#### Task
Given a positive integral number n, return a **strictly increasing** sequence (list/array/string depending on the language) of numbers, so that the sum of the squares is equal to n².
If there are multiple solutions (and there will be), return as far as possible the result with the largest possible values:
#### Examples
`decompose(11)` must return `[1,2,4,10]`. Note that there are actually two ways to decompose 11²,
11² = 121 = 1 + 4 + 16 + 100 = 1² + 2² + 4² + 10² but don't return `[2,6,9]`, since 9 is smaller than 10.
For `decompose(50)` don't return `[1, 1, 4, 9, 49]` but `[1, 3, 5, 8, 49]` since `[1, 1, 4, 9, 49]`
doesn't form a strictly increasing sequence.
#### Note
Neither `[n]` nor `[1,1,1,…,1]` are valid solutions. If no valid solution exists, return `nil`, `null`, `Nothing`, `None` (depending on the language) or `"[]"` (C) ,`{}` (C++), `[]` (Swift, Go).
The function "decompose" will take a positive integer n
and return the decomposition of N = n² as:
- [x1 ... xk]
or
- "x1 ... xk"
or
- Just [x1 ... xk]
or
- Some [x1 ... xk]
or
- {x1 ... xk}
or
- "[x1,x2, ... ,xk]"
depending on the language (see "Sample tests")
#### Note for Bash
```
decompose 50 returns "1,3,5,8,49"
decompose 4 returns "Nothing"
```
#### Hint
Very often `xk` will be `n-1`.
| 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 worry about sorting the output.
* Your string will never be empty.
Have fun! | 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 a nose are `-` or `~`
- Every smiling face must have a smiling mouth that should be marked with either `)` or `D`
No additional characters are allowed except for those mentioned.
**Valid smiley face examples:** `:) :D ;-D :~)`
**Invalid smiley faces:** `;( :> :} :]`
## Example
```
countSmileys([':)', ';(', ';}', ':-D']); // should return 2;
countSmileys([';D', ':-(', ':-)', ';~)']); // should return 3;
countSmileys([';]', ':[', ';*', ':$', ';-D']); // should return 1;
```
## Note
In case of an empty array return 0. You will not be tested with invalid input (input will always be an array). Order of the face (eyes, nose, mouth) elements will always be the same.
| 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 values.
```
```if:java
You will be provided with an array of `Person` objects with each instance containing the name and department for a staff member.
~~~java
public class Person {
public final String name; // name of the staff member
public final String department; // department they work in
}
~~~
```
Each department has a different boredom assessment score, as follows:
accounts = 1<br>
finance = 2 <br>
canteen = 10 <br>
regulation = 3 <br>
trading = 6 <br>
change = 6<br>
IS = 8<br>
retail = 5<br>
cleaning = 4<br>
pissing about = 25<br>
Depending on the cumulative score of the team, return the appropriate sentiment:
<=80: 'kill me now'<br>
< 100 & > 80: 'i can handle this'<br>
100 or over: 'party time!!'
<a href='https://www.codewars.com/kata/the-office-i-outed'>The Office I - Outed</a><br>
<a href='https://www.codewars.com/kata/the-office-iii-broken-photocopier'>The Office III - Broken Photocopier</a><br>
<a href='https://www.codewars.com/kata/the-office-iv-find-a-meeting-room'>The Office IV - Find a Meeting Room</a><br>
<a href='https://www.codewars.com/kata/the-office-v-find-a-chair'>The Office V - Find a Chair</a><br> | 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 . values())
if n <= 80:
return "kill me now"
if n < 100:
return "i can handle this"
return "party time!!"
| 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 add it to the sum. See the 4th example below.
**Examples**
~~~if-not:nasm
```
2,2,2 --> 2
2,6,2 --> 12 (2 + 4 + 6)
1,5,1 --> 15 (1 + 2 + 3 + 4 + 5)
1,5,3 --> 5 (1 + 4)
```
~~~
```if:nasm
mov edi, 2
mov esi, 2
mov edx, 2
call sequence_sum ; EAX <- 2
mov edi, 2
mov esi, 6
mov edx, 2
call sequence_sum ; EAX <- 12 = 2 + 4 + 6
mov edi, 1
mov esi, 5
mov edx, 1
call sequence_sum ; EAX <- 15 = 1 + 2 + 3 + 4 + 5
mov edi, 1
mov esi, 5
mov edx, 3
call sequence_sum ; EAX <- 5 = 1 + 4
```
This is the first kata in the series:
1) Sum of a sequence (this kata)
2) [Sum of a Sequence [Hard-Core Version]](https://www.codewars.com/kata/sum-of-a-sequence-hard-core-version/javascript)
| 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 will have for my gift on Saturday evening after I have saved 12? (Your function finance(6) should return 168 which is the sum of the savings in the table).
Imagine now that we live on planet XY140Z-n where the days of the week are numbered from 0 to n (integer n > 0) and where
I save from week number 0 to week number n included (in the table below n = 6).
How much money would I have at the end of my financing plan on planet XY140Z-n?
-- |Su|Mo|Tu|We|Th|Fr|Sa|
--|--|--|--|--|--|--|--|
W6 | | | | | | |12|
W5 | | | | | |10|11|
W4 | | | | |8 |9 |10|
W3 | | | |6 |7 |8 |9 |
W2 | | |4 |5 |6 |7 |8 |
W1 | |2 |3 |4 |5 |6 |7 |
W0 |0 |1 |2 |3 |4 |5 |6 |
#### Example:
```
finance(5) --> 105
finance(6) --> 168
finance(7) --> 252
finance(5000) --> 62537505000
```
#### Note:
your solution will be nicer without loops.
| 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's computer, and we have a box hooked up that reads mileage numbers. We've got a box glued to his dash that lights up yellow or green depending on whether it receives a `1` or a `2` (respectively).
It's up to you, intrepid warrior, to glue the parts together. Write the function that parses the mileage number input, and returns a `2` if the number is "interesting" (see below), a `1` if an interesting number occurs within the next two miles, or a `0` if the number is not interesting.
**Note:** In Haskell, we use `No`, `Almost` and `Yes` instead of `0`, `1` and `2`.
## "Interesting" Numbers
Interesting numbers are 3-or-more digit numbers that meet one or more of the following criteria:
```if-not:ruby,python
* Any digit followed by all zeros: `100`, `90000`
* Every digit is the same number: `1111`
* The digits are sequential, incementing<sup>†</sup>: `1234`
* The digits are sequential, decrementing<sup>‡</sup>: `4321`
* The digits are a palindrome: `1221` or `73837`
* The digits match one of the values in the `awesomePhrases` array
```
```if:ruby,python
* Any digit followed by all zeros: `100`, `90000`
* Every digit is the same number: `1111`
* The digits are sequential, incementing<sup>†</sup>: `1234`
* The digits are sequential, decrementing<sup>‡</sup>: `4321`
* The digits are a palindrome: `1221` or `73837`
* The digits match one of the values in the `awesome_phrases` array
```
> <sup>†</sup> For incrementing sequences, `0` should come after `9`, and not before `1`, as in `7890`.<br>
> <sup>‡</sup> For decrementing sequences, `0` should come after `1`, and not before `9`, as in `3210`.
So, you should expect these inputs and outputs:
```javascript
// "boring" numbers
isInteresting(3, [1337, 256]); // 0
isInteresting(3236, [1337, 256]); // 0
// progress as we near an "interesting" number
isInteresting(11207, []); // 0
isInteresting(11208, []); // 0
isInteresting(11209, []); // 1
isInteresting(11210, []); // 1
isInteresting(11211, []); // 2
// nearing a provided "awesome phrase"
isInteresting(1335, [1337, 256]); // 1
isInteresting(1336, [1337, 256]); // 1
isInteresting(1337, [1337, 256]); // 2
```
```haskell
-- "boring" numbers
isInteresting 3 [1337, 256] -- 0
isInteresting 3236 [1337, 256] -- 0
-- progress as we near an "interesting" number
isInteresting 11207 [] -- No
isInteresting 11208 [] -- No
isInteresting 11209 [] -- Almost
isInteresting 11210 [] -- Almost
isInteresting 11211 [] -- Yes
-- nearing a provided "awesome phrase"
isInteresting 1335 [1337, 256] -- Almost
isInteresting 1336 [1337, 256] -- Almost
isInteresting 1337 [1337, 256] -- Yes
```
```coffeescript
# "boring" numbers
isInteresting(3, [1337, 256]) # 0
isInteresting(3236, [1337, 256]) # 0
# progress as we near an "interesting" number
isInteresting(11207, []) # 0
isInteresting(11208, []) # 0
isInteresting(11209, []) # 1
isInteresting(11210, []) # 1
isInteresting(11211, []) # 2
# nearing a provided "awesome phrase"
isInteresting(1335, [1337, 256]) # 1
isInteresting(1336, [1337, 256]) # 1
isInteresting(1337, [1337, 256]) # 2
```
```java
// "boring" numbers
CarMileage.isInteresting(3, new int[]{1337, 256}); // 0
CarMileage.isInteresting(3236, new int[]{1337, 256}); // 0
// progress as we near an "interesting" number
CarMileage.isInteresting(11207, new int[]{}); // 0
CarMileage.isInteresting(11208, new int[]{}); // 0
CarMileage.isInteresting(11209, new int[]{}); // 1
CarMileage.isInteresting(11210, new int[]{}); // 1
CarMileage.isInteresting(11211, new int[]{}); // 2
// nearing a provided "awesome phrase"
CarMileage.isInteresting(1335, new int[]{1337, 256}); // 1
CarMileage.isInteresting(1336, new int[]{1337, 256}); // 1
CarMileage.isInteresting(1337, new int[]{1337, 256}); // 2
```
```python
# "boring" numbers
is_interesting(3, [1337, 256]) # 0
is_interesting(3236, [1337, 256]) # 0
# progress as we near an "interesting" number
is_interesting(11207, []) # 0
is_interesting(11208, []) # 0
is_interesting(11209, []) # 1
is_interesting(11210, []) # 1
is_interesting(11211, []) # 2
# nearing a provided "awesome phrase"
is_interesting(1335, [1337, 256]) # 1
is_interesting(1336, [1337, 256]) # 1
is_interesting(1337, [1337, 256]) # 2
```
```ruby
# "boring" numbers
is_interesting(3, [1337, 256]) # 0
is_interesting(3236, [1337, 256]) # 0
# progress as we near an "interesting" number
is_interesting(11207, []) # 0
is_interesting(11208, []) # 0
is_interesting(11209, []) # 1
is_interesting(11210, []) # 1
is_interesting(11211, []) # 2
# nearing a provided "awesome phrase"
is_interesting(1335, [1337, 256]) # 1
is_interesting(1336, [1337, 256]) # 1
is_interesting(1337, [1337, 256]) # 2
```
```csharp
// "boring" numbers
Kata.IsInteresting(3, new List<int>() { 1337, 256 }); // 0
Kata.IsInteresting(3236, new List<int>() { 1337, 256 }); // 0
// progress as we near an "interesting" number
Kata.IsInteresting(11207, new List<int>() { }); // 0
Kata.IsInteresting(11208, new List<int>() { }); // 0
Kata.IsInteresting(11209, new List<int>() { }); // 1
Kata.IsInteresting(11210, new List<int>() { }); // 1
Kata.IsInteresting(11211, new List<int>() { }); // 2
// nearing a provided "awesome phrase"
Kata.IsInteresting(1335, new List<int>() { 1337, 256 }); // 1
Kata.IsInteresting(1336, new List<int>() { 1337, 256 }); // 1
Kata.IsInteresting(1337, new List<int>() { 1337, 256 }); // 2
```
## Error Checking
* A number is only interesting if it is greater than `99`!
* Input will *always* be an integer greater than `0`, and less than `1,000,000,000`.
* The `awesomePhrases` array will always be provided, and will always be an array, but may be empty. (Not *everyone* thinks numbers spell funny words...)
* You should only ever output `0`, `1`, or `2`. | 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_phrases):
tests = (is_round, is_incrementing, is_decrementing,
is_palindrome, awesome_phrases . __contains__)
for num, color in zip(range(number, number + 3), (2, 1, 1)):
if num >= 100 and any(test(num) for test in tests):
return color
return 0
| 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 the day **AFTER** the expiration date. All dates will be passed as strings in this format: `"MONTH DATE, YEAR"`.
## Examples:
```javascript
checkCoupon("123", "123", "July 9, 2015", "July 9, 2015") === true
checkCoupon("123", "123", "July 9, 2015", "July 2, 2015") === false
```
```typescript
checkCoupon("123", "123", "July 9, 2015", "July 9, 2015") === true
checkCoupon("123", "123", "July 9, 2015", "July 2, 2015") === false
```
```csharp
CheckCoupon("123", "123", "July 9, 2015", "July 9, 2015") == true
CheckCoupon("123", "123", "July 9, 2015", "July 2, 2015") == false
```
```python
checkCoupon("123", "123", "July 9, 2015", "July 9, 2015") == True
checkCoupon("123", "123", "July 9, 2015", "July 2, 2015") == False
``` | 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 return {1,2,3,4,5,6,7,8,9,10}
countBy(2,5) should return {2,4,6,8,10}
```
```java
countBy(1,10) // should return {1,2,3,4,5,6,7,8,9,10}
countBy(2,5) // should return {2,4,6,8,10}
```
```javascript
countBy(1,10) === [1,2,3,4,5,6,7,8,9,10]
countBy(2,5) === [2,4,6,8,10]
```
```nasm
mov rdi, .memory ; {,,,,,,,,}
mov esi, 1
mov rdx, 10
call cntbyx ; [RAX] <- {1,2,3,4,5,6,7,8,9,10}
mov rdi, .memory ; {,,,,}
mov esi 2
mov rdx, 5
call cntbyx ; [RAX] <- {2,4,6,8,10}
```
```coffeescript
countBy(1,10) == [1,2,3,4,5,6,7,8,9,10]
countBy(2,5) == [2,4,6,8,10]
```
```dart
countBy(1,10) === [1,2,3,4,5,6,7,8,9,10]
countBy(2,5) === [2,4,6,8,10]
```
```coffeescript
countBy(1,10) == [1,2,3,4,5,6,7,8,9,10]
countBy(2,5) == [2,4,6,8,10]
```
```python
count_by(1,10) #should return [1,2,3,4,5,6,7,8,9,10]
count_by(2,5) #should return [2,4,6,8,10]
```
```ruby
count_by(1,10) #should return [1,2,3,4,5,6,7,8,9,10]
count_by(2,5) #should return [2,4,6,8,10]
```
```crystal
count_by(1,10) #should return [1,2,3,4,5,6,7,8,9,10]
count_by(2,5) #should return [2,4,6,8,10]
```
```julia
countby(1,10) === [1,2,3,4,5,6,7,8,9,10]
countby(2,5) === [2,4,6,8,10]
```
```r
count_by(1,10) #should return c(1,2,3,4,5,6,7,8,9,10)
count_by(2,5) #should return c(2,4,6,8,10)
```
```haskell
countBy 1 10 `shouldBe` [1,2,3,4,5,6,7,8,9,10]
countBy 2 5 `shouldBe` [2,4,6,8,10]
```
```lambdacalc
count-by 1 10 -> [1,2,3,4,5,6,7,8,9,10]
count-by 2 5 -> [2,4,6,8,10]
```
```elixir
count_by(1, 10) == [1,2,3,4,5,6,7,8,9,10]
count_by(2, 5) == [2,4,6,8,10]
```
```solidity
countBy(1,10) // should return [1,2,3,4,5,6,7,8,9,10]
countBy(2,5) // should return [2,4,6,8,10]
```
```php
countBy(1,10) // should return [1,2,3,4,5,6,7,8,9,10]
countBy(2,5) // should return [2,4,6,8,10]
```
```groovy
Kata.countBy(1, 10) == [1,2,3,4,5,6,7,8,9,10]
Kata.countBy(2, 5) == [2,4,6,8,10]
```
```racket
(count-by 1 10) ; returns '(1 2 3 4 5 6 7 8 9 10)
(count-by 2 5) ; returns '(2 4 6 8 10)
```
```rust
count_by(1, 10) // should return vec![1,2,3,4,5,6,7,8,9,10]
count_by(2,5) // should return vec![2,4,6,8,10]
```
~~~if:lambdacalc
### Encodings
purity: `LetRec`
numEncoding: `Scott`
export `foldl` for your `List` encoding
~~~ | 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 rule of the series to complete this.
## Rules
* You need to round the answer to 2 decimal places and return it as String.
* If the given value is `0` then it should return `"0.00"`.
* You will only be given Natural Numbers as arguments.
## Examples (Input --> Output)
n
1 --> 1 --> "1.00"
2 --> 1 + 1/4 --> "1.25"
5 --> 1 + 1/4 + 1/7 + 1/10 + 1/13 --> "1.57"
| 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){
var COLLECTION = 'https://www.codewars.com/collections/bug-fixing';
var qCode = String.fromCharCode(34);
function ioa(str, f) {
var a=[],i=-1;
while((i=str.indexOf(f,i+1)) >= 0) a.push(i);
return a;
}
function fc(op,cl) {
var arr=[], d=0;
op = op.map(a => {return {i:a,q:'<'};});
cl = cl.map(a => {return {i:a,q:'>'};});
var cmb = [].concat(op,cl).sort((a,b) =>a.i-b.i);
for(var i=0;i<cmb.length-1;i++) {
d += cmb[i].q === '<' ? 1 : -1;
if(d === 0 || (i > 2 && d === 2))
return cmb[i].i;
}
return -1;
}
function processKataData(data) {
var kataData = {};
var inx1 = data.indexOf('data-title='+qCode)+12;
var kataTitle = data.slice(inx1).slice(0,data.slice(inx1).indexOf(qCode))
var inx2 = data.indexOf('href='+qCode)+6;
var kataLink = data.slice(inx2).slice(0,data.slice(inx2).indexOf(qCode))
kataData.title = kataTitle;
kataData.link = kataLink;
return kataData;
}
function processData(msg) {
var data = msg.split('\n');
var dindex = data.slice(7,8).join('').indexOf('<div class='+qCode+'nine columns prn'+qCode+'>');
var filteredData = data.slice(7,8).join('').split('').filter((a,i) => i>=dindex).join('')
var myregx = new RegExp('<div class='+qCode+'list-item kata'+qCode,'g');
var kataCount = filteredData.match(myregx).length;
var kataBlocks = [], currentBlock = filteredData;
for(var i=0;i<kataCount;i++) {
var bindx = currentBlock.indexOf('<div class='+qCode+'list-item kata'+qCode+''),
block = currentBlock.slice(bindx),
closingBlock = fc(ioa(block, '<div').slice(0,10),ioa(block, '</div').slice(0,10)),
kataData = block.slice(0,closingBlock).replace(/(<)/g,'[').replace(/(>)/g,']');
kataBlocks.push(kataData);
currentBlock = block.slice(closingBlock+3);
}
var kataDatas = kataBlocks.map(processKataData);
return kataDatas;
}
function getData() {
$.ajax({
type: 'GET',
url: COLLECTION,
headers: {
Host: 'www.codewars.com',
Accept: 'text/html, */*; q=0.01',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate, br',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-PJAX': 'true',
'X-PJAX-Container': 'body',
'X-Requested-With': 'XMLHttpRequest',
Referer: 'https://www.codewars.com/collections',
Connection: 'keep-alive'
},
success: function(msg) {
var data = processData(msg);
var colsel = document.getElementById('collectionSelect');
for(var i=0;i<data.length;i++) {
var option = document.createElement('option');
option.text = data[i].title;
option.value = data[i].link
colsel.add(option);
}
function onchanging(e) {
alert(e);
}
colsel.addEventListener(
'change',
function(e) {
var options = colsel.options;
if(colsel.selectedIndex < options.length) {
var selected = options[colsel.selectedIndex];
if(selected) {
console.log(selected.value);
window.location.href = 'https://www.codewars.com' + selected.value;
}
}
},
false
);
}
});
}
getData();
})(this)" />
--> | 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 replace these words with the word "awesome" to make the message more positive. Your task is to implement a function, that replaces all occurrences of these offensive words with "awesome" in the input string `phrase`.
**Input:**
- A string `phrase` containing words separated by spaces.
**Output:**
- A string with the same words as `phrase`, but with any offensive words replaced by "awesome."
**Example:**
```plaintext
Input: "You're Bad! timmy!"
Output: "You're awesome! timmy!"
```
```plaintext
Input: "You're MEAN! timmy!"
Output: "You're awesome! timmy!"
``` | 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 |