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 |
---|---|---|---|---|---|---|---|
# Rock Paper Scissors
Let's play! You have to return which player won! In case of a draw return `Draw!`.
**Examples(Input1, Input2 --> Output):**
```
"scissors", "paper" --> "Player 1 won!"
"scissors", "rock" --> "Player 2 won!"
"paper", "paper" --> "Draw!"
```
![rockpaperscissors](http://i.imgur.com/aimOQVX.png) | reference | def rps(p1, p2):
beats = {'rock': 'scissors', 'scissors': 'paper', 'paper': 'rock'}
if beats[p1] == p2:
return "Player 1 won!"
if beats[p2] == p1:
return "Player 2 won!"
return "Draw!"
| Rock Paper Scissors! | 5672a98bdbdd995fad00000f | [
"Fundamentals"
] | https://www.codewars.com/kata/5672a98bdbdd995fad00000f | 8 kyu |
This code should store `"codewa.rs"` as a variable called `name` but it's not working. Can you figure out why? | bug_fixes | a = "code"
b = "wa.rs"
name = a + b
| Basic variable assignment | 50ee6b0bdeab583673000025 | [
"Debugging"
] | https://www.codewars.com/kata/50ee6b0bdeab583673000025 | 8 kyu |
## Task
* **_Given_** *three integers* `a` ,`b` ,`c`, **_return_** *the **_largest number_** obtained after inserting the following operators and brackets*: `+`, `*`, `()`
* In other words , **_try every combination of a,b,c with [*+()] , and return the Maximum Obtained_** <span style="color:red">(Read the notes for more detail about it)</span>
## Example
**_With the numbers are 1, 2 and 3_** , *here are some ways of placing signs and brackets*:
* `1 * (2 + 3) = 5`
* `1 * 2 * 3 = 6`
* `1 + 2 * 3 = 7`
* `(1 + 2) * 3 = 9`
So **_the maximum value_** that you can obtain is **_9_**.
## Notes
* **_The numbers_** *are always* **_positive_**.
* **_The numbers_** *are in the range* **_(1 ≤ a, b, c ≤ 10)_**.
* *You can use the same operation* **_more than once_**.
* **It's not necessary** *to place all the signs and brackets*.
* **_Repetition_** *in numbers may occur* .
* You **_cannot swap the operands_**. For instance, in the given example **_you cannot get expression_** `(1 + 3) * 2 = 8`.
___
# Input >> Output Examples:
```
expressionsMatter(1,2,3) ==> return 9
```
## **_Explanation_**:
*After placing signs and brackets, the **_Maximum value_** obtained from the expression* `(1+2) * 3 = 9`.
___
```
expressionsMatter(1,1,1) ==> return 3
```
## **_Explanation_**:
*After placing signs, the **_Maximum value_** obtained from the expression is* `1 + 1 + 1 = 3`.
___
```
expressionsMatter(9,1,1) ==> return 18
```
## **_Explanation_**:
*After placing signs and brackets, the **_Maximum value_** obtained from the expression is* `9 * (1+1) = 18`.
___# Task
* **_Given_** *three integers* `a` ,`b` ,`c`, **_return_** *the **_largest number_** obtained after inserting the following operators and brackets*: `+`, `*`, `()`
* In other words , **_try every combination of a,b,c with [*+()] , and return the Maximum Obtained_**
## Example
**_With the numbers are 1, 2 and 3_** , *here are some ways of placing signs and brackets*:
* `1 * (2 + 3) = 5`
* `1 * 2 * 3 = 6`
* `1 + 2 * 3 = 7`
* `(1 + 2) * 3 = 9`
So **_the maximum value_** that you can obtain is **_9_**.
## Notes
* **_The numbers_** *are always* **_positive_**.
* **_The numbers_** *are in the range* **_(1 ≤ a, b, c ≤ 10)_**.
* *You can use the same operation* **_more than once_**.
* **It's not necessary** *to place all the signs and brackets*.
* **_Repetition_** *in numbers may occur* .
* You **_cannot swap the operands_**. For instance, in the given example **_you cannot get expression_** `(1 + 3) * 2 = 8`.
___
# Input >> Output Examples:
```
expressionsMatter(1,2,3) ==> return 9
```
## **_Explanation_**:
*After placing signs and brackets, the **_Maximum value_** obtained from the expression* `(1+2) * 3 = 9`.
___
```
expressionsMatter(1,1,1) ==> return 3
```
___
___
# [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
# [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)
# [Bizarre Sorting-katas](https://www.codewars.com/collections/bizarre-sorting-katas)
# [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored)
___
## ALL translations are welcomed
## Enjoy Learning !!
# Zizou
| reference | def expression_matter(a, b, c):
return max(a * b * c, a + b + c, (a + b) * c, a * (b + c))
| Expressions Matter | 5ae62fcf252e66d44d00008e | [
"Algorithms",
"Fundamentals"
] | https://www.codewars.com/kata/5ae62fcf252e66d44d00008e | 8 kyu |
Given a set of numbers, return the additive inverse of each. Each positive becomes negatives, and the negatives become positives.
~~~if-not:racket
```
invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5]
invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5]
invert([]) == []
```
~~~
```if:javascript,python,ruby,php,elixir,dart,go
You can assume that all values are integers. Do not mutate the input array/list.
```
```if:c,riscv
### Notes:
- All values are greater than `INT_MIN`
- The input should be modified, not returned.
```
~~~if:racket
```racket
(invert '(1 2 3 4 5)) ; '(-1 -2 -3 -4 -5)
(invert '(1 -2 3 -4 5)) ; '(-1 2 -3 4 -5)
(invert '()) ; '()
```
~~~
~~~if:riscv
RISC-V: The function signature is:
```c
void invert(int *arr, size_t size);
```
The input array is `arr` which contains `size` elements. Mutate the array in-place according to the above specification. You do not need to return anything.
~~~
| reference | def invert(lst):
return [- x for x in lst]
| Invert values | 5899dc03bc95b1bf1b0000ad | [
"Lists",
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/5899dc03bc95b1bf1b0000ad | 8 kyu |
Who remembers back to their time in the schoolyard, when girls would take a flower and tear its petals, saying each of the following phrases each time a petal was torn:
1. "I love you"
2. "a little"
3. "a lot"
4. "passionately"
5. "madly"
6. "not at all"
If there are more than 6 petals, you start over with `"I love you"` for 7 petals, `"a little"` for 8 petals and so on.
When the last petal was torn there were cries of excitement, dreams, surging thoughts and emotions.
Your goal in this kata is to determine which phrase the girls would say at the last petal for a flower of a given number of petals. The number of petals is always greater than 0. | reference | def how_much_i_love_you(nb_petals):
return ["I love you", "a little", "a lot", "passionately", "madly", "not at all"][nb_petals % 6 - 1] # g
| I love you, a little , a lot, passionately ... not at all | 57f24e6a18e9fad8eb000296 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/57f24e6a18e9fad8eb000296 | 8 kyu |
Simple, given a string of words, return the length of the shortest word(s).
String will never be empty and you do not need to account for different data types.
| reference | def find_short(s):
return min(len(x) for x in s . split())
| Shortest Word | 57cebe1dc6fdc20c57000ac9 | [
"Fundamentals"
] | https://www.codewars.com/kata/57cebe1dc6fdc20c57000ac9 | 7 kyu |
An isogram is a word that has no repeating letters, consecutive or non-consecutive. Implement a function that determines whether a string that contains only letters is an isogram. Assume the empty string is an isogram. Ignore letter case.
**Example: (Input --> Output)**
```if-not:factor
"Dermatoglyphics" --> true
"aba" --> false
"moOse" --> false (ignore letter case)
```
```if:factor
"Dermatoglyphics" -> t
"aba" -> f
"moOse" -> f (ignore letter case)
```
```fsharp
isIsogram "Dermatoglyphics" = true
isIsogram "moose" = false
isIsogram "aba" = false
```
| reference | def is_isogram(string):
return len(string) == len(set(string . lower()))
| Isograms | 54ba84be607a92aa900000f1 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/54ba84be607a92aa900000f1 | 7 kyu |
You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer `N`. Write a method that takes the array as an argument and returns this "outlier" `N`.
## Examples
```
[2, 4, 0, 100, 4, 11, 2602, 36] --> 11 (the only odd number)
[160, 3, 1719, 19, 11, 13, -21] --> 160 (the only even number)
```
| algorithms | def find_outlier(int):
odds = [x for x in int if x % 2 != 0]
evens = [x for x in int if x % 2 == 0]
return odds[0] if len(odds) < len(evens) else evens[0]
| Find The Parity Outlier | 5526fc09a1bbd946250002dc | [
"Algorithms"
] | https://www.codewars.com/kata/5526fc09a1bbd946250002dc | 6 kyu |
A hero is on his way to the castle to complete his mission. However, he's been told that the castle is surrounded with a couple of powerful dragons! each dragon takes 2 bullets to be defeated, our hero has no idea how many bullets he should carry.. Assuming he's gonna grab a specific given number of bullets and move forward to fight another specific given number of dragons, will he survive?
Return true if yes, false otherwise :) | reference | def hero(bullets, dragons):
return bullets >= dragons * 2
| Is he gonna survive? | 59ca8246d751df55cc00014c | [
"Fundamentals"
] | https://www.codewars.com/kata/59ca8246d751df55cc00014c | 8 kyu |
~~~if:bf
Write a program which accepts a single byte `n` and then a sequence of bytes `string` and outputs the `string` exactly `n` times.
The first input byte will be `n`. Following bytes will be characters of `string`. The end of the input `string` will be indicated with a null byte `\0`.
### Examples:
"\6I" -> "IIIIII"
"\5Hello" -> "HelloHelloHelloHelloHello"
~~~
Write a function that accepts an integer `n` and a string `s` as parameters, and returns a string of `s` repeated exactly `n` times.
### Examples (input -> output)
```
6, "I" -> "IIIIII"
5, "Hello" -> "HelloHelloHelloHelloHello"
```
| reference | def repeat_str(repeat, string):
return repeat * string
| String repeat | 57a0e5c372292dd76d000d7e | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/57a0e5c372292dd76d000d7e | 8 kyu |
I'm new to coding and now I want to get the sum of two arrays... Actually the sum of all their elements. I'll appreciate for your help.
P.S. Each array includes only integer numbers. Output is a number too. | bug_fixes | def array_plus_array(arr1, arr2):
return sum(arr1 + arr2)
| Array plus array | 5a2be17aee1aaefe2a000151 | [
"Fundamentals",
"Arrays",
"Debugging"
] | https://www.codewars.com/kata/5a2be17aee1aaefe2a000151 | 8 kyu |
Given a positive integer `n: 0 < n < 1e6`, remove the last digit until you're left with a number that is a multiple of three.
Return `n` if the input is already a multiple of three, and if no such number exists, return `null`, a similar empty value, or `-1`.
## Examples
```
1 => null
25 => null
36 => 36
1244 => 12
952406 => 9
```
| reference | def prev_mult_of_three(n):
while n % 3:
n / /= 10
return n or None
| Previous multiple of three | 61123a6f2446320021db987d | [
"Fundamentals"
] | https://www.codewars.com/kata/61123a6f2446320021db987d | 7 kyu |
An **anagram** is the result of rearranging the letters of a word to produce a new word (see [wikipedia](https://en.wikipedia.org/wiki/Anagram)).
**Note:** anagrams are case insensitive
Complete the function to return `true` if the two arguments given are anagrams of each other; return `false` otherwise.
## Examples
* `"foefet"` is an anagram of `"toffee"`
* `"Buckethead"` is an anagram of `"DeathCubeK"`
| reference | def is_anagram(test, original):
return sorted(original . lower()) == sorted(test . lower())
| Anagram Detection | 529eef7a9194e0cbc1000255 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/529eef7a9194e0cbc1000255 | 7 kyu |
### Unfinished Loop - Bug Fixing #1
Oh no, Timmy's created an infinite loop! Help Timmy find and fix the bug in his unfinished for loop!
| bug_fixes | def create_array(n):
res = []
i = 1
while i <= n:
res += [i]
i += 1
return res
| Unfinished Loop - Bug Fixing #1 | 55c28f7304e3eaebef0000da | [
"Debugging"
] | https://www.codewars.com/kata/55c28f7304e3eaebef0000da | 8 kyu |
### The Story:
Bob is working as a bus driver. However, he has become extremely popular amongst the city's residents. With so many passengers wanting to get aboard his bus, he sometimes has to face the problem of not enough space left on the bus! He wants you to write a simple program telling him if he will be able to fit all the passengers.
### Task Overview:
You have to write a function that accepts three parameters:
* `cap` is the amount of people the bus can hold excluding the driver.
* `on` is the number of people on the bus excluding the driver.
* `wait` is the number of people waiting to get on to the bus excluding the driver.
If there is enough space, return 0, and if there isn't, return the number of passengers he can't take.
### Usage Examples:
```
cap = 10, on = 5, wait = 5 --> 0 # He can fit all 5 passengers
cap = 100, on = 60, wait = 50 --> 10 # He can't fit 10 of the 50 waiting
```
```if:csharp
<h1>Documentation:</h1>
<h2>Kata.Enough Method (Int32, Int32, Int32)</h2>
Returns the number of passengers the bus cannot fit, or 0 if the bus can fit every passenger.
<span style="font-size:20px">Syntax</span>
<div style="margin-top:-10px;padding:2px;background-color:Grey;position:relative;left:20px;width:600px;">
<div style="background-color:White;color:Black;border:1px;display:block;padding:10px;padding-left:18px;font-family:Consolas,Courier,monospace;">
<span style="color:Blue;">public</span>
<span style="color:Blue;">static</span>
<span style="color:Blue;">int</span> Enough(</br>
<span style="position:relative;left:62px;">int cap,</span></br>
<span style="position:relative;left:62px;">int on,</span></br>
<span style="position:relative;left:62px;">int wait</span></br>
)
</div>
</div>
</br>
<div style="position:relative;left:20px;">
<strong>Parameters</strong>
</br>
<i>cap</i>
</br>
<span style="position:relative;left:50px;">Type: <a href="https://msdn.microsoft.com/en-us/library/system.int32(v=vs.110).aspx">System.Int32</a></span></br>
<span style="position:relative;left:50px;">The amount of people that can fit on the bus excluding the driver.</span>
</br></br>
<i>on</i>
</br>
<span style="position:relative;left:50px;">Type: <a href="https://msdn.microsoft.com/en-us/library/system.int32(v=vs.110).aspx">System.Int32</a></span></br>
<span style="position:relative;left:50px;">The amount of people on the bus excluding the driver.</span>
</br></br>
<i>wait</i>
</br>
<span style="position:relative;left:50px;">Type: <a href="https://msdn.microsoft.com/en-us/library/system.int32(v=vs.110).aspx">System.Int32</a></span></br>
<span style="position:relative;left:50px;">The amount of people waiting to enter the bus.</span>
</br></br>
<strong>Return Value</strong>
</br>
<span>Type: <a href="https://msdn.microsoft.com/en-us/library/system.int32(v=vs.110).aspx">System.Int32</a></span></br>
An integer representing how many passengers cannot fit on the bus, or 0 if every passenger can fit on the bus.
</div>
```
| reference | def enough(cap, on, wait):
return max(0, wait - (cap - on))
| Will there be enough space? | 5875b200d520904a04000003 | [
"Fundamentals"
] | https://www.codewars.com/kata/5875b200d520904a04000003 | 8 kyu |
# altERnaTIng cAsE <=> ALTerNAtiNG CaSe
Define `String.prototype.toAlternatingCase` (or a similar function/method *such as* `to_alternating_case`/`toAlternatingCase`/`ToAlternatingCase` in your selected language; **see the initial solution for details**) such that each lowercase letter becomes uppercase and each uppercase letter becomes lowercase. For example:
```javascript
"hello world".toAlternatingCase() === "HELLO WORLD"
"HELLO WORLD".toAlternatingCase() === "hello world"
"hello WORLD".toAlternatingCase() === "HELLO world"
"HeLLo WoRLD".toAlternatingCase() === "hEllO wOrld"
"12345".toAlternatingCase() === "12345" // Non-alphabetical characters are unaffected
"1a2b3c4d5e".toAlternatingCase() === "1A2B3C4D5E"
"String.prototype.toAlternatingCase".toAlternatingCase() === "sTRING.PROTOTYPE.TOaLTERNATINGcASE"
```
```ruby
"hello world".to_alternating_case() === "HELLO WORLD"
"HELLO WORLD".to_alternating_case() === "hello world"
"hello WORLD".to_alternating_case() === "HELLO world"
"HeLLo WoRLD".to_alternating_case() === "hEllO wOrld"
"12345".to_alternating_case() === "12345" # Non-alphabetical characters are unaffected
"1a2b3c4d5e".to_alternating_case() === "1A2B3C4D5E"
"String.prototype.toAlternatingCase".to_alternating_case() === "sTRING.PROTOTYPE.TOaLTERNATINGcASE"
```
```crystal
"hello world".to_alternating_case() === "HELLO WORLD"
"HELLO WORLD".to_alternating_case() === "hello world"
"hello WORLD".to_alternating_case() === "HELLO world"
"HeLLo WoRLD".to_alternating_case() === "hEllO wOrld"
"12345".to_alternating_case() === "12345" # Non-alphabetical characters are unaffected
"1a2b3c4d5e".to_alternating_case() === "1A2B3C4D5E"
"String.prototype.toAlternatingCase".to_alternating_case() === "sTRING.PROTOTYPE.TOaLTERNATINGcASE"
```
```java
StringUtils.toAlternativeString("hello world") == "HELLO WORLD"
StringUtils.toAlternativeString("HELLO WORLD") == "hello world"
StringUtils.toAlternativeString("hello WORLD") == "HELLO world"
StringUtils.toAlternativeString("HeLLo WoRLD") == "hEllO wOrld"
StringUtils.toAlternativeString("12345") == "12345" // Non-alphabetical characters are unaffected
StringUtils.toAlternativeString("1a2b3c4d5e") == "1A2B3C4D5E"
StringUtils.toAlternativeString("StringUtils.toAlternatingCase") == "sTRINGuTILS.TOaLTERNATINGcASE"
```
``` haskell
toAlternatingCase "hello world" `shouldBe` "HELLO WORLD"
toAlternatingCase "HELLO WORLD" `shouldBe` "hello world"
toAlternatingCase "hello WORLD" `shouldBe` "HELLO world"
toAlternatingCase "HeLLo WoRLD" `shouldBe` "hEllO wOrld"
toAlternatingCase "12345" `shouldBe` "12345"
toAlternatingCase "1a2b3c4d5e" `shouldBe` "1A2B3C4D5E"
```
```csharp
"hello world".ToAlternatingCase() == "HELLO WORLD"
"HELLO WORLD".ToAlternatingCase() == "hello world"
"hello WORLD".ToAlternatingCase() == "HELLO world"
"HeLLo WoRLD".ToAlternatingCase() == "hEllO wOrld"
"12345".ToAlternatingCase() == "12345" // Non-alphabetical characters are unaffected
"1a2b3c4d5e".ToAlternatingCase() == "1A2B3C4D5E"
"String.ToAlternatingCase".ToAlternatingCase() == "sTRING.tOaLTERNATINGcASE"
```
```elixir
alter_case("hello world") == "HELLO WORLD"
alter_case("HELLO WORLD") == "hello world"
alter_case("hello WORLD") == "HELLO world"
alter_case("HeLLo WoRLD") == "hEllO wOrld"
alter_case("12345") == "12345" # Non-alphabetical characters are unaffected
alter_case("1a2b3c4d5e") == "1A2B3C4D5E"
alter_case("StringUtils.toAlternatingCase") == "sTRINGuTILS.TOaLTERNATINGcASE"
```
```julia
to_alternating_case("hello world") # => "HELLO WORLD"
to_alternating_case("HELLO WORLD") # => "hello world"
to_alternating_case("hello WORLD") # => "HELLO world"
to_alternating_case("HeLLo WoRLD") # => "hEllO wOrld"
to_alternating_case("12345") # => "12345" (Non-alphabetical characters are unaffected)
to_alternating_case("1a2b3c4d5e") # => "1A2B3C4D5E"
to_alternating_case("String.prototype.toAlternatingCase") # => "sTRING.PROTOTYPE.TOaLTERNATINGcASE"
```
```c
to_alternating_case("hello world"); // => "HELLO WORLD"
to_alternating_case("HELLO WORLD"); // => "hello world"
to_alternating_case("hello WORLD"); // => "HELLO world"
to_alternating_case("HeLLo WoRLD"); // => "hEllO wOrld"
to_alternating_case("12345"); // => "12345" (Non-alphabetical characters are unaffected)
to_alternating_case("1a2b3c4d5e"); // => "1A2B3C4D5E"
to_alternating_case("String.prototype.toAlternatingCase"); // => "sTRING.PROTOTYPE.TOaLTERNATINGcASE"
```
```C++
string source = "HeLLo WoRLD";
string upperCase = to_alternating_case(source);
cout << upperCase << endl; // outputs: hEllO wOrld
```
```typescript
toAlternatingCase("hello world") === "HELLO WORLD"
toAlternatingCase("HELLO WORLD") === "hello world"
toAlternatingCase("hello WORLD") === "HELLO world"
toAlternatingCase("HeLLo WoRLD") === "hEllO wOrld"
toAlternatingCase("12345") === "12345" // Non-alphabetical characters are unaffected
toAlternatingCase("1a2b3c4d5e") === "1A2B3C4D5E"
toAlternatingCase("String.prototype.toAlternatingCase") === "sTRING.PROTOTYPE.TOaLTERNATINGcASE"
```
```factor
"hello world" >alternating ! "HELLO WORLD"
"HELLO WORLD" >alternating ! "hello world"
"hello WORLD" >alternating ! "HELLO world"
"HeLLo WoRLD" >alternating ! "hEllO wOrld"
"12345" >alternating ! "12345" (Non-alphabetical characters are unaffected)
"1a2b3c4d5e" >alternating ! "1A2B3C4D5E"
"String.prototype.toAlternatingCase" >alternating ! "sTRING.PROTOTYPE.TOaLTERNATINGcASE"
```
```go
ToAlternatingCase("hello world"); // => "HELLO WORLD"
ToAlternatingCase("HELLO WORLD"); // => "hello world"
ToAlternatingCase("hello WORLD"); // => "HELLO world"
ToAlternatingCase("HeLLo WoRLD"); // => "hEllO wOrld"
ToAlternativeCase("12345"); // => "12345" (Non-alphabetical characters are unaffected)
ToAlternativeCase("1a2b3c4d5e"); // => "1A2B3C4D5E"
ToAlternativeCase("String.prototype.toAlternatingCase"); // => "sTRING.PROTOTYPE.TOaLTERNATINGcASE"
```
As usual, your function/method should be pure, i.e. it should **not** mutate the original string.
| reference | def to_alternating_case(string):
return string . swapcase()
| altERnaTIng cAsE <=> ALTerNAtiNG CaSe | 56efc695740d30f963000557 | [
"Fundamentals"
] | https://www.codewars.com/kata/56efc695740d30f963000557 | 8 kyu |
Write a class called User that is used to calculate the amount that a user will progress through a ranking system similar to the one Codewars uses.
##### Business Rules:
* A user starts at rank -8 and can progress all the way to 8.
* There is no 0 (zero) rank. The next rank after -1 is 1.
* Users will complete activities. These activities also have ranks.
* Each time the user completes a ranked activity the users rank progress is updated based off of the activity's rank
* The progress earned from the completed activity is relative to what the user's current rank is compared to the rank of the activity
* A user's rank progress starts off at zero, each time the progress reaches 100 the user's rank is upgraded to the next level
* Any remaining progress earned while in the previous rank will be applied towards the next rank's progress (we don't throw any progress away). The exception is if there is no other rank left to progress towards (Once you reach rank 8 there is no more progression).
* A user cannot progress beyond rank 8.
* The only acceptable range of rank values is -8,-7,-6,-5,-4,-3,-2,-1,1,2,3,4,5,6,7,8. Any other value should raise an error.
The progress is scored like so:
* Completing an activity that is ranked the same as that of the user's will be worth 3 points
* Completing an activity that is ranked one ranking lower than the user's will be worth 1 point
* Any activities completed that are ranking 2 levels or more lower than the user's ranking will be ignored
* Completing an activity ranked higher than the current user's rank will accelerate the rank progression. The greater the difference between rankings the more the progression will be increased. The formula is `10 * d * d` where `d` equals the difference in ranking between the activity and the user.
##### Logic Examples:
* If a user ranked -8 completes an activity ranked -7 they will receive 10 progress
* If a user ranked -8 completes an activity ranked -6 they will receive 40 progress
* If a user ranked -8 completes an activity ranked -5 they will receive 90 progress
* If a user ranked -8 completes an activity ranked -4 they will receive 160 progress, resulting in the user being upgraded to rank -7 and having earned 60 progress towards their next rank
* If a user ranked -1 completes an activity ranked 1 they will receive 10 progress (remember, zero rank is ignored)
##### Code Usage Examples:
```javascript
var user = new User()
user.rank // => -8
user.progress // => 0
user.incProgress(-7)
user.progress // => 10
user.incProgress(-5) // will add 90 progress
user.progress # => 0 // progress is now zero
user.rank # => -7 // rank was upgraded to -7
```
```coffeescript
user = new User()
user.rank # => -8
user.progress # => 0
user.incProgress(-7)
user.progress # => 10
user.incProgress(-5) # will add 90 progress
user.progress # => 0 # progress is now zero
user.rank # => -7 # rank was upgraded to -7
```
```ruby
user = User.new
user.rank # => -8
user.progress # => 0
user.inc_progress(-7)
user.progress # => 10
user.inc_progress(-5) # will add 90 progress
user.progress # => 0 # progress is now zero
user.rank # => -7 # rank was upgraded to -7
```
```python
user = User()
user.rank # => -8
user.progress # => 0
user.inc_progress(-7)
user.progress # => 10
user.inc_progress(-5) # will add 90 progress
user.progress # => 0 # progress is now zero
user.rank # => -7 # rank was upgraded to -7
```
```java
User user = new User();
user.rank; // => -8
user.progress; // => 0
user.incProgress(-7);
user.progress; // => 10
user.incProgress(-5); // will add 90 progress
user.progress; // => 0 // progress is now zero
user.rank; // => -7 // rank was upgraded to -7
```
```haskell
rank newUser -- => -8
progress newUser -- => 0
let u2 = incProgress (-7) newUser
progress u2 -- => 10
let u3 = incProgress (-5) u2 -- will add 90 progress
progress u3 -- => 0 -- progress is now zero
rank u3 -- => -7 -- rank was upgraded to -7
```
```csharp
User user = new User();
user.rank; // => -8
user.progress; // => 0
user.incProgress(-7);
user.progress; // => 10
user.incProgress(-5); // will add 90 progress
user.progress; // => 0 // progress is now zero
user.rank; // => -7 // rank was upgraded to -7
```
~~~if:java
**Note:** In **Java** some methods may throw an `IllegalArgumentException`.
~~~
~~~if:csharp
**Note:** In **C#** some methods may throw an `ArgumentException`.
~~~
**Note**: Codewars no longer uses this algorithm for its own ranking system. It uses a pure Math based solution that gives consistent results no matter what order a set of ranked activities are completed at.
| algorithms | class User:
Ranks = [- 8, - 7, - 6, - 5, - 4, - 3, - 2, - 1, 1, 2, 3, 4, 5, 6, 7, 8]
def __init__(self):
self . __rank = - 8
self . __progress = 0
@ property
def rank(self):
return self . __rank
@ property
def progress(self):
return self . __progress
def inc_progress(self, kata_rank):
self . __validate_rank(kata_rank)
progress_made = self . __calc_progress(kata_rank)
new_progress = self . progress + progress_made
extra_rank, progress_left = self . __calc_rank(new_progress)
self . __update_rank(extra_rank)
self . __update_progress(progress_left)
def __validate_rank(self, in_rank):
if (in_rank not in self . Ranks):
raise ValueError("Rank must be in range [-8,-1]U[1,8]")
def __calc_progress(self, kata_rank):
diff = self . Ranks . index(kata_rank) - self . Ranks . index(self . rank)
if (kata_rank > self . rank):
return 10 * diff * * 2
elif (kata_rank == self . rank):
return 3
elif (diff == - 1):
return 1
else:
return 0
def __calc_rank(self, new_progress):
extra_rank = 0
progress_left = new_progress
if (new_progress > 99 and self . rank < 8):
extra_rank = new_progress / / 100
progress_left = new_progress % 100
return extra_rank, progress_left
def __update_progress(self, new_progress):
self . __progress = new_progress
if (self . rank == 8 and self . progress > 0):
self . __progress = 0
def __update_rank(self, extra_rank):
new_rank = self . rank + extra_rank
if (self . rank < 0 and new_rank >= 0):
new_rank = new_rank + 1
if (new_rank > 8):
self . __rank = 8
else:
self . __rank = new_rank
| Codewars style ranking system | 51fda2d95d6efda45e00004e | [
"Algorithms",
"Object-oriented Programming"
] | https://www.codewars.com/kata/51fda2d95d6efda45e00004e | 4 kyu |
Your start-up's BA has told marketing that your website has a large audience in Scandinavia and surrounding countries. Marketing thinks it would be great to welcome visitors to the site in their own language. Luckily you already use an API that detects the user's location, so this is an easy win.
### The Task
- Think of a way to store the languages as a database. The languages are listed below so you can copy and paste!
- Write a 'welcome' function that takes a parameter 'language', with a type `String`, and returns a greeting - if you have it in your database. It should default to English if the language is not in the database, or in the event of an invalid input.
### The Database
```haskell
[ ("english", "Welcome")
, ("czech", "Vitejte")
, ("danish", "Velkomst")
, ("dutch", "Welkom")
, ("estonian", "Tere tulemast")
, ("finnish", "Tervetuloa")
, ("flemish", "Welgekomen")
, ("french", "Bienvenue")
, ("german", "Willkommen")
, ("irish", "Failte")
, ("italian", "Benvenuto")
, ("latvian", "Gaidits")
, ("lithuanian", "Laukiamas")
, ("polish", "Witamy")
, ("spanish", "Bienvenido")
, ("swedish", "Valkommen")
, ("welsh", "Croeso")
]
```
Possible invalid inputs include:
~~~~
IP_ADDRESS_INVALID - not a valid ipv4 or ipv6 ip address
IP_ADDRESS_NOT_FOUND - ip address not in the database
IP_ADDRESS_REQUIRED - no ip address was supplied
~~~~
| reference | def greet(language):
return {
'czech': 'Vitejte',
'danish': 'Velkomst',
'dutch': 'Welkom',
'english': 'Welcome',
'estonian': 'Tere tulemast',
'finnish': 'Tervetuloa',
'flemish': 'Welgekomen',
'french': 'Bienvenue',
'german': 'Willkommen',
'irish': 'Failte',
'italian': 'Benvenuto',
'latvian': 'Gaidits',
'lithuanian': 'Laukiamas',
'polish': 'Witamy',
'spanish': 'Bienvenido',
'swedish': 'Valkommen',
'welsh': 'Croeso'
}. get(language, 'Welcome')
| Welcome! | 577ff15ad648a14b780000e7 | [
"Fundamentals"
] | https://www.codewars.com/kata/577ff15ad648a14b780000e7 | 8 kyu |
According to the creation myths of the Abrahamic religions, Adam and Eve were the first Humans to wander the Earth.
You have to do God's job. The creation method must return an array of length 2 containing objects (representing Adam and Eve). The first object in the array should be an instance of the class `Man`. The second should be an instance of the class `Woman`. Both objects have to be subclasses of `Human`. Your job is to implement the ```Human, Man and Woman``` classes.
| reference | def God():
return [Man(), Woman()]
class Human (object):
pass
class Man (Human):
pass
class Woman (Human):
pass
| Basic subclasses - Adam and Eve | 547274e24481cfc469000416 | [
"Fundamentals",
"Object-oriented Programming"
] | https://www.codewars.com/kata/547274e24481cfc469000416 | 8 kyu |
In this kata, your task is to create all permutations of a non-empty input string and remove duplicates, if present.
Create as many "shufflings" as you can!
Examples:
```
With input 'a':
Your function should return: ['a']
With input 'ab':
Your function should return ['ab', 'ba']
With input 'abc':
Your function should return ['abc','acb','bac','bca','cab','cba']
With input 'aabb':
Your function should return ['aabb', 'abab', 'abba', 'baab', 'baba', 'bbaa']
```
Note: The order of the permutations doesn't matter.
Good luck!
| algorithms | import itertools
def permutations(string):
return list("" . join(p) for p in set(itertools . permutations(string)))
| So Many Permutations! | 5254ca2719453dcc0b00027d | [
"Permutations",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5254ca2719453dcc0b00027d | 4 kyu |
In a factory a printer prints labels for boxes. For one kind of boxes
the printer has to use colors which, for the sake of simplicity,
are named with letters from `a to m`.
The colors used by the printer are
recorded in a control string. For example a "good" control string would be
`aaabbbbhaijjjm` meaning that the printer used three times color a, four times
color b, one time color h then one time color a...
Sometimes there are problems: lack of colors, technical malfunction and a "bad"
control string is produced e.g. `aaaxbbbbyyhwawiwjjjwwm` with letters not from `a to m`.
You have to write a function `printer_error` which given a string will return
the error rate of the printer as a **string** representing a rational whose numerator
is the number of errors and the denominator the length of the control string.
Don't reduce this fraction to a simpler expression.
The string has a length greater or equal to one and contains only letters
from `a`to `z`.
#### Examples:
```
s="aaabbbbhaijjjm"
printer_error(s) => "0/14"
s="aaaxbbbbyyhwawiwjjjwwm"
printer_error(s) => "8/22"
``` | reference | from re import sub
def printer_error(s):
return "{}/{}" . format(len(sub("[a-m]", '', s)), len(s))
| Printer Errors | 56541980fa08ab47a0000040 | [
"Fundamentals"
] | https://www.codewars.com/kata/56541980fa08ab47a0000040 | 7 kyu |
It's bonus time in the big city! The fatcats are rubbing their paws in anticipation... but who is going to make the most money?
Build a function that takes in two arguments (salary, bonus). Salary will be an integer, and bonus a boolean.
If bonus is true, the salary should be multiplied by 10. If bonus is false, the fatcat did not make enough money and must receive only his stated salary.
Return the total figure the individual will receive as a string prefixed with "£" (= `"\u00A3"`, JS, Go, Java, Scala, and Julia), "$" (C#, C++, Ruby, Clojure, Elixir, PHP, Python, Haskell, and Lua) or "¥" (Rust). | algorithms | def bonus_time(salary, bonus):
return "${}" . format(salary * (10 if bonus else 1))
| Do I get a bonus? | 56f6ad906b88de513f000d96 | [
"Strings",
"Logic"
] | https://www.codewars.com/kata/56f6ad906b88de513f000d96 | 8 kyu |
# Task Overview
Given a non-negative integer `n`, write a function `to_binary`/`ToBinary` which returns that number in a binary format.
<!-- C# documentation -->
```if:csharp
<h1>Documentation:</h1>
<h2>Kata.ToBinary Method (Int32)</h2>
Returns the binary representation of a non-negative integer as an integer.
<span style="font-size:20px">Syntax</span>
<div style="margin-top:-10px;padding:2px;background-color:Grey;position:relative;left:20px;width:600px;">
<div style="background-color:White;color:Black;border:1px;display:block;padding:10px;padding-left:18px;font-family:Consolas,Courier,monospace;">
<span style="color:Blue;">public</span>
<span style="color:Blue;">static</span>
<span style="color:Blue;">int</span> ToBinary(</br>
<span style="position:relative;left:62px;">int n</span></br>
)
</div>
</div>
</br>
<div style="position:relative;left:20px;">
<strong>Parameters</strong>
</br>
<i>n</i>
</br>
<span style="position:relative;left:50px;">Type: <a href="https://msdn.microsoft.com/en-us/library/system.int32(v=vs.110).aspx">System.Int32</a></span></br>
<span style="position:relative;left:50px;">The integer to convert.</span>
</br></br>
<strong>Return Value</strong>
</br>
<span>Type: <a href="https://msdn.microsoft.com/en-us/library/system.int32(v=vs.110).aspx">System.Int32</a></span></br>
The binary representation of the argument as an integer.
</div>
```
<!-- end C# documentation -->
<!-- C -->
```if:c
Example:
```
```c
to_binary(1) /* should return 1 */
to_binary(5) /* should return 101 */
to_binary(11) /* should return 1011 */
```
<!-- end of C -->
<!-- Javascript-->
```if:javascript
Example:
```
```javascript
toBinary(1) /* should return 1 */
toBinary(5) /* should return 101 */
toBinary(11) /* should return 1011 */
```
<!-- end of Javascript -->
<!-- NASM -->
```if:nasm
Example:
```
```nasm
mov di, 1
call to_binary ; RAX <- 1
mov di, 5
call to_binary ; RAX <- 101
mov di, 11
call to_binary ; RAX <- 1011
```
<!-- end of NASM -->
<!-- Python -->
```if:Python
Example:
```
```python
to_binary(1) # should return 1
to_binary(5) # should return 101
to_binary(11) # should return 1011
```
<!-- end of Python -->
<!-- Ruby-->
```if:ruby
Example:
```
```ruby
to_binary(1) # should return 1
to_binary(5) # should return 101
to_binary(11) # should return 1011
```
<!-- end of Ruby -->
<!-- Racket-->
```racket
(->binary 1) ; 1
(->binary 5) ; 101
(->binary 11) ; 1011
```
<!-- end of Racket -->
| reference | def to_binary(n):
return int(f' { n : b } ')
| Convert to Binary | 59fca81a5712f9fa4700159a | [
"Mathematics",
"Algorithms",
"Fundamentals"
] | https://www.codewars.com/kata/59fca81a5712f9fa4700159a | 8 kyu |
We need a function that can transform a number (integer) into a string.
What ways of achieving this do you know?
```if:c
In C, return a dynamically allocated string that will be freed by the test suite.
```
#### Examples (input --> output):
```
123 --> "123"
999 --> "999"
-100 --> "-100"
```
~~~if:riscv
RISC-V: The function signature is:
```c
void number_to_string(int n, char *out);
```
Convert the input number `n` to a string, and write the result to `out`. You may assume `out` is large enough to hold the result. You do not need to return anything.
~~~ | reference | def number_to_string(num):
return str(num)
| Convert a Number to a String! | 5265326f5fda8eb1160004c8 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5265326f5fda8eb1160004c8 | 8 kyu |
Write a function that finds the sum of all its arguments.
eg:
```javascript
sum(1, 2, 3) // => 6
sum(8, 2) // => 10
sum(1, 2, 3, 4, 5) // => 15
```
```php
sum(1, 2, 3) // => 6
sum(8, 2) // => 10
sum(1, 2, 3, 4, 5) // => 15
```
```python
sum_args(1, 2, 3) # => 6
sum_args(8, 2) # => 10
sum_args(1, 2, 3, 4, 5) # => 15
```
```coffeescript
sum 1, 2, 3 # => 6
sum 8, 2 # => 10
sum 1, 2, 3, 4, 5 # => 15
```
```ruby
sum 1, 2, 3 # => 6
sum 8, 2 # => 10
sum 1, 2, 3, 4, 5 # => 15
```
```clojure
(sum 1 2 3) ; => 6
(sum 8 2) ; => 10
(sum 1 2 3 4 5) ; => 15
```
```c
sum(3, 10, 20, 3); // --> 33
sum(2, 10, 15); // --> 25
sum(1, 10); // --> 10
sum(0); // --> 0
```
-----
##### TIPS:
ruby/python : http://lmgtfy.com/?q=Ruby+splat+operator
JS/Coffeescript : http://lmgtfy.com/?q=Javascript+arguments+variable
C: https://www.geeksforgeeks.org/variadic-functions-in-c/ | reference | def sum_args(* args):
return sum(args)
| Sum of all arguments | 540c33513b6532cd58000259 | [
"Fundamentals"
] | https://www.codewars.com/kata/540c33513b6532cd58000259 | 7 kyu |
You take your son to the forest to see the monkeys. You know that there are a certain number there (n), but your son is too young to just appreciate the full number, he has to start counting them from 1.
As a good parent, you will sit and count with him. Given the number (n), populate an array with all numbers up to and including that number, but excluding zero.
**For example(Input --> Output):**
```
10 --> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
1 --> [1]
```
| algorithms | def monkey_count(n):
return range(1, n + 1)
| Count the Monkeys! | 56f69d9f9400f508fb000ba7 | [
"Arrays",
"Fundamentals",
"Lists",
"Algorithms"
] | https://www.codewars.com/kata/56f69d9f9400f508fb000ba7 | 8 kyu |
The purpose of this kata is to work out just how many bottles of duty free whiskey you would have to buy such that the savings over the normal high street price would effectively cover the cost of your holiday.
You will be given the high street price (normPrice, in £ (Pounds)), the duty free discount (discount, in percent) and the cost of the holiday (in £).
For example, if a bottle costs £10 normally and the duty free discount is 10%, you would save £1 per bottle. If your holiday will cost £500, you would have to purchase 500 bottles to save £500, so the answer you return should be 500.
Another example: if a bottle costs £12 normally and the duty free discount is 50%, you would save £6 per bottle. If your holiday will cost £1000, you would have to purchase 166.66 bottles to save £1000, so your answer should be 166 bottles.
All inputs will be integers. Please return an integer. Round down.
| reference | def duty_free(price, discount, holiday_cost):
saving = price * discount / 100.0
return int(holiday_cost / saving)
| Holiday VIII - Duty Free | 57e92e91b63b6cbac20001e5 | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/57e92e91b63b6cbac20001e5 | 8 kyu |
Create a function that checks if a number `n` is divisible by two numbers `x` **AND** `y`. All inputs are positive, non-zero numbers.
```text
Examples:
1) n = 3, x = 1, y = 3 => true because 3 is divisible by 1 and 3
2) n = 12, x = 2, y = 6 => true because 12 is divisible by 2 and 6
3) n = 100, x = 5, y = 3 => false because 100 is not divisible by 3
4) n = 12, x = 7, y = 5 => false because 12 is neither divisible by 7 nor 5
```
| refactoring | def is_divisible(n, x, y):
return n % x == 0 and n % y == 0
| Is n divisible by x and y? | 5545f109004975ea66000086 | [
"Refactoring"
] | https://www.codewars.com/kata/5545f109004975ea66000086 | 8 kyu |
~~~if:java
Create an endless stream of prime numbers - a bit like `IntStream.of(2,3,5,7,11,13,17)`, but infinite. The stream must be able to produce a million primes in a few seconds.
~~~
~~~if:csharp
Create an endless stream of prime numbers - a bit like `IEnumerable<int>(2,3,5,7,11,13,17)`, but infinite. The stream must be able to produce a million primes in a few seconds.
~~~
~~~if:rust
Create an endless iterator that returns prime numbers.
the iterator must be able to produce a million primes in a few seconds
~~~
~~~if:python
Create an endless generator that yields prime numbers.
the generator must be able to produce a million primes in a few seconds
~~~
~~~if:coffeescript
Create an endless stream that yields prime numbers.
the generator must be able to produce a million primes in a few seconds
~~~
~~~if:javascript
Create an endless stream that yields prime numbers.
The stream must be able to produce a million primes in a few seconds.
~~~
~~~if:ruby
Create an endless stream that yields prime numbers.
The stream must be able to produce a million primes in a few seconds.
~~~
If this is too easy, try [Prime Streaming (NC-17)](/kata/prime-streaming-nc-17/).
~~~if:ruby
Note: the `require` keyword is disabled.
~~~ | algorithms | import numpy as np
class PrimeSieve:
def __init__(self, maximum):
self . primes = [2, 3]
# self.sieve = [0] * (maximum + 1)
self . sieve = np . zeros(maximum + 1, dtype=np . int8)
for p in self . primes:
self . sieve[p * p:: p] = 1
def extend(self):
p = self . primes[- 1] + 2
while self . sieve[p]:
p += 2
self . sieve[p * p:: p] = 1
self . primes . append(p)
return p
class Primes:
@ staticmethod
def stream():
prime_sieve = PrimeSieve(2 * 10 * * 7)
yield from iter(prime_sieve . primes)
yield from iter(prime_sieve . extend, 0)
| Prime Streaming (PG-13) | 5519a584a73e70fa570005f5 | [
"Algorithms"
] | https://www.codewars.com/kata/5519a584a73e70fa570005f5 | 3 kyu |
You probably know the "like" system from Facebook and other pages. People can "like" blog posts, pictures or other items. We want to create the text that should be displayed next to such an item.
Implement the function which takes an array containing the names of people that like an item. It must return the display text as shown in the examples:
```
[] --> "no one likes this"
["Peter"] --> "Peter likes this"
["Jacob", "Alex"] --> "Jacob and Alex like this"
["Max", "John", "Mark"] --> "Max, John and Mark like this"
["Alex", "Jacob", "Mark", "Max"] --> "Alex, Jacob and 2 others like this"
```
```if:c
* return must be an allocated string
* do not mutate input
```
Note: For 4 or more names, the number in `"and 2 others"` simply increases.
| reference | def likes(names):
n = len(names)
return {
0: 'no one likes this',
1: '{} likes this',
2: '{} and {} like this',
3: '{}, {} and {} like this',
4: '{}, {} and {others} others like this'
}[min(4, n)]. format(* names[: 3], others=n - 2)
| Who likes it? | 5266876b8f4bf2da9b000362 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5266876b8f4bf2da9b000362 | 6 kyu |
Removed due to copyright infringement.
<!---
# It's too hot, and they can't even…
One hot summer day Pete and his friend Billy decided to buy watermelons. They chose the biggest crate. They rushed home, dying of thirst, and decided to divide their loot, however they faced a hard problem.
Pete and Billy are great fans of even numbers, that's why they want to divide the number of watermelons in such a way that each of the two parts consists of an even number of watermelons. However, it is not obligatory that the parts are equal.
Example: the boys can divide a stack of 8 watermelons into 2+6 melons, or 4+4 melons.
The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, whether they can divide the fruits in the way they want. For sure, each of them should get a part of positive weight.
# Task
Given an integral number of watermelons `w` (`1 ≤ w ≤ 100`; `1 ≤ w` in Haskell), check whether Pete and Billy can divide the melons so that each of them gets an even amount.
## Examples
```elixir
divide(2) == false # 2 = 1 + 1
divide(3) == false # 3 = 1 + 2
divide(4) == true # 4 = 2 + 2
divide(5) == false # 5 = 2 + 3
divide(6) == true # 6 = 2 + 4
```
```crystal
divide(2) == false # 2 = 1 + 1
divide(3) == false # 3 = 1 + 2
divide(4) == true # 4 = 2 + 2
divide(5) == false # 5 = 2 + 3
divide(6) == true # 6 = 2 + 4
```
```clojure
(divide 2) ;; false ;; 2 = 1 + 1
(divide 3) ;; false ;; 3 = 1 + 2
(divide 4) ;; true ;; 4 = 2 + 2
(divide 5) ;; false ;; 5 = 2 + 3
(divide 6) ;; true ;; 6 = 2 + 4
```
```csharp
Watermelon.divide(2) == false // 2 = 1 + 1
Watermelon.divide(3) == false // 3 = 1 + 2
Watermelon.divide(4) == true // 4 = 2 + 2
Watermelon.divide(5) == false // 5 = 2 + 3
Watermelon.divide(6) == true // 6 = 2 + 4
```
```javascript
divide(2) === false // 2 = 1 + 1
divide(3) === false // 3 = 1 + 2
divide(4) === true // 4 = 2 + 2
divide(5) === false // 5 = 2 + 3
divide(6) === true // 6 = 2 + 4
```
```haskell
divide 1 `shouldBe` False
divide 2 `shouldBe` False
divide 3 `shouldBe` False
divide 4 `shouldBe` True
divide 5 `shouldBe` False
divide 6 `shouldBe` True
```
```prolog
divide(2) == 0 (2 = 1 + 1)
divide(3) == 0 (3 = 1 + 2)
divide(4) == 1 (4 = 2 + 2)
divide(5) == 0 (5 = 2 + 3)
divide(6) == 1 (6 = 2 + 4)
```
```java
divide(2) == false // 2 = 1 + 1
divide(3) == false // 3 = 1 + 2
divide(4) == true // 4 = 2 + 2
divide(5) == false // 5 = 2 + 3
divide(6) == true // 6 = 2 + 4
```
```kotlin
divide(2) == false // 2 = 1 + 1
divide(3) == false // 3 = 1 + 2
divide(4) == true // 4 = 2 + 2
divide(5) == false // 5 = 2 + 3
divide(6) == true // 6 = 2 + 4
```
```cpp
divide(2) == false // 2 = 1 + 1
divide(3) == false // 3 = 1 + 2
divide(4) == true // 4 = 2 + 2
divide(5) == false // 5 = 2 + 3
divide(6) == true // 6 = 2 + 4
```
```c
divide(2) == false // 2 = 1 + 1
divide(3) == false // 3 = 1 + 2
divide(4) == true // 4 = 2 + 2
divide(5) == false // 5 = 2 + 3
divide(6) == true // 6 = 2 + 4
```
```dart
divide(2) == false // 2 = 1 + 1
divide(3) == false // 3 = 1 + 2
divide(4) == true // 4 = 2 + 2
divide(5) == false // 5 = 2 + 3
divide(6) == true // 6 = 2 + 4
```
```cfml
divide(2) == false // 2 = 1 + 1
divide(3) == false // 3 = 1 + 2
divide(4) == true // 4 = 2 + 2
divide(5) == false // 5 = 2 + 3
divide(6) == true // 6 = 2 + 4
```
```nasm
divide(2) == false // 2 = 1 + 1
divide(3) == false // 3 = 1 + 2
divide(4) == true // 4 = 2 + 2
divide(5) == false // 5 = 2 + 3
divide(6) == true // 6 = 2 + 4
```
```julia
divide(2) == false # 2 = 1 + 1
divide(3) == false # 3 = 1 + 2
divide(4) == true # 4 = 2 + 2
divide(5) == false # 5 = 2 + 3
divide(6) == true # 6 = 2 + 4
```
```cobol
SOLUTION(2) == 0 2 = 1 + 1
SOLUTION(3) == 0 3 = 1 + 2
SOLUTION(4) == 1 4 = 2 + 2
SOLUTION(5) == 0 5 = 2 + 3
SOLUTION(6) == 1 6 = 2 + 4
```
---> | reference | def divide(weight):
return weight > 2 and weight % 2 == 0
| Watermelon | 55192f4ecd82ff826900089e | [
"Fundamentals",
"Mathematics",
"Algorithms",
"Logic",
"Numbers"
] | https://www.codewars.com/kata/55192f4ecd82ff826900089e | 8 kyu |
Fibonacci numbers are generated by setting F<sub>0</sub> = 0, F<sub>1</sub> = 1, and then using the formula:
# F<sub>n</sub> = F<sub>n-1</sub> + F<sub>n-2</sub>
Your task is to efficiently calculate the **n**th element in the Fibonacci sequence and then count the occurrence of each digit in the number. Return a list of integer pairs sorted in **descending** order.
10 ≤ n ≤ 100000
## Examples
```
f(10) = 55 # returns [(2, 5)], as there are two occurances of digit 5
f(10000) # returns:
[(254, 3),
(228, 2),
(217, 6),
(217, 0),
(202, 5),
(199, 1),
(198, 7),
(197, 8),
(194, 4),
(184, 9)]
```
If two integers have the same count, sort them in descending order.
Your algorithm must be efficient.
~~~if:javascript
Thanks to `kazk` for assisting with the translation.
~~~ | algorithms | from collections import Counter
def fib_digits(n):
a, b = 0, 1
for i in range(n):
a, b = b, a + b
return sorted(((b, int(a)) for a, b in Counter(str(a)). items()), reverse=True)
| Calculate Fibonacci return count of digit occurrences | 5779f894ec8832493f00002d | [
"Algorithms"
] | https://www.codewars.com/kata/5779f894ec8832493f00002d | 5 kyu |
You're writing code to control your town's traffic lights. You need a function to handle each change from `green`, to `yellow`, to `red`, and then to `green` again.
Complete the function that takes a string as an argument representing the current state of the light and returns a string representing the state the light should change to.
For example, when the input is `green`, output should be `yellow`.
```if:c
In C the state of the light is represented by an `enum`, not a string.
``` | reference | def update_light(current):
return {"green": "yellow", "yellow": "red", "red": "green"}[current]
| Thinkful - Logic Drills: Traffic light | 58649884a1659ed6cb000072 | [
"Fundamentals"
] | https://www.codewars.com/kata/58649884a1659ed6cb000072 | 8 kyu |
Complete the square sum function so that it squares each number passed into it and then sums the results together.
For example, for `[1, 2, 2]` it should return `9` because `$1^2 + 2^2 + 2^2 = 9$`.
```if:racket
In Racket, use a list instead of an array, so '(1 2 2) should return 9.
```
| reference | def square_sum(numbers):
return sum(x * * 2 for x in numbers)
| Square(n) Sum | 515e271a311df0350d00000f | [
"Arrays",
"Lists",
"Fundamentals"
] | https://www.codewars.com/kata/515e271a311df0350d00000f | 8 kyu |
Given a string s, write a method (function) that will return true if its a valid single integer or floating number or false if its not.
Valid examples, should return true:
```javascript
isDigit("3")
isDigit(" 3 ")
isDigit("-3.23")
```
should return false:
```javascript
isDigit("3-4")
isDigit(" 3 5")
isDigit("3 5")
isDigit("zero")
``` | reference | def isDigit(string):
try:
float(string)
return True
except:
return False
| Is it a number? | 57126304cdbf63c6770012bd | [
"Fundamentals"
] | https://www.codewars.com/kata/57126304cdbf63c6770012bd | 8 kyu |
Your task is to write function `factorial`.
https://en.wikipedia.org/wiki/Factorial
| reference | from math import factorial
| Factorial | 57a049e253ba33ac5e000212 | [
"Fundamentals"
] | https://www.codewars.com/kata/57a049e253ba33ac5e000212 | 7 kyu |
Implement a function which convert the given boolean value into its string representation.
Note: Only valid inputs will be given.
| reference | def boolean_to_string(b):
return str(b)
| Convert a Boolean to a String | 551b4501ac0447318f0009cd | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/551b4501ac0447318f0009cd | 8 kyu |
write me a function `stringy` that takes a `size` and returns a `string` of alternating `1`s and `0`s.
the string should start with a `1`.
a string with `size` 6 should return :`'101010'`.
with `size` 4 should return : `'1010'`.
with `size` 12 should return : `'101010101010'`.
The size will always be positive and will only use whole numbers.
| algorithms | def stringy(size):
return ('10' * size)[: size]
| Stringy Strings | 563b74ddd19a3ad462000054 | [
"Strings",
"Binary",
"Algorithms"
] | https://www.codewars.com/kata/563b74ddd19a3ad462000054 | 8 kyu |
Write a function that accepts a square matrix (`N x N` 2D array) and returns the determinant of the matrix.
How to take the determinant of a matrix -- it is simplest to start with the smallest cases:
A 1x1 matrix `|a|` has determinant `a`.
A 2x2 matrix `[ [a, b], [c, d] ]` or
```
|a b|
|c d|
```
has determinant: `a*d - b*c`.
The determinant of an `n x n` sized matrix is calculated by reducing the problem to the calculation of the determinants of `n` matrices of`n-1 x n-1` size.
For the 3x3 case, `[ [a, b, c], [d, e, f], [g, h, i] ]` or
```
|a b c|
|d e f|
|g h i|
```
the determinant is: `a * det(a_minor) - b * det(b_minor) + c * det(c_minor)` where `det(a_minor)` refers to taking the determinant of the 2x2 matrix created by crossing out the row and column in which the element a occurs:
```
|- - -|
|- e f|
|- h i|
```
Note the alternation of signs.
The determinant of larger matrices are calculated analogously, e.g. if M is a 4x4 matrix with first row `[a, b, c, d]`, then:
`det(M) = a * det(a_minor) - b * det(b_minor) + c * det(c_minor) - d * det(d_minor)`
| algorithms | import numpy as np
def determinant(a):
return round(np . linalg . det(np . matrix(a)))
| Matrix Determinant | 52a382ee44408cea2500074c | [
"Matrix",
"Linear Algebra",
"Mathematics",
"Recursion",
"Algorithms"
] | https://www.codewars.com/kata/52a382ee44408cea2500074c | 4 kyu |
What could be easier than comparing integer numbers? However, the given piece of code doesn't recognize some of the special numbers for a reason to be found. Your task is to find the bug and eliminate it. | bug_fixes | def what_is(x):
if x == 42:
return 'everything'
elif x == 42 * 42:
return 'everything squared'
else:
return 'nothing'
| How do I compare numbers? | 55d8618adfda93c89600012e | [
"Fundamentals",
"Debugging"
] | https://www.codewars.com/kata/55d8618adfda93c89600012e | 8 kyu |
~~~if:pascal
Make a simple function called `Greet` that returns the most-famous "hello world!".
~~~
~~~if-not:pascal
Make a simple function called `greet` that returns the most-famous "hello world!".
~~~
### Style Points
Sure, this is about as easy as it gets. But how clever can you be to create the most creative "hello world" you can think of? What is a "hello world" solution you would want to show your friends?
| reference | def greet():
return "hello world!"
| Function 1 - hello world | 523b4ff7adca849afe000035 | [
"Fundamentals"
] | https://www.codewars.com/kata/523b4ff7adca849afe000035 | 8 kyu |
Just like in the ["father" kata](http://www.codewars.com/kata/find-fibonacci-last-digit/), you will have to return the last digit of the nth element in the Fibonacci sequence (starting with 1,1, to be extra clear, not with 0,1 or other numbers).
You will just get much bigger numbers, so good luck bruteforcing your way through it ;)
```javascript
lastFibDigit(1) == 1
lastFibDigit(2) == 1
lastFibDigit(3) == 2
lastFibDigit(1000) == 5
lastFibDigit(1000000) == 5
```
```csharp
Kata.LastFibDigit(1) == 1
Kata.LastFibDigit(2) == 1
Kata.LastFibDigit(3) == 2
Kata.LastFibDigit(1000) == 5
Kata.LastFibDigit(1000000) == 5
```
```python
last_fib_digit(1) == 1
last_fib_digit(2) == 1
last_fib_digit(3) == 2
last_fib_digit(1000) == 5
last_fib_digit(1000000) == 5
```
```ruby
last_fib_digit(1) == 1
last_fib_digit(2) == 1
last_fib_digit(3) == 2
last_fib_digit(1000) == 5
last_fib_digit(1000000) == 5
```
``` haskell
lastFibDigit 1 == 1
lastFibDigit 2 == 1
lastFibDigit 3 == 2
lastFibDigit 1000 == 5
lastFibDigit 1000000 == 5
```
```java
Kata.lastFibDigit(1) == 1
Kata.lastFibDigit(2) == 1
Kata.lastFibDigit(3) == 2
Kata.lastFibDigit(1000) == 5
Kata.lastFibDigit(1000000) == 5
```
```go
LastFibDigit(1) == 1
LastFibDigit(2) == 1
LastFibDigit(3) == 2
LastFibDigit(1000) == 5
LastFibDigit(1000000) == 5
```
```cobol
Last-Fibonacci-Digit (1) = 1
Last-Fibonacci-Digit (2) = 1
Last-Fibonacci-Digit (3) = 2
Last-Fibonacci-Digit (1000) = 5
Last-Fibonacci-Digit (1000000) = 5
```
| algorithms | def last_fib_digit(n):
return [0, 1, 1, 2, 3, 5, 8, 3, 1, 4, 5, 9, 4, 3, 7, 0, 7, 7, 4, 1, 5, 6, 1, 7, 8, 5, 3, 8, 1, 9, 0, 9, 9, 8, 7, 5, 2, 7, 9, 6, 5, 1, 6, 7, 3, 0, 3, 3, 6, 9, 5, 4, 9, 3, 2, 5, 7, 2, 9, 1][n % 60]
| Find last Fibonacci digit [hardcore version] | 56b7771481290cc283000f28 | [
"Algorithms"
] | https://www.codewars.com/kata/56b7771481290cc283000f28 | 6 kyu |
### Problem Context
The [Fibonacci](http://en.wikipedia.org/wiki/Fibonacci_number) sequence is traditionally used to explain tree recursion.
```javascript
function fibonacci(n) {
if(n==0 || n == 1)
return n;
return fibonacci(n-1) + fibonacci(n-2);
}
```
```ruby
def fibonacci(n)
return n if (0..1).include? n
fibonacci(n - 1) + fibonacci(n - 2)
end
```
```python
def fibonacci(n):
if n in [0, 1]:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
```
```haskell
fibonacci 0 = 0
fibonacci 1 = 1
fibonacci n = fibonacci (n-1) + fibonacci (n-2)
```
```lambdacalc
fibonacci = \ n . if (is-zero n)
0
(if (is-zero (pred n))
1
# else
(add (fibonacci (pred n)) (fibonacci (pred (pred n)))
))
```
```scala
def fibonacci(n: Int): Int = n match {
case 0 | 1 => n
case _ => fibonacci(n - 1) + fibonacci(n - 2)
}
```
This algorithm serves welll its educative purpose but it's [tremendously inefficient](https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-11.html#%_sec_1.2.2), not only because of recursion, but because we invoke the fibonacci function twice, and the right branch of recursion (i.e. `fibonacci(n-2)`) recalculates all the Fibonacci numbers already calculated by the left branch (i.e. `fibonacci(n-1)`).
This algorithm is so inefficient that the time to calculate any Fibonacci number over 50 is simply too much. You may go for a cup of coffee or go take a nap while you wait for the answer. But if you try it here in Code Wars you will most likely get a code timeout before any answers.
For this particular Kata we want to **implement the memoization solution**. This will be cool because it will let us *keep using the tree recursion* algorithm while still keeping it sufficiently optimized to get an answer very rapidly.
The trick of the memoized version is that we will keep a cache data structure (most likely an associative array) where we will store the Fibonacci numbers as we calculate them. When a Fibonacci number is calculated, we first look it up in the cache, if it's not there, we calculate it and put it in the cache, otherwise we returned the cached number.
Refactor the function into a recursive Fibonacci function that using a memoized data structure avoids the deficiencies of tree recursion. Can you make it so the memoization cache is private to this function?
~~~if:lambdacalc
### Encodings
`numEncoding: BinaryScott`
~~~ | refactoring | def memoized(f):
cache = {}
def wrapped(k):
v = cache . get(k)
if v is None:
v = cache[k] = f(k)
return v
return wrapped
@ memoized
def fibonacci(n):
if n in [0, 1]:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
| Memoized Fibonacci | 529adbf7533b761c560004e5 | [
"Memoization",
"Refactoring"
] | https://www.codewars.com/kata/529adbf7533b761c560004e5 | 5 kyu |
Write two functions that convert a roman numeral to and from an integer value. Multiple roman numeral values will be tested for each function.
Modern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals:
* `1990` is rendered: `1000`=`M`, `900`=`CM`, `90`=`XC`; resulting in `MCMXC`
* `2008` is written as `2000`=`MM`, `8`=`VIII`; or `MMVIII`
* `1666` uses each Roman symbol in descending order: `MDCLXVI`.
Input range : `1 <= n < 4000`
In this kata `4` should be represented as `IV`, NOT as `IIII` (the "watchmaker's four").
### Examples
```
to roman:
2000 -> "MM"
1666 -> "MDCLXVI"
86 -> "LXXXVI"
1 -> "I"
from roman:
"MM" -> 2000
"MDCLXVI" -> 1666
"LXXXVI" -> 86
"I" -> 1
```
### Help
```
+--------+-------+
| Symbol | Value |
+--------+-------+
| M | 1000 |
| CM | 900 |
| D | 500 |
| CD | 400 |
| C | 100 |
| XC | 90 |
| L | 50 |
| XL | 40 |
| X | 10 |
| IX | 9 |
| V | 5 |
| IV | 4 |
| I | 1 |
+--------+-------+
``` | algorithms | from collections import OrderedDict
import re
ROMAN_NUMERALS = OrderedDict([
('M', 1000),
('CM', 900),
('D', 500),
('CD', 400),
('C', 100),
('XC', 90),
('L', 50),
('XL', 40),
('X', 10),
('IX', 9),
('V', 5),
('IV', 4),
('I', 1),
])
DECIMAL_TO_ROMAN = [(v, k) for k, v in ROMAN_NUMERALS . items()]
ROMAN_RE = '|' . join(ROMAN_NUMERALS)
class RomanNumerals (object):
@ staticmethod
def from_roman(roman):
return sum(ROMAN_NUMERALS[d] for d in re . findall(ROMAN_RE, roman))
@ staticmethod
def to_roman(decimal):
result = []
for number, roman in DECIMAL_TO_ROMAN:
while decimal >= number:
decimal -= number
result . append(roman)
return '' . join(result)
| Roman Numerals Helper | 51b66044bce5799a7f000003 | [
"Algorithms",
"Object-oriented Programming"
] | https://www.codewars.com/kata/51b66044bce5799a7f000003 | 4 kyu |
Some numbers have funny properties. For example:
* 89 --> 8¹ + 9² = 89 * 1
* 695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2
* 46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51
Given two positive integers `n` and `p`, we want to find a positive integer `k`, if it exists, such that the sum of the digits of `n` raised to consecutive powers starting from `p` is equal to `k * n`.
In other words, writing the consecutive digits of `n` as `a, b, c, d ...`, is there an integer `k` such that :
```math
(a^p + b^{p + 1} + c^{p + 2} + d^{p + 3} + ...) = n * k
```
If it is the case we will return `k`, if not return `-1`.
**Note**: `n` and `p` will always be strictly positive integers.
## Examples:
```
n = 89; p = 1 ---> 1 since 8¹ + 9² = 89 = 89 * 1
n = 92; p = 1 ---> -1 since there is no k such that 9¹ + 2² equals 92 * k
n = 695; p = 2 ---> 2 since 6² + 9³ + 5⁴= 1390 = 695 * 2
n = 46288; p = 3 ---> 51 since 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51
```
| reference | def dig_pow(n, p):
s = 0
for i, c in enumerate(str(n)):
s += pow(int(c), p + i)
return s / n if s % n == 0 else - 1
| Playing with digits | 5552101f47fc5178b1000050 | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/5552101f47fc5178b1000050 | 6 kyu |
Your task is to make a function that can take any non-negative integer as an argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number.
### Examples:
Input: `42145`
Output: `54421`
Input: `145263`
Output: `654321`
Input: `123456789`
Output: `987654321`
| reference | def Descending_Order(num):
return int("" . join(sorted(str(num), reverse=True)))
| Descending Order | 5467e4d82edf8bbf40000155 | [
"Fundamentals"
] | https://www.codewars.com/kata/5467e4d82edf8bbf40000155 | 7 kyu |
Write a function called `LCS` that accepts two sequences and returns the longest subsequence common to the passed in sequences.
### Subsequence
A subsequence is different from a substring. The terms of a subsequence need not be consecutive terms of the original sequence.
### Example subsequence
Subsequences of `"abc"` = `"a"`, `"b"`, `"c"`, `"ab"`, `"ac"`, `"bc"` and `"abc"`.
### LCS examples
```javascript
LCS( "abcdef" , "abc" ) => returns "abc"
LCS( "abcdef" , "acf" ) => returns "acf"
LCS( "132535365" , "123456789" ) => returns "12356"
```
```haskell
lcs "a" "b" `shouldBe` ""
lcs "abcdef" "abc" `shouldBe` "abc"
lcs "132535365" "123456789" `shouldBe` "12356"
```
```python
lcs( "abcdef" , "abc" ) => returns "abc"
lcs( "abcdef" , "acf" ) => returns "acf"
lcs( "132535365" , "123456789" ) => returns "12356"
```
```ruby
lcs( "abcdef" , "abc" ) => returns "abc"
lcs( "abcdef" , "acf" ) => returns "acf"
lcs( "132535365" , "123456789" ) => returns "12356"
```
```java
Solution.lcs("abcdef", "abc") => returns "abc"
Solution.lcs("abcdef", "acf") => returns "acf"
Solution.lcs("132535365", "123456789") => returns "12356"
```
```go
LCS( "abcdef", "abc" ) => returns "abc"
LCS( "abcdef", "acf" ) => returns "acf"
LCS( "132535365", "123456789" ) => returns "12356"
```
```ocaml
lcs ['a';'b';'c';'d';'e';'f'] ['a';'b';'c'] => returns ['a';'b';'c']
lcs ['a';'b';'c';'d';'e';'f'] ['a';'c';'f'] => returns ['a';'c';'f']
lcs [1;3;2;5;3;5;3;6;5] [1;2;3;4;5;6;7;8;9] => returns [1;2;3;5;6]
```
### Notes
* Both arguments will be strings
* Return value must be a string
* Return an empty string if there exists no common subsequence
* Both arguments will have one or more characters (in JavaScript)
* All tests will only have a single longest common subsequence. Don't worry about cases such as `LCS( "1234", "3412" )`, which would have two possible longest common subsequences: `"12"` and `"34"`.
Note that the Haskell variant will use randomized testing, but any longest common subsequence will be valid.
Note that the OCaml variant is using generic lists instead of strings, and will also have randomized tests (any longest common subsequence will be valid).
### Tips
Wikipedia has an explanation of the two properties that can be used to solve the problem:
- [First property](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#First_property)
- [Second property](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem#Second_property)
| algorithms | def lcs(x, y):
if len(x) == 0 or len(y) == 0:
return ''
if x[- 1] == y[- 1]:
return lcs(x[: - 1], y[: - 1]) + x[- 1]
else:
lcs1 = lcs(x, y[: - 1])
lcs2 = lcs(x[: - 1], y)
if len(lcs1) > len(lcs2):
return lcs1
else:
return lcs2
| Longest Common Subsequence | 52756e5ad454534f220001ef | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/52756e5ad454534f220001ef | 5 kyu |
- A friend of mine takes the sequence of all numbers from 1 to n (where n > 0).
- Within that sequence, he chooses two numbers, a and b.
- He says that the product of a and b should be equal to the sum of all numbers in the sequence, excluding a and b.
- Given a number n, could you tell me the numbers he excluded from the sequence?
The function takes the parameter: `n`
(n is always strictly greater than 0) and returns an array or a string (depending on the language) of the form:
```
[(a, b), ...] or [[a, b], ...] or {{a, b}, ...} or or [{a, b}, ...]
```
with **all** `(a, b)` which are the possible removed numbers in the sequence `1 to n`.
`[(a, b), ...] or [[a, b], ...] or {{a, b}, ...} or ... `will be sorted in increasing order of the "a".
It happens that there are several possible (a, b).
The function returns an empty array (or an empty string) if no possible numbers are found which will prove that my friend has not told the truth! (Go: in this case return `nil`).
#### Examples:
```
removNb(26) should return [(15, 21), (21, 15)]
or
removNb(26) should return { {15, 21}, {21, 15} }
or
removeNb(26) should return [[15, 21], [21, 15]]
or
removNb(26) should return [ {15, 21}, {21, 15} ]
or
removNb(26) should return "15 21, 21 15"
```
or
```
in C:
removNb(26) should return {{15, 21}{21, 15}} tested by way of strings.
Function removNb should return a pointer to an allocated array of Pair pointers, each one also allocated.
```
#### Note
See examples of returns for each language in "RUN SAMPLE TESTS"
| games | def removNb(n):
total = n * (n + 1) / 2
sol = []
for a in range(1, n + 1):
b = (total - a) / (a + 1.0)
if b . is_integer() and b <= n:
sol . append((a, int(b)))
return sol
| Is my friend cheating? | 5547cc7dcad755e480000004 | [
"Fundamentals",
"Mathematics",
"Puzzles"
] | https://www.codewars.com/kata/5547cc7dcad755e480000004 | 5 kyu |
Complete the solution so that it returns true if the first argument(string) passed in ends with the 2nd argument (also a string).
Examples:
```javascript
solution('abc', 'bc') // returns true
solution('abc', 'd') // returns false
```
```coffeescript
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
```python
solution('abc', 'bc') # returns true
solution('abc', 'd') # returns false
```
```go
solution("abc", "bc") // returns true
solution("abc", "d") // returns false
```
```prolog
solution("abc", "bc"). % match
\+ solution("abc", "d"). % no match
```
```clojure
(solution "abc" "bc") ; returns true
(solution "abc" "d'" ; returns false
```
```lua
strEndsWith('abc', 'bc') -- returns true
strEndsWith('abc', 'd') -- returns false
```
```cobol
StringEndsWith('abc', 'bc')
* --> result = 1
StringEndsWith('abc', 'd')
* --> result = 0
```
```scala
solution("abc", "bc") // returns true
solution("abc", "d") //returns false
``` | reference | def solution(string, ending):
return string . endswith(ending)
| String ends with? | 51f2d1cafc9c0f745c00037d | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/51f2d1cafc9c0f745c00037d | 7 kyu |
Given a month as an integer from 1 to 12, return to which quarter of the year it belongs as an integer
number.
For example: month 2 (February), is part of the first quarter; month 6 (June), is part of the second quarter; and month 11 (November), is part of the fourth quarter.
Constraint:
* `1 <= month <= 12` | reference | def quarter_of(month):
# your code here
if month in range(1, 4):
return 1
elif month in range(4, 7):
return 2
elif month in range(7, 10):
return 3
elif month in range(10, 13):
return 4
| Quarter of the year | 5ce9c1000bab0b001134f5af | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/5ce9c1000bab0b001134f5af | 8 kyu |
Complete the function, which calculates how much you need to tip based on the total amount of the bill and the service.
You need to consider the following ratings:
- Terrible: tip 0%
- Poor: tip 5%
- Good: tip 10%
- Great: tip 15%
- Excellent: tip 20%
The rating is **case insensitive** (so "great" = "GREAT"). If an unrecognised rating is received, then you need to return:
* `"Rating not recognised"` in Javascript, Python and Ruby...
* ...or `null` in Java
* ...or `-1` in C#
Because you're a nice person, you **always round up** the tip, regardless of the service.
| reference | from math import ceil
def calculate_tip(amount, rating):
tips = {
'terrible': 0,
'poor': .05,
'good': .1,
'great': .15,
'excellent': .2
}
if rating . lower() in tips:
return ceil(amount * tips[rating . lower()])
else:
return 'Rating not recognised'
| Tip Calculator | 56598d8076ee7a0759000087 | [
"Fundamentals"
] | https://www.codewars.com/kata/56598d8076ee7a0759000087 | 8 kyu |
Removed due to copyright infringement.
<!---
Polycarpus works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words (that don't contain WUB). To make the dubstep remix of this song, Polycarpus inserts a certain number of words "WUB" before the first word of the song (the number may be zero), after the last word (the number may be zero), and between words (at least one between any pair of neighbouring words), and then the boy glues together all the words, including "WUB", in one string and plays the song at the club.
For example, a song with words "I AM X" can transform into a dubstep remix as "WUBWUBIWUBAMWUBWUBX" and cannot transform into "WUBWUBIAMWUBX".
Recently, Jonny has heard Polycarpus's new dubstep track, but since he isn't into modern music, he decided to find out what was the initial song that Polycarpus remixed. Help Jonny restore the original song.
## Input
The input consists of a single non-empty string, consisting only of uppercase English letters, the string's length doesn't exceed 200 characters
## Output
Return the words of the initial song that Polycarpus used to make a dubsteb remix. Separate the words with a space.
## Examples
```javascript
songDecoder("WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB")
// => WE ARE THE CHAMPIONS MY FRIEND
```
```ruby
song_decoder("WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB")
# => WE ARE THE CHAMPIONS MY FRIEND
```
```haskell
songDecoder "WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB"
`shouldBe` "WE ARE THE CHAMPIONS MY FRIEND"
```
```python
song_decoder("WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB")
# => WE ARE THE CHAMPIONS MY FRIEND
```
```clojure
(song-decoder "WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB")
; => WE ARE THE CHAMPIONS MY FRIEND
```
```scala
songDecoder("WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB")
// => WE ARE THE CHAMPIONS MY FRIEND
```
```rust
songDecoder("WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB")
// => WE ARE THE CHAMPIONS MY FRIEND
```
---> | reference | def song_decoder(song):
return " " . join(song . replace('WUB', ' '). split())
| Dubstep | 551dc350bf4e526099000ae5 | [
"Fundamentals",
"Strings",
"Data Types"
] | https://www.codewars.com/kata/551dc350bf4e526099000ae5 | 6 kyu |
Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative.
*Example*: The binary representation of `1234` is `10011010010`, so the function should return `5` in this case
| algorithms | def countBits(n):
return bin(n). count("1")
| Bit Counting | 526571aae218b8ee490006f4 | [
"Bits",
"Algorithms"
] | https://www.codewars.com/kata/526571aae218b8ee490006f4 | 6 kyu |
You are going to be given a string. Your job is to return that string in a certain order that I will explain below:
Let's say you start with this: `"012345"`
The first thing you do is reverse it:`"543210"`
Then you will take the string from the 1st position and reverse it again:`"501234"`
Then you will take the string from the 2nd position and reverse it again:`"504321"`
Then you will take the string from the 3rd position and reverse it again:`"504123"`
Continue this pattern until you have done every single position, and then you will return the string you have created. For this particular number, you would return:`"504132"`
# Input:
A string of length 1 - 1000
# Output:
A correctly reordered string.
~~~if:lambdacalc
# Encodings
purity: `LetRec`
numEncoding: `None`
`String`s are encoded as `List`s. The values in the `String` don't actually matter!
Export constructors `nil, cons` and deconstructor `foldl` for your `List` encoding.
~~~ | algorithms | def reverse_fun(n):
for i in range(len(n)):
n = n[: i] + n[i:][:: - 1]
return n
| Reversing Fun | 566efcfbf521a3cfd2000056 | [
"Strings",
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/566efcfbf521a3cfd2000056 | 7 kyu |
Nickname Generator
Write a function, `nicknameGenerator` that takes a string name as an argument and returns the first 3 or 4 letters as a nickname.
If the 3rd letter is a consonant, return the first 3 letters.
```javascript
nickname("Robert") //=> "Rob"
nickname("Kimberly") //=> "Kim"
nickname("Samantha") //=> "Sam"
```
If the 3rd letter is a vowel, return the first 4 letters.
```javascript
nickname("Jeannie") //=> "Jean"
nickname("Douglas") //=> "Doug"
nickname("Gregory") //=> "Greg"
```
If the string is less than 4 characters, return "Error: Name too short".
**Notes:**
- Vowels are "aeiou", so discount the letter "y".
- Input will always be a string.
- Input will always have the first letter capitalised and the rest lowercase (e.g. Sam).
- The input can be modified
| reference | def nickname_generator(name):
return "Error: Name too short" if len(name) < 4 else name[: 3 + (name[2] in "aeiuo")]
| Nickname Generator | 593b1909e68ff627c9000186 | [
"Strings",
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/593b1909e68ff627c9000186 | 7 kyu |
<h1>How many bees are in the beehive?</h1>
* bees can be facing UP, DOWN, LEFT, or RIGHT
* bees can share parts of other bees
<h1>Examples</h1>
Ex1
```
bee.bee
.e..e..
.b..eeb
```
*Answer: 5*
<hr>
Ex2
```
bee.bee
e.e.e.e
eeb.eeb
```
*Answer: 8*
# Notes
* The hive may be empty or null/None/nil/...
* Python: the hive is passed as a list of lists (not a list of strings)
| reference | from itertools import chain
def how_many_bees(hive):
return bool(hive) and sum(s . count('bee') + s . count('eeb') for s in map('' . join, chain(hive, zip(* hive))))
| Spelling Bee | 57d6b40fbfcdc5e9280002ee | [
"Fundamentals"
] | https://www.codewars.com/kata/57d6b40fbfcdc5e9280002ee | 6 kyu |
All of the animals are having a feast! Each animal is bringing one dish. There is just one rule: the dish must start and end with the same letters as the animal's name. For example, the great blue heron is bringing garlic naan and the chickadee is bringing chocolate cake.
Write a function `feast` that takes the animal's name and dish as arguments and returns true or false to indicate whether the beast is allowed to bring the dish to the feast.
Assume that `beast` and `dish` are always lowercase strings, and that each has at least two letters. `beast` and `dish` may contain hyphens and spaces, but these will not appear at the beginning or end of the string. They will not contain numerals.
| reference | def feast(beast, dish):
return beast[0] == dish[0] and dish[- 1] == beast[- 1]
| The Feast of Many Beasts | 5aa736a455f906981800360d | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5aa736a455f906981800360d | 8 kyu |
## Grade book
Complete the function so that it finds the average of the three scores passed to it and returns the letter value associated with that grade.
Numerical Score | Letter Grade
--- | ---
90 <= score <= 100 | 'A'
80 <= score < 90 | 'B'
70 <= score < 80 | 'C'
60 <= score < 70 | 'D'
0 <= score < 60 | 'F'
Tested values are all between 0 and 100. Theres is no need to check for negative values or values greater than 100.
| reference | def get_grade(s1, s2, s3):
m = (s1 + s2 + s3) / 3.0
if 90 <= m <= 100:
return 'A'
elif 80 <= m < 90:
return 'B'
elif 70 <= m < 80:
return 'C'
elif 60 <= m < 70:
return 'D'
return "F"
| Grasshopper - Grade book | 55cbd4ba903825f7970000f5 | [
"Fundamentals"
] | https://www.codewars.com/kata/55cbd4ba903825f7970000f5 | 8 kyu |
Write a function that takes a positive integer n, sums all the cubed values from 1 to n (inclusive), and returns that sum.
Assume that the input n will always be a positive integer.
Examples: **(Input --> output)**
```
2 --> 9 (sum of the cubes of 1 and 2 is 1 + 8)
3 --> 36 (sum of the cubes of 1, 2, and 3 is 1 + 8 + 27)
``` | reference | def sum_cubes(n):
return sum(i * * 3 for i in range(0, n + 1))
| Sum of Cubes | 59a8570b570190d313000037 | [
"Fundamentals"
] | https://www.codewars.com/kata/59a8570b570190d313000037 | 7 kyu |
## Snail Sort
Given an `n x n` array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.
```
array = [[1,2,3],
[4,5,6],
[7,8,9]]
snail(array) #=> [1,2,3,6,9,8,7,4,5]
```
For better understanding, please follow the numbers of the next array consecutively:
```
array = [[1,2,3],
[8,9,4],
[7,6,5]]
snail(array) #=> [1,2,3,4,5,6,7,8,9]
```
This image will illustrate things more clearly:
<svg version="1.0" xmlns="http://www.w3.org/2000/svg"
width="715.000000pt" height="354.000000pt" viewBox="0 0 715.000000 354.000000"
preserveAspectRatio="xMidYMid meet" style="background-color:lightgray">
<g transform="translate(0.000000,354.000000) scale(0.100000,-0.100000)"
fill="#000000" stroke="none">
<path d="M0 1770 l0 -1770 3575 0 3575 0 0 1770 0 1770 -3575 0 -3575 0 0 -1770z m7080 10 l0 -1700 -3510 0 -3510 0 0 1700 0 1700 3510 0 3510 0 0 -1700z"/>
<path d="M160 2180 l0 -1200 1200 0 1200 0 0 1200 0 1200 -1200 0 -1200 0 0 -1200z m800 970 l0 -210 -175 0 -175 0 0 58 c0 32 -3 62 -6 65 -4 4 -20 -5 -36 -18 -16 -14 -34 -25 -39 -25 -5 0 -9 -7 -9 -15 0 -11 8 -13 30 -8 l30 6 0 -93 c0 -69 3 -91 13 -88 6 3 13 25 15 51 l3 47 175 0 174 0 0 -170 0 -170 -390 0 -390 0 0 390 0 390 390 0 390 0 0 -210z m800 0 l0 -210 -161 0 -161 0 6 34 c9 47 -7 81 -44 96 -44 18 -100 -7 -100 -45 0 -30 11 -32 28 -5 14 22 61 27 80 8 16 -16 15 -49 -2 -70 -12 -16 -35 -18 -220 -18 l-206 0 0 210 0 210 390 0 390 0 0 -210z m780 -180 l0 -390 -170 0 -170 0 0 123 c0 111 2 126 20 142 24 22 27 80 4 102 -9 9 -12 22 -8 32 24 52 -5 100 -60 101 -28 0 -76 -33 -76 -52 0 -13 30 -9 46 7 20 19 48 19 64 0 17 -20 6 -43 -25 -55 -14 -5 -24 -15 -23 -22 2 -10 -38 -14 -179 -16 l-183 -2 0 210 0 210 380 0 380 0 0 -390z m-1213 -88 c-54 -56 -50 -62 43 -62 47 0 80 4 80 10 0 6 -22 10 -48 10 -27 0 -52 3 -56 7 -3 4 8 22 26 40 l32 33 178 0 178 0 0 -170 0 -170 -390 0 -390 0 0 170 0 170 192 0 192 0 -37 -38z m853 -2 c0 -32 -4 -40 -18 -40 -11 0 -27 9 -37 20 -18 20 -45 27 -45 12 0 -20 29 -44 60 -51 l35 -7 3 -117 3 -117 -201 0 -200 0 0 170 0 170 200 0 200 0 0 -40z m32 8 c-9 -9 -12 -7 -12 12 0 19 3 21 12 12 9 -9 9 -15 0 -24z m-1252 -538 l0 -210 -170 0 -170 0 0 65 c0 50 -3 65 -15 65 -17 0 -137 -158 -132 -174 2 -6 27 -12 55 -14 l52 -3 0 -150 0 -149 -200 0 -200 0 0 390 0 390 390 0 390 0 0 -210z m800 -180 l0 -390 -390 0 -390 0 0 170 0 170 205 0 c130 0 205 4 205 10 0 6 -11 10 -25 10 -14 0 -25 5 -25 10 0 6 16 10 35 10 41 0 60 -26 50 -70 -9 -43 -84 -54 -99 -15 -8 22 -26 18 -26 -4 0 -26 37 -51 76 -51 45 0 86 49 82 99 -4 44 -55 85 -95 75 -22 -6 -24 -4 -21 22 3 26 7 29 47 34 69 8 65 30 -6 30 l-59 0 -12 -45 c-7 -25 -12 -56 -12 -70 l0 -25 -160 0 -160 0 0 210 0 210 390 0 390 0 0 -390z m420 250 l0 -139 -28 -15 c-39 -20 -52 -55 -52 -136 0 -64 2 -70 31 -94 17 -14 35 -26 40 -26 5 0 9 -51 9 -115 l0 -115 -200 0 -200 0 0 390 0 390 200 0 200 0 0 -140z m360 -250 l0 -390 -170 0 -170 0 0 116 c0 104 2 116 18 121 23 6 52 53 52 86 0 28 -35 77 -56 77 -9 0 -14 11 -14 30 0 34 5 37 26 15 19 -19 34 -19 34 -1 0 8 -13 24 -30 36 l-30 21 0 140 0 139 170 0 170 0 0 -390z m-360 41 c0 -26 -17 -40 -52 -41 -10 0 2 31 20 53 22 25 32 21 32 -12z m-1590 -38 c0 -45 -12 -63 -41 -63 -35 0 -36 12 -6 50 25 33 47 38 47 13z m1590 -78 c0 -30 -3 -55 -7 -55 -14 0 -30 15 -42 38 -10 19 -10 28 4 48 28 43 45 31 45 -31z m48 43 c19 -19 14 -63 -8 -83 -20 -18 -20 -17 -20 38 0 57 6 67 28 45z m-1268 -188 l0 -170 -180 0 -180 0 0 120 c0 73 4 120 10 120 6 0 10 13 10 29 0 17 6 31 16 35 13 5 14 9 4 21 -11 13 8 15 154 15 l166 0 0 -170z m-380 -334 l0 -145 -37 -3 c-52 -4 -56 -28 -4 -28 41 0 41 0 41 -38 0 -21 -9 -57 -20 -80 -21 -42 -27 -102 -11 -102 10 0 31 54 31 81 0 18 12 19 190 19 l190 0 0 -160 0 -160 -390 0 -390 0 0 380 0 380 200 0 200 0 0 -144z m380 -66 l0 -210 -180 0 c-121 0 -180 3 -180 11 0 6 14 30 31 55 33 48 31 64 -7 64 l-24 0 0 145 0 145 180 0 180 0 0 -210z m800 0 l0 -210 -165 0 c-141 0 -167 2 -172 16 -3 8 -1 20 6 27 32 32 -11 97 -63 97 -59 -1 -75 -28 -64 -110 l3 -25 -162 -3 -163 -2 0 210 0 210 390 0 390 0 0 -210z m420 71 l0 -140 -27 -3 c-39 -4 -76 -62 -68 -105 l6 -33 -156 0 -155 0 0 210 0 210 200 0 200 0 0 -139z m360 -241 l0 -380 -380 0 -380 0 0 160 0 160 171 0 c95 0 179 -4 189 -10 13 -7 27 -6 44 2 15 6 29 8 32 5 13 -12 -6 -54 -31 -67 -22 -12 -27 -11 -48 8 -13 12 -26 22 -30 22 -12 0 -8 -35 5 -48 19 -19 85 -15 107 7 20 20 41 80 41 118 0 33 -29 101 -46 107 -11 4 -14 34 -14 151 l0 145 170 0 170 0 0 -380z m-1146 54 c18 -18 19 -24 7 -42 -12 -20 -75 -11 -79 11 -8 40 42 62 72 31z m786 -39 c0 -46 -3 -55 -18 -55 -27 0 -42 20 -42 57 0 20 7 36 18 42 35 21 42 13 42 -44z m-1560 35 c0 -5 -4 -10 -10 -10 -5 0 -10 5 -10 10 0 6 5 10 10 10 6 0 10 -4 10 -10z m1600 -35 c0 -19 -4 -35 -10 -35 -5 0 -10 16 -10 35 0 19 5 35 10 35 6 0 10 -16 10 -35z m-940 -102 c0 -69 106 -102 149 -47 12 15 21 37 21 50 l0 24 155 0 155 0 0 -160 0 -160 -390 0 -390 0 0 160 0 160 150 0 150 0 0 -27z m140 2 c0 -52 -76 -70 -101 -24 -18 35 -4 49 51 49 47 0 50 -2 50 -25z"/>
<path d="M3760 1790 l0 -1590 1600 0 1600 0 0 1590 0 1590 -1600 0 -1600 0 0 -1590z m800 1360 l0 -210 -175 0 -175 0 0 58 c0 32 -3 62 -6 65 -4 4 -20 -5 -36 -18 -16 -14 -34 -25 -39 -25 -5 0 -9 -7 -9 -15 0 -11 8 -13 30 -8 l30 6 0 -93 c0 -69 3 -91 13 -88 6 3 13 25 15 51 l3 47 175 0 174 0 0 -170 0 -170 -390 0 -390 0 0 390 0 390 390 0 390 0 0 -210z m800 0 l0 -210 -161 0 -161 0 6 34 c9 47 -7 81 -44 96 -44 18 -100 -7 -100 -45 0 -30 11 -32 28 -5 14 22 61 27 80 8 16 -16 15 -49 -2 -70 -12 -16 -35 -18 -220 -18 l-206 0 0 210 0 210 390 0 390 0 0 -210z m780 0 l0 -210 -159 0 c-135 0 -160 2 -165 16 -3 8 -1 24 5 35 21 41 -13 88 -65 89 -28 0 -76 -33 -76 -52 0 -13 30 -9 46 7 20 19 48 19 64 0 17 -20 6 -43 -25 -55 -14 -5 -24 -15 -23 -22 2 -10 -38 -14 -179 -16 l-183 -2 0 210 0 210 380 0 380 0 0 -210z m800 -180 l0 -390 -169 0 -168 0 -5 234 c-3 129 -9 239 -13 245 -4 8 -17 3 -37 -14 -16 -14 -34 -25 -39 -25 -5 0 -9 -7 -9 -15 0 -11 8 -13 30 -8 28 5 30 4 30 -26 l0 -31 -200 0 -200 0 0 210 0 210 390 0 390 0 0 -390z m-2013 -88 c-54 -56 -50 -62 43 -62 47 0 80 4 80 10 0 6 -22 10 -48 10 -27 0 -52 3 -56 7 -3 4 8 22 26 40 l32 33 178 0 178 0 0 -170 0 -170 -390 0 -390 0 0 170 0 170 192 0 192 0 -37 -38z m888 28 c9 -15 -20 -57 -46 -65 -14 -5 -28 0 -43 14 -40 38 -65 20 -26 -19 46 -46 140 -11 140 52 l0 28 150 0 150 0 0 -170 0 -170 -380 0 -380 0 0 170 0 170 214 0 c139 0 217 -4 221 -10z m745 -40 c0 -27 5 -50 10 -50 6 0 10 -47 10 -120 l0 -120 -210 0 -210 0 0 170 0 170 200 0 200 0 0 -50z m-2000 -520 l0 -210 -170 0 -170 0 0 65 c0 50 -3 65 -15 65 -17 0 -137 -158 -132 -174 2 -6 27 -12 55 -14 l52 -3 0 -150 0 -149 -200 0 -200 0 0 390 0 390 390 0 390 0 0 -210z m800 0 l0 -210 -149 0 c-123 0 -151 3 -162 16 -21 25 -64 43 -88 37 -20 -5 -22 -2 -19 23 3 26 7 29 47 34 69 8 65 30 -6 30 l-59 0 -12 -45 c-7 -25 -12 -56 -12 -70 l0 -25 -160 0 -160 0 0 210 0 210 390 0 390 0 0 -210z m780 -180 l0 -390 -170 0 -170 0 0 116 c0 104 2 116 18 121 23 6 52 53 52 86 0 13 -10 37 -22 52 -20 25 -25 27 -74 22 -46 -5 -52 -3 -47 11 17 49 69 68 99 37 20 -20 36 -19 32 2 -2 9 -18 26 -36 36 -28 17 -37 17 -63 7 -35 -15 -59 -56 -59 -100 l0 -30 -160 0 -160 0 0 210 0 210 380 0 380 0 0 -390z m440 250 l0 -139 -65 -87 c-36 -48 -64 -92 -62 -98 2 -6 28 -13 57 -16 67 -6 68 -9 69 -177 l1 -123 -210 0 -210 0 0 390 0 390 210 0 210 0 0 -140z m360 -250 l0 -390 -170 0 -170 0 0 146 c0 128 2 148 18 160 16 12 16 13 0 19 -16 7 -18 27 -18 231 l0 224 170 0 170 0 0 -390z m-2750 3 c0 -45 -12 -63 -41 -63 -35 0 -36 12 -6 50 25 33 47 38 47 13z m2378 -20 c-3 -35 -6 -38 -35 -41 -39 -4 -42 9 -10 48 32 41 49 38 45 -7z m-1553 -3 c4 -6 -10 -10 -34 -10 -23 0 -41 5 -41 10 0 6 15 10 34 10 19 0 38 -4 41 -10z m803 -6 c28 -19 29 -65 2 -89 -20 -18 -20 -17 -20 33 0 46 -2 52 -21 52 -11 0 -17 5 -14 10 9 14 27 12 53 -6z m-1258 -194 l0 -170 -180 0 -180 0 0 120 c0 73 4 120 10 120 6 0 10 13 10 29 0 17 6 31 16 35 13 5 14 9 4 21 -11 13 8 15 154 15 l166 0 0 -170z m465 143 c-8 -34 -5 -32 -42 -39 -24 -5 -35 -1 -49 15 -23 26 -34 27 -34 2 0 -26 37 -51 76 -51 36 0 84 46 84 81 0 18 9 19 150 19 l150 0 0 -170 0 -170 -390 0 -390 0 0 170 0 170 226 0 226 0 -7 -27z m675 -2 c0 -20 9 -37 31 -55 17 -14 35 -26 40 -26 5 0 9 -51 9 -115 l0 -115 -200 0 -200 0 0 170 0 170 160 0 160 0 0 -29z m80 -11 c0 -22 -3 -40 -7 -40 -23 1 -59 53 -48 70 3 6 17 10 31 10 21 0 24 -4 24 -40z m-1600 -464 l0 -145 -37 -3 c-52 -4 -56 -28 -4 -28 41 0 41 0 41 -38 0 -21 -9 -57 -20 -80 -19 -39 -27 -102 -14 -102 4 0 13 8 20 18 11 14 13 -2 14 -110 l0 -128 -200 0 -200 0 0 380 0 380 200 0 200 0 0 -144z m380 -236 l0 -380 -180 0 -180 0 0 181 0 180 31 45 c33 48 31 64 -7 64 l-24 0 0 145 0 145 180 0 180 0 0 -380z m800 170 l0 -210 -165 0 c-141 0 -167 2 -172 16 -3 8 -1 20 6 27 32 32 -11 97 -63 97 -56 -1 -87 -45 -65 -94 10 -21 9 -29 -4 -44 -23 -26 -21 -71 5 -99 32 -34 99 -32 127 3 12 15 21 37 21 50 l0 24 155 0 155 0 0 -160 0 -160 -390 0 -390 0 0 380 0 380 390 0 390 0 0 -210z m420 71 l0 -140 -27 -3 c-39 -4 -76 -62 -68 -105 l6 -33 -156 0 -155 0 0 210 0 210 200 0 200 0 0 -139z m360 -241 l0 -380 -380 0 -380 0 0 160 0 160 171 0 c95 0 179 -4 189 -10 13 -7 27 -6 44 2 15 6 29 8 32 5 13 -12 -6 -54 -31 -67 -22 -12 -27 -11 -48 8 -13 12 -26 22 -30 22 -12 0 -8 -35 5 -48 19 -19 85 -15 107 7 20 20 41 80 41 118 0 33 -29 101 -46 107 -11 4 -14 34 -14 151 l0 145 170 0 170 0 0 -380z m440 236 l0 -145 -47 -3 c-66 -4 -70 -28 -4 -28 62 0 64 -8 21 -95 -28 -58 -40 -125 -21 -125 10 0 31 54 31 81 0 11 5 19 10 19 6 0 10 -60 10 -160 l0 -160 -210 0 -210 0 0 380 0 380 210 0 210 0 0 -144z m360 -236 l0 -380 -170 0 -170 0 0 196 c0 182 1 198 21 225 21 30 19 49 -7 49 -11 0 -14 25 -14 145 l0 145 170 0 170 0 0 -380z m-1946 54 c18 -18 19 -24 7 -42 -12 -20 -75 -11 -79 11 -8 40 42 62 72 31z m786 -39 c0 -46 -3 -55 -18 -55 -27 0 -42 20 -42 57 0 20 7 36 18 42 35 21 42 13 42 -44z m-1560 35 c0 -5 -4 -10 -10 -10 -5 0 -10 5 -10 10 0 6 5 10 10 10 6 0 10 -4 10 -10z m1600 -35 c0 -19 -4 -35 -10 -35 -5 0 -10 16 -10 35 0 19 5 35 10 35 6 0 10 -16 10 -35z m-827 -67 c35 -17 36 -52 2 -74 -47 -31 -101 17 -75 66 12 23 34 25 73 8z m-813 -492 l0 -145 -37 -3 c-52 -4 -56 -28 -4 -28 41 0 41 0 41 -38 0 -21 -9 -57 -20 -80 -21 -43 -27 -102 -10 -102 5 0 15 18 21 40 l12 40 189 0 188 0 0 -150 0 -150 -390 0 -390 0 0 380 0 380 200 0 200 0 0 -144z m380 -76 l0 -220 -180 0 c-175 0 -180 1 -180 21 0 11 14 40 31 65 33 48 31 64 -7 64 l-24 0 0 145 0 145 180 0 180 0 0 -220z m800 0 l0 -220 -158 0 -159 0 -13 25 c-10 20 -11 28 -2 37 33 33 -9 98 -62 98 -56 -1 -87 -45 -65 -94 10 -22 9 -29 -6 -46 -17 -18 -31 -20 -167 -20 l-148 0 0 220 0 220 390 0 390 0 0 -220z m780 0 l0 -220 -140 0 -140 0 0 30 c0 44 -28 105 -54 119 -38 21 -78 10 -104 -29 -22 -33 -23 -44 -7 -97 l7 -23 -161 0 -161 0 0 220 0 220 380 0 380 0 0 -220z m440 76 l0 -145 -47 -3 c-66 -4 -70 -28 -4 -28 60 0 64 -11 29 -77 l-23 -43 -187 0 -188 0 0 220 0 220 210 0 210 0 0 -144z m360 -236 l0 -380 -390 0 -390 0 0 150 0 150 180 0 180 0 0 -40 c0 -51 16 -51 31 -1 7 24 19 41 30 44 15 4 19 15 19 47 0 26 8 53 21 71 21 30 19 49 -7 49 -11 0 -14 25 -14 145 l0 145 170 0 170 0 0 -380z m-1946 54 c18 -18 19 -24 7 -42 -12 -20 -75 -11 -79 11 -8 40 42 62 72 31z m807 6 c13 -7 19 -21 19 -43 0 -40 -15 -57 -50 -57 -35 0 -50 17 -50 57 0 45 38 66 81 43z m-1581 -10 c0 -5 -4 -10 -10 -10 -5 0 -10 5 -10 10 0 6 5 10 10 10 6 0 10 -4 10 -10z m780 -100 c0 -5 -18 -10 -41 -10 -24 0 -38 4 -34 10 3 6 22 10 41 10 19 0 34 -4 34 -10z m-120 -47 c0 -60 109 -87 149 -37 12 15 21 33 21 40 0 11 31 14 155 14 l155 0 0 -150 0 -150 -390 0 -390 0 0 150 0 150 150 0 c134 0 150 -2 150 -17z m140 3 c0 -16 -37 -46 -57 -46 -15 0 -53 36 -53 50 0 6 25 10 55 10 41 0 55 -4 55 -14z m800 4 c0 -13 -41 -50 -55 -50 -7 0 -20 9 -30 20 -22 25 -35 26 -35 2 0 -27 20 -42 58 -42 45 0 67 13 82 50 l12 30 144 0 144 0 0 -150 0 -150 -380 0 -380 0 0 150 0 150 220 0 c134 0 220 -4 220 -10z"/>
</g>
</svg>
NOTE: The idea is not sort the elements from the lowest value to the highest; the idea is to traverse the 2-d array in a clockwise snailshell pattern.
NOTE 2: The 0x0 (empty matrix) is represented as en empty array inside an array `[[]]`.
| algorithms | import numpy as np
def snail(array):
m = []
array = np . array(array)
while len(array) > 0:
m += array[0]. tolist()
array = np . rot90(array[1:])
return m
| Snail | 521c2db8ddc89b9b7a0000c1 | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/521c2db8ddc89b9b7a0000c1 | 4 kyu |
Your task is to find the first element of an array that is not consecutive.
By not consecutive we mean not exactly 1 larger than the previous element of the array.
E.g. If we have an array `[1,2,3,4,6,7,8]` then `1` then `2` then `3` then `4` are all consecutive but `6` is not, so that's the first non-consecutive number.
```if:c
If a non consecutive number is found then return `true` and set the passed in pointer to the number found.
If the whole array is consecutive then return `false`.
```
```if-not:c
If the whole array is consecutive then return `null`<sup>2</sup>.
```
The array will always have at least `2` elements<sup>1</sup> and all elements will be numbers. The numbers will also all be unique and in ascending order. The numbers could be positive or negative and the first non-consecutive could be either too!
If you like this Kata, maybe try this one next: https://www.codewars.com/kata/represent-array-of-numbers-as-ranges
```if:c
<sup>1</sup> Can you write a solution that will return `false` for both `[]` and `[ x ]` (an empty array and one with a single number) though? (This is an empty array and one with a single number and is not tested for, but you can write your own example test. )
```
```if-not:c
<sup>1</sup> Can you write a solution that will return `null`<sup>2</sup> for both `[]` and `[ x ]` though? (This is an empty array and one with a single number and is not tested for, but you can write your own example test. )
<sup>2</sup>
Swift, Ruby and Crystal: `nil`
Haskell: `Nothing`
Python, Rust, Scala: `None`
Julia: `nothing`
Nim: `none(int)` (See [options](https://nim-lang.org/docs/options.html))
``` | reference | def first_non_consecutive(arr):
if not arr:
return 0
for i, x in enumerate(arr[: - 1]):
if x + 1 != arr[i + 1]:
return arr[i + 1]
| Find the first non-consecutive number | 58f8a3a27a5c28d92e000144 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/58f8a3a27a5c28d92e000144 | 8 kyu |
You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters.
#Examples:
```
Kata.getMiddle("test") should return "es"
Kata.getMiddle("testing") should return "t"
Kata.getMiddle("middle") should return "dd"
Kata.getMiddle("A") should return "A"
```
#Input
A word (string) of length `0 < str < 1000` (In javascript you may get slightly more than 1000 in some test cases due to an error in the test cases). You do not need to test for this. This is only here to tell you that you do not need to worry about your solution timing out.
#Output
The middle character(s) of the word represented as a string.
| reference | def get_middle(s):
index, odd = divmod(len(s), 2)
return s[index] if odd else s[index - 1: index + 1]
| Get the Middle Character | 56747fd5cb988479af000028 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/56747fd5cb988479af000028 | 7 kyu |
Write a function which converts the input string to uppercase.
~~~if:bf
For BF all inputs end with \0, all inputs are lowercases and there is no space between.
~~~
~~~if:riscv
RISC-V: The function signature is
```c
void to_upper_case(const char *str, char *out);
```
`str` is the input string. Write your result to `out`. You may assume it is large enough to hold the result. You do not need to return anything.
~~~
| reference | def make_upper_case(s): return s . upper()
| MakeUpperCase | 57a0556c7cb1f31ab3000ad7 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/57a0556c7cb1f31ab3000ad7 | 8 kyu |
Finish the solution so that it sorts the passed in array of numbers. If the function passes in an empty array or null/nil value then it should return an empty array.
For example:
```r
solution(c(1, 2, 3, 10, 5)) # should return c(1, 2, 3, 5, 10)
solution(NULL) # should return NULL
```
```php
solution([1, 2, 10, 50, 5]); // should return [1,2,5,10,50]
solution(null); // should return []
```
```javascript
solution([1, 2, 10, 50, 5]); // should return [1,2,5,10,50]
solution(null); // should return []
```
```typescript
solution([1, 2, 10, 50, 5]); // should return [1, 2, 5, 10, 50]
solution([]); // should return []
```
```coffeescript
solution([1, 2, 10, 50, 5]) # should return [1,2,5,10,50]
solution(null) # should return []
```
```ruby
solution([1, 2, 10, 50, 5]) # should return [1,2,5,10,50]
solution(nil) # should return []
```
```python
solution([1,2,3,10,5]) # should return [1,2,3,5,10]
solution(None) # should return []
```
```julia
solution([1, 2, 10, 50, 5]) # should return [1,2,5,10,50]
solution(nothing) # should return []
```
```csharp
SortNumbers(new int[] { 1, 2, 10, 50, 5 }); // should return new int[] { 1, 2, 5, 10, 50 }
SortNumbers(null); // should return new int[] { }
```
```rust
sort_numbers(&vec![1, 2, 3, 10, 5]); // should return vec![1, 2, 3, 5, 10]
sort_numbers(&vec![]); // should return !vec[]
```
```haskell
sortNumbers [1, 2, 10, 50, 5] = Just [1, 2, 5, 10, 50]
sortNumbers [] = Nothing
```
```lambdacalc
# (Note in Lambda Calculus we have lists instead of arrays.)
nums = cons 1 (cons 2 (cons 10 (cons 50 (cons 5 nil))))
sort nums # cons 1 (cons 2 (cons 5 (cons 10 (cons 50 nil))))
```
```cpp
sortNumbers({1, 2, 10, 50, 5}) // sholud return {1, 2, 5, 10, 50}
sortNumbers({}) // should return {}
```
```c
int array[5] = {1, 2, 10, 50, 5};
sort_ascending(5, array); // array is now {1, 2, 5, 10, 50}
sort_ascending(0, NULL); // nothing to do for empty array
```
```cobol
SortNumbers([1, 2, 10, 50, 5])
* -> res = [1, 2, 5, 10, 50]
SortNumbers([])
* -> res = []
```
```scala
sol(List(0, 3, 2, 5, 4, 1)) // returns List(0, 1, 2, 3, 4, 5)
sol(List()) // returns List()
```
```crystal
solution([1, 2, 10, 50, 5]) # should return [1,2,5,10,50]
solution(nil) # should return [] of Int32
```
~~~if:lambdacalc
## Lambda Calculus
- Purity: LetRec
- Num encoding: BinaryScott
- For LC, there won't be `null` inputs.
- Instead of arrays, we have cons lists. Define the following, which the tests will use to construct inputs and test outputs:
- `nil : List a` (empty list)
- `cons : a -> List a -> List a` (add to head)
- `foldr : (a -> b -> b) -> b -> List a -> b` (right-associative fold / reduce)
### Optional Performance Check
By default the tests are lenient with respect to performance. If you would like to demonstrate that your solution is fast, you can opt in to a stricter test suite ( more lists, longer lists, higher numbers ). Just change `perf-tests = Low` to `perf-tests = High`.
~~~ | reference | def solution(nums):
return sorted(nums) if nums else []
| Sort Numbers | 5174a4c0f2769dd8b1000003 | [
"Fundamentals"
] | https://www.codewars.com/kata/5174a4c0f2769dd8b1000003 | 7 kyu |
# Remove Duplicates
You are to write a function called `unique` that takes an array of integers and returns the array with duplicates removed. It must return the values in the same order as first seen in the given array. Thus no sorting should be done, if 52 appears before 10 in the given array then it should also be that 52 appears before 10 in the returned array.
## Assumptions
* All values given are integers (they can be positive or negative).
* You are given an array but it may be empty.
* They array may have duplicates or it may not.
## Example
```ruby
puts unique([1, 5, 2, 0, 2, -3, 1, 10]).inspect
[1, 5, 2, 0, -3, 10]
puts unique([]).inspect
[]
puts unique([5, 2, 1, 3]).inspect
[5, 2, 1, 3]
```
```coffeescript
unique([1, 5, 2, 0, 2, -3, 1, 10])
# -> [1, 5, 2, 0, -3, 10]
unique([])
# -> []
unique([5, 2, 1, 3])
# -> [5, 2, 1, 3]
```
```java
UniqueArray.unique([1, 5, 2, 0, 2, -3, 1, 10])
// -> [1, 5, 2, 0, -3, 10]
```
```lua
unique {1, 5, 2, 0, 2, -3, 1, 10} --> {1, 5, 2, 0, -3, 10}
```
```haskell
λ unique [1,5,2,0,2,-3,1,10]
[1,5,2,0,-3,10]
```
```python
print unique([1, 5, 2, 0, 2, -3, 1, 10])
[1, 5, 2, 0, -3, 10]
print unique([])
[]
print unique([5, 2, 1, 3])
[5, 2, 1, 3]
``` | reference | from collections import OrderedDict
def unique(integers):
return list(OrderedDict . fromkeys(integers))
| Remove Duplicates | 53e30ec0116393fe1a00060b | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/53e30ec0116393fe1a00060b | 7 kyu |
## Too long, didn't read
You get a list of integers, and you have to write a function `mirror` that returns the "mirror" (or symmetric) version of this list: i.e. the middle element is the greatest, then the next greatest on both sides, then the next greatest, and so on...
## More info
The list will always consist of integers in range `-1000..1000` and will vary in size between 0 and 10000. Your function **should not mutate the input** array, and this will be tested (where applicable). Notice that the returned list will always be of odd size, since there will always be a definitive middle element.
## Examples
```
[] --> []
[1] --> [1]
[2, 1] --> [1, 2, 1]
[1, 3, 2] --> [1, 2, 3, 2, 1]
[-8, 42, 18, 0, -16] --> [-16, -8, 0, 18, 42, 18, 0, -8, -16]
[-3, 15, 8, -1, 7, -1] --> [-3, -1, -1, 7, 8, 15, 8, 7, -1, -1, -3]
[-5, 10, 8, 10, 2, -3, 10] --> [-5, -3, 2, 8, 10, 10, 10, 10, 10, 8, 2, -3, -5]
```
Good luck!
~~~if:c
## For C language:
* do not allocate memory for the return value
* assign ints to the provided pointer `*result`
Due to these details, the function should not return anything, so the signature will look like this:
```c
void mirror(const int *data, size_t n, int *result)
```
where `data` is, of course, an input array (though technically its a pointer to an int), `n` is the size of the array and `result` is the array to which you should assign the resulting elements (again, technically a pointer).
~~~
| reference | def mirror(data: list) - > list:
arr = sorted(data)
return arr + arr[- 2:: - 1]
| Mirror, mirror, on the wall... | 5f55ecd770692e001484af7d | [
"Algorithms",
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/5f55ecd770692e001484af7d | 7 kyu |
In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative?
### Examples
``` text
Input: 1 => Output: -1
Input: -5 => Output: -5
Input: 0 => Output: 0
```
``` c
makeNegative(1); // return -1
makeNegative(-5); // return -5
makeNegative(0); // return 0
```
``` d
makeNegative(1); // return -1
makeNegative(-5); // return -5
makeNegative(0); // return 0
```
``` cfml
makeNegative(1); // return -1
makeNegative(-5); // return -5
makeNegative(0); // return 0
```
``` csharp
Kata.MakeNegative(1); // return -1
Kata.MakeNegative(-5); // return -5
Kata.MakeNegative(0); // return 0
```
``` java
Kata.makeNegative(1); // return -1
Kata.makeNegative(-5); // return -5
Kata.makeNegative(0); // return 0
```
``` crystal
make_negative(1); # return -1
make_negative(-5); # return -5
make_negative(0); # return 0
```
``` r
make_negative(1); # return -1
make_negative(-5); # return -5
make_negative(0); # return 0
```
``` python
make_negative(1); # return -1
make_negative(-5); # return -5
make_negative(0); # return 0
```
``` javascript
makeNegative(1); // return -1
makeNegative(-5); // return -5
makeNegative(0); // return 0
makeNegative(0.12); // return -0.12
```
``` dart
makeNegative(1); // return -1
makeNegative(-5); // return -5
makeNegative(0); // return 0
makeNegative(0.12); // return -0.12
```
``` typescript
makeNegative(1); // return -1
makeNegative(-5); // return -5
makeNegative(0); // return 0
```
``` cpp
makeNegative(1); // return -1
makeNegative(-5); // return -5
makeNegative(0); // return 0
```
``` haskell
makeNegative 1 -- return -1
makeNegative (-5) -- return -5
makeNegative 0 -- return 0
makeNegative 0.12 -- return -0.12
```
``` ruby
makeNegative(1); # return -1
makeNegative(-5); # return -5
makeNegative(0); # return 0
```
``` coffeescript
makeNegative 1 # return -1
makeNegative -5 # return -5
makeNegative 0 # return 0
```
``` elixir
make_negative 1 # return -1
make_negative -5 # return -5
make_negative 0 # return 0
```
``` go
MakeNegative(1) // return -1
MakeNegative(-5) // return -5
MakeNegative(0) // return 0
```
``` julia
Kata.makenegative(1) # return -1
Kata.makenegative(-5) # return -5
Kata.makenegative(0) # return 0
```
``` kotlin
Kata().makeNegative(1) // return -1
Kata().makeNegative(-5) // return -5
Kata().makeNegative(0) // return 0
```
``` nasm
make_negative(1); // return -1
make_negative(-5); // return -5
make_negative(0); // return 0
```
``` groovy
Kata.makeNegative(1) // return -1
Kata.makeNegative(-5) // return -5
Kata.makeNegative(0) // return 0
```
``` php
makeNegative(1) // return -1
makeNegative(-5) // return -5
makeNegative(0) // return 0
makeNegative(0.12) // return -0.12
```
``` racket
(make-negative 1) ; -1
(make-negative -5) ; -5
(make-negative 0) ; 0
(make-negative 0.12) ; -0.12
```
``` rust
make_negative(1); // return -1
make_negative(-5); // return -5
make_negative(0); // return 0
```
``` scala
Negative.makeNegative(1) // return -1
Negative.makeNegative(-5) // return -5
Negative.makeNegative(0) // return 0
```
``` perl
Kata::make_negative(1) # return -1
Kata::make_negative(-5) # return -5
Kata::make_negative(0) # return 0
Kata::make_negative(0.12); # return -0.12
```
``` cobol
MAKE-NEGATIVE 1
* RESULT = -1
MAKE-NEGATIVE -5
* RESULT = -5
MAKE-NEGATIVE 0
* RESULT = 0
```
``` clojure
(make-negative 1) ; return -1
(make-negative -5) ; return -5
(make-negative 0) ; return 0
```
### Notes
- The number can be negative already, in which case no change is required.
- Zero (0) is not checked for any specific sign. Negative zeros make no mathematical sense.
| reference | def make_negative(number):
return - abs(number)
| Return Negative | 55685cd7ad70877c23000102 | [
"Fundamentals"
] | https://www.codewars.com/kata/55685cd7ad70877c23000102 | 8 kyu |
Given a positive number n > 1 find the prime factor decomposition of n.
The result will be a string with the following form :
```
"(p1**n1)(p2**n2)...(pk**nk)"
```
with the p(i) in increasing order and n(i) empty if
n(i) is 1.
```
Example: n = 86240 should return "(2**5)(5)(7**2)(11)"
```
| reference | def primeFactors(n):
i = 2
r = ''
while n != 1:
k = 0
while n % i == 0:
n = n / i
k += 1
if k == 1:
r = r + '(' + str(i) + ')'
elif k == 0:
pass
else:
r = r + '(' + str(i) + '**' + str(k) + ')'
i += 1
return r
| Primes in numbers | 54d512e62a5e54c96200019e | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/54d512e62a5e54c96200019e | 5 kyu |
[Digital root](https://en.wikipedia.org/wiki/Digital_root) is the _recursive sum of all the digits in a number._
Given `n`, take the sum of the digits of `n`. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer.
## Examples
```
16 --> 1 + 6 = 7
942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6
132189 --> 1 + 3 + 2 + 1 + 8 + 9 = 24 --> 2 + 4 = 6
493193 --> 4 + 9 + 3 + 1 + 9 + 3 = 29 --> 2 + 9 = 11 --> 1 + 1 = 2
```
| algorithms | def digital_root(n):
return n if n < 10 else digital_root(sum(map(int, str(n))))
| Sum of Digits / Digital Root | 541c8630095125aba6000c00 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/541c8630095125aba6000c00 | 6 kyu |
<div style="border:1px solid;position:relative;padding:1ex 1ex 1ex 11.1em;"><div style="position:absolute; left:0;top:0;bottom:0; width:10em; padding:1ex;text-align:center;border:1px solid;margin:0 1ex 0 0;color:#000;background-color:#eee;font-variant:small-caps">Part of Series 2/3</div>
<div>
This kata is part of a series on the Morse code. Make sure you solve the [previous part](/kata/decode-the-morse-code) before you try this one. After you solve this kata, you may move to the [next one](/kata/decode-the-morse-code-for-real).
</div></div><br>
In this kata you have to write a <a href="https://en.wikipedia.org/wiki/Morse_code">Morse code</a> decoder for <a href="https://en.wikipedia.org/wiki/Electrical_telegraph">wired electrical telegraph</a>.
Electric telegraph is operated on a 2-wire line with a key that, when pressed, connects the wires together, which can be detected on a remote station. The Morse code encodes every character being transmitted as a sequence of "dots" (short presses on the key) and "dashes" (long presses on the key).
When transmitting the Morse code, the international standard specifies that:
<ul><li>"Dot" – is 1 time unit long.</li>
<li>"Dash" – is 3 time units long.</li>
<li>Pause between dots and dashes in a character – is 1 time unit long.</li>
<li>Pause between characters inside a word – is 3 time units long.</li>
<li>Pause between words – is 7 time units long.</li></ul>
However, the standard does not specify how long that "time unit" is. And in fact different operators would transmit at different speed. An amateur person may need a few seconds to transmit a single character, a skilled professional can transmit 60 words per minute, and robotic transmitters may go way faster.
For this kata we assume the message receiving is performed automatically by the hardware that checks the line periodically, and if the line is connected (the key at the remote station is down), <code>1</code> is recorded, and if the line is not connected (remote key is up), <code>0</code> is recorded. After the message is fully received, it gets to you for decoding as a string containing only symbols <code>0</code> and <code>1</code>.
For example, the message <code>HEY JUDE</code>, that is <code>···· · −·−− ·−−− ··− −·· ·</code> may be received as follows:
<code>1100110011001100000011000000111111001100111111001111110000000000000011001111110011111100111111000000110011001111110000001111110011001100000011</code>
As you may see, this transmission is perfectly accurate according to the standard, and the hardware sampled the line exactly two times per "dot".
That said, your task is to implement two functions:
1. Function <code>decodeBits(bits)</code>, that should find out the transmission rate of the message, correctly decode the message to dots <code>.</code>, dashes <code>-</code> and spaces (one between characters, three between words) and return those as a string. Note that some extra <code>0</code>'s may naturally occur at the beginning and the end of a message, make sure to ignore them. Also if you have trouble discerning if the particular sequence of <code>1</code>'s is a dot or a dash, assume it's a dot.
2. Function <code>decodeMorse(morseCode)</code>, that would take the output of the previous function and return a human-readable string.
**NOTE:** For coding purposes you have to use ASCII characters `.` and `-`, not Unicode characters.
The Morse code table is preloaded for you (see the solution setup, to get its identifier in your language).
```scala
Eg:
morseCodes(".--") //to access the morse translation of ".--"
```
All the test strings would be valid to the point that they could be reliably decoded as described above, so you may skip checking for errors and exceptions, just do your best in figuring out what the message is!
Good luck!
After you master this kata, you may try to <a href="http://www.codewars.com/kata/decode-the-morse-code-for-real">Decode the Morse code, for real</a>.
| algorithms | def decodeBits(bits):
import re
# remove trailing and leading 0's
bits = bits . strip('0')
# find the least amount of occurrences of either a 0 or 1, and that is the time hop
time_unit = min(len(m) for m in re . findall(r'1+|0+', bits))
# hop through the bits and translate to morse
return bits[:: time_unit]. replace('111', '-'). replace('1', '.'). replace('0000000', ' '). replace('000', ' '). replace('0', '')
def decodeMorse(morseCode):
return ' ' . join('' . join(MORSE_CODE[l] for l in w . split()) for w in morseCode . split(' '))
| Decode the Morse code, advanced | 54b72c16cd7f5154e9000457 | [
"Algorithms"
] | https://www.codewars.com/kata/54b72c16cd7f5154e9000457 | 4 kyu |
Given the triangle of consecutive odd numbers:
```
1
3 5
7 9 11
13 15 17 19
21 23 25 27 29
...
```
Calculate the sum of the numbers in the n<sup>th</sup> row of this triangle (starting at index 1) e.g.: (**Input --> Output**)
```
1 --> 1
2 --> 3 + 5 = 8
```
| reference | def row_sum_odd_numbers(n):
# your code here
return n * * 3
| Sum of odd numbers | 55fd2d567d94ac3bc9000064 | [
"Arrays",
"Lists",
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/55fd2d567d94ac3bc9000064 | 7 kyu |
Clock shows `h` hours, `m` minutes and `s` seconds after midnight.
Your task is to write a function which returns the time since midnight in milliseconds.
## Example:
```
h = 0
m = 1
s = 1
result = 61000
```
Input constraints:
* `0 <= h <= 23`
* `0 <= m <= 59`
* `0 <= s <= 59`
~~~if:riscv
RISC-V: The function signature is:
```c
int past(int h, int m, int s);
```
~~~
| reference | def past(h, m, s):
return (3600 * h + 60 * m + s) * 1000
| Beginner Series #2 Clock | 55f9bca8ecaa9eac7100004a | [
"Fundamentals"
] | https://www.codewars.com/kata/55f9bca8ecaa9eac7100004a | 8 kyu |
## Intro:
I was doing a coding challenge. It was one of those multi-step challenges. I don't know if my approach was good or bad, but in one of these steps I was writing a function to convert word to numbers. I did it.. eventually, but... I didn't like how it was written. So I thought why not create kata and check how other people do it :) So:
## Task:
Your task is to write the word to number converter. Digits in the number should match letters in the word. Plus generated number should be the **smallest** possible number you can get.
- Words will contain of maximum 10 **distinct** letters, but word can be any length, even longer than 10 characters long.
- Number can NOT start with `0`
- ***Same letters*** share the ***same digit*** regardless of case
- For empty string return `0`
## Examples:
> `"A"` -> `1` - OK
> `"ABA"` -> `353` - WRONG ( number is OK, but it's not the smallest number )
> `"ABA"` -> `333` - WRONG ( different letters map to same digits )
>`"ABA"` -> `357` - WRONG ( same letters map to different digits ) | reference | def convert(s):
w2n = dict(zip(dict . fromkeys(s . upper()), '1023456789'))
return int('0' + '' . join([w2n[ch] for ch in s . upper()]))
| Word to initial number | 5bb148b840196d1be50000b1 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5bb148b840196d1be50000b1 | 6 kyu |
You're on your way to the market when you hear beautiful music coming from a nearby street performer. The notes come together like you wouln't believe as the musician puts together patterns of tunes. As you wonder what kind of algorithm you could use to shift octaves by 8 pitches or something silly like that, it dawns on you that you have been watching the musician for some 10 odd minutes. You ask, *"how much do people normally tip for something like this?"* The artist looks up. *"It's always gonna be about tree fiddy."*
It was then that you realize the musician was a 400 foot tall beast from the paleolithic era! The Loch Ness Monster almost tricked you!
There are only 2 guaranteed ways to tell if you are speaking to The Loch Ness Monster: A) it is a 400 foot tall beast from the paleolithic era; B) it will ask you for tree fiddy.
Since Nessie is a master of disguise, the only way accurately tell is to look for the phrase `"tree fiddy"`. Since you are tired of being grifted by this monster, the time has come to code a solution for finding The Loch Ness Monster. Note that the phrase can also be written as `"3.50"` or `"three fifty"`. Your function should return true if you're talking with The Loch Ness Moster, false otherwise. | reference | def is_lock_ness_monster(s):
return any(i in s for i in ('tree fiddy', 'three fifty', '3.50'))
| A Strange Trip to the Market | 55ccdf1512938ce3ac000056 | [
"Regular Expressions",
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/55ccdf1512938ce3ac000056 | 8 kyu |
## Debugging sayHello function
The starship Enterprise has run into some problem when creating a program to greet everyone as they come aboard. It is your job to fix the code and get the program working again!
Example output:
```
Hello, Mr. Spock
``` | reference | def say_hello(name):
return f"Hello, { name } "
| Grasshopper - Debug sayHello | 5625618b1fe21ab49f00001f | [
"Fundamentals"
] | https://www.codewars.com/kata/5625618b1fe21ab49f00001f | 8 kyu |
Consider a sequence `u` where u is defined as follows:
1. The number `u(0) = 1` is the first one in `u`.
2. For each `x` in `u`, then `y = 2 * x + 1` and `z = 3 * x + 1` must be in `u` too.
3. There are no other numbers in `u`.
Ex:
`u = [1, 3, 4, 7, 9, 10, 13, 15, 19, 21, 22, 27, ...]`
1 gives 3 and 4, then 3 gives 7 and 10, 4 gives 9 and 13, then 7 gives 15 and 22 and so on...
#### Task:
Given parameter `n` the function `dbl_linear` (or dblLinear...) returns the element `u(n)` of
the ordered (with <) sequence `u` (so, there are no duplicates).
#### Example:
`dbl_linear(10) should return 22`
#### Note:
Focus attention on efficiency
| algorithms | from collections import deque
def dbl_linear(n):
h = 1
cnt = 0
q2, q3 = deque([]), deque([])
while True:
if (cnt >= n):
return h
q2 . append(2 * h + 1)
q3 . append(3 * h + 1)
h = min(q2[0], q3[0])
if h == q2[0]:
h = q2 . popleft()
if h == q3[0]:
h = q3 . popleft()
cnt += 1
| Twice linear | 5672682212c8ecf83e000050 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5672682212c8ecf83e000050 | 4 kyu |
Write function bmi that calculates body mass index (bmi = weight / height<sup>2</sup>).
if bmi <= 18.5 return "Underweight"
if bmi <= 25.0 return "Normal"
if bmi <= 30.0 return "Overweight"
if bmi > 30 return "Obese" | reference | def bmi(weight, height):
bmi = weight / height * * 2
if bmi <= 18.5:
return "Underweight"
elif bmi <= 25:
return "Normal"
elif bmi <= 30:
return "Overweight"
else:
return "Obese"
| Calculate BMI | 57a429e253ba3381850000fb | [
"Fundamentals"
] | https://www.codewars.com/kata/57a429e253ba3381850000fb | 8 kyu |
You are given a method called `main`, make it print the line `Hello World!`, (yes, that includes a new line character at the end) and don't return anything
Note that for some languages, the function `main` is the entry point of the program.
Here's how it will be tested:
```java
java Solution.class parameter1 parameter2
```
```javascript
Solution.main("parameter1","parameter2");
```
```coffeescript
Solution.main "parameter1", "parameter2","parametern"
```
```ruby
Solution.main("parameter1", "parameter2","parametern")
```
```python
Solution.main("parameter1", "parameter2","parametern")
```
```csharp
Solution.Main("parameter1", "parameter2","parametern")
```
```php
Solution::main("parameter1", "parameter2", "parametern")
```
```sh
no extra lines there
```
```prolog
greet:greet
```
Hints:
1. Check your references
2. Think about the scope of your method
3. For prolog you can use write but there are [better ways](https://gist.github.com/dtonhofer/20bd01f68a924912771d8405fca66a09)
4. If you still don't get it probably you can define main as an attribute of the Solution class that accepts a single argument, and that only prints "Hello World!" without any return. | reference | class Solution:
@ staticmethod
def main(self, * args):
print("Hello World!")
| Classic Hello World | 57036f007fd72e3b77000023 | [
"Fundamentals",
"Object-oriented Programming"
] | https://www.codewars.com/kata/57036f007fd72e3b77000023 | 8 kyu |
### Story
Ben has a very simple idea to make some profit: he buys something and sells it again. Of course, this wouldn't give him any profit at all if he was simply to buy and sell it at the same price. Instead, he's going to buy it for the lowest possible price and sell it at the highest.
### Task
Write a function that returns both the minimum and maximum number of the given list/array.
### Examples (Input --> Output)
```
[1,2,3,4,5] --> [1,5]
[2334454,5] --> [5,2334454]
[1] --> [1,1]
```
### Remarks
All arrays or lists will always have at least one element, so you don't need to check the length. Also, your function will always get an array or a list, you don't have to check for `null`, `undefined` or similar.
~~~if:lambdacalc
### Encodings
purity: `LetRec`
numEncoding: `BinaryScott`
export constructors `nil, cons` for your `List` encoding
export deconstructors `fst, snd` for your `Pair` encoding
~~~ | reference | def min_max(lst):
return [min(lst), max(lst)]
| The highest profit wins! | 559590633066759614000063 | [
"Lists",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/559590633066759614000063 | 7 kyu |
And here is Fibonacci again. This time we want to go one step further. Our `fib()` function must be faster! Can you do it?
In case you don't know, what the Fibonacci number is:
The `n`th Fibonacci number is defined by the sum of the two previous Fibonacci numbers. In our case: `fib(1) := 0` and `fib(2) := 1`. With these initial values you should be able to calculate each following Fibonacci number.
Examples:
```
fib(1) // === 0
fib(2) // === 1
fib(3) // === 1
fib(4) // === 2
fib(5) // === 3
``` | algorithms | def fib(n):
a, b = 0, 1
for _ in range(n - 1):
a, b = b, a + b
return a
| Fibonacci Reloaded | 52549d3e19453df56f0000fe | [
"Algorithms"
] | https://www.codewars.com/kata/52549d3e19453df56f0000fe | 6 kyu |
In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example:
5! = 5 \* 4 \* 3 \* 2 \* 1 = 120. By convention the value of 0! is 1.
~~~if-not:factor
Write a function to calculate factorial for a given input. If input is below 0 or above 12 throw an exception of type `ArgumentOutOfRangeException` (C#) or `IllegalArgumentException` (Java) or `RangeException` (PHP) or throw a `RangeError` (JavaScript) or `ValueError` (Python) or return `-1` (C).
~~~
~~~if:factor
Write a word to calculate factorial for a given input. If input is below 0 or above 12 throw an error using the given word `range-error`.
~~~
More details about factorial can be found [here](https://www.wikiwand.com/en/Factorial). | reference | def factorial(n):
if n < 0 or n > 12:
raise ValueError
return 1 if n <= 1 else n * factorial(n - 1)
| Factorial | 54ff0d1f355cfd20e60001fc | [
"Algorithms",
"Fundamentals"
] | https://www.codewars.com/kata/54ff0d1f355cfd20e60001fc | 7 kyu |
# Are the numbers in order?
In this Kata, your function receives an array of integers as input. Your task is to determine whether the numbers are in ascending order. An array is said to be in ascending order if there are no two adjacent integers where the left integer exceeds the right integer in value.
For the purposes of this Kata, you may assume that all inputs are valid, i.e. arrays containing only integers.
Note that an array of 0 or 1 integer(s) is automatically considered to be sorted in ascending order since all (zero) adjacent pairs of integers satisfy the condition that the left integer does not exceed the right integer in value.
For example:
```java
isAscOrder(new int[]{1,2,4,7,19}) == true
isAscOrder(new int[]{1,2,3,4,5}) == true
isAscOrder(new int[]{1,6,10,18,2,4,20}) == false
isAscOrder(new int[]{9,8,7,6,5,4,3,2,1}) == false // numbers are in DESCENDING order
```
```c
in_asc_order({1,2,4,7,19}, 5); // returns true
in_asc_order({1,2,3,4,5}, 5); // returns true
in_asc_order({1,6,10,18,2,4,20}, 7); // returns false
in_asc_order({9,8,7,6,5,4,3,2,1}, 9); // returns false because the numbers are in DESCENDING order
```
```javascript
inAscOrder([1,2,4,7,19]); // returns true
inAscOrder([1,2,3,4,5]); // returns true
inAscOrder([1,6,10,18,2,4,20]); // returns false
inAscOrder([9,8,7,6,5,4,3,2,1]); // returns false because the numbers are in DESCENDING order
```
```cpp
inAscOrder([1,2,4,7,19]); // returns true
inAscOrder([1,2,3,4,5]); // returns true
inAscOrder([1,6,10,18,2,4,20]); // returns false
inAscOrder([9,8,7,6,5,4,3,2,1]); // returns false because the numbers are in DESCENDING order
```
```csharp
Kata.IsAscOrder(new int[]{1,2,4,7,19}) == true
Kata.IsAscOrder(new int[]{1,2,3,4,5}) == true
Kata.IsAscOrder(new int[]{1,6,10,18,2,4,20}) == false
Kata.IsAscOrder(new int[]{9,8,7,6,5,4,3,2,1}) == false // numbers are in DESCENDING order
```
```python
in_asc_order([1,2,4,7,19]) # returns True
in_asc_order([1,2,3,4,5]) # returns True
in_asc_order([1,6,10,18,2,4,20]) # returns False
in_asc_order([9,8,7,6,5,4,3,2,1]) # returns False because the numbers are in DESCENDING order
```
```php
in_asc_order([1, 2, 4, 7, 19]); // true
in_asc_order([1, 2, 3, 4, 5]); // true
in_asc_order([1, 6, 10, 18, 2, 4, 20]); // false
in_asc_order([9, 8, 7, 6, 5, 4, 3, 2, 1]); // false (NOTE: because the numbers are in DESCENDING order, not ascending order)
```
```haskell
isAscOrder [1, 2, 4, 7, 19] -- True
isAscOrder [1, 2, 3, 4, 5] -- True
isAscOrder [1, 6, 10, 18, 2, 4, 20] -- False
isAscOrder [9, 8, 7, 6, 5, 4, 3, 2, 1] -- False (NOTE: because the numbers are in DESCENDING order, not ascending order)
```
```ruby
is_asc_order([1,2,4,7,19]) # returns True
is_asc_order([1,2,3,4,5]); # returns True
is_asc_order([1,6,10,18,2,4,20]) # returns False
is_asc_order([9,8,7,6,5,4,3,2,1]) # returns False because the numbers are in DESCENDING order
```
```crystal
is_asc_order([1,2,4,7,19]) # returns True
is_asc_order([1,2,3,4,5]); # returns True
is_asc_order([1,6,10,18,2,4,20]) # returns False
is_asc_order([9,8,7,6,5,4,3,2,1]) # returns False because the numbers are in DESCENDING order
```
```go
InAscOrder([]int{1, 2, 4, 7, 19}) // returns True
InAscOrder([]int{1, 2, 3, 4, 5}) // returns True
InAscOrder([]int{1, 6, 10, 18, 2, 4, 20}) // returns False
InAscOrder([]int{9, 8, 7, 6, 5, 4, 3, 2, 1}) // returns False because the numbers are in DESCENDING order
```
```nasm
in_asc_order({1,2,4,7,19}, 5); // => 1
in_asc_order({1,2,3,4,5}, 5); // => 1
in_asc_order({1,6,10,18,2,4,20}, 7); // => 0
in_asc_order({9,8,7,6,5,4,3,2,1}, 9); // => 0
```
```factor
{ 1 2 4 7 19 } in-asc-order? ! returns t
{ 1 2 3 4 5 } in-asc-order? ! returns t
{ 1 6 10 18 2 4 20 } in-asc-order? ! returns f
{ 9 8 7 6 5 4 3 2 1 } in-asc-order? ! returns f because the numbers are in DESCENDING order
```
```cobol
InAscOrder([1,2,4,7,19]) => 1
InAscOrder([1,2,3,4,5]) => 1
InAscOrder([1,6,10,18,2,4,20]) => 0
InAscOrder([9,8,7,6,5,4,3,2,1]) => 0
```
```riscv
in_asc_order({1,2,4,7,19}, 5); // returns true
in_asc_order({1,2,3,4,5}, 5); // returns true
in_asc_order({1,6,10,18,2,4,20}, 7); // returns false
in_asc_order({9,8,7,6,5,4,3,2,1}, 9); // returns false because the numbers are in DESCENDING order
```
~~~if:nasm
**10/08/2018: Codewars doesn't support NASM code blocks in the Kata Description yet - please refer to the Sample Test Cases instead.**
~~~
~~~if:riscv
RISC-V: The function signature is
```c
bool in_asc_order(const int *arr, size_t n);
```
~~~
*N.B. If your solution passes all fixed tests but fails at the random tests, make sure you aren't mutating the input array.* | algorithms | def in_asc_order(arr):
return arr == sorted(arr)
| Are the numbers in order? | 56b7f2f3f18876033f000307 | [
"Fundamentals",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/56b7f2f3f18876033f000307 | 7 kyu |
````if:cobol
Implement a function called **`mult`**, which takes two numbers and returns their product:
```
call 'mult' using by content 10 20 by reference result
result = 200
call 'mult' using by content 0 758 by reference result
result = 0
call 'mult' using by content 154 99 by reference result
result = 15246
```
````
````if:csharp,go
Implement a function called **`Multiply`**, which takes two numbers and returns their product:
```
Multiply(2, 3) = 6
Multiply(0, 188) = 0
Multiply(85, 144) = 12240
```
````
````if-not:cobol, csharp, go
Implement a function called **`multiply`**, which takes two numbers and returns their product:
```
multiply(2, 3) = 6
multiply(0, 188) = 0
multiply(85, 144) = 12240
```
````
| reference | def multiply(x, y):
return x * y
| Function 3 - multiplying two numbers | 523b66342d0c301ae400003b | [
"Fundamentals"
] | https://www.codewars.com/kata/523b66342d0c301ae400003b | 8 kyu |
Create a function which answers the question "Are you playing banjo?".
If your name starts with the letter "R" or lower case "r", you are playing banjo!
The function takes a name as its only argument, and returns one of the following strings:
```
name + " plays banjo"
name + " does not play banjo"
```
Names given are always valid strings. | reference | def areYouPlayingBanjo(name):
if name[0]. lower() == 'r':
return name + ' plays banjo'
else:
return name + ' does not play banjo'
| Are You Playing Banjo? | 53af2b8861023f1d88000832 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/53af2b8861023f1d88000832 | 8 kyu |
Your task is to create a function that does four basic mathematical operations.
The function should take three arguments - operation(string/char), value1(number), value2(number).
The function should return result of numbers after applying the chosen operation.
### Examples(Operator, value1, value2) --> output
~~~if-not:nasm
```
('+', 4, 7) --> 11
('-', 15, 18) --> -3
('*', 5, 5) --> 25
('/', 49, 7) --> 7
```
~~~
~~~if:nasm
```nasm
mov dil, '+'
mov rax, __float64__(4.0)
mov rdx, __float64__(7.0)
movq xmm0, rax
movq xmm1, rdx
call basic_op ; XMM0 <- 11.0
mov dil, '-'
mov rax, __float64__(15.0)
mov rdx, __float64__(18.0)
movq xmm0, rax
movq xmm1, rdx
call basic_op ; XMM0 <- -3.0
mov dil, '*'
mov rax, __float64__(5.0)
movq xmm0, rax
movq xmm1, rax
call basic_op ; XMM0 <- 25.0
mov dil, '/'
mov rax, __float64__(49.0)
mov rdx, __float64__(7.0)
movq xmm0, rax
movq xmm1, rdx
call basic_op ; XMM0 <- 7.0
```
~~~ | reference | def basic_op(operator, value1, value2):
if operator == '+':
return value1 + value2
if operator == '-':
return value1 - value2
if operator == '/':
return value1 / value2
if operator == '*':
return value1 * value2
| Basic Mathematical Operations | 57356c55867b9b7a60000bd7 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/57356c55867b9b7a60000bd7 | 8 kyu |
Given an array of integers, return a new array with each value doubled.
For example:
`[1, 2, 3] --> [2, 4, 6]`
~~~if:racket
```racket
;for racket you are given a list
(maps '(1 2 3)) ; returns '(2 4 6)
```
~~~ | reference | def maps(a):
return [2 * x for x in a]
| Beginner - Lost Without a Map | 57f781872e3d8ca2a000007e | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/57f781872e3d8ca2a000007e | 8 kyu |
Deoxyribonucleic acid (DNA) is a chemical found in the nucleus of cells and carries the "instructions" for the development and functioning of living organisms.
If you want to know more: http://en.wikipedia.org/wiki/DNA
In DNA strings, symbols "A" and "T" are complements of each other, as "C" and "G".
Your function receives one side of the DNA (string, except for Haskell); you need to return the other complementary side. DNA strand is never empty or there is no DNA at all (again, except for Haskell).
More similar exercise are found here: http://rosalind.info/problems/list-view/ (source)
Example: (**input --> output**)
~~~if-not:haskell
```
"ATTGC" --> "TAACG"
"GTAT" --> "CATA"
```
~~~
```if:haskell
dnaStrand [] `shouldBe` []
dnaStrand [A,T,G,C] `shouldBe` [T,A,C,G]
dnaStrand [G,T,A,T] `shouldBe` [C,A,T,A]
dnaStrand [A,A,A,A] `shouldBe` [T,T,T,T]
```
| reference | import string
def DNA_strand(dna):
return dna . translate(string . maketrans("ATCG", "TAGC"))
# Python 3.4 solution || you don't need to import anything :)
# return dna.translate(str.maketrans("ATCG","TAGC"))
| Complementary DNA | 554e4a2f232cdd87d9000038 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/554e4a2f232cdd87d9000038 | 7 kyu |
```if-not:javascript
Find the sum of the odd numbers within an array, after cubing the initial integers. The function should return `undefined`/`None`/`nil`/`NULL` if any of the values aren't numbers.
```
```if:javascript
Find the sum of the odd numbers within an array, after cubing the initial integers. The function should return `undefined` if any of the values aren't numbers.
```
~~~if:java,csharp
Note: There are ONLY integers in the JAVA and C# versions of this Kata.
~~~
~~~if:python
Note: Booleans should not be considered as numbers.
~~~
| reference | def cube_odd(arr):
return sum(n * * 3 for n in arr if n % 2) if all(type(n) == int for n in arr) else None
| Sum of Odd Cubed Numbers | 580dda86c40fa6c45f00028a | [
"Fundamentals",
"Functional Programming",
"Arrays"
] | https://www.codewars.com/kata/580dda86c40fa6c45f00028a | 7 kyu |
In computer science, cycle detection is the algorithmic problem of finding a cycle in a sequence of iterated function values.
For any function `$f$`, and any initial value `$x_0$` in S, the sequence of iterated function values
```math
x_0, x_1 = f(x_0), \dots ,x_i = f(x_{i-1}), \dots
```
may eventually use the same value twice under some assumptions: S finite, f periodic ... etc. So there will be some `$i \neq j$` such that `$x_i = x_j$`. Once this happens, the sequence must continue by repeating the cycle of values from `$x_i $` to `$x_{j−1}$`. Cycle detection is the problem of finding `$i$` and `$j$`, given `$ƒ$` and `$x_0$`. Let `$\mu$` be the smallest index such that the value associated will reappears and `$\lambda$` the smallest value such that `$x_{\mu} = x_{\lambda + \mu}$`, `$\lambda$` is the loop length.
Example:
Consider the sequence:
```
2, 0, 6, 3, 1, 6, 3, 1, 6, 3, 1, ....
```
The cycle in this value sequence is 6, 3, 1.
`$\mu$` is 2 (first 6)
`$\lambda$` is 3 (length of the sequence or difference between position of consecutive 6).
The goal of this kata is to build a function that will return [`$\mu$`,`$\lambda$`] when given a short sequence. Simple loops will be sufficient. The sequence will be given in the form of an array. All array will be valid sequence associated with deterministic function. It means that the sequence will repeat itself when a value is reached a second time. (So you treat two cases: non repeating [1,2,3,4] and repeating [1,2,1,2], no hybrid cases like [1,2,1,4]). If there is no repetition you should return [].
This kata is followed by two other cycle detection algorithms:
Loyd's: http://www.codewars.com/kata/cycle-detection-floyds-tortoise-and-the-hare
Bret's: http://www.codewars.com/kata/cycle-detection-brents-tortoise-and-hare
| algorithms | def cycle(sequence):
for j, x in enumerate(sequence):
i = sequence . index(x)
if 0 <= i < j:
return [i, j - i]
return []
| Cycle Detection: greedy algorithm | 5416f1834c24604c46000696 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5416f1834c24604c46000696 | 6 kyu |
### Introduction
The first century spans from the **year 1** up to *and including* the year 100, the second century - from the year 101 up to *and including* the year 200, etc.
### Task
Given a year, return the century it is in.
### Examples
```
1705 --> 18
1900 --> 19
1601 --> 17
2000 --> 20
2742 --> 28
```
```if:sql
In SQL, you will be given a table `years` with a column `yr` for the year. Return a table with a column `century`.
```
Note: this kata uses strict construction as shown in the description and the examples, you can read more about it [here](https://en.wikipedia.org/wiki/Century) | reference | def century(year):
return (year + 99) / / 100
| Century From Year | 5a3fe3dde1ce0e8ed6000097 | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/5a3fe3dde1ce0e8ed6000097 | 8 kyu |
In this Kata we are passing a number (n) into a function.
Your code will determine if the number passed is even (or not).
The function needs to return either a true or false.
Numbers may be positive or negative, integers or floats.
Floats with decimal part non equal to zero are considered UNeven for this kata. | reference | def is_even(n):
return n % 2 == 0
| Is it even? | 555a67db74814aa4ee0001b5 | [
"Fundamentals"
] | https://www.codewars.com/kata/555a67db74814aa4ee0001b5 | 8 kyu |
# Dot Calculator
You have to write a calculator that receives strings for input.
The dots will represent the number in the equation.
There will be dots on one side, an operator, and dots again after the operator.
The dots and the operator will be separated by one space.
Here are the following valid operators :
- `+` Addition
- `-` Subtraction
- `*` Multiplication
- `//` Integer Division
## Your Work (Task)
You'll have to return a string that contains dots, as many the equation returns.
If the result is 0, return the empty string.
When it comes to subtraction, the first number will always be greater than or equal to the second number.
### Examples (Input => Output)
```
* "..... + ..............." => "...................."
* "..... - ..." => ".."
* "..... - ." => "...."
* "..... * ..." => "..............."
* "..... * .." => ".........."
* "..... // .." => ".."
* "..... // ." => "....."
* ". // .." => ""
* ".. - .." => ""
```
| reference | def calculator(txt):
a, op, b = txt . split()
a, b = len(a), len(b)
return '.' * eval(f' { a } { op } { b } ')
| Dot Calculator | 6071ef9cbe6ec400228d9531 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/6071ef9cbe6ec400228d9531 | 7 kyu |
This is an easy twist to the example kata (provided by Codewars when learning how to create your own kata).
Add the value "codewars" to the array `websites` 1,000 times.
| reference | websites = ["codewars"] * 1000
| Kata Example Twist | 525c1a07bb6dda6944000031 | [
"Fundamentals"
] | https://www.codewars.com/kata/525c1a07bb6dda6944000031 | 8 kyu |
Create a function that accepts a string and a single character, and returns an integer of the count of occurrences the 2nd argument is found in the first one.
If no occurrences can be found, a count of 0 should be returned.
```
("Hello", "o") ==> 1
("Hello", "l") ==> 2
("", "z") ==> 0
```
```c
str_count("Hello", 'o'); // returns 1
str_count("Hello", 'l'); // returns 2
str_count("", 'z'); // returns 0
```
```nasm
str_count("Hello", 'o'); // returns 1
str_count("Hello", 'l'); // returns 2
str_count("", 'z'); // returns 0
```
### Notes
* The first argument can be an empty string
* In languages with no distinct character data type, the second argument will be a string of length 1
| reference | def strCount(string, letter):
return string . count(letter)
| All Star Code Challenge #18 | 5865918c6b569962950002a1 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/5865918c6b569962950002a1 | 8 kyu |
There was a test in your class and you passed it. Congratulations!
But you're an ambitious person. You want to know if you're better than the average student in your class.
You receive an array with your peers' test scores. Now calculate the average and compare your score!
~~~if-not:nasm,racket
Return `true` if you're better, else `false`!
~~~
~~~if:racket
Return #t if you're better, else #f.
~~~
~~~if:nasm
Return `1` if you're better, else `0`!
~~~
### Note:
Your points are not included in the array of your class's points. Do not forget them when calculating the average score! | reference | def better_than_average(class_points, your_points):
return your_points > sum(class_points) / len(class_points)
| How good are you really? | 5601409514fc93442500010b | [
"Fundamentals"
] | https://www.codewars.com/kata/5601409514fc93442500010b | 8 kyu |
Write a function that determines whether a string is a valid guess in a Boggle board, as per the rules of Boggle. A Boggle board is a 2D array of individual characters, e.g.:
```javascript
[ ["I","L","A","W"],
["B","N","G","E"],
["I","U","A","O"],
["A","S","R","L"] ]
```
```python
[ ["I","L","A","W"],
["B","N","G","E"],
["I","U","A","O"],
["A","S","R","L"] ]
```
```java
[ ['I','L','A','W'],
['B','N','G','E'],
['I','U','A','O'],
['A','S','R','L'] ]
```
```cpp
{ {'I','L','A','W'},
{'B','N','G','E'},
{'I','U','A','O'},
{'A','S','R','L'} }
```
```haskell
[ "ILAW"
, "BNGE"
, "IUAO"
, "ASRL"
]
```
Valid guesses are strings which can be formed by connecting adjacent cells (horizontally, vertically, or diagonally) without re-using any previously used cells.
For example, in the above board "BINGO", "LINGO", and "ILNBIA" would all be valid guesses, while "BUNGIE", "BINS", and "SINUS" would not.
Your function should take two arguments (a 2D array and a string) and return true or false depending on whether the string is found in the array as per Boggle rules.
Test cases will provide various array and string sizes (squared arrays up to 150x150 and strings up to 150 uppercase letters). You do not have to check whether the string is a real word or not, only if it's a valid guess. | games | def find_word(board, word):
grid = [l + [''] for l in board] + [[''] * (len(board[0]) + 1)]
def rc(x, y, i):
if i == len(word):
return True
if grid[x][y] != word[i]:
return False
grid[x][y] = ''
r = any(rc(x + u, y + v, i + 1)
for u in range(- 1, 2)
for v in range(- 1, 2))
grid[x][y] = word[i]
return r
return any(rc(x, y, 0)
for x in range(len(board))
for y in range(len(board[x])))
| Boggle Word Checker | 57680d0128ed87c94f000bfd | [
"Arrays",
"Recursion",
"Puzzles"
] | https://www.codewars.com/kata/57680d0128ed87c94f000bfd | 4 kyu |
Note: This kata is inspired by [Convert a Number to a String!](http://www.codewars.com/kata/convert-a-number-to-a-string/). Try that one too.
## Description
We need a function that can transform a string into a number. What ways of achieving this do you know?
Note: Don't worry, all inputs will be strings, and every string is a perfectly valid representation of an integral number.
## Examples
```
"1234" --> 1234
"605" --> 605
"1405" --> 1405
"-7" --> -7
```
| reference | def string_to_number(s):
return int(s)
| Convert a String to a Number! | 544675c6f971f7399a000e79 | [
"Parsing",
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/544675c6f971f7399a000e79 | 8 kyu |
Born a misinterpretation of [this kata](https://www.codewars.com/kata/simple-fun-number-334-two-beggars-and-gold/), your task here is pretty simple: given an array of values and an amount of beggars, you are supposed to return an array with the sum of what each beggar brings home, assuming they all take regular turns, from the first to the last.
For example: `[1,2,3,4,5]` for `2` beggars will return a result of `[9,6]`, as the first one takes `[1,3,5]`, the second collects `[2,4]`.
The same array with `3` beggars would have in turn have produced a better out come for the second beggar: `[5,7,3]`, as they will respectively take `[1,4]`, `[2,5]` and `[3]`.
Also note that not all beggars have to take the same amount of "offers", meaning that the length of the array is not necessarily a multiple of `n`; length can be even shorter, in which case the last beggars will of course take nothing (`0`).
***Note:*** in case you don't get why this kata is about *English* beggars, then you are not familiar on how religiously queues are taken in the kingdom ;)
***Note 2:*** do not modify the input array. | reference | def beggars(values, n):
return [sum(values[i:: n]) for i in range(n)]
| English beggars | 59590976838112bfea0000fa | [
"Queues",
"Arrays",
"Lists",
"Recursion",
"Fundamentals"
] | https://www.codewars.com/kata/59590976838112bfea0000fa | 6 kyu |
Write a function to convert a name into initials. This kata strictly takes two words with one space in between them.
The output should be two capital letters with a dot separating them.
It should look like this:
`Sam Harris` => `S.H`
`patrick feeney` => `P.F`
~~~if:riscv
RISC-V: The function signature is:
```c
char *get_initials(const char *full_name, char initials[4]);
```
Write your result to `initials`, and return that buffer.
~~~ | reference | def abbrevName(name):
return '.' . join(w[0] for w in name . split()). upper()
| Abbreviate a Two Word Name | 57eadb7ecd143f4c9c0000a3 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/57eadb7ecd143f4c9c0000a3 | 8 kyu |
Given a non-empty array of integers, return the result of multiplying the values together in order. Example:
```
[1, 2, 3, 4] => 1 * 2 * 3 * 4 = 24
```
| reference | def grow(arr):
product = 1
for i in arr :
product *= i
return product | Beginner - Reduce but Grow | 57f780909f7e8e3183000078 | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/57f780909f7e8e3183000078 | 8 kyu |
End of preview. Expand
in Dataset Viewer.
This dataset contains Python solutions to codewars problems. It is scraped from the most-voted "best practice" by users in the solution tabs
- Downloads last month
- 33