description
stringlengths 38
154k
| category
stringclasses 5
values | solutions
stringlengths 13
289k
| name
stringlengths 3
179
| id
stringlengths 24
24
| tags
listlengths 0
13
| url
stringlengths 54
54
| rank_name
stringclasses 8
values |
|---|---|---|---|---|---|---|---|
Taking into consideration the [3.5 edition rules](http://www.dandwiki.com/wiki/SRD:Ability_Scores#Table:_Ability_Modifiers_and_Bonus_Spells), your goal is to build a function that takes an ability score (worry not about validation: it is always going to be a non negative integer), will return:
* attribute modifier, as indicated on the table of the above link;
* maximum spell level for the spells you can cast (-1 for no spells at all) with that score;
* the eventual extra spells you might get (as an array/list, with elements representing extra spells for 1st, 2nd,... spell level in order; empty array for no extra spells).
The result needs to be an object (associative array in PHP), as shown in the examples:
```javascript
charAttribute(0) === {modifier: 0, maximumSpellLevel: -1, extraSpells: []}
charAttribute(1) === {modifier: -5, maximumSpellLevel: -1, extraSpells: []}
charAttribute(5) === {modifier: -3, maximumSpellLevel: -1, extraSpells: []}
charAttribute(10) === {modifier: 0, maximumSpellLevel: 0, extraSpells: []}
charAttribute(20) === {modifier: +5, maximumSpellLevel: 9, extraSpells: [2,1,1,1,1]}
```
```php
char_attribute(0); // => ['modifier' => 0, 'maximum_spell_level' => -1, 'extra_spells' => []]
char_attribute(1); // => ['modifier' => -5, 'maximum_spell_level' => -1, 'extra_spells' => []]
char_attribute(5); // => ['modifier' => -3, 'maximum_spell_level' => -1, 'extra_spells' => []]
char_attribute(10); // => ['modifier' => 0, 'maximum_spell_level' => 0, 'extra_spells' => []]
char_attribute(20); // => ['modifier' => +5, 'maximum_spell_level' => 9, 'extra_spells' => [2, 1, 1, 1, 1]]
```
```python
char_attribute(0) == {"modifier": 0, "maximum_spell_level": -1, "extra_spells": []}
char_attribute(1) == {"modifier": -5, "maximum_spell_level": -1, "extra_spells": []}
char_attribute(5) == {"modifier": -3, "maximum_spell_level": -1, "extra_spells": []}
char_attribute(10) == {"modifier": 0, "maximum_spell_level": 0, "extra_spells": []}
char_attribute(20) == {"modifier": +5, "maximum_spell_level": 9, "extra_spells": [2,1,1,1,1]}
```
```ruby
char_attribute(0) == {"modifier"=>0, "maximum_spell_level"=>-1, "extra_spells"=>[]}
char_attribute(1) == {"modifier"=>-5, "maximum_spell_level"=>-1, "extra_spells"=>[]}
char_attribute(5) == {"modifier"=>-3, "maximum_spell_level"=>-1, "extra_spells"=>[]}
char_attribute(10) == {"modifier": 0, "maximum_spell_level"=>0, "extra_spells"=>[]}
char_attribute(20) == {"modifier": +5, "maximum_spell_level"=>9, "extra_spells"=>[2,1,1,1,1]}
```
```crystal
char_attribute(0) == {"modifier"=>0, "maximum_spell_level"=>-1, "extra_spells"=>[]}
char_attribute(1) == {"modifier"=>-5, "maximum_spell_level"=>-1, "extra_spells"=>[]}
char_attribute(5) == {"modifier"=>-3, "maximum_spell_level"=>-1, "extra_spells"=>[]}
char_attribute(10) == {"modifier": 0, "maximum_spell_level"=>0, "extra_spells"=>[]}
char_attribute(20) == {"modifier": +5, "maximum_spell_level"=>9, "extra_spells"=>[2,1,1,1,1]}
```
```csharp
CharAttribute(0) => (modifier: 0, maximumSpellLevel: -1, extraSpells: new int[0])
CharAttribute(1) => (modifier: -5, maximumSpellLevel: -1, extraSpells: new int[0])
CharAttribute(5) => (modifier: -3, maximumSpellLevel: -1, extraSpells: new int[0])
CharAttribute(10) => (modifier: 0, maximumSpellLevel: 0, extraSpells: new int[0])
CharAttribute(20) => (modifier: +5, maximumSpellLevel: 9, extraSpells: new []{2,1,1,1,1})
```
*Note: I didn't explain things in detail and just pointed out to the table on purpose, as my goal is also to train the pattern recognition skills of whoever is going to take this challenges, so do not complain about a summary description. Thanks :)*
In the same series:
* [D&D Character generator #1: attribute modifiers and spells](https://www.codewars.com/kata/d-and-d-character-generator-number-1-attribute-modifiers-and-spells/)
* [D&D Character generator #2: psion power points](https://www.codewars.com/kata/d-and-d-character-generator-number-2-psion-power-points/)
* [D&D Character generator #3: carrying capacity](https://www.codewars.com/kata/d-and-d-character-generator-number-3-carrying-capacity/)
|
reference
|
def char_attribute(score):
return ({"modifier": 0, "maximum_spell_level": - 1, "extra_spells": []} if not score
else {"modifier": score / / 2 - 5,
"maximum_spell_level": - 1 if score / / 2 - 5 < 0 else min(9, score - 10),
"extra_spells": [1 + n / / 4 for n in range(score / / 2 - 5)][:: - 1][: 9]})
|
D&D Character generator #1: attribute modifiers and spells
|
596a690510ffee5c0b00006a
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/596a690510ffee5c0b00006a
|
6 kyu
|
The goal of this kata is to multiply two integers using the [ancient Egyptian method](https://en.wikipedia.org/wiki/Ancient_Egyptian_multiplication), which only requires divisions and multiplications by two, and additions.
Your function takes two integers as input. It shall return a list of the steps in the multiplication.
Let `m` be the largest and `n` the smallest. While `m` is superior to `0`, at each step:
* if `m` is not divisible by `2`, add `n` to the list
* divide `m` by `2` (integer division)
* multiply `n` by `2`
At the end, return the list in descending order.
The result of the multiplication is the sum of the list elements, but you have to return only the list.
## Input
`n` and `m` integers, from `0` to `10,000`. It is **not** guaranteed that `m` > `n`.
## Example
| m | n | m % 2 | list |
|------|------|---|------------------|
| 100 | 15 | 0 | `[]` |
| 50 | 30 | 0 | `[]` |
| 25 | 60 | 1 | `[60]` |
| 12 | 120 | 0 | `[60]` |
| 6 | 240 | 0 | `[60]` |
| 3 | 480 | 1 | `[480, 60]` |
| 1 | 960 | 1 | `[960, 480, 60]` |
| 0 | | 0 | `[960, 480, 60]` |
`100 * 15 = 1500 = 60 + 480 + 960`
So the expected result is `[960, 480, 60]`.
|
algorithms
|
def bin_mul(m, n):
if m < n:
return bin_mul(n, m)
if n == 0:
return []
res = []
while m > 0:
if m % 2 == 1:
res . append(n)
m = m / / 2
n *= 2
return res[:: - 1]
|
Binary multiplication.
|
596a81352240711f3b00006e
|
[
"Mathematics",
"Puzzles",
"Algorithms"
] |
https://www.codewars.com/kata/596a81352240711f3b00006e
|
6 kyu
|
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said
# Task
We have a rectangular cake with some raisins on it:
```
cake =
........
..o.....
...o....
........
// o is the raisins
```
We need to cut the cake evenly into `n` small rectangular pieces, so that each small cake has `1` raisin. `n` is not an argument, it is the number of raisins contained inside the cake:
```
cake =
........
..o.....
...o....
........
result should be an array:
[
........
..o.....
,
...o....
........
]
// In order to clearly show, we omit the quotes and "\n"
```
If there is no solution, return an empty array `[]`
# Note
- The number of raisins is always more than 1 and less than 10.
- If there are multiple solutions, select the one with the largest width of the first element of the array. (See also the examples below.)
- Evenly cut into `n` pieces, meaning the same area. But their shapes can be different. (See also the examples below.)
- In the result array, the order of pieces is from top to bottom and from left to right (according to the location of the upper left corner).
- Each piece of cake should be rectangular.
# Examples
### An example of multiple solutions:
```
cake =
.o......
......o.
....o...
..o.....
In this test case, we can found three solution:
solution 1 (horizontal cutting):
[
.o...... //piece 1
,
......o. //piece 2
,
....o... //piece 3
,
..o..... //piece 4
]
solution 2 (vertical cutting):
[
.o //piece 1
..
..
..
,
.. //piece 2
..
..
o.
,
.. //piece 3
..
o.
..
,
.. //piece 4
o.
..
..
]
solution 3 (cross cutting):
[
.o.. //piece 1
....
,
.... //piece 2
..o.
,
.... //piece 3
..o.
,
o... //piece 4
....
]
we need choose solution 1 as result
```
### An example of different shapes:
```
cake =
.o.o....
........
....o...
........
.....o..
........
the result should be:
[
.o //pieces 1
..
..
..
..
..
,
.o.... //pieces 2
......
,
..o... //pieces 3
......
,
...o.. //pieces 4
......
]
Although they have different shapes,
they have the same area(2 x 6 = 12 and 6 x 2 = 12).
```
### An example of no solution case:
```
cake =
.o.o....
.o.o....
........
........
........
........
the result should be []
```
Kata may contains bug, please help me to test it, thanks ;-)
|
games
|
def cut(cake):
def DFS(x0, y0, nShape):
if nShape == nSeeds:
yield True
else:
for h, w in models:
xN, yN, covSeed = setup(x0, y0, h, w, nShape)
if covSeed:
yield from DFS(xN, yN, nShape + 1)
tearDown(* shapes . pop())
def setup(x0, y0, h, w, nShape):
seedAt = []
inside = [board[x][y] == 'o' and seedAt . append((x, y)) or (x, y)
for x, y in ((x0 + x, y0 + y) for y in range(w) for x in range(h))
if x < lX and y < lY and board[x][y] in BASE]
if len(inside) != area or len(seedAt) != 1:
return 0, 0, 0
sShape = str(nShape)
for x, y in inside:
board[x][y] = sShape
xN, yN = next(((x, y) for x in range(lX)
for y in range(lY) if board[x][y] in BASE), (None, None))
shapes . append((x0, y0, h, w, seedAt[0]))
return xN, yN, 1
def tearDown(x0, y0, h, w, seed):
for y in range(w):
for x in range(h):
a, b = pos = (x0 + x, y0 + y)
board[a][b] = BASE[pos == seed]
def shaper(tup):
x0, y0, h, w, seed = tup
return '\n' . join('' . join(BASE[(x0 + x, y0 + y) == seed] for y in range(w)) for x in range(h))
if not cake:
return []
board = list(map(list, cake . split('\n')))
nSeeds = sum(r . count('o') for r in board)
lX, lY = len(board), len(board[0])
area = lX * lY / nSeeds
if area % 1:
return []
area = int(area)
models = [(h, area / / h) for h in range(1, min(lX, area) + 1) if not area % h and area / / h <= lY]
shapes = []
BASE = '.o'
return list(map(shaper, shapes)) if next(DFS(0, 0, 0), False) else []
|
Cut the cake
|
586214e1ef065414220000a8
|
[
"Puzzles"
] |
https://www.codewars.com/kata/586214e1ef065414220000a8
|
2 kyu
|
In this kata you're given an `n x n` array and you're expected to traverse the elements diagonally from the `bottom right` to the `top left`.
### Example
```
1 6 7
7 2 4
3 5 9
```
your solution should return elements in the following order
```
9
4 5
7 2 3
6 7
1
```
`//=> [9, 4, 5, 7, 2, 3, 6, 7, 1]`
Your task is to write the function `diagonal()` that returns the array elements in the above manner.
### Another Example
```javascript
arr = [
[4, 5, 7],
[3, 9, 1],
[7, 6, 2]
]
diagonal(arr) //=> [2, 1, 6, 7, 9, 7, 5, 3, 4]
```
You can assume the test cases are well formed.
|
algorithms
|
import numpy as np
def diagonal(ar):
arr = np . rot90(np . array(ar))
return np . concatenate([np . diagonal(arr, a) for a in range(len(ar) - 1, - len(ar), - 1)]). tolist()
|
Traverse array elements diagonally
|
5968fb556875980bd900000f
|
[
"Arrays",
"Logic",
"Algorithms"
] |
https://www.codewars.com/kata/5968fb556875980bd900000f
|
6 kyu
|
There is a common problem given to interviewees in software. It is called FizzBuzz.
It works as follows:
For the numbers between 1 and 100, print fizz if it is a multiple of 3 and buzz if it is a mutiple of 5, else print the number itself.
You are in an interview and they ask you to complete fizzbuzz (which can be done in a one-liner in a few langs) and you knock it out of the park.
Surprised by your ability, the interviewer gives you a harder problem. Given a list of coprime numbers, (that is that the g.c.d. of all the numbers == 1) and an equally sized list of words. compute its fizzbuzz representation up until the pattern of strings repeats itself.
Here's an example
```
fizzbuzz_plusplus([2, 3, 5], ['fizz', 'buzz', 'bazz']); // => [1, 'fizz', 'buzz', 'fizz', 'bazz', 'fizzbuzz', 7, 'fizz', 'buzz', 'fizzbazz', 11, 'fizzbuzz', 13, 'fizz', 'buzzbazz', 'fizz', 17, 'fizzbuzz', 19, 'fizzbazz', 'buzz', 'fizz', 23, 'fizzbuzz', 'bazz', 'fizz', 'buzz', 'fizz', 29 , 'fizzbuzzbazz']
```
Things to note:
* Your function should return an Array of the output for each index, not print it.
* If elements are 1-indexed, the 10th item is fizz + bazz as 10 == 0 (mod 2) and 10 == 0 (mod 5).
* The strings are always concatenated from left to right in appearance of array.
* The number array may not always be sorted - just use the given order of the numbers
* All numbers in the first array will always be coprime. This is a safe assumption for your program.
* The list stops where it does because if you were to filter the numbers out, the remaining strings would repeat after this point.
Hint: What is the relation to the numbers given in the list and the length of the list?
|
algorithms
|
from functools import reduce
def fizzbuzz_plusplus(nums, words):
return ["" . join(w for n, w in zip(nums, words) if not i % n) or i
for i in range(1, reduce(lambda a, b: a * b, nums, 1) + 1)]
# limit = reduce(lambda a, b: a * b, nums, 1) + 1
# result = []
# for i in range(1, limit):
# s = ""
# for n, w in zip(nums, words):
# if not i % n:
# s = f"{s}{w}"
# result.append(s if s else i)
# return result
|
FizzBuzz++
|
596925532f709fccf3000077
|
[
"Algorithms"
] |
https://www.codewars.com/kata/596925532f709fccf3000077
|
6 kyu
|
# Task
Write a function `nico`/`nico()` that accepts two parameters:
- `key`/`$key` - string consists of unique letters and digits
- `message`/`$message` - string to encode
and encodes the `message` using the `key`.
First create a numeric key basing on a provided `key` by assigning each letter position in which it is located after setting the letters from `key` in an alphabetical order.
For example, for the key `crazy` we will get `23154` because of `acryz` (sorted letters from the key).
Let's encode `secretinformation` using our `crazy` key.
```
2 3 1 5 4
---------
s e c r e
t i n f o
r m a t i
o n
```
After using the key:
```
1 2 3 4 5
---------
c s e e r
n t i o f
a r m i t
o n
```
# Examples
```
nico("crazy", "secretinformation") => "cseerntiofarmit on "
nico("abc", "abcd") => "abcd "
nico("ba", "1234567890") => "2143658709"
nico("key", "key") => "eky"
```
Check the test cases for more samples.
# Collection
[Basic DeNico](https://www.codewars.com/kata/596f610441372ee0de00006e) - if you like this kata , try to decode the message in the next kata
|
reference
|
def nico(key, message):
res = ""
for x in range(0, len(message), len(key)):
for i in sorted(key):
try:
res += message[x: x + len(key)][key . index(i)]
except IndexError:
res += " "
return res
|
Basic Nico variation
|
5968bb83c307f0bb86000015
|
[
"Ciphers",
"Strings",
"Fundamentals"
] |
https://www.codewars.com/kata/5968bb83c307f0bb86000015
|
5 kyu
|
Create a function that will take any amount of money and break it down to the smallest number of bills as possible. Only integer amounts will be input, NO floats. This function should output a sequence, where each element in the array represents the amount of a certain bill type.
The array will be set up in this manner:
array[0] ---> represents $1 bills
array[1] ---> represents $5 bills
array[2] ---> represents $10 bills
array[3] ---> represents $20 bills
array[4] ---> represents $50 bills
array[5] ---> represents $100 bills
In the case below, we broke up $365 into 1 $5 bill, 1 $10 bill, 1 $50 bill, and 3 $100 bills:
```
365 => [0,1,1,0,1,3]
```
In this next case, we broke $217 into 2 $1 bills, 1 $5 bill, 1 $10 bill, and 2 $100 bills:
```
217 => [2,1,1,0,0,2]
```
|
reference
|
def give_change(money):
arr = []
for i in [100, 50, 20, 10, 5, 1]:
arr = [money / / i] + arr
money -= arr[0] * i
return tuple(arr)
|
You Got Change?
|
5966f6343c0702d1dc00004c
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/5966f6343c0702d1dc00004c
|
7 kyu
|
ASC Week 1 Challenge 4 (Medium #1)
Write a function that converts any sentence into a V A P O R W A V E sentence. a V A P O R W A V E sentence converts all the letters into uppercase, and adds 2 spaces between each letter (or special character) to create this V A P O R W A V E effect.
**Note that spaces should be ignored in this case.**
## Examples
```
"Lets go to the movies" --> "L E T S G O T O T H E M O V I E S"
"Why isn't my code working?" --> "W H Y I S N ' T M Y C O D E W O R K I N G ?"
```
|
reference
|
def vaporcode(s):
return " " . join(s . replace(" ", ""). upper())
|
V A P O R C O D E
|
5966eeb31b229e44eb00007a
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/5966eeb31b229e44eb00007a
|
7 kyu
|
Create a function that tells the user how to get around Midtown in Manhattan.
The function should be able to help the user to get from one location in this
area to another.
Streets run east-west. Street numbers increase as they move northward, from 1st street in Greenwich Village to 220th street in the Inwood section. Avenues run south-north, with numbers beginning on the east side of the island and increase to the west.
"The Encyclopedia of New York City" defines Midtown as extending from 34th Street to 59th Street (going northwards) and from 3rd Avenue to 8th Avenue (going westwards).
Streets are prefixed with E or W depending on if the adress is on the eastside or westside (East or West of 5th Avenue).
For example:
```python
start = "8th Ave and W 38th St"
end = "7th Ave and W 36th St"
```
The code above should tell the user how to get from 8th Ave and W 38th St to 7th Ave and W 36th St. It should then output as a string how many blocks north/south, and then how many blocks east/west the user should travel.
```python
start = "8th Ave and W 38th St"
end = "7th Ave and W 36th St"
output => "Walk 2 blocks south, and 1 blocks east"
start = "5th Ave and E 46th St"
end = "7th Ave and W 58th St"
output => "Walk 12 blocks north, and 2 blocks west"
```
Note: When the avenues are same, the direction of movement should be west and when the streets are same the direction should be north.
|
reference
|
import re
def midtown_nav(* start_end):
sAv, sSt, eAv, eSt = map(int, re . findall(r'\d+', ' ' . join(start_end)))
nV, nH = abs(eSt - sSt), abs(eAv - sAv)
V, H = 'south' if sSt > eSt else 'north', 'east' if sAv > eAv else 'west'
return f"Walk { nV } blocks { V } , and { nH } blocks { H } "
|
Midtown Navigator
|
59665001dc23af735700092b
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/59665001dc23af735700092b
|
6 kyu
|
This function takes two numbers as parameters, the first number being the coefficient, and the second number being the exponent.
Your function should multiply the two numbers, and then subtract 1 from the exponent. Then, it has to return an expression (like 28x^7). `"^1"` should not be truncated when exponent = 2.
For example:
``` javascript
derive(7, 8)
```
``` haskell
derive 7 8
```
In this case, the function should multiply 7 and 8, and then subtract 1 from 8. It should output `"56x^7"`, the first number 56 being the product of the two numbers, and the second number being the exponent minus 1.
``` javascript
derive(7, 8) --> this should output "56x^7"
derive(5, 9) --> this should output "45x^8"
```
``` haskell
derive 7 8 == "56x^7"
derive 5 9 == "45x^8"
```
**Notes:**
* The output of this function should be a string
* The exponent will never be 1, and neither number will ever be 0
|
reference
|
def derive(coefficient, exponent):
return f' { coefficient * exponent } x^ { exponent - 1 } '
|
Take the Derivative
|
5963c18ecb97be020b0000a2
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/5963c18ecb97be020b0000a2
|
8 kyu
|
A marine themed rival site to Codewars has started. Codwars is advertising their website all over the internet using subdomains to hide or obfuscate their domain to trick people into clicking on their site.
Your task is to write a function that accepts a URL as a string and determines if it would result in an http request to codwars.com.
Function should return true for all urls in the codwars.com domain. All other URLs should return false.
The urls are all valid but may or may not contain http://, https:// at the beginning or subdirectories or querystrings at the end.
For additional confusion, directories in can be named "codwars.com" in a url with the codewars.com domain and vise versa. Also, a querystring may contain codewars.com or codwars.com for any other domain - it should still return true or false based on the domain of the URL and not the domain in the querystring. Subdomains can also add confusion: for example `http://codwars.com.codewars.com` is a valid URL in the codewars.com domain in the same way that `http://mail.google.com` is a valid URL within google.com
Urls will not necessarily have either codewars.com or codwars.com in them. The folks at Codwars aren't very good about remembering the contents of their paste buffers.
All urls contain domains with a single TLD; you need not worry about domains like company.co.uk.
```
findCodwars("codwars.com"); // true
findCodwars("https://subdomain.codwars.com/a/sub/directory?a=querystring"); // true
findCodwars("codewars.com"); // false
findCodwars("https://subdomain.codwars.codewars.com/a/sub/directory/codwars.com?a=querystring"); // false
```
|
reference
|
import re
def find_codwars(url):
return bool(re . match(r''
'^(https?://)?' # http(s)://
'([a-z]+\.)*' # subdomains
'codwars\.com' # codwars.com
'([/?].*)?$' # directories or querystrings
, url))
|
Codwars or Codewars?
|
5967a67c8b0fc0093e000062
|
[
"Regular Expressions",
"Fundamentals"
] |
https://www.codewars.com/kata/5967a67c8b0fc0093e000062
|
6 kyu
|
# Alternating Among Three Values
Suppose a variable `x` can have only three possible different values `a`, `b` and `c`, and you wish to assign to `x` the value other than its current one, and you wish your code to be independent of the values of `a`, `b` and `c`.
What is the most efficient way to cycle among three values? Write a function `f` so that it satisfies
```
f(a) = b
f(b) = c
f(c) = a
```
### EXAMPLE
```python
f(10, a=10, b=20, c=100) -> 20
f(20, a=10, b=20, c=100) -> 100
f(100, a=10, b=20, c=100) -> 10
```
```javascript
f( 3, { a:3, b:4, c:5 } ) => 4
```
```haskell
f [ 3, 4, 5 ] 3 -> 4
```
```c
f(3, 3, 4, 5); // should return 4
```
```typescript
f( 3, { a:3, b:4, c:5 } ) => 4
```
|
reference
|
def f(x, a, b, c):
return {a: b, b: c, c: a}[x]
|
Alternating between three values
|
596776fbb4f24d0d82000141
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/596776fbb4f24d0d82000141
|
7 kyu
|
Santa has misplaced his list of gift to all the children, he has however a condensed version lying around.
In this condensed verison, instead of a list of gifts for each child, each one has an integer.
He also have a list of gifts corresponding to each integer. His list is as follows:
```ruby
GIFTS = {
1 => 'Toy Soldier',
2 => 'Wooden Train',
4 => 'Hoop',
8 => 'Chess Board',
16 => 'Horse',
32 => 'Teddy',
64 => 'Lego',
128 => 'Football',
256 => 'Doll',
512 => "Rubik's Cube"
}
```
```python
GIFTS = {
1: 'Toy Soldier',
2: 'Wooden Train',
4: 'Hoop',
8: 'Chess Board',
16: 'Horse',
32: 'Teddy',
64: 'Lego',
128: 'Football',
256: 'Doll',
512: "Rubik's Cube"
}
```
This list is made available to you, as `GIFTS`.
The integer for each child is such that the child should get the highest toy lower than or equal to that integer, and then, if there's more left, also get the highest toy lower than the rest and so on. Know that Santa never gives the same gift twice.
For example, by Timmy's name is `160`. This means that Timmy should get both a football and a teddy, because `128 + 32 = 160`.
You should help Santa by decoding his own list and recreate the missing list for him. Santa's elf wants the list sorted alphabetically by the toys, so you should help them as well and list the toys in a sorted order.
|
algorithms
|
def gifts(number):
return sorted(v for k, v in GIFTS . items() if k & number)
|
Santa's Missing Gift List
|
5665d30b3ea3d84a2c000025
|
[
"Binary",
"Algorithms"
] |
https://www.codewars.com/kata/5665d30b3ea3d84a2c000025
|
6 kyu
|
Given an D-dimension array, where each axis is of length N, your goal is to find the sum of every index in the array starting from 0.
For Example if D=1 and N=10 then the answer would be 45 ([0,1,2,3,4,5,6,7,8,9])
If D=2 and N = 3 the answer is 18 which would be the sum of every number in the following:
```python
[
[(0,0), (0,1), (0,2)],
[(1,0), (1,1), (1,2)],
[(2,0), (2,1), (2,2)]
]
```
A naive solution could be to loop over every index in every dimension and add to a global sum. This won't work as the number of dimension is expected to be quite large.
Hint: A formulaic approach would be best
Hint 2: Gauss could solve the one dimensional case in his earliest of years, This is just a generalization.
~~~if:javascript
Note for JS version: Because the results will exceed the maximum safe integer easily, for such values you're only required to have a precision of at least `1 in 1e-9` to the actual answer.
~~~
|
games
|
def super_sum(D, N):
# Number of possible combinations of D length from set [0...N]
num = pow(N, D)
# 2x average value of a combination; 2x because dividing results in float and loss of precision
dblAvg = D * (N - 1)
# Multiply number of possible combinations by the avergae value; now use true division to ensure result is an integer
return num * dblAvg / / 2
|
Super Coordinate Sums!
|
5966ec8e62d030d8530000a7
|
[
"Mathematics",
"Puzzles"
] |
https://www.codewars.com/kata/5966ec8e62d030d8530000a7
|
6 kyu
|
You are given a string of numbers between 0-9. Find the average of these numbers and return it as a floored whole number (ie: no decimal places) written out as a string. Eg:
"zero nine five two" -> "four"
If the string is empty or includes a number greater than 9, return "n/a"
|
algorithms
|
N = ['zero', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine']
def average_string(s):
try:
return N[sum(N . index(w) for w in s . split()) / / len(s . split())]
except (ZeroDivisionError, ValueError):
return 'n/a'
|
String average
|
5966847f4025872c7d00015b
|
[
"Strings",
"Algorithms"
] |
https://www.codewars.com/kata/5966847f4025872c7d00015b
|
6 kyu
|
Doesn't everyone love a haiku?
If you don't know what that is, let me make your day :D
A haiku is a traditional form of Japanese poetry, they normally have 3 lines with 5, 7 and 5 syllables respectively. For example:
```
codewars training day
regular expressions mean
many cups of tea
```
Feeling a little concerned that I'm about to ask you to write poetry? Fear not! You only have to translate the haiku from numbers to words, no need to start looking frantically for creative inspiration. Let me explain:
I'm giving you:
1. a function, `haikuWizard()`, which you have to complete.
2. a big, predefined array with lots of words organised in subarrays! As you can see, each subarray has 10 members and they are all words with the same number of syllables. So `words[0]` contains words of 1 syllable, `words[1]` contains words of 2 syllables and so on.
```javascript
var words = [
["like", "a", "tweet", "what", "for", "world", "whale", "one", "last", "sun"],
["ocean", "beauty", "tweet", "monster", "yellow", "return", "despair", "flower", "return", "contrast"],
["romantic", "curious", "banana", "jealousy", "tactlessly", "remorseful", "follower", "elephant", "however", "instagram"],
["salmonella", "consequently", "irregular", "intelligence", "vegetable", "ordinary", "alternative", "watermelon", "controversial", "marijuana"],
["lackadaisical", "serendipity", "colonoscopy", "dramatically", "parsimonius", "imagination", "electricity", "diabolical", "deforestation", "abomination"],
["extraterrestrial", "onomatopoeia", "responsibility", "revolutionary", "generalisation", "enthusiastically", "biodiversity", "veterinarian", "characteristically", "indefatigable"],
["oversimplification", "individuality", "decriminalisation", "compartmentalisation", "anaesthesiologist", "industrialisation", "buckminsterfullerene", "irresponsibility", "autobiographical", "utilitarianism"]]
```
Back to our function: `haikuWizard()` takes an array as its input. This array has 3 subarrays - each subarray represents a line of the haiku. For example:
`[[52], [17, 23, 39, 18], [33, 22]]`
For each number, the first digit tells you the number of syllables of the word, the second digit tells you which member of the relevant subarray it is.
For example:
`52`: This means that the first line is made up of one word with 5 syllables, at index 2 in `words[4]`.
`[17, 23, 39, 18]`: This means that the second line is made up of 4 words. The first has 1 syllable and is at index 7 in `words[0]`. The second has 2 syllables and is at index3 in `words[1]`.
And so on...
All you have to do is complete the function `haikuWizard()` so that it translates the given array back into the beautiful haiku it came from :)
You should return a string, which on using console.log should display in the appropriate haiku format:
```
console.log(str);
there's a trumpet man
waltzing around the canals
he's getting dizzy
```
The string itself will not have this format.
To summarise in case you don't feel like reading all that again:
- ```haikuWizard()``` should turn ```arr``` into a haiku using the array ```words```.
- ```arr``` has 3 subarrays, each represents a line of the haiku.
- the first digit of each number in ```arr``` represents the number of syllables of the word, the second digit is its index in the relevant subarray of ```words```.
- the return string should display a beautiful haiku with the correct structure.
Enjoy!
|
reference
|
def haiku_wizard(arr):
return '\n' . join(' ' . join(words[i / / 10 - 1][i % 10] for i in row) for row in arr)
|
Haiku Wizard
|
595f4df2e8f12961ab00007f
|
[
"Arrays",
"Fundamentals"
] |
https://www.codewars.com/kata/595f4df2e8f12961ab00007f
|
7 kyu
|
Description:
At 'We Rate Dogs', we try our best to give dogs accurate ratings, which will always be above 10/10. Because they're good dogs. Over the weekend Bront has come in and hacked our system, lowering the ratings of dogs to below 10/10.
Please help to fix Brant's bad system and give the dogs their original ratings. _They're good dogs Brent._
Task:
The `function weRateDogs(str, rating)` takes a string and an integer as the inputs. Within the string is an incorrect rating x/y.
You will need to change the incorrect rating `x/y` to the correct rating `rating/10`. The given string may contain numbers and letters, but no special characters other than `/`.
For example:
if you are given the following string:
`'This is Max99. She has one ear that is always s1ightly higher than the other 4/10 wonky af'`
And the following rating: `11`
return: `'This is Max99. She has one ear that is always s1ightly heigher than the other 11/10 wonky af'`
|
reference
|
import re
def we_rate_dogs(s, rating):
return re . sub(r"\d+\/\d+", f" { rating } /10", s)
|
They're good dogs.
|
5965144da82d479517000001
|
[
"Regular Expressions",
"Fundamentals"
] |
https://www.codewars.com/kata/5965144da82d479517000001
|
7 kyu
|
A twin prime is a prime number that is either 2 less or 2 more than another prime number—for example, either member of the twin prime pair (41, 43). In other words, a twin prime is a prime that has a prime gap of two. Sometimes the term twin prime is used for a pair of twin primes; an alternative name for this is prime twin or prime pair. (from wiki https://en.wikipedia.org/wiki/Twin_prime)
Your mission, should you choose to accept it, is to write a function that counts the number of sets of twin primes from 1 to n.
If n is wrapped by twin primes (n-1 == prime && n+1 == prime) then that should also count even though n+1 is outside the range.
Ex n = 10
Twin Primes are (3,5) (5,7) so your function should return 2!
|
games
|
from gmpy2 import is_prime
def twin_prime(n):
return sum(is_prime(i) and is_prime(i + 2) for i in range(n))
|
The search for Primes! Twin Primes!
|
596549c7743cf369b900021b
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/596549c7743cf369b900021b
|
6 kyu
|
Get the next prime number!
You will get a number`n` (>= 0) and your task is to find the next prime number.
Make sure to optimize your code: there will numbers tested up to about `10^12`.
## Examples
```
5 => 7
12 => 13
```
|
algorithms
|
def nextPrime(n):
while True:
n += 1
if n == 2 or (n > 2 and n % 2 and all(n % i for i in range(3, int(n * * 0.5) + 1, 2))):
return n
|
Next Prime
|
58e230e5e24dde0996000070
|
[
"Algorithms"
] |
https://www.codewars.com/kata/58e230e5e24dde0996000070
|
7 kyu
|
<h2>Digit Recovery</h2>
Some letters in the input string are representing a written-out digit. Some of the letters may randomly shuffled. Your task is to recover them all.
Note that:
<ul>
<li> Only consecutive letters can be used. "OTNE" cannot be recovered to 1!
<li> Every letter has to start with an increasing index.. "ONENO" results to 11, because the E can be used two times. Endless loops are not possible!</li>
<li> If there are letters in the string, which don't create a number you can ignore them.</li>
<li> If no digits can be found, return <code>"No digits found"</code></li>
<li> Take care about the order! "ENOWT" will be recovered to 12 and not to 21.</li>
<li> The input string consists only UpperCase letters </li>
</ul>
e.g.
<pre>
<code>
recover("NEO") => "1"
recover("ONETWO") => "12"
recover("ONENO") => "11"
recover("TWWTONE") => "21"
recover("ZYX") => "No digits found"
recover("NEOTWONEINEIGHTOWSVEEN") => "12219827"
</code>
</pre>
You can use the following preloaded dictionary in your solution:
<pre>
<code>
const alph = {"ZERO":0,"ONE":1,"TWO":2,"THREE":3,"FOUR":4,"FIVE":5,"SIX":6,"SEVEN":7,"EIGHT":8,"NINE":9};
</code>
</pre>
|
algorithms
|
def recover(st):
res = []
for i in range(len(st)):
for k, v in alph . items():
if sorted(k) == sorted(st[i: i + len(k)]):
res . append(v)
return '' . join(map(str, res)) or "No digits found"
|
Digit Recovery
|
5964d7e633b908e172000046
|
[
"Algorithms"
] |
https://www.codewars.com/kata/5964d7e633b908e172000046
|
6 kyu
|
# Fix My Phone Numbers
Oh thank goodness you're here! The last intern has completely ruined everything!
All of our customer's phone numbers have been scrambled, and we need those phone numbers to annoy them with endless sales calls!
### The Format
Phone numbers are stored as strings and comprise 11 digits, eg ```'02078834982'``` and must always start with a ```0```.
However, something strange has happened and now all of the phone numbers contain lots of random characters, whitespace and some are not phone numbers at all!
For example,
```'02078834982'``` has somehow become ```'efRFS:)0207ERGQREG88349F82!'``` and there are lots more lines that we need to check.
### The Task
Given a string, you must decide whether or not it contains a valid phone number. If it does, return the corrected phone number as a string ie. ```'02078834982'``` with no whitespace or special characters, else return ``"Not a phone number"``.
|
reference
|
def is_it_a_num(s: str) - > str:
t = '' . join(i for i in s if i . isdigit())
return t if len(t) == 11 and t[0] == "0" else "Not a phone number"
|
Fix My Phone Numbers!
|
596343a24489a8b2a00000a2
|
[
"Strings",
"Regular Expressions",
"Fundamentals"
] |
https://www.codewars.com/kata/596343a24489a8b2a00000a2
|
7 kyu
|
Unscramble the eggs.
The string given to your function has had an "egg" inserted directly after each consonant. You need to return the string before it became eggcoded.
## Example
```javascript
unscrambleEggs("Beggegeggineggneggeregg"); => "Beginner"
// "B---eg---in---n---er---"
```
Kata is supposed to be for beginners to practice regular expressions, so commenting would be appreciated.
|
reference
|
def unscramble_eggs(word):
return word . replace('egg', '')
|
Unscrambled eggs
|
55ea5650fe9247a2ea0000a7
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/55ea5650fe9247a2ea0000a7
|
7 kyu
|
Create a function `longer` that accepts a string and sorts the words in it based on their respective lengths in an ascending order. If there are two words of the same lengths, sort them alphabetically. Look at the examples below for more details.
```python
longer("Another Green World") => Green World Another
longer("Darkness on the edge of Town") => of on the Town edge Darkness
longer("Have you ever Seen the Rain") => the you Have Rain Seen ever
```
Assume that only only Alphabets will be entered as the input.
Uppercase characters have priority over lowercase characters. That is,
```python
longer("hello Hello") => Hello hello
```
Don't forget to rate this kata and leave your feedback!!
Thanks
|
reference
|
def longer(s):
return ' ' . join(sorted(s . split(), key=lambda w: (len(w), w)))
|
I'm longer than you!
|
5963314a51c68a26600000ae
|
[
"Strings",
"Fundamentals"
] |
https://www.codewars.com/kata/5963314a51c68a26600000ae
|
6 kyu
|
The mean and standard deviation of a sample of data can be thrown off if the sample contains one or many outlier(s) :
<img src = 'http://www.ukoln.ac.uk/web-focus/webwatch/reports/hei-lib-may1998/fig11.gif' href = 'http://www.ukoln.ac.uk/web-focus/webwatch/reports/hei-lib-may1998/report.html'><div></div>
(<a href = 'http://www.ukoln.ac.uk/web-focus/webwatch/reports/hei-lib-may1998/report.html'>image source</a>)
For this reason, it is usually a good idea to check for and remove outliers before computing the mean or the standard deviation of a sample. To this aim, your function will receive a list of numbers representing a <code>sample</code> of data. Your function must remove any outliers and return the mean of the <code>sample</code>, <strong>rounded</strong> to <strong>two</strong> decimal places (round only at the end).
Since there is no objective definition of "outlier" in statistics, your function will also receive a <code>cutoff</code>, in standard deviation units. So for example if the cutoff is 3, then any value that is <strong>more</strong> than 3 standard deviations above or below the mean must be removed. <em>Notice that, once outlying values are removed in a first "sweep", other less extreme values may then "become" outliers, that you'll have to remove as well!</em>
<strong>Example :</strong>
```python
sample = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100]
cutoff = 3
clean_mean(sample, cutoff) → 5.5
```
```r
# R uses sam instead of sample to avoid conflicts with the
# base function sample()
sam <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100)
cutoff <- 3
clean_mean(sam, cutoff)
[1] 5.5
```
<strong>Formula for the <a href = 'https://en.wikipedia.org/wiki/Mean'>mean</a> :</strong>
<img src = 'https://wikimedia.org/api/rest_v1/media/math/render/svg/bd2f5fb530fc192e4db7a315777f5bbb5d462c90' style="background-color:lightgray"><div></div>
(where n is the sample size)
<strong>Formula for the <a href = 'https://en.wikipedia.org/wiki/Standard_deviation#Estimation'>standard deviation</a> :</strong>
<img src = 'https://wikimedia.org/api/rest_v1/media/math/render/svg/9a937016f00f1978197aa562c5f2d58619f90806' style="background-color:lightgray"><div></div>
(where N is the sample size, x<sub>i</sub> is observation i and x̄ is the sample mean)
<em>Note : since we are not computing the sample standard deviation for inferential purposes, the denominator is n, not n - 1.</em>
|
algorithms
|
def clean_mean(sample, cutoff):
mean = sum(sample) / len(sample)
dev = ((1 / len(sample)) * sum((num - mean) * * 2 for num in sample)) * * (1 / 2)
cleaned = [num for num in sample if abs(num - mean) <= cutoff * dev]
if sample == cleaned:
return round(mean, 2)
else:
return clean_mean(cleaned, cutoff)
|
Mean without outliers
|
5962d557be3f8bb0ca000010
|
[
"Recursion",
"Statistics",
"Algorithms",
"Data Science"
] |
https://www.codewars.com/kata/5962d557be3f8bb0ca000010
|
5 kyu
|
In an attempt to boost sales, the manager of the pizzeria you work at has devised a pizza rewards system: if you already made at least 5 orders of at least 20 dollars, you get a free 12 inch pizza with 3 toppings of your choice.
However, the rewards system may change in the future. Your manager wants you to implement a function that, given a dictionary of customers, a minimum number of orders and a minimum order value, returns a <strong>set</strong> of the customers who are eligible for a reward.
Customers in the dictionary are represented as:
```python
{ 'customerName' : [list_of_order_values_as_integers] }
```
See example test case for more details.
|
reference
|
def pizza_rewards(customers, min_orders, min_price):
return {k for k, v in customers . items() if sum(x >= min_price for x in v) >= min_orders}
|
Free pizza
|
595910299197d929a10005ae
|
[
"Fundamentals",
"Puzzles"
] |
https://www.codewars.com/kata/595910299197d929a10005ae
|
6 kyu
|
You just got done writing a function that calculates the player's final score for your new game, "Flight of the <a href = 'https://upload.wikimedia.org/wikipedia/commons/thumb/7/71/Cacatua_moluccensis_excited.jpg/1280px-Cacatua_moluccensis_excited.jpg'>cockatoo</a>".
Now all you need is a high score table that can be updated with the player's final scores. With such a feature, the player will be motivated to try to beat his previous scores, and hopefully, never stop playing your game.
The high score table will start out empty. A limit to the size of the table will be specified upon creation of the table.
<strong>Here's an example of the expected behavior of the high score table :</strong>
```python
highScoreTable = HighScoreTable(3)
highScoreTable.scores == [] # evaluates to True
highScoreTable.update(10)
highScoreTable.scores == [10]
highScoreTable.update(8)
highScoreTable.update(12)
highScoreTable.update(5)
highScoreTable.update(10)
highScoreTable.scores == [12, 10, 10]
highScoreTable.reset()
highScoreTable.scores == []
# And so on...
```
```coffeescript
highScoreTable = new HighScoreTable 3
highScoreTable.scores # => []
highScoreTable.update 10
highScoreTable.scores # => [10]
highScoreTable.update 8
highScoreTable.update 12
highScoreTable.update 5
highScoreTable.update 10
highScoreTable.scores # => [12, 10, 10]
highScoreTable.reset()
highScoreTable.scores # => []
# And so on...
```
|
algorithms
|
class HighScoreTable:
def __init__(self, limit):
self . __limit__ = limit
self . scores = []
def update(self, n):
self . scores . append(n)
self . scores = sorted(self . scores, reverse=True)[: self . __limit__]
def reset(self):
self . scores = []
|
High score table
|
5962bbea6878a381ed000036
|
[
"Algorithms",
"Sorting",
"Searching",
"Arrays",
"Object-oriented Programming"
] |
https://www.codewars.com/kata/5962bbea6878a381ed000036
|
6 kyu
|
Array inversion indicates how far the array is from being sorted.
Inversions are pairs of elements in array that are out of order.
## Examples
```
[1, 2, 3, 4] => 0 inversions
[1, 3, 2, 4] => 1 inversion: 2 and 3
[4, 1, 2, 3] => 3 inversions: 4 and 1, 4 and 2, 4 and 3
[4, 3, 2, 1] => 6 inversions: 4 and 3, 4 and 2, 4 and 1, 3 and 2, 3 and 1, 2 and 1
```
## Goal
The goal is to come up with a function that can calculate inversions for any arbitrary array
|
algorithms
|
def count_inversions(array):
inv_count = 0
for i in range(len(array)):
for j in range(i, len(array)):
if array[i] > array[j]:
inv_count += 1
return inv_count
|
Calculate number of inversions in array
|
537529f42993de0e0b00181f
|
[
"Algorithms",
"Arrays"
] |
https://www.codewars.com/kata/537529f42993de0e0b00181f
|
6 kyu
|
Triangular number is any amount of points that can fill an equilateral triangle.
Example: the number `6` is a triangular number because all sides of a triangle has the same amount of points.

```
Hint!
T(n) = n * (n + 1) / 2,
n - is the size of one side.
T(n) - is the triangular number.
```
Given a number `T` from interval `[1..2147483646]`, find if it is triangular number or not.
Appreciate the feedback!
|
reference
|
def is_triangular(t):
x = int((t * 2) * * 0.5)
return t == x * (x + 1) / 2
|
Beginner Series #5 Triangular Numbers
|
56d0a591c6c8b466ca00118b
|
[
"Mathematics",
"Fundamentals"
] |
https://www.codewars.com/kata/56d0a591c6c8b466ca00118b
|
7 kyu
|
In this kata, your task is to identify the <code>pattern</code> underlying a <code>sequence</code> of numbers. For example, if the sequence is <code>[1, 2, 3, 4, 5]</code>, then the pattern is <code>[1]</code>, since each number in the sequence is equal to the number preceding it, plus 1. See the test cases for more examples.
<em>A few more rules :</em>
<ul>
<li><code>pattern</code> may contain negative numbers.</li>
<li><code>sequence</code> will always be made of a whole number of repetitions of the pattern.</li>
<li>Your answer must correspond to the shortest form of the pattern, e.g. if the pattern is <code>[1]</code>, then <code>[1, 1, 1, 1]</code> will not be considered a correct answer.</li>
</ul>
|
algorithms
|
from itertools import cycle
def find_pattern(s):
diffs = [y - x for x, y in zip(s, s[1:])]
for i in range(1, len(diffs) + 1):
if len(diffs) % i == 0 and all(a == b for a, b in zip(diffs, cycle(diffs[: i]))):
return diffs[: i]
|
What's the pattern?
|
596185fe9c3097a345000a18
|
[
"Mathematics",
"Algorithms"
] |
https://www.codewars.com/kata/596185fe9c3097a345000a18
|
6 kyu
|
<div style="float:right;border:5px"><img src="http://modernhealthmonk.com/wp-content/uploads/2013/01/Arnold.jpg" style="width:375px" alt="Leonardo Fibonacci in a rare portrait of his younger days"><p><i>Leonardo Fibonacci in a rare portrait of his younger days</i></p></div>
I assume you are all familiar with the famous Fibonacci sequence, having to get each number as the sum of the previous two (and typically starting with either `[0,1]` or `[1,1]` as the first numbers).
While there are plenty of variation on it ([including](https://www.codewars.com/kata/tribonacci-sequence) [a few](https://www.codewars.com/kata/fibonacci-tribonacci-and-friends) [I wrote](https://www.codewars.com/kata/triple-shiftian-numbers/)), usually the catch is all the same: get a starting (signature) list of numbers, then proceed creating more with the given rules.
What if you were to get to get two parameters, one with the signature (starting value) and the other with the number you need to sum at each iteration to obtain the next one?
And there you have it, getting 3 parameters:
* a signature of length `length`
* a second parameter is a list/array of indexes of the last `length` elements you need to use to obtain the next item in the sequence (consider you can end up not using a few or summing the same number multiple times)' in other words, if you get a signature of length `5` and `[1,4,2]` as indexes, at each iteration you generate the next number by summing the 2nd, 5th and 3rd element (the ones with indexes `[1,4,2]`) of the last 5 numbers
* a third and final parameter is of course which sequence element you need to return (starting from zero, I don't want to bother you with adding/removing 1s or just coping with the fact that after years on CodeWars we all count as computers do):
```
Classical Fibonnaci:
signature = [1,1], indexes = [0,1], n = 2
---> 2
signature = [1,1], indexes = [0,1], n = 3
---> 3
signature = [1,1], indexes = [0,1], n = 4
---> 5
Similar to my Tribonacci:
signature = [3,5,2], indexes = [0,1,2], n = 4
---> 17
Can you figure out how it worked ? ;)
signature = [7,3,4,1], indexes = [1,1], n = 6
---> 2
If n < length, the element is already in the signature:
signature = [7,3,4,1], indexes = [1,1], n = 2
---> 4
```
|
algorithms
|
from collections import deque
def custom_fib(signature, indexes, n):
fib = deque(signature)
for _ in range(n):
fib . append(sum(map(fib . __getitem__, indexes)))
fib . popleft()
return fib[0]
|
Fibonacci on roids
|
596144f0ada6db581200004f
|
[
"Recursion",
"Lists",
"Arrays",
"Algorithms"
] |
https://www.codewars.com/kata/596144f0ada6db581200004f
|
6 kyu
|
Sam has opened a new sushi train restaurant - a restaurant where sushi is served on plates that travel around the bar on a conveyor belt and customers take the plate that they like.
Sam is using Glamazon's new visual recognition technology that allows a computer to record the number of plates at a customer's table and the colour of those plates. The number of plates is returned as a string. For example, if a customer has eaten 3 plates of sushi on a red plate the computer will return the string `"rrr"`.
Currently, Sam is only serving sushi on red plates as he's trying to attract customers to his restaurant. There are also small plates on the conveyor belt for condiments such as ginger and wasabi - the computer notes these in the string that is returned as a space; e.g. `"rrr r"` denotes 4 plates of red sushi and a plate of condiment.
Sam would like your help to write a program for the cashier's machine to read the string and return the total amount a customer has to pay when they ask for the bill. The current price for the dishes are as follows:
* Red plates of sushi: $2 each - but every 5th one is free!
* Condiments: free
## Examples
```python
"rr" --> 4 # 2 plates
"rr rrr" --> 8 # 5 plates, 1 free
"rrrrr rrrrr" --> 16 # 10 plates, 2 free
```
|
reference
|
def total_bill(s):
num = s . count('r')
return (num - num / / 5) * 2
|
Sushi-go-round (Beginner's)
|
59619e4609868dd923000041
|
[
"Fundamentals",
"Strings",
"Logic"
] |
https://www.codewars.com/kata/59619e4609868dd923000041
|
7 kyu
|
Groups of characters decided to make a battle. Help them to figure out what group is more powerful. Create a function that will accept 2 variables and return the one who's stronger.
### Rules
* Each character has its own power:
```
A = 1, B = 2, ... Y = 25, Z = 26
a = 0.5, b = 1, ... y = 12.5, z = 13
```
* Only alphabetical characters can and will participate in a battle.
* Only two groups to a fight.
* Group whose total power (`a + B + c + ...`) is bigger wins.
* If the powers are equal, it's a tie.
### Examples
```
"One", "Two" --> "Two"
"ONE", "NEO" --> "Tie!"
```
### Related kata
- [Battle of the characters (Easy)](https://www.codewars.com/kata/595519279be6c575b5000016)
|
algorithms
|
def battle(x, y):
sum_x, sum_y = sum(ord(i) - 64 if i . isupper() else (ord(i) - 96) * 0.5 for i in x), sum(
ord(i) - 64 if i . isupper() else (ord(i) - 96) * 0.5 for i in y)
return x if sum_x > sum_y else y if sum_x < sum_y else "Tie!"
|
Battle of the characters (Medium)
|
595e9f258b763bc2d2000032
|
[
"Algorithms"
] |
https://www.codewars.com/kata/595e9f258b763bc2d2000032
|
7 kyu
|
The pepe market is on the verge of collapse. In a last ditch attempt to make some quick cash, you decide to sift through the thousands of pepes on the Internet in order to identify the rarest, which are worth more. Since this would be tedious to do by hand, you decide to use your programming skills to streamline the process.
Your task in this kata is to implement a function that, given a list of pepes (<code>pepes</code>), returns the rarest pepe in the list. If two or more pepes are equally rare, return a list of these pepes, sorted in alphabetical order. Also, if the rarest pepe (or pepes) has a frequency of 5 or more, then it is not really a rare pepe, so your function should return <code>'No rare pepes!'</code>.
More info on rare pepes <a href = 'http://knowyourmeme.com/memes/rare-pepe'>here</a>.
|
algorithms
|
from collections import Counter
def find_rarest_pepe(pepes):
counts = Counter(pepes)
rarest = min(counts . values())
rare_pepes = [pepe for pepe, count in counts . items()
if count == rarest < 5]
return (rare_pepes[0] if len(rare_pepes) == 1
else sorted(rare_pepes) if rare_pepes
else 'No rare pepes!')
|
The rarest pepe
|
595d4823c31ba629d90000d2
|
[
"Algorithms"
] |
https://www.codewars.com/kata/595d4823c31ba629d90000d2
|
6 kyu
|
You have been hired by a large stout brewery in order to improve the quality testing of their beer. Your superiors want you to devise a way of determining whether a batch of beer is likely to be good enough for sale using a small sample of beers from this batch. Luckily for you, a smart Englishman found a solution to this problem a bit more than a hundred years ago...
Your task in this kata is to implement a function to do Student's one-sample t-test. In the current problem, you will be testing for alcohol content. Your function will receive :
<ol>
<li>A list of the alcohol content of each beer in a sample of beers : <code>sample</code></li>
<li>A target alcohol content : <code>pop_mean</code></li>
<li>A probability threshold : <code>alpha</code></li></ol><div></div>
By calculating a t value for the sample, you will be able to determine whether the current batch is likely to have an average alcohol content close to the target, or not. In statistical terms, if the likelihood that the current sample of beers was taken from the population of beers with a mean of <code>pop_mean</code> (the target alcohol content) is too small (it is too different from the "average" sample), then the whole batch will be rejected.
<strong>Specifically,</strong> your solution will calculate a t statistic (formula below) and compare it to a "critical" t value, corresponding to the threshold. You are given a table of critical t values (<code>t_table</code>), containing only <strong>positive</strong> values of t (the t distribution is symmetrical) which you may access like so : <code>t_table[degrees_of_freedom - 1][probability]</code>. Degrees of freedom in a one sample t-test are equal to n - 1, where n is the sample size. If the sample's t value is greater than the "critical" t value (and therefore less probable), then your function will return "Reject". Else, your function will return "Good to drink". All samples will range in size from 2 to 20.
<h3>Formula for the <a href = 'https://en.wikipedia.org/wiki/Student%27s_t-test'>t statistic</a> :</h3>
<img src = 'https://wikimedia.org/api/rest_v1/media/math/render/svg/1063f91f450e9fd0094a38f1856eb11bd201d232'style="background-color:white"><div></div>
Where x̄ is the sample mean, μ<sub>0</sub> is the population mean, s is the sample standard deviation and n is the sample size.
<h3>Formula for the <a href = 'https://en.wikipedia.org/wiki/Standard_deviation#Estimation'>sample standard deviation (s)</a> :</h3>
<img src = 'https://wikimedia.org/api/rest_v1/media/math/render/svg/1bffdcb1ecd0b326bb7ad67397b073af9c15fa6e' style="background-color:white"><div></div>
Where N is the sample size, x<sub>i</sub> is observation i and x̄ is the sample mean.
<p>Kata inspired by <a href='https://priceonomics.com/the-guinness-brewer-who-revolutionized-statistics/'>this</a>.</p>
|
algorithms
|
from statistics import mean, stdev
def t_test(sample, pop_mean, alpha):
mn, sd, n = mean(sample), stdev(sample), len(sample)
return 'Good to drink' if abs(mn - pop_mean) * n * * .5 / sd <= t_table[n - 2][alpha] else 'Reject'
|
Is this a good batch of stout? (Student's t test)
|
595dab6c5834558a5d0000cd
|
[
"Statistics",
"Algorithms",
"Data Science",
"Probability"
] |
https://www.codewars.com/kata/595dab6c5834558a5d0000cd
|
5 kyu
|
# Introduction
Hamsters are rodents belonging to the subfamily Cricetinae. The subfamily contains about 25 species, classified in six or seven genera. They have become established as popular small house pets, and, partly because they are easy to breed in captivity, hamsters are often used as laboratory animals. [Wikipedia Link](http://en.wikipedia.org/wiki/Hamster)

And you could have skipped the introduction as it is entirely unrelated to your task. xD
# Task
Write a function that accepts two inputs: `code` and `message` and returns an encrypted string from `message` using the `code`.
The `code` is a string that generates the key in the way shown below:
```
1 | h a m s t e r
2 | i b n u f
3 | j c o v g
4 | k d p w
5 | l q x
6 | y
7 | z
```
All letters from `code` get number `1`. All letters which directly follow letters from `code` get number `2` (unless they already have a smaller number assigned), etc. It's difficult to describe but it should be easy to understand from the example below:
```
1 | a e h m r s t
2 | b f i n u
3 | c g j o v
4 | d k p w
5 | l q x
6 | y
7 | z
```
How does the encoding work using the `hamster` code?
```
a => a1
b => a2
c => a3
d => a4
e => e1
f => e2
...
```
And applying it to strings :
```
hamsterMe('hamster', 'hamster') => h1a1m1s1t1e1r1
hamsterMe('hamster', 'helpme') => h1e1h5m4m1e1
```
And you probably started wondering what will happen if there is no `a` in the `code`.
Just add these letters after the last available letter (in alphabetic order) in the `code`.
The key for code `hmster` is:
```
1 | e h m r s t
2 | f i n u
3 | g j o v
4 | k p w
5 | l q x
6 | y
7 | z
8 | a
9 | b
10 | c
11 | d
```
# Additional notes
The `code` will have at least 1 letter.
Duplication of letters in `code` is possible and should be handled.
The `code` and `message` consist of only lowercase letters.
|
reference
|
def hamster_me(code, message):
cache = {k: k + "1" for k in code}
for l in code:
for i in range(2, 27):
shifted = chr(97 + (ord(l) - 98 + i) % 26)
if shifted in cache:
break
cache[shifted] = l + str(i)
return "" . join(map(lambda x: cache[x], message))
|
Hamster me
|
595ddfe2fc339d8a7d000089
|
[
"Strings",
"Fundamentals"
] |
https://www.codewars.com/kata/595ddfe2fc339d8a7d000089
|
5 kyu
|
# Task
Given an positive integer `n(5 <= n <= 100)`. Your task is to divide `n` into some `different` integers, maximize the product of these integers.
# Example
For `n = 5`, the output should be `6`.
`5 can divide into 2 and 3, 2 x 3 = 6`
For `n = 8`, the output should be `15`.
`8 can divide into 3 and 5, 3 x 5 = 15`
For `n = 10`, the output should be `30`.
`10 can divide into 2, 3 and 5, 2 x 3 x 5 = 30`
For `n = 15`, the output should be `144`.
`15 can divide into 2, 3, 4 and 6, 2 x 3 x 4 x 6 = 144`
|
algorithms
|
from functools import lru_cache
@ lru_cache(maxsize=None)
def maximum_product(n, m=2):
return n < m or max(x * maximum_product(n - x, x + 1) for x in range(m, n + 1))
|
Simple Fun #339: Maximum Product 2
|
595bd047b96bed1f59000001
|
[
"Algorithms",
"Mathematics"
] |
https://www.codewars.com/kata/595bd047b96bed1f59000001
|
5 kyu
|
An ordered sequence of numbers from 1 to N is given. One number might have deleted from it, then the remaining numbers were mixed. Find the number that was deleted.
```if-not:rust
Example:
- The starting array sequence is `[1,2,3,4,5,6,7,8,9]`
- The mixed array with one deleted number is `[3,2,4,6,7,8,1,9]`
- Your function should return the int `5`.
If no number was deleted from the starting array, your function should return the int `0`.
```
```if:rust
Example:
- The starting array sequence is `[1,2,3,4,5,6,7,8,9]`
- The mixed array with one deleted number is `[3,2,4,6,7,8,1,9]`
- Your function should return `Some(5)`.
If no number was deleted from the starting list, your function should return `None`.
```
**Note**: N may be 1 or less (in the latter case, the first array will be `[]`).
|
algorithms
|
def find_deleted_number(arr, mixed_arr):
return sum(arr) - sum(mixed_arr)
|
Lost number in number sequence
|
595aa94353e43a8746000120
|
[
"Arrays",
"Algorithms"
] |
https://www.codewars.com/kata/595aa94353e43a8746000120
|
7 kyu
|
Create a regular expression capable of evaluating *binary strings* (which consist of only `1`'s and `0`'s) and determining whether the given string represents a number divisible by `7`.
Note:
* Empty strings should be rejected.
* Your solution should reject strings with any character other than `0` and `1`.
* No leading `0`'s will be tested unless the string exactly denotes `0`.
~~~if:c
Use POSIX Extended Regular Expressions
~~~
~~~if:rust
Note that the regex crate's Regex matches anywhere in a string. You need to ensure you anchor your pattern accordingly.
~~~
|
algorithms
|
# Write a string representing a regular expression to detect whether a binary number is divisible by 7
# It won't be accepted if you code something else like Function
'''
FSM -> regex conversion
FSM - states = {0,1,2,3,4,5,6} # first n bits modulo 7
- input = {0, 1}
- init state = 0
- final state = 0
- state-transition function
state: 0, in: 0 -> 0
state: 0, in: 1 -> 1
...
state: 3, in: 0 -> 6 # 3 * 2 = 6, 11 + in: 0 -> 110
state: 3, in: 1 -> 0 # 3 * 2 + 1 = 7 mod 7 = 0, 11 + in: 1 -> 111
state: 4, in: 0 -> 1 # 4 * 2 = 8 mod 7 = 1, 100 + in: 0 -> 1000
state: 4, in: 1 -> 2 # 4 * 2 + 1 = 9 mod 7 = 2, 100 + in: 1 -> 1001
...
https://cs.stackexchange.com/questions/2016/how-to-convert-finite-automata-to-regular-expressions
'''
solution = '\A((0|1(0(111|01)*(00|110))*(1|0(111|01)*10)(01*0(0|11(111|01)*10|(10|11(111|01)*(00|110))(0(111|01)*(00|110))*(1|0(111|01)*10)))*1)0*)+\Z'
|
Regular Expression - Check if divisible by 0b111 (7)
|
56a73d2194505c29f600002d
|
[
"Puzzles",
"Regular Expressions",
"Strings",
"Algorithms"
] |
https://www.codewars.com/kata/56a73d2194505c29f600002d
|
2 kyu
|
My 5th kata, and 1st in a planned series of rock climbing themed katas.
In rock climbing ([bouldering](https://en.wikipedia.org/wiki/Bouldering) specifically), the V/Vermin (USA) climbing grades start at `'VB'` (the easiest grade), and then go `'V0'`, `'V0+'`, `'V1'`, `'V2'`, `'V3'`, `'V4'`, `'V5'` etc. up to `'V17'` (the hardest grade). You will be given a `list` (`lst`) of climbing grades and you have to write a function (`sort_grades`) to `return` a `list` of the grades sorted easiest to hardest.
If the input is an empty `list`, `return` an empty `list`; otherwise the input will always be a valid `list` of one or more grades.
Please do vote, rank, and provide any feedback on the kata.
|
reference
|
def sort_grades(gs):
return sorted(gs, key=grade)
def grade(v):
if v == 'VB':
return - 2
if v == 'V0':
return - 1
if v == 'V0+':
return 0
return int(v[1:])
|
Sort the climbing grades
|
58a08e622e7fb654a300000e
|
[
"Fundamentals",
"Lists",
"Data Structures",
"Sorting",
"Arrays",
"Strings"
] |
https://www.codewars.com/kata/58a08e622e7fb654a300000e
|
7 kyu
|
# Introduction
A grille cipher was a technique for encrypting a plaintext by writing it onto a sheet of paper through a pierced sheet (of paper or cardboard or similar). The earliest known description is due to the polymath Girolamo Cardano in 1550. His proposal was for a rectangular stencil allowing single letters, syllables, or words to be written, then later read, through its various apertures. The written fragments of the plaintext could be further disguised by filling the gaps between the fragments with anodyne words or letters. This variant is also an example of steganography, as are many of the grille ciphers.
<a href="https://en.wikipedia.org/wiki/Grille_(cryptography)">Wikipedia Link</a>


# Task
Write a function that accepts two inputs: `message` and `code` and returns hidden message decrypted from `message` using the `code`.
The `code` is a nonnegative integer and it decrypts in binary the `message`.
```txt
message : abcdef
code : 000101
----------------
result : df
```
|
reference
|
def grille(msg, code):
return '' . join(msg[- 1 - i] for i, c in enumerate(bin(code)[:: - 1]) if c == '1' and i < len(msg))[:: - 1]
|
Grill it!
|
595b3f0ad26b2d817400002a
|
[
"Strings",
"Binary",
"Fundamentals"
] |
https://www.codewars.com/kata/595b3f0ad26b2d817400002a
|
6 kyu
|
## Description
Given an array X of positive integers, its elements are to be transformed by running the following operation on them as many times as required:
```if X[i] > X[j] then X[i] = X[i] - X[j]```
When no more transformations are possible, return its sum ("smallest possible sum").
For instance, the successive transformation of the elements of input X = [6, 9, 21] is detailed below:
```
X_1 = [6, 9, 12] # -> X_1[2] = X[2] - X[1] = 21 - 9
X_2 = [6, 9, 6] # -> X_2[2] = X_1[2] - X_1[0] = 12 - 6
X_3 = [6, 3, 6] # -> X_3[1] = X_2[1] - X_2[0] = 9 - 6
X_4 = [6, 3, 3] # -> X_4[2] = X_3[2] - X_3[1] = 6 - 3
X_5 = [3, 3, 3] # -> X_5[1] = X_4[0] - X_4[1] = 6 - 3
```
The returning output is the sum of the final transformation (here 9).
## Example
```ruby
solution([6, 9, 21]) #-> 9
```
```clojure
(solution [6 9 21]) ;-> 9
```
```racket
(solution (list 6 9 21)) ;-> 9
```
```go
Solution([]int{6,9,21}) //-> 9
```
## Solution steps:
```ruby
[6, 9, 12] #-> X[2] = 21 - 9
[6, 9, 6] #-> X[2] = 12 - 6
[6, 3, 6] #-> X[1] = 9 - 6
[6, 3, 3] #-> X[2] = 6 - 3
[3, 3, 3] #-> X[1] = 6 - 3
```
```clojure
[6 9 12] ;-> X[2] = 21 - 9
[6 9 6] ;-> X[2] = 12 - 6
[6 3 6] ;-> X[1] = 9 - 6
[6 3 3] ;-> X[2] = 6 - 3
[3 3 3] ;-> X[1] = 6 - 3
```
```go
[6, 9, 12] //-> X[2] = 21 - 9
[6, 9, 6] //-> X[2] = 12 - 6
[6, 3, 6] //-> X[1] = 9 - 6
[6, 3, 3] //-> X[2] = 6 - 3
[3, 3, 3] //-> X[1] = 6 - 3
```
## Additional notes:
There are performance tests consisted of very big numbers and arrays of size at least 30000. Please write an efficient algorithm to prevent timeout.
|
algorithms
|
from math import gcd
def solution(a):
return gcd(* a) * len(a)
|
Smallest possible sum
|
52f677797c461daaf7000740
|
[
"Algorithms",
"Mathematics",
"Arrays"
] |
https://www.codewars.com/kata/52f677797c461daaf7000740
|
4 kyu
|
We're going to create a cipher, so that we can send messages to our friends and no one else will know what cool things we're discussing. Our cipher will take two arguments: a key, in the form of an integer, and a message, in the form of a string.
Our first step is to find the largest prime of the key. For example, the prime factorization of 18 is 2 x 3 x 3, so the largest prime is 3. We'll also accept negative integers as keys, so -18 would give us a "largest" prime of -3. Once we've gotten our prime number, we'll encrypt our message.
The way we'll encrypt is to use the base ASCII table values of 0-127. We'll take the ASCII value of every character and add the value of our prime number. For example, the character 'D' has an ASCII value of 68, Adding 3 would give 71, which is 'G'.
So, this will look like the following:
If we're given a key of 18, and a message of "Hello, world", we'll calculate the largest prime to be 3, and then add it to the ASCII values of our string, giving an output of "Khoor/#zruog".
We'll let values greater than 127 or less than 0 "wrap around", and start at the other side of the ASCII table, so a -1 will be considered a 127, and a 128 will be considered a 0.
|
games
|
def ascii_cipher(message, key):
sign, n, rot = key / / abs(key), abs(key), - 1
while n > 1:
rot, n = [(max(i, rot), n / / i) for i in range(2, n + 1) if n % i == 0][0]
return '' . join(chr((ord(c) + rot * sign) % 128) for c in message)
|
ASCII Cipher
|
55e29a6b4d99b59e98000089
|
[
"Ciphers"
] |
https://www.codewars.com/kata/55e29a6b4d99b59e98000089
|
6 kyu
|
Alex is transitioning from website design to coding and wants to sharpen his skills with CodeWars.
He can do ten kata in an hour, but when he makes a mistake, he must do pushups. These pushups really tire poor Alex out, so every time he does them they take twice as long. His first set of redemption pushups takes 5 minutes. Create a function, `alexMistakes`, that takes two arguments: the number of kata he needs to complete, and the time in minutes he has to complete them. Your function should return how many mistakes Alex can afford to make.
|
reference
|
def alex_mistakes(katas, time):
mistakes = 0
pushup_time = 5
time_left = time - katas * 6
while time_left >= pushup_time:
time_left -= pushup_time
pushup_time *= 2
mistakes += 1
return mistakes
|
Upper <body> Strength
|
571640812ad763313600132b
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/571640812ad763313600132b
|
7 kyu
|
# Task
John has an important number, and he doesn't want others to see it.
He decided to encrypt the number, using the following steps:
```
His number is always a non strict increasing sequence
ie. "123"
He converted each digit into English words.
ie. "123"--> "ONETWOTHREE"
And then, rearrange the letters randomly.
ie. "ONETWOTHREE" --> "TTONWOHREEE"
```
John felt that his number were safe in doing so. In fact, such encryption can be easily decrypted :(
Given the encrypted string `s`, your task is to decrypt it, return the original number in string format.
Note, You can assume that the input string `s` is always valid; It contains only uppercase Letters; The decrypted numbers are arranged in ascending order; The leading zeros are allowed.
# Example
For `s = "ONE"`, the output should be `1`.
For `s = "EON"`, the output should be `1` too.
For `s = "ONETWO"`, the output should be `12`.
For `s = "OONETW"`, the output should be `12` too.
For `s = "ONETWOTHREE"`, the output should be `123`.
For `s = "TTONWOHREEE"`, the output should be `123` too.
|
algorithms
|
from collections import Counter
EXECUTIONS_ORDER = [('Z', Counter("ZERO"), '0'),
('W', Counter("TWO"), '2'),
('U', Counter("FOUR"), '4'),
('X', Counter("SIX"), '6'),
('G', Counter("EIGHT"), '8'),
('O', Counter("ONE"), '1'),
('H', Counter("THREE"), '3'),
('F', Counter("FIVE"), '5'),
('V', Counter("SEVEN"), '7'),
('I', Counter("NINE"), '9')]
def original_number(s):
ans, count, executions = [], Counter(s), iter(EXECUTIONS_ORDER)
while count:
c, wordCount, value = next(executions)
ans . extend([value] * count[c])
for _ in range(count[c]):
count -= wordCount
return '' . join(sorted(ans))
|
Simple Fun #337: The Original Number
|
5959b637030042889500001d
|
[
"Algorithms"
] |
https://www.codewars.com/kata/5959b637030042889500001d
|
5 kyu
|
## Python:
Create a function `running_average()` that returns a callable function object. Update the series with each given value and calculate the current average.
r_avg = running_average()
r_avg(10) = 10.0
r_avg(11) = 10.5
r_avg(12) = 11
All input values are valid. Round to two decimal places.
This Kata is based on a example from Fluent Python book.
## Javascript // Lua // C++:
Create a function `runningAverage()` that returns a callable function object. Update the series with each given value and calculate the current average.
rAvg = runningAverage();
rAvg(10) = 10.0;
rAvg(11) = 10.5;
rAvg(12) = 11;
|
reference
|
def running_average():
count = 0
total = 0
def avg(new):
nonlocal count, total
count += 1
total += new
return round(total / count, 2)
return avg
|
Running Average
|
589e4d646642d144a90000d8
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/589e4d646642d144a90000d8
|
6 kyu
|
Don Drumphet lives in a nice neighborhood, but one of his neighbors has started to let his house go. Don Drumphet wants to build a wall between his house and his neighbor’s, and is trying to get the neighborhood association to pay for it. He begins to solicit his neighbors to petition to get the association to build the wall. Unfortunately for Don Drumphet, he cannot read very well, has a very limited attention span, and can only remember two letters from each of his neighbors’ names. As he collects signatures, he insists that his neighbors keep truncating their names until two letters remain, and he can finally read them.
Your code will show Full name of the neighbor and the truncated version of the name as an array. If the number of the characters in name is less than or equal to two, it will return an array containing only the name as is"
|
reference
|
def who_is_paying(name):
return [name, name[0: 2]] if len(name) > 2 else [name]
|
Who is going to pay for the wall?
|
58bf9bd943fadb2a980000a7
|
[
"Fundamentals",
"Strings"
] |
https://www.codewars.com/kata/58bf9bd943fadb2a980000a7
|
8 kyu
|
At the end of the last semester, Prof. Joey Greenhorn implemented an online report card for his students in order to save paper. Everything seemed to be working fine back then, but since the start of the new semester he has received several emails from students complaining about erroneous grades showing up in their online report cards. Can you help him correct his implementation of the "Student" class?
<strong>The "Student" class should behave like this :</strong>
```python
someStudent = Student()
someOtherStudent = Student()
someStudent.add_grade(98)
someOtherStudent.add_grade(77)
someStudent.grades == [98] # Evaluates to True
someOtherStudent.grades == [77] # Evaluates to True
```
<strong>But right now, this is happening :</strong>
```python
someStudent = Student()
someOtherStudent = Student()
someStudent.add_grade(98)
someOtherStudent.add_grade(77)
someStudent.grades == [98, 77] # Evaluates to True
someOtherStudent.grades == [98, 77] # Evaluates to True
```
|
reference
|
class Student:
def __init__(self, first_name, last_name, grades=[]):
self . first_name = first_name
self . last_name = last_name
self . grades = grades[:]
def add_grade(self, grade):
self . grades . append(grade)
def get_average(self):
return sum(self . grades) / len(self . grades)
|
These are not my grades! (Revamped !)
|
5956d127a817c7c51b000026
|
[
"Object-oriented Programming",
"Debugging",
"Fundamentals"
] |
https://www.codewars.com/kata/5956d127a817c7c51b000026
|
7 kyu
|
In the nation of CodeWars, there lives an Elder who has lived for a long time. Some people call him the Grandpatriarch, but most people just refer to him as the Elder.
There is a secret to his longetivity: he has a lot of `young` worshippers, who regularly perform a ritual to ensure that the Elder stays immortal:
- The worshippers line up in a magic rectangle, of dimensions `m` and `n`.
- They channel their will to wish for the Elder. In this magic rectangle, any worshipper can donate time equal to the `xor` of the column and the row (zero-indexed) he's on, in seconds, to the Elder.
- However, not every ritual goes perfectly. The donation of time from the worshippers to the Elder will experience a transmission loss `l` (in seconds). Also, if a specific worshipper cannot channel more than `l` seconds, the Elder will not be able to receive this worshipper's donation.
The estimated age of the Elder is so old it's probably bigger than the total number of atoms in the universe. However, the lazy programmers (who `made a big news` by inventing [the Y2K bug and other related things](https://en.wikipedia.org/wiki/Time_formatting_and_storage_bugs)) apparently didn't think thoroughly enough about this, and so their `simple` date-time system can only record time from 0 to `t-1` seconds. If the elder received the total amount of time (in seconds) more than the system can store, it will be wrapped around so that the time would be between the range 0 to `t-1`.
Given `m`, `n`, `l` and `t`, please find the number of seconds the Elder has received, represented in the poor programmer's date-time system.
(Note: `t` will never be bigger than `2^32 - 1`, and in JS, `2^26 - 1`.)
---
Example:
```
m=8, n=5, l=1, t=100
Let's draw out the whole magic rectangle:
0 1 2 3 4 5 6 7
1 0 3 2 5 4 7 6
2 3 0 1 6 7 4 5
3 2 1 0 7 6 5 4
4 5 6 7 0 1 2 3
Applying a transmission loss of 1:
0 0 1 2 3 4 5 6
0 0 2 1 4 3 6 5
1 2 0 0 5 6 3 4
2 1 0 0 6 5 4 3
3 4 5 6 0 0 1 2
Adding up all the time gives 105 seconds.
Because the system can only store time between 0 to 99 seconds, the first 100 seconds of time will be lost, giving the answer of 5.
```
---
This is no ordinary magic (the Elder's life is at stake), so *you need to care about performance*. All test cases (900 tests) can be passed within 1 second, but `naive` solutions will time out easily. Good luck, and do not displease the Elder.
|
algorithms
|
def elder_age(m, n, l, t, s=0):
if m > n:
m, n = n, m
if m < 2 or not n & (n - 1): # n is a power of 2
s, p = max(s - l, 0), max(n + s - l - 1, 0)
return (p - s + 1) * (s + p) / / 2 * m % t
p = 1 << n . bit_length() - 1 # Biggest power of 2 lesser than n
if m < p:
return (elder_age(m, p, l, t, s) + elder_age(m, n - p, l, t, s + p)) % t
return (elder_age(p, p, l, t, s) + elder_age(m - p, n - p, l, t, s) +
elder_age(p, n - p, l, t, s + p) + elder_age(m - p, p, l, t, s + p)) % t
|
BECOME IMMORTAL
|
59568be9cc15b57637000054
|
[
"Puzzles",
"Dynamic Programming",
"Performance",
"Algorithms"
] |
https://www.codewars.com/kata/59568be9cc15b57637000054
|
1 kyu
|
Write a function called "filterEvenLengthWords".
Given an array of strings, "filterEvenLengthWords" returns an array containing only the elements of the given array whose length is an even number.
var output = filterEvenLengthWords(['word', 'words', 'word', 'words']);
console.log(output); // --> ['word', 'word']
|
reference
|
def filter_even_length_words(words):
return [word for word in words if len(word) % 2 == 0]
|
filterEvenLengthWords
|
59564f3bcc15b5591a00004a
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/59564f3bcc15b5591a00004a
|
7 kyu
|
Do you remember the old mobile display keyboards? Do you also remember how inconvenient it was to write on it?
Well, here you have to calculate how many keystrokes you have to do for a specific word.
This is the layout:
<img src="https://raw.githubusercontent.com/zruF/CodewarsData/master/Mobile_phone_keyboard.svg.png" style="max-width:20%;max-height:20%"/>
Given a string, return the number of keystrokes necessary to type it. You can assume that the input will entirely consist of characters included in the mobile layout (lowercase letters, digits, and the symbols `*` and `#`).
### Examples
```
"*#" => 2 (1 + 1)
"123" => 3 (1 + 1 + 1)
"abc" => 9 (2 + 3 + 4)
"codewars" => 26 (4 + 4 + 2 + 3 + 2 + 2 + 4 + 5)
```
|
reference
|
def mobile_keyboard(s):
lookup = {
c: i
for s in "1,2abc,3def,4ghi,5jkl,6mno,7pqrs,8tuv,9wxyz,*,0,#" . split(",")
for i, c in enumerate(s, start=1)
}
return sum(lookup[c] for c in s)
|
Mobile Display Keystrokes
|
59564a286e595346de000079
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/59564a286e595346de000079
|
7 kyu
|
## Task
In the field, two programmers A and B found some gold at the same time. They all wanted the gold, and they decided to use the following rules to distribute gold:
They divided gold into n piles and be in line. The amount of each pile and the order of piles all are randomly.
They took turns to take away a pile of gold from the far left or the far right.
In each round, the programmer will use his wisdom to choose the gold that is best for him.
### Input
A list<sup>\*</sup> of integers representing gold.
### Output
Calculated final amount of gold obtained by A and B in a tuple<sup>\*</sup> ( amount of A, amount of B ).
<sup>\*</sup>list / tuple representation varies with language - see Example tests
Note, we can assume that A always takes first, and each time they used the best strategy.
### Example
For `gold = [10,1000,2,1]`, the output should be `[1001,12]`.
```
At 1st turn, A can take 10 or 1, 10 is greater than 1.
Should we choose 10? No, clever programmer don't think so ;-)
Because if A choose 10, next turn B can choose 1000.
So, A choose 1 is the best choice.
At 2nd turn, Whether B chooses 10 or 2, in the 3rd turn, A can always choose 1000.
So, B choose 10 is the best choice.
Final result:
A: 1 + 1000 = 1001
B: 10 + 2 = 12
```
For `golds = [10,1000,2]`, the output should be `[12,1000]`.
In this example, the choice A faces is the same as the 2nd turn in the previous example.
|
algorithms
|
from functools import lru_cache
def distribution_of(gold):
mini = lru_cache(maxsize=None)(lambda i, j: j -
i and min(maxi(i + 1, j), maxi(i, j - 1)))
maxi = lru_cache(maxsize=None)(
lambda i, j: j - i and max(gold[i] + mini(i + 1, j), gold[j - 1] + mini(i, j - 1)))
return (res := maxi(0, len(gold))), sum(gold) - res
|
Simple Fun #335: Two Programmers And Gold
|
59549d482a68fe3bc2000146
|
[
"Performance",
"Algorithms"
] |
https://www.codewars.com/kata/59549d482a68fe3bc2000146
|
5 kyu
|
# Task
You are a lonely frog.
You live on a coordinate axis.
The meaning of your life is to jump and jump ..
The only rule is that each jump is 1 units more than the last time.
Now, here comes your new task. Your starting point is 0, the target point is `n`.
Your first jump distance is 1, and the second step is 2, and so on ..
Of course, you can choose to jump forward or jump backward.
You need to jump to the target point with `minimal steps`. Please tell me, what's the `minimal steps`?
`-10^7 <= n <= 10^7`
# Example
For `n = 2`, the output should be `3`.
```
step 1: 0 -> 1 (Jump forward, distance 1)
step 2: 1 -> -1 (Jump backward, distance 2)
step 3: -1 -> 2 (Jump forward, distance 3)
```
For `n = 6`, the output should be `3`.
```
step 1: 0 -> 1 (Jump forward, distance 1)
step 2: 1 -> 3 (Jump forward, distance 2)
step 3: 3 -> 6 (Jump forward, distance 3)
```
For `n = 7`, the output should be `5`.
```
step 1: 0 -> 1 (Jump forward, distance 1)
step 2: 1 -> 3 (Jump forward, distance 2)
step 3: 3 -> 6 (Jump forward, distance 3)
step 4: 6 -> 2 (Jump backward, distance 4)
step 5: 2 -> 7 (Jump forward, distance 5)
```
|
algorithms
|
def jump_to(x): return (n: = - int((1 - (8 * abs(x) + 1) * * .5) / / 2)) + (- ~ n / / 2 - x) % 2 * (n % 2 + 1)
|
Simple Fun #336: Lonely Frog
|
5954b48ad8e0053403000040
|
[
"Algorithms"
] |
https://www.codewars.com/kata/5954b48ad8e0053403000040
|
6 kyu
|
# Task
Your task in the kata is to determine how many boats are sunk damaged and untouched from a set amount of attacks. You will need to create a function that takes two arguments, the playing board and the attacks.
# Example Game
### The board
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="200"><table width="200" border="0" cellspacing="0" cellpadding="0">
<tr>
<td> </td>
<td colspan="7"><strong><center>X</center></strong></td>
</tr>
<tr>
<td rowspan="5"><strong><center>Y</center></strong></td>
<td> </td>
<td><strong><center>1</center></strong></td>
<td><strong><center>2</center></strong></td>
<td><strong><center>3</center></strong></td>
<td><strong><center>4</center></strong></td>
<td><strong><center>5</center></strong></td>
<td><strong><center>6</center></strong></td>
</tr>
<tr>
<td><strong><center>4</center></strong></td>
<td colspan="6" rowspan="4">
<table width="100%" border="1" cellpadding="0" cellspacing="0">
<tr>
<td bgcolor="#CCCCCC"><center>0</center></td>
<td bgcolor="#CCCCCC"><center>0</center></td>
<td bgcolor="#FF0000"><center>2</center></td>
<td bgcolor="#FF0000"><center>2</center></td>
<td bgcolor="#FF0000"><center>2</center></td>
<td bgcolor="#FF0000"><center>2</center></td>
</tr>
<tr>
<td bgcolor="#CCCCCC"><center>0</center></td>
<td bgcolor="#FF00FF"><center>3</center></td>
<td bgcolor="#CCCCCC"><center>0</center></td>
<td bgcolor="#CCCCCC"><center>0</center></td>
<td bgcolor="#CCCCCC"><center>0</center></td>
<td bgcolor="#CCCCCC"><center>0</center></td>
</tr>
<tr>
<td bgcolor="#CCCCCC"><center>0</center></td>
<td bgcolor="#FF00FF"><center>3</center></td>
<td bgcolor="#CCCCCC"><center>0</center></td>
<td bgcolor="#0000FF"><center>1</center></td>
<td bgcolor="#CCCCCC"><center>0</center></td>
<td bgcolor="#CCCCCC"><center>0</center></td>
</tr>
<tr>
<td bgcolor="#CCCCCC"><center>0</center></td>
<td bgcolor="#FF00FF"><center>3</center></td>
<td bgcolor="#CCCCCC"><center>0</center></td>
<td bgcolor="#0000FF"><center>1</center></td>
<td bgcolor="#CCCCCC"><center>0</center></td>
<td bgcolor="#CCCCCC"><center>0</center></td>
</tr>
</table>
</td>
</tr>
<tr>
<td><strong><center>3</center></strong></td>
</tr>
<tr>
<td><strong><center>2</center></strong></td>
</tr>
<tr>
<td><strong><center>1</center></strong></td>
</tr>
</table></td>
<td> </td>
</tr>
</table>
<br>Boats are placed either horizontally, vertically or diagonally on the board. `0` represents a space <b> not</b> occupied by a boat. Digits `1-3` represent boats which vary in length 1-4 spaces long. There will always be at least 1 boat up to a maximum of 3 in any one game. Boat sizes and board dimentions will vary from game to game.
### Attacks
Attacks are calculated from the bottom left, first the X coordinate then the Y. There will be at least one attack per game, and the array will not contain duplicates.
```javascript
[[2, 1], [1, 3], [4, 2]];
```
```python
[[2, 1], [1, 3], [4, 2]]
```
```ruby
[[2, 1], [1, 3], [4, 2]]
```
```csharp
{ {2, 1}, {1, 3}, {4, 2} };
```
```java
{ {2, 1}, {1, 3}, {4, 2} };
```
<li> First attack `[2, 1]` = `3`<br>
<li> Second attack `[1, 3]` = `0`<br>
<li> Third attack `[4, 2]` = `1`<br>
## Function Initialization
```javascript
board = [[0,0,0,2,2,0],
[0,3,0,0,0,0],
[0,3,0,1,0,0],
[0,3,0,1,0,0]];
attacks = [[2, 1], [1, 3], [4, 2]];
damagedOrSunk(board, attacks);
```
```ruby
board = [[0,0,0,2,2,0],
[0,3,0,0,0,0],
[0,3,0,1,0,0],
[0,3,0,1,0,0]]
attacks = [[2, 1], [1, 3], [4, 2]]
damaged_or_sunk(board, attacks)
```
```python
board = [[0,0,0,2,2,0],
[0,3,0,0,0,0],
[0,3,0,1,0,0],
[0,3,0,1,0,0]]
attacks = [[2, 1], [1, 3], [4, 2]]
damaged_or_sunk(board, attacks)
```
```csharp
var kata = new Kata();
int[,] board = { {0,0,0,2,2,0},
{0,3,0,0,0,0},
{0,3,0,1,0,0},
{0,3,0,1,0,0} };
int[,] attacks = { {2, 1}, {1, 3}, {4, 2} };
var result = Kata.damagedOrSunk(board, attacks);
```
```java
int[][] board = new int[][] {new int[] {0,0,1,0},
new int[] {0,0,1,0},
new int[] {0,0,1,0}};
int[][] attacks = new int[][] {new int[] {3,1},new int[] {3,2},new int[] {3,3}};
BattleShips.damagedOrSunk(board, attacks);
```
## Scoring
<li> 1 point for every whole boat sank.
<li> 0.5 points for each boat hit at least once (<b>not</b> including boats that are sunk).
<li> -1 point for each whole boat that was not hit at least once.
## Sunk or Damaged
<li> `sunk` = all boats that are sunk
<li> `damaged` = all boats that have been hit at least once but not sunk
<li> `notTouched/not_touched` = all boats that have not been hit at least once
## Output
You should return a hash with the following data
```javascript
`sunk`, `damaged`, `notTouched`, `points`
```
```python
`sunk`, `damaged`, `not_touched`, `points`
```
```ruby
`sunk`, `damaged`, `not_touched`, `points`
```
```csharp
`sunk`, `damaged`, `notTouched`, `points`
```
## Example Game Output
In our above example..
<li> First attack: `boat 3` was damaged, which increases the `points` by `0.5`
<li> Second attack: miss nothing happens
<li> Third attack: `boat 1` was damaged, which increases the `points` by `0.5`
<li> `boat 2` was untouched so `points -1` and `notTouched +1` in Javascript/Java/C# and `not_touched +1` in Python/Ruby.
<li> No whole boats sank
### Return Hash
```javascript
{ sunk: 0, damaged: 2 , notTouched: 1, points: 0 }
```
```python
{ 'sunk': 0, 'damaged': 2 , 'not_touched': 1, 'points': 0 }
```
```ruby
{ 'sunk': 0, 'damaged': 2 , 'not_touched': 1, 'points': 0 }
```
```csharp
Dictionary<string, double> { {"sunk", 0}, {"damaged", 2}, {"notTouched", 1}, {"points", 0} };
```
|
reference
|
from collections import Counter
def damaged_or_sunk(board, attacks):
# Invert board and shift attacks to 0 based indexcing
board = board[:: - 1]
attacks = [(r - 1, c - 1) for r, c in attacks]
# Quantify initial state
start_ships = Counter(v for r in board for v in r)
# Apply attacks
for r, c in attacks:
board[c][r] = "X"
# Quantify end state
end_ships = Counter(v for r in board for v in r)
# Analyse change in state
sunk, damaged, not_touched = 0, 0, 0
for id, count in start_ships . items():
if id != 0:
if end_ships[id] == count:
not_touched += 1
elif end_ships[id] == 0:
sunk += 1
else:
damaged += 1
score = sunk + 0.5 * damaged - not_touched
return {'sunk': sunk, 'damaged': damaged, 'not_touched': not_touched, 'points': score}
|
Battle ships: Sunk damaged or not touched?
|
58d06bfbc43d20767e000074
|
[
"Arrays",
"Fundamentals"
] |
https://www.codewars.com/kata/58d06bfbc43d20767e000074
|
5 kyu
|
# Task
You are given an array of integers. Your task is to determine the minimum number of its elements that need to be changed so that elements of the array will form an arithmetic progression. Note that if you swap two elements, you're changing both of them, for the purpose of this kata.
Here an arithmetic progression is defined as a sequence of integers such that the difference between consecutive terms is constant. For example, `6 4 2 0 -2` and `3 3 3 3 3` are arithmetic progressions, but `0 0.5 1 1.5` and `1 -1 1 -1 1` are not.
# Examples
For `arr = [1, 3, 0, 7, 9]` the answer is `1`
Because only one element has to be changed in order to create an arithmetic progression.
For `arr = [1, 10, 2, 12, 3, 14, 4, 16, 5]` the answer is `5`
The array will be changed into `[9, 10, 11, 12, 13, 14, 15, 16, 17]`.
# Input/Output
- `[input]` integer array `arr`
An array of N integers.
`2 ≤ arr.length ≤ 100`
`-1000 ≤ arr[i] ≤ 1000`
Note for Java users: you'll have a batch of 100 bigger random arrays, with lengths as `150 ≤ arr.length ≤ 300`.
- `[output]` an integer
The minimum number of elements to change.
|
games
|
from collections import defaultdict
def fix_progression(arr):
res = 0
for i in range(len(arr)):
D = defaultdict(int)
for j in range(i):
q, r = divmod(arr[i] - arr[j], i - j)
if not r:
D[q] += 1
res = max(res, D[q])
return len(arr) - res - 1
|
Simple Fun #134: Fix Progression
|
58a65c82586e98266200005b
|
[
"Puzzles"
] |
https://www.codewars.com/kata/58a65c82586e98266200005b
|
5 kyu
|
# Task
Mr.Nam has `n` candies, he wants to put one candy in each cell of a table-box. The table-box has `r` rows and `c` columns.
Each candy was labeled by its cell number. The cell numbers are in range from 1 to N and the direction begins from right to left and from bottom to top.
Nam wants to know the position of a specific `candy` and which box is holding it.
The result should be an array and contain exactly 3 elements. The first element is the `label` of the table; The second element is the `row` of the candy; The third element is the `column` of the candy.
If there is no candy with the given number, return `[-1, -1, -1]`.
Note:
When the current box is filled up, Nam buys another one.
The boxes are labeled from `1`.
Rows and columns are `0`-based numbered from left to right and from top to bottom.
# Example
For `n=6,r=2,c=2,candy=3`, the result should be `[1,0,1]`
the candies will be allocated like this:
```
Box 1
+-----+-----+
| 4 | (3) | --> box 1,row 0, col 1
+-----+-----+
| 2 | 1 |
+-----+-----+
Box 2
+-----+-----+
| x | x |
+-----+-----+
| 6 | (5) | --> box 2,row 1, col 1
+-----+-----+```
For `candy = 5(n,r,c same as above)`, the output should be `[2,1,1]`.
For `candy = 7(n,r,c same as above)`, the output should be `[-1,-1,-1]`.
For `n=8,r=4,c=2,candy=3`, the result should be `[1,2,1]`
```
Box 1
+-----+-----+
| 8 | 7 |
+-----+-----+
| 6 | 5 |
+-----+-----+
| 4 | (3) |--> box 1,row 2, col 1
+-----+-----+
| 2 | 1 |
+-----+-----+
```
# Input/Output
- `[input]` integer `n`
The number of candies.
`0 < n <= 100`
- `[input]` integer `r`
The number of rows.
`0 < r <= 100`
- `[input]` integer `c`
The number of columns.
`0 < c <= 100`
- `[input]` integer `candy`
The label of the candy Nam wants to get position of.
`0 < c <= 120`
- `[output]` an integer array
Array of 3 elements: a label, a row and a column.
|
algorithms
|
def get_candy_position(n, r, c, candy):
if candy > n:
return [- 1, - 1, - 1]
linIdx = r * c - ((candy - 1) % (r * c) + 1)
return [(candy - 1) / / (r * c) + 1, linIdx / / c, linIdx % c]
|
Simple Fun #171: Get Candy Position
|
58b626ee2da07adf3e00009c
|
[
"Algorithms",
"Puzzles"
] |
https://www.codewars.com/kata/58b626ee2da07adf3e00009c
|
6 kyu
|
# Task
Changu and Mangu are great buddies. Once they found an infinite paper which had 1,2,3,4,5,6,7,8,......... till infinity, written on it.
Both of them did not like the sequence and started deleting some numbers in the following way.
```
First they deleted every 2nd number.
So remaining numbers on the paper: 1,3,5,7,9,11..........till infinity.
Then they deleted every 3rd number.
So remaining numbers on the paper: 1,3,7,9,13,15..........till infinity..
Then they deleted every 4th number.
So remaining numbers on the paper: 1,3,7,13,15..........till infinity.
```
Then kept on doing this (deleting every 5th, then every 6th ...) untill they got old and died.
It is obvious that some of the numbers will never get deleted(E.g. 1,3,7,13..) and hence are know to us as survivor numbers.
Given a number `n`, check whether its a survivor number or not.
# Input/Output
- `[input]` integer `n`
`0 < n <= 10^8`
- `[output]` a boolean value
`true` if the number is a survivor else `false`.
|
algorithms
|
def survivor(n):
k = 2
while n >= k and n % k:
n -= n / / k
k += 1
return n % k > 0
|
Simple Fun #143: Is Survivor Number?
|
58aa6141c9eb047fec000133
|
[
"Algorithms"
] |
https://www.codewars.com/kata/58aa6141c9eb047fec000133
|
6 kyu
|
# Task
In the field, two beggars A and B found some gold at the same time. They all wanted the gold, and they decided to use simple rules to distribute gold:
```
They divided gold into n piles and be in line.
The amount of each pile and the order of piles all are randomly.
They took turns to take away a pile of gold from the
far left or the far right.
They always choose the bigger pile. That is to say,
if the left is 1, the right is 2, then choose to take 2.
If the both sides are equal, take the left pile.
```
Given an integer array `golds`, and assume that A always takes first. Please calculate the final amount of gold obtained by A and B. returns a two-element array `[amount of A, amount of B]`.
# Example
For `golds = [4,2,9,5,2,7]`, the output should be `[14,15]`.
```
The pile of most left is 4,
The pile of most right is 7,
A choose the largest one -- > take 7
The pile of most left is 4,
The pile of most right is 2,
B choose the largest one -- > take 4
The pile of most left is 2,
The pile of most left is 2,
A choose the most left one -- > take 2
The pile of most left is 9,
The pile of most right is 2,
B choose the largest one -- > take 9
The pile of most left is 5,
The pile of most left is 2,
A choose the largest one -- > take 5
Tehn, only 1 pile left,
B -- > take 2
A: 7 + 2 + 5 = 14
B: 4 + 9 + 2 = 15
```
For `golds = [10,1000,2,1]`, the output should be `[12,1001]`.
```
A take 10
B take 1000
A take 2
B take 1
A: 10 + 2 = 12
B: 1000 + 1 = 1001
```
|
reference
|
def distribution_of(golds):
g = golds[:]
turn, total = 0, [0, 0]
while g:
total[turn % 2] += g . pop(- (g[0] < g[- 1]))
turn += 1
return total
|
Simple Fun #334: Two Beggars And Gold
|
59547688d8e005759e000092
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/59547688d8e005759e000092
|
7 kyu
|
# Task
You are the manager of the famous rescue team: The Knights. Your task is to assign your knights to a rescue missions on an infinite 2D-plane.
Your knights can move only by `n-knight` jumps.
For example, if a knight has n = 2, they can only move exactly as a knight on a chess board.
If n = 3, they can move from (0, 0) to one of the following 8 points:
`(3, 1) (3, -1), ( -3, 1), (-3, -1), (1, 3), (1, -3), (-1, 3) or (-1, -3).`
You are given an array containing the `n`s of all of your knights `n-knight` jumps, and the coordinates (`x`, `y`) of a civilian who need your squad's help.
Your head quarter is located at (0, 0). Your must determine if `at least one` of your knight can reach that point `(x, y)`.
# Input/Output
- `[input]` integer array `N`
The ways your knights move.
`1 <= N.length <=20`
- `[input]` integer `x`
The x-coordinate of the civilian
- `[input]` integer `y`
The y-coordinate of the civilian
- `[output]` a boolean value
`true` if one of your knights can reach point (x, y), `false` otherwise.
|
games
|
def knight_rescue(N, x, y):
return any(n % 2 == 0 for n in N) or (x + y) % 2 == 0
|
Simple Fun #153: Knight Rescue
|
58ad0159c9e5b0399b0001b8
|
[
"Puzzles",
"Algorithms"
] |
https://www.codewars.com/kata/58ad0159c9e5b0399b0001b8
|
6 kyu
|
# Task
Given an integer `n`, lying in range `[0; 1_000_000]`, calculate the number of digits in `n!` (factorial of `n`).
### Example
* For `n = 0`, the output should be `1` because `0! = 1` has 1 digit;
* For `n = 4`, the output should be `2` because `4! = 24` has 2 digits;
* For `n = 10`, the output should be `7` because `10! = 3628800` has 7 digits.
|
algorithms
|
import math
def factor_digit(n):
if n < 0:
return 0
if n <= 1:
return 1
# Kamenetsky formula
x = ((n * math . log10(n / math . e) + math . log10(2 * math . pi * n) / 2.0))
return math . floor(x) + 1
|
Simple Fun #206: Factorial Digits
|
58fea5baf3dff03a6e000102
|
[
"Puzzles",
"Algorithms"
] |
https://www.codewars.com/kata/58fea5baf3dff03a6e000102
|
5 kyu
|
## Task
You're given an array `arr`. Apply the following algorithm to it:
1. find intervals of consecutive prime numbers and consecutive non-prime numbers;
1. replace each such interval with the sum of numbers in it;
1. if the resulting array is different from the initial one, return to step 1, otherwise return the result.
### Input
A non-empty integer array such that:
* `-10000 ≤ arr[i] ≤ 10000`
* `1 ≤ arr.length ≤ 1000`
### Output
An integer array.
### Examples
For `arr = [1, 2, 3, 5, 6, 4, 2, 3]` the result should be `[21, 5]`:
```
[1, 2, 3, 5, 6, 4, 2, 3] --> [(1), (2 + 3 + 5), (6 + 4), (2 + 3)] --> [1, 10, 10, 5]
[1, 10, 10, 5] --> [(1 + 10 + 10), (5)] --> [21, 5]
```
For `arr = [-3, 4, 5, 2, 0, -10]` the result should be `[1, 7, -10]`:
```
[-3, 4, 5, 2, 0, -10] --> [(-3 + 4), (5 + 2), (0 + -10)] --> [1, 7, -10]
```
|
reference
|
from functools import cache
from itertools import groupby
from gmpy2 import is_prime as gmpy2_isprime
isprime = cache(gmpy2_isprime)
def simplified_array(a):
b = [sum(v) for k, v in groupby(a, isprime)]
return a if a == b else simplified_array(b)
|
Simple Fun #220: Simplified Array
|
59015f8cc842a3e7f10000a4
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/59015f8cc842a3e7f10000a4
|
5 kyu
|
# Task
John is a hacker. He succeeded in invading a server.
His next job is to write `n` numbers(1...n) in the memory of the server. He did this by using a virus code he wrote.
Unfortunately, since the server only accepts binary digits, and his virus code doesn't take into account the problem, only a fraction of the numbers are written into memory.
Given a number `n`, your task is to calculate how many numbers are written into memory.
Note, `n` may be very huge, so, it will be given by a string.
# Example
For `n = "10"`, the output should be `2`.
2 number `"1"` and `"10"` are written into memory.
For `n = "20"`, the output should be `3`.
3 number `"1"`, `"10"` and `"11"` are written into memory.
For `n = "100"`, the output should be `4`.
4 number `"1"`, `"10"`, `"11"` and `"100"` are written into memory.
|
games
|
def incomplete_virus(s):
out = ""
for i, c in enumerate(s):
if c > "1":
out += "1" * (len(s) - i)
break
out += c
return int(out, 2)
|
Simple Fun #333: Incomplete Virus
|
595467c63074e38ba4000063
|
[
"Puzzles"
] |
https://www.codewars.com/kata/595467c63074e38ba4000063
|
5 kyu
|
# Task
You're given an array of positive integers `arr`, and an array `guide` of the same length. Sort array `arr` using array `guide` by the following rules:
```
if guide[i] = -1, arr[i] shouldn't be sorted;
if guide[i] ≠ -1, arr[i] should be sorted,
and among all elements that should be sorted,
arr[i] should be the guide[i]th one (1-based).
```
## Input/Output
- `[input]` integer array `arr`
Array of positive integers.
`1 ≤ a.length ≤ 100`
`1 ≤ A[i] ≤ 10^4`
- `[input]` integer array `guide`
It is guaranteed that `guide.length = a.length`.
- `[output]` an integer array
Array sorted as described above.
### Example
For
`arr = [56, 78, 3, 45, 4, 66, 2, 2, 4]`
`guide = [3, 1, -1, -1, 2, -1, 4, -1, 5]`
the output should be `[78,4,3,45,56,66,2,2,4]`
Here's how `arr` was sorted:
```
Elements 3, 45, 66 and 2 don't need to be sorted,
so we can put them in the resulting array right away:
[?, ?, 3, 45, ?, 66, ?, 2, ?].
Now we need to sort the remaining elements.
According to the guide,
they should be sorted in the following order:
[78, 4, 56, 2, 4]
Thus, the final answer is:
[78, 4, 3, 45, 56, 66, 2, 2, 4].
```
|
reference
|
def sort_by_guide(arr, guide):
it = iter(sorted((y, x) for x, y in zip(arr, guide) if y > 0))
return [next(it)[1] if y > 0 else x for x, y in zip(arr, guide)]
|
Simple Fun #217: Sort By Guide
|
590148d79097384be600001e
|
[
"Algorithms",
"Arrays",
"Sorting"
] |
https://www.codewars.com/kata/590148d79097384be600001e
|
6 kyu
|
## Task
There are some `apples` that you want to give out as a present. You are going to distribute them between some gift boxes in such a way that all the boxes will contain an equal number of apples. You can leave out some of the apples, but no more than `max_left`. You also don't want to leave out more apples than necessary; that is, if each box contains `N` apples, the number of left out apples should be less than `N`.
Assume that you have an infinite number of gift boxes, and that all of them have the capacity of `capacity`. In how many ways can you distribute the apples satisfying all of the above conditions?
### Input
* The total number of apples (`4 <= apples <= 100`)
* The maximum amount of apples you can put into a single box (`4 <= capacity <= 20`)
* The maximum amount of apples you can leave out (`0 <= max_left <= 3`)
### Output
* The number of possible distributions
### Example
```
apples = 7
capacity = 4
max_left = 1
result = 3
```
There are three ways to distribute the apples:
* seven boxes, one apple per box, no apples left out
* three boxes, two apples per box, one apple left out
* two boxes, three apples per box, one apple left out
|
reference
|
def apples_distribution(a, c, m):
return sum(a % i <= m for i in range(1, min(a, c) + 1))
|
Simple Fun #251: Apples Distribution
|
590fca79b5f8a69285000465
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/590fca79b5f8a69285000465
|
7 kyu
|
Given a string of binary numbers of length 3
sort the numbers in ascending order but only order the even numbers and leave all odd numbers in their place.
Example:
```javascript
evenBinary("101 111 100 001 010") // returns "101 111 010 001 100"
```
```ruby
even_binary("101 111 100 001 010") # returns "101 111 010 001 100"
```
```python
even_binary("101 111 100 001 010") # returns "101 111 010 001 100"
```
Note: make sure all the binary numbers have a length of 3
|
reference
|
def even_binary(s):
s = s . split()
e = sorted(filter(lambda b: b[- 1] == '0', s), reverse=True)
return ' ' . join(map(lambda b: e . pop() if b[- 1] == '0' else b, s))
|
Even Binary Sorting
|
582bbdbcc190132e3e0001f3
|
[
"Binary",
"Sorting",
"Algorithms",
"Fundamentals"
] |
https://www.codewars.com/kata/582bbdbcc190132e3e0001f3
|
6 kyu
|
Kevin is noticing his space run out! Write a function that removes the spaces from the values and returns an array showing the space decreasing.
For example, running this function on the array `['i', 'have','no','space']` would produce `['i','ihave','ihaveno','ihavenospace']`
|
reference
|
def spacey(array):
return ['' . join(array[: i + 1]) for i in range(len(array))]
|
Running out of space
|
56576f82ab83ee8268000059
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/56576f82ab83ee8268000059
|
7 kyu
|
# RoboScript #4 - RS3 Patterns to the Rescue
## Disclaimer
The story presented in this Kata Series is purely fictional; any resemblance to actual programming languages, products, organisations or people should be treated as purely coincidental.
## About this Kata Series
This Kata Series is based on a fictional story about a computer scientist and engineer who owns a firm that sells a toy robot called MyRobot which can interpret its own (esoteric) programming language called RoboScript. Naturally, this Kata Series deals with the software side of things (I'm afraid Codewars cannot test your ability to build a physical robot!).
## Story
Ever since you released [RS2](https://www.codewars.com/kata/58738d518ec3b4bf95000192) to the market, there have been much fewer complaints from RoboScript developers about the inefficiency of the language and the popularity of your programming language has continuously soared. It has even gained so much attention that Zachary Mikowski, the CEO of the world-famous Doodle search engine, has contacted you to try out your product! Initially, when you explain the RoboScript (RS2) syntax to him, he looks satisfied, but then he soon finds a major loophole in the efficiency of the RS2 language and brings forth the following program:
<pre style="background: #161616; color: #c5c8c6; font-family: 'CamingoCode-Regular', monospace; display: block; padding: 10px; margin-bottom: 15px; font-weight: normal; overflow-x: auto">
(F2LF2R)2FRF4L(F2LF2R)2(FRFL)4(F2LF2R)2
</pre>
As you can see from the program above, the movement sequence `(F2LF2R)2` has to be rewritten every time and no amount of RS2 syntax can simplify it because the movement sequences in between are different each time (`FRF4L` and `(FRFL)4`). If only RoboScript had a movement sequence reuse feature that makes writing programs like these less repetitive ...
## Task
Define and implement the RS3 specification whose syntax is a superset of [RS2](https://www.codewars.com/kata/58738d518ec3b4bf95000192) (and RS1) syntax. Your interpreter should be named `execute()` and accept exactly 1 argument `code`, the RoboScript code to be executed.
### Patterns - The New Feature
To solve the problem outlined in the Story above, you have decided to introduce a new syntax feature to RS3 called the "pattern". The "pattern" as defined in RS3 behaves rather like a primitive version of functions/methods in other programming languages - it allows the programmer to define and name (to a certain extent) a certain sequence of movements which can be easily referenced and reused later instead of rewriting the whole thing.
The basic syntax for defining a pattern is as follows:
<pre style="background: #161616; color: #c5c8c6; font-family: 'CamingoCode-Regular', monospace; display: block; padding: 10px; margin-bottom: 15px; font-weight: normal; overflow-x: auto">
p(n)<CODE_HERE>q
</pre>
Where:
- `p` is a "keyword" that declares the beginning of a pattern definition (much like the `function` keyword in JavaScript or the `def` keyword in Python)
- `(n)` is any non-negative integer (without the round brackets) which acts as a unique identifier for the pattern (much like a function/method name)
- `<CODE_HERE>` is any valid RoboScript code (without the angled brackets)
- `q` is a "keyword" that marks the end of a pattern definition (like the `end` keyword in Ruby)
For example, if I want to define `(F2LF2R)2` as a pattern and reuse it later in my code:
<pre style="background: #161616; color: #c5c8c6; font-family: 'CamingoCode-Regular', monospace; display: block; padding: 10px; margin-bottom: 15px; font-weight: normal; overflow-x: auto">
p0(F2LF2R)2q
</pre>
It can also be rewritten as below since `(n)` only serves as an identifier and its value doesn't matter:
<pre style="background: #161616; color: #c5c8c6; font-family: 'CamingoCode-Regular', monospace; display: block; padding: 10px; margin-bottom: 15px; font-weight: normal; overflow-x: auto">
p312(F2LF2R)2q
</pre>
Like function/method definitions in other languages, merely defining a pattern (or patterns) in RS3 should cause no side effects, so:
<pre style="background: #161616; color: #c5c8c6; font-family: 'CamingoCode-Regular', monospace; display: block; padding: 10px; margin-bottom: 15px; font-weight: normal; overflow-x: auto">
execute("p0(F2LF2R)2q"); # => '*'
execute("p312(F2LF2R)2q"); # => '*'
</pre>
To invoke a pattern (i.e. make the MyRobot move according to the movement sequences defined inside the pattern), a capital `P` followed by the pattern identifier `(n)` is used:
<pre style="background: #161616; color: #c5c8c6; font-family: 'CamingoCode-Regular', monospace; display: block; padding: 10px; margin-bottom: 15px; font-weight: normal; overflow-x: auto">
P0
</pre>
(or `P312`, depending on which example you are using)
So:
<pre style="background: #161616; color: #c5c8c6; font-family: 'CamingoCode-Regular', monospace; display: block; padding: 10px; margin-bottom: 15px; font-weight: normal; overflow-x: auto">
execute("p0(F2LF2R)2qP0"); # => " *\r\n *\r\n ***\r\n * \r\n*** "
execute("p312(F2LF2R)2qP312"); # => " *\r\n *\r\n ***\r\n * \r\n*** "
</pre>
### Additional Rules for parsing RS3
It doesn't matter whether the invocation of the pattern or the pattern definition comes first - pattern definitions should **always** be parsed first, so:
<pre style="background: #161616; color: #c5c8c6; font-family: 'CamingoCode-Regular', monospace; display: block; padding: 10px; margin-bottom: 15px; font-weight: normal; overflow-x: auto">
execute("P0p0(F2LF2R)2q"); # => " *\r\n *\r\n ***\r\n * \r\n*** "
execute("P312p312(F2LF2R)2q"); # => " *\r\n *\r\n ***\r\n * \r\n*** "
</pre>
Of course, RoboScript code can occur anywhere before and/or after a pattern definition/invocation, so:
<pre style="background: #161616; color: #c5c8c6; font-family: 'CamingoCode-Regular', monospace; display: block; padding: 10px; margin-bottom: 15px; font-weight: normal; overflow-x: auto">
execute("F3P0Lp0(F2LF2R)2qF2"); # => " *\r\n *\r\n *\r\n *\r\n ***\r\n * \r\n****** "
</pre>
Much like a function/definition can be invoked multiple times in other languages, a pattern should also be able to be invoked multiple times in RS3. So:
<pre style="background: #161616; color: #c5c8c6; font-family: 'CamingoCode-Regular', monospace; display: block; padding: 10px; margin-bottom: 15px; font-weight: normal; overflow-x: auto">
execute("(P0)2p0F2LF2RqP0"); # => " *\r\n *\r\n ***\r\n * \r\n *** \r\n * \r\n*** "
</pre>
If a pattern is invoked which does not exist, your interpreter should `throw`/`raise` an exception (depending on the language you are attempting this Kata in) of any kind. This could be anything and will not be tested, but *ideally* it should provide a useful message which describes the error in detail.
```if:php
**In PHP this must be an inst**
```
```if:java
In java, throw a `RuntimeException`.
```
<pre style="background: #161616; color: #c5c8c6; font-family: 'CamingoCode-Regular', monospace; display: block; padding: 10px; margin-bottom: 15px; font-weight: normal; overflow-x: auto">
execute("p0(F2LF2R)2qP1"); # throws
execute("P0p312(F2LF2R)2q"); # throws
execute("P312"); # throws
</pre>
Much like any good programming language will allow you to define an unlimited number of functions/methods, your RS3 interpreter should also allow the user to define a virtually unlimited number of patterns. A pattern definition should be able to invoke other patterns if required. If the same pattern (i.e. both containing the same identifier `(n)`) is defined more than once, your interpreter should `throw`/`raise` an exception (depending on the language you are attempting this Kata in) of any kind.
```if:php
**In PHP this error must again be an instance of** `ParseError`.**
```
```if:java
In java, throw a `RuntimeException`.
```
<pre style="background: #161616; color: #c5c8c6; font-family: 'CamingoCode-Regular', monospace; display: block; padding: 10px; margin-bottom: 15px; font-weight: normal; overflow-x: auto">
execute("P1P2p1F2Lqp2F2RqP2P1"); # => " ***\r\n * *\r\n*** *"
execute("p1F2Lqp2F2Rqp3P1(P2)2P1q(P3)3"); # => " *** *** ***\r\n * * * * * *\r\n*** *** *** *"
execute("p1F2Lqp1(F3LF4R)5qp2F2Rqp3P1(P2)2P1q(P3)3"); # throws exception
</pre>
Furthermore, your interpreter should be able to detect (potentially) infinite recursion, including mutual recursion. Instead of just getting stuck in an infinite loop and timing out, your interpreter should `throw`/`raise` an exception (depending on the language you are attempting this Kata in) of any kind when the "stack" (or just the total number of pattern invocations) exceeds a particular very high (but sensible) threshold, *but only if said pattern with infinite recursion is invoked at least once*.
```if:php
**In PHP this error must again be an instance of** `ParseError`.**
```
```if:java
In java, throw a `RuntimeException`.
```
<pre style="background: #161616; color: #c5c8c6; font-family: 'CamingoCode-Regular', monospace; display: block; padding: 10px; margin-bottom: 15px; font-weight: normal; overflow-x: auto">
execute("p1F2RP1F2LqP1"); # throws
execute("p1F2LP2qp2F2RP1qP1"); # throws
execute("p1F2RP1F2Lq"); # does not throw
</pre>
For the sake of simplicity, you may assume that all programs passed into your interpreter contains valid syntax. Furthermore, nesting pattern definitions is not allowed either (it is considered a syntax error) so your interpreter will not need to account for these.
## Kata in this Series
1. [RoboScript #1 - Implement Syntax Highlighting](https://www.codewars.com/kata/roboscript-number-1-implement-syntax-highlighting)
2. [RoboScript #2 - Implement the RS1 Specification](https://www.codewars.com/kata/roboscript-number-2-implement-the-rs1-specification)
3. [RoboScript #3 - Implement the RS2 Specification](https://www.codewars.com/kata/58738d518ec3b4bf95000192)
4. **RoboScript #4 - RS3 Patterns to the Rescue**
5. [RoboScript #5 - The Final Obstacle (Implement RSU)](https://www.codewars.com/kata/5a12755832b8b956a9000133)
|
algorithms
|
import re
class ParseError (Exception):
pass
def execute (code):
def parse_and_remove_patterns(code):
patterns = {}
for match in re . finditer(r'p(\d+)([^q]*)q', code):
name, pattern_code = match . groups ((1, 2))
if name in patterns:
raise ParseError("duplicate pattern {}" . format (name))
patterns[name] = pattern_code
code = re . sub (r'p\d+[^q]*q', '', code)
return code, patterns
def replace_patterns(code):
def f(match):
name = match . group(1)
if name not in patterns:
raise ParseError("undefined pattern P{}" . format (name))
return patterns[name]
code, patterns = parse_and_remove_patterns(code)
stack_counter = 1
while stack_counter < 32 and 'P' in code:
code = re . sub (r'P(\d+)', f, code)
stack_counter += 1
if 'P' in code:
raise ParseError("infinite recursion detected")
return code
def simplify_code(code):
code = replace_patterns(code)
while '(' in code:
code = re . sub(r'\(([^()]*)\)(\d*)',
lambda match : match . group (1 ) * int (match . group (2 ) or 1 ),
code)
code = re . sub(r'([FLR])(\d+)',
lambda match : match . group (1 ) * int (match . group (2 )),
code)
return code
def compute_path(simplified_code):
pos, dir = (0, 0 ), (1 , 0 )
path = [pos]
for cmd in simplified_code:
if cmd == 'F':
pos = tuple (a + b for a, b in zip (pos, dir ))
path . append(pos)
elif cmd == 'L':
dir = (dir [1], - dir [0 ])
elif cmd == 'R':
dir = (- dir [1], dir [0 ])
return path
def compute_bounding_box(path):
min_x = min (pos [0] for pos in path)
min_y = min (pos [1] for pos in path)
max_x = max (pos [0] for pos in path)
max_y = max (pos [1] for pos in path)
return (min_x, min_y), (max_x , max_y )
def build_grid(path):
min_xy, max_xy = compute_bounding_box(path)
width = max_xy [0] - min_xy [0 ] + 1
height = max_xy [1] - min_xy [1 ] + 1
grid = [[' '] * width for _ in range (height)]
for x, y in path:
grid [y - min_xy [1 ]][x - min_xy [0 ]] = '*'
return grid
def grid_to_string(grid):
return '\r\n' . join ('' . join (row) for row in grid)
code = simplify_code(code)
path = compute_path(code)
grid = build_grid(path)
return grid_to_string(grid)
|
RoboScript #4 - RS3 Patterns to the Rescue
|
594b898169c1d644f900002e
|
[
"Esoteric Languages",
"Interpreters",
"Functional Programming",
"Algorithms"
] |
https://www.codewars.com/kata/594b898169c1d644f900002e
|
3 kyu
|
<a style="float:right; margin:5px" href="https://www.youtube.com/watch?v=66tQR7koR_Q"><img alt="coins balance scale problem" src="https://activerain-store.s3.amazonaws.com/image_store/uploads/agents/kcrowson/files/Scale%20and%20Gold%20Coins.jpg"></a>I found this interesting interview question just today:
> *8 coins are given where all the coins have equal weight, except one. The odd one weights less than the others, not being of pure gold. In the worst case, how many iterations are actually needed to find the odd one out on a two plates scale*.
I am asking you then to tell me what is the *minimum* amount of weighings it will take to measure `n` coins in every possible occurrence (including worst case scenario, ie: without relying on luck at all).
`n` is guaranteed to be a positive integer.
***Tip:*** being able to think *recursively* might help here :p
***Note:*** albeit this is more clearly a logical than a coding problem, do not underestimate (or under-rank) the kata for requiring not necessarily wizard-class coding skills: a good coder is a master of pattern recognition and subsequent optimization ;)
|
reference
|
from math import ceil, log
def how_many_measurements(n):
return ceil(log(n, 3))
|
Number of measurements to spot the counterfeit coin
|
59530d2401d6039f8600001f
|
[
"Logic",
"Fundamentals"
] |
https://www.codewars.com/kata/59530d2401d6039f8600001f
|
6 kyu
|
For a certain simulation, a group of students have to produce numbers close to ```2``` in a certain order. Their instructor guide them explaining an algorithm useful for that task.
An array of integers, arr, is received.
arr = [n1, n2, ....,nk]
The array should be transformed, doing the following steps:
- each value of the array, ```ni```, will be substituted by the value ```(ni + μ) / μ```
```μ = (Σ ni) / k (mean of the array)```
After doing this process recursively, it will be seen that the final array will trend to this final one: ```[2.0, 2.0, .....2.0]```
Let's start with this one: ```[12, 7, 23]```
```
array μ transformed array number of calls
[12, 7, 23] 14.0 [1.8571428571428572, 1.5, 2.642857142857143] 1
[1.8571428571428572, 1.5, 2.642857142857143] 2.0 [1.9285714285714286, 1.75, 2.321428571428571] 2
[1.9285714285714286, 1.75, 2.321428571428571] 2.0 [1.9642857142857144, 1.875, 2.1607142857142856] 3
............................................. .... ............................................ ...
............................................. .... ............................................ ...
[2.0, 2.0, 2.0] 2.0 [2.0, 2.0, 2.0] 54
```
After certain number of recursive steps, the difference between ```2``` and the obtained values is so small that cannot be detected by the programming language system.
In order to estimate the amount of generated values, they need to determine the number of recursive calls for this process.
Do you want to help them?
They need the function ```simul_close_to2()``` that receives a certain array, and a minimum absolute error, ```abs_error```. The function will output the inner calls.
The recursion should stop when ```|arr[i] - arr[i + 1]| ≤ abs_error``` for all ```i``` of the array. For that purpose we need a helper function ```are_contigElemen_closeEnough()``` that receives an array and the abs_error and outputs True when this condition is fulfilled and False when not.
Let's see the above case for different absolute errors:
```python
simul_close_to2([12, 7, 23], pow(10, -5)) == 18 # final array [1.9999989100864957, 1.9999961853027344, 2.00000490461077]
simul_close_to2([12, 7, 23], pow(10, -8)) == 28 # final array [1.9999999989356314, 1.9999999962747097, 2.000000004789659]
simul_close_to2([12, 7, 23], pow(10, -12)) == 42 # final array [1.9999999999999352, 1.9999999999997726, 2.000000000000292]
```
The tests for the function will have the following features:
```
N < 250 (N, number of tests)
3 ≤ L ≤ 5000 (L, length of the array)
1 ≤ ni ≤ 10000000 (arr = [n1, n2,..., ni, ..., nk])
10^(-17) ≤ abs_error ≤ 0.001
```
Enjoy it!
|
reference
|
def are_contigElemen_closeEnough(arr, abs_error):
return all(abs(x - y) <= abs_error for x, y in zip(arr, arr[1:]))
def simul_close_to2(arr, abs_error, count=0):
while not are_contigElemen_closeEnough(arr, abs_error):
mu = sum(arr) / len(arr)
arr = [(x + mu) / mu for x in arr]
count += 1
return count
|
Inner Calls In Recursion I
|
5737f14449fc581de9001845
|
[
"Fundamentals",
"Data Structures",
"Algorithms",
"Mathematics",
"Recursion"
] |
https://www.codewars.com/kata/5737f14449fc581de9001845
|
6 kyu
|
As most of you might know already, a prime number is an integer `n` with the following properties:
* it must be greater than 1
* it must be divisible only by itself and 1
And that's it: -15 or 8 are not primes, 5 or 97 are; pretty easy, isn't it?
Well, turns out that primes are not just a mere mathematical curiosity and are very important, for example, to allow a lot of cryptographic algorithms.
Being able to tell if a number is a prime or not is thus not such a trivial matter and doing it with some efficient algo is thus crucial.
There are already more or less efficient (or sloppy) katas asking you to find primes, but here I try to be even more zealous than other authors.
You will be given a preset array/list with the first few `primes`. And you must write a function that checks if a given number `n` is a prime looping through it and, possibly, expanding the array/list of known primes only if/when necessary (ie: as soon as you check for a **potential prime which is greater than a given threshold for each** `n`, stop).
# Memoization
Storing precomputed results for later re-use is a very popular programming technique that you would better master soon and that is called [memoization](https://en.wikipedia.org/wiki/Memoization); while you have your wiki open, you might also wish to get some info about the [sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) (one of the few good things I learnt as extra-curricular activity in middle grade) and, to be even more efficient, you might wish to consider [an interesting reading on searching from prime from a friend of mine](https://medium.com/@lcthornhill/why-does-the-6-iteration-method-work-for-testing-prime-numbers-ba6176f58082#.dppj0il3a) [she thought about an explanation all on her own after an evening event in which I discussed primality tests with my guys].
Yes, you will be checked even on that part. And you better be **very** efficient in your code if you hope to pass all the tests ;)
**Dedicated to my trainees that worked hard to improve their skills even on a holiday: good work guys!**
**Or should I say "girls" ;)? [Agata](https://www.codewars.com/users/aghh1504), [Ania](https://www.codewars.com/users/lisowska) [Dina](https://www.codewars.com/users/deedeeh) and (although definitely not one of my trainees) special mention to [NaN](https://www.codewars.com/users/nbeck)**
|
algorithms
|
primes = [2, 3, 5, 7]
def is_prime(n):
if n < 2:
return False
m = int(n * * .5) + 1
for p in primes:
if p >= m:
break
if not n % p:
return False
q, d = primes[- 1], 4 if (n + 1) % 6 else 2
while q < m:
q, d = q + d, 4 - d
if is_prime(q):
primes . append(q)
if not n % q:
return False
return True
|
Master your primes: sieve with memoization
|
58603c898989d15e9e000475
|
[
"Memoization",
"Algorithms",
"Tutorials"
] |
https://www.codewars.com/kata/58603c898989d15e9e000475
|
5 kyu
|
## Background
You're modelling the interaction between a large number of quarks and have decided to create a `Quark` class so you can generate your own quark objects.
[Quarks](https://en.wikipedia.org/wiki/Quark) are fundamental particles and the only fundamental particle to experience all four fundamental forces.
## Your task
Your `Quark` class should allow you to create quarks of any valid color (`"red"`, `"blue"`, and `"green"`) and any valid flavor (`'up'`, `'down'`, `'strange'`, `'charm'`, `'top'`, and `'bottom'`).
Every quark has the same `baryon_number` (`BaryonNumber` in `C#`): 1/3.
```if:factor
In Factor, the `<quark>` constructor should be defined. This will be tested to ensure quark objects are initialized correctly.
```
Every quark should have an `.interact()` (`.Interact()` in `C#`) method that allows any quark to interact with another quark via the strong force. When two quarks interact they exchange colors.
## Example
```python
>>> q1 = Quark("red", "up")
>>> q1.color
"red"
>>> q1.flavor
"up"
>>> q2 = Quark("blue", "strange")
>>> q2.color
"blue"
>>> q2.baryon_number
0.3333333333333333
>>> q1.interact(q2)
>>> q1.color
"blue"
>>> q2.color
"red"
```
```csharp
>>> Quark q1 = new Quark("red", "up");
>>> q1.Color;
"red"
>>> Quark q2 = new Quark("blue", "strange");
>>> q2.Color;
"blue"
>>> q2.BaryonNumber;
0.3333333333333333
>>> q1.Interact(q2);
>>> q1.Color;
"blue"
>>> q2.Color;
"red"
```
```factor
[let
"red" "up" <quark> :> q1
q1 color>> . ! "red"
"blue" "strange" <quark> :> q2
q2 color>> . ! "blue"
q2 baryon-number>> . ! 1/3
q1 q2 interact
q1 color>> . ! "blue"
q2 color>> . ! "red"
]
```
```rust
>>> q1 = Quark::new("red", "up")
>>> q1.color()
"red"
>>> q1.flavor()
"up"
>>> q2 = Quark::new("blue", "strange")
>>> q2.color()
"blue"
>>> q2.baryon_number()
0.3333333333333333_f64
>>> q1.interact(q2)
>>> q1.color
"blue"
>>> q2.color
"red"
```
|
reference
|
class Quark (object):
_COLOR = frozenset(["red", "blue", "green"])
_FLAVOR = frozenset(['up', 'down', 'strange', 'charm', 'top', 'bottom'])
baryon_number = 1 / 3
def __init__(self, color, flavor):
if color in self . _COLOR:
self . color = color
else:
raise ValueError(f" { color } is not allowed color for quarks!")
if flavor in self . _FLAVOR:
self . flavor = flavor
else:
raise ValueError(f" { flavor } is not allowed flavor for quarks!")
def interact(self, quark):
self . color, quark . color = quark . color, self . color
|
Thinkful - Object Drills: Quarks
|
5882b052bdeafec15e0000e6
|
[
"Fundamentals",
"Object-oriented Programming"
] |
https://www.codewars.com/kata/5882b052bdeafec15e0000e6
|
7 kyu
|
The Tower of Hanoi problem involves 3 towers. A number of rings decreasing in size are placed on one tower. All rings must then be moved to another tower, but at no point can a larger ring be placed on a smaller ring.
Your task: Given a number of rings, return the MINIMUM number of moves needed to move all the rings from one tower to another.
Reference: [Tower of Hanoi](https://www.mathsisfun.com/games/towerofhanoi.html)
#### Note
This problem may seem very complex, but in reality there is an amazingly simple formula to calculate the minimum number. Just Learn how to solve the problem via the above link (if you are not familiar with it), and then think hard. Your solution should be in no way extraordinarily long and complex. The kata ranking is for figuring out the solution, but the coding skills required are minimal.
|
games
|
def tower_of_hanoi(rings):
return 2 * * rings - 1
|
Tower of Hanoi
|
5899f1df27926b7d000000eb
|
[
"Puzzles",
"Mathematics",
"Logic"
] |
https://www.codewars.com/kata/5899f1df27926b7d000000eb
|
7 kyu
|
[Query string](https://en.wikipedia.org/wiki/Query_string) is a way to _serialize_ object, which is used in HTTP requests. You may see it in URL:
```
codewars.com/kata/search/?q=querystring
```
The part `q=querystring` represents that parameter `q` has value `querystring`. Also sometimes querystring used in HTTP POST body:
```
POST /api/users
Content-Type: application/x-www-form-urlencoded
username=warrior&kyu=1&age=28
```
The string `username=warrior&kyu=1&age=28` represents an entity (user in this example) with username equals warrior, kyu equals 1 and age equals 28. The entity may be represented as object:
```
{
"username": "warrior",
"kyu": 1,
"age": 28
}
```
Sometimes there are more than one value for property:
```
{
"name": "shirt",
"colors": [ "white", "black" ]
}
```
Then it represents as repeated param:
```
name=shirt&colors=white&colors=black
```
So, your task is to write a function that convert an object to query string:
```crystal
to_query_string({ "bar": [ 2, 3 ], "foo": 1 }) # => "bar=2&bar=3&foo=1"
```
```javascript
toQueryString({ foo: 1, bar: [ 2, 3 ] }) // => "foo=1&bar=2&bar=3"
```
```python
to_query_string({ "bar": [ 2, 3 ], "foo": 1 }) // => "bar=2&bar=3&foo=1"
```
```ruby
to_query_string({ "bar": [ 2, 3 ], "foo": 1 }) # => "bar=2&bar=3&foo=1"
```
Next you may enjoy kata [Objectify a URL Query String](https://www.codewars.com/kata/objectify-a-url-query-string).
```if:python
Note: `urllib.parse.urlencode` has been deactivated.
```
```if:javascript
Note: `require` has been disabled.
```
|
algorithms
|
def to_query_string(data):
result = []
for key, value in sorted(data . items()):
if not isinstance(value, (list, tuple, set)):
value = [value]
for val in value:
result . append("{}={}" . format(key, val))
return "&" . join(result)
|
Do you know how to make Query String?
|
595249fc10b69f4f7a000003
|
[
"Algorithms",
"Data Structures",
"Strings"
] |
https://www.codewars.com/kata/595249fc10b69f4f7a000003
|
7 kyu
|
# Task
John is playing a RPG game. The initial attack value of the player is `x`. The player will face a crowd of monsters. Each monster has different defense value.
If the monster's defense value is less than or equal to the player's attack value, the player can easily defeat the monster, and the player's attack value will increase. The amount increased is equal to the monster's defense value.
If the monster's defense value is greater than the player's attack value, the player can still defeat monsters, but the player's attack value can only be increased little, equal to the `greatest common divisor` of the monster's defense value and the player's current attack value.
The defense values for all monsters are provided by `monsterList/monster_list`. The player will fight with the monsters from left to right.
Please help John calculate the player's final attack value.
# Example
For `x = 50, monsterList=[50,105,200]`, the output should be `110`.
The attack value increased: `50 --> 100 --> 105 --> 110`
For `x = 20, monsterList=[30,20,15,40,100]`, the output should be `205`.
The attack value increased:
`20 --> 30 --> 50 --> 65 --> 105 --> 205`
|
games
|
from fractions import gcd
def final_attack_value(x, monster_list):
for i in monster_list:
x += gcd(i, x) if i > x else i
return x
|
Simple Fun #327: The Final Attack Value
|
5951b409aea9beff3f0000c6
|
[
"Puzzles"
] |
https://www.codewars.com/kata/5951b409aea9beff3f0000c6
|
7 kyu
|
# Task:
Your task is to generate a palindrome string, using the specified length `n`, the specified characters `c`(all characters in `c` must be used at least once), and the code length should less than: ```python 55 characters``` ```javascript 62 characters```
|
games
|
def palindrome(n, s): return (s + s[- 1 - n % 2:: - 1]). center(n, s[0])
|
One Line Task: Palindrome String
|
58b57f984f353b3dc9000030
|
[
"Puzzles",
"Restricted"
] |
https://www.codewars.com/kata/58b57f984f353b3dc9000030
|
4 kyu
|
[Gratipay](https://gratipay.com) helps fund open source projects by providing a platform for weekly tips/donations. The current homepage lists **all** projects, along with images. Due to an ever-increasing number of projects, Gratipay is now hitting scaling problems! Help Gratipay design a solution such that only a handful of 'featured' projects are displayed on the homepage.
At the heart of this solution, lies a single function:
```ruby
def get_featured_projects(all_projects)
...
end
```
```python
def get_featured_projects(all_projects):
...
```
```javascript
function getFeaturedProjects(allProjects) {
// ...
}
```
```java
public static Project[] getFeaturedProjects(Project[] projects) {
// ...
}
```
`all_projects` is an array of projects, which are dictionaries/hashes of the format:
```ruby
{
name: "Project name",
nreceiving_from: 10,
receiving: 10,
}
```
```python
{
'name': 'Project name',
'nreceiving_from': 10,
'receiving': 10,
}
```
```javascript
{
"name": "Project name",
"nreceiving_from": 10,
"receiving": 10,
}
```
```java
public class Project {
public final String name;
public final int nreceivingFrom;
public final int receiving;
}
```
`get_featured_projects`/`getFeaturedProjects` is expected to filter out a list of featured projects, based on the following specification:
- Always return 10 projects or less.
- Seven of the projects should be drawn randomly from a pool of the popular projects (a project with `nreceiving_from` > 5 is considered as popular). The remaining three should be taken randomly from amongst the rest.
- If there are less than 10 projects in total, just return all projects.
- If there are less than 7 popular projects, or less than 3 unpopular projects, fill the gaps from the other group of projects if possible.
- Randomize the order of results so that the popular projects don't always appear on top
Note: Gratipay's codebase is [open source](https://github.com/gratipay/gratipay.com), try to resist the temptation to cheat!
|
algorithms
|
import random
def get_featured_projects(all_projects):
all_projects = all_projects[:]
random . shuffle(all_projects)
if len(all_projects) <= 10:
return all_projects
result = [p for p, i in zip(
(p for p in all_projects if p["nreceiving_from"] > 5), range(7))]
result . extend([p for p, i in zip(
(p for p in all_projects if p["nreceiving_from"] <= 5), range(10 - len(result)))])
random . shuffle(result)
return result
|
Choose featured projects for Gratipay's homepage!
|
591b9c07266a3164c90001fe
|
[
"Sorting",
"Algorithms"
] |
https://www.codewars.com/kata/591b9c07266a3164c90001fe
|
5 kyu
|
# Task
John is a programmer. He treasures his time very much. He lives on the `n` floor of a building. Every morning he will go downstairs as quickly as possible to begin his great work today.
There are two ways he goes downstairs: walking or taking the elevator.
When John uses the elevator, he will go through the following steps:
```
1. Waiting the elevator from m floor to n floor;
2. Waiting the elevator open the door and go in;
3. Waiting the elevator close the door;
4. Waiting the elevator down to 1 floor;
5. Waiting the elevator open the door and go out;
(the time of go in/go out the elevator will be ignored)
```
Given the following arguments:
```
n: An integer. The floor of John(1-based).
m: An integer. The floor of the elevator(1-based).
speeds: An array of integer. It contains four integer [a,b,c,d]
a: The seconds required when the elevator rises or falls 1 floor
b: The seconds required when the elevator open the door
c: The seconds required when the elevator close the door
d: The seconds required when John walks to n-1 floor
```
Please help John to calculate the shortest time to go downstairs.
# Example
For `n = 5, m = 6 and speeds = [1,2,3,10]`, the output should be `12`.
John go downstairs by using the elevator:
`1 + 2 + 3 + 4 + 2 = 12`
For `n = 1, m = 6 and speeds = [1,2,3,10]`, the output should be `0`.
John is already at 1 floor, so the output is `0`.
For `n = 5, m = 4 and speeds = [2,3,4,5]`, the output should be `20`.
John go downstairs by walking:
`5 x 4 = 20`
|
games
|
def shortest_time(n, m, speeds):
lift, open, close, walk = speeds
return min(
# taking the elevator
abs(m - n) * lift + open + close + (n - 1) * lift + open,
# walking
(n - 1) * walk
)
|
Simple Fun #326: The Shortest Time
|
5950a4bfc6bf4f433f000031
|
[
"Puzzles"
] |
https://www.codewars.com/kata/5950a4bfc6bf4f433f000031
|
7 kyu
|
Jump is a simple one-player game:
You are initially at the first cell of an array of cells containing non-negative integers;
At each step you can jump ahead in the array as far as the integer at the current cell, or any smaller number of cells.
You win if there is a path that allows you to jump from one cell to another, eventually jumping past the end of the array, otherwise you lose.
For instance, if the array contains the integers
`[2, 0, 3, 5, 0, 0, 3, 0, 0, 3, 1, 0]`,
you can win by jumping from **2**, to **3**, to **5**, to **3**, to **3**, then past the end of the array.
You can also directly jump from from the initial cell(first cell) past the end of the array if they are integers to the right of that cell.
E.g
`[6, 1, 1]` is winnable
`[6]` is **not** winnable
Note: You can **not** jump from the last cell!
`[1, 1, 3]` is **not** winnable
## -----
Your task is to complete the function that determines if a given game is winnable.
### More Examples
```
[5] => false (you can't jump from the last cell)
[2, 5] => true
[3, 0, 2, 3] => true (3 to 2 then past end of array)
[4, 1, 2, 0, 1] => false
[5, 0, 0, 0] => true
[1, 1] => false
```
|
algorithms
|
def can_jump(arr):
if arr[0] == 0 or len(arr) == 1:
return False
if arr[0] >= len(arr):
return True
for jump in range(1, arr[0] + 1):
if can_jump(arr[jump:]):
return True
return False
|
Jump!
|
594fae1a0462da7beb000046
|
[
"Algorithms",
"Arrays",
"Games"
] |
https://www.codewars.com/kata/594fae1a0462da7beb000046
|
6 kyu
|
## Task
You are given an odd integer `n` and a two-dimensional array `s`, which contains `n` equal-sized arrays of `0s` and `1s`.
Return an array of the same length as the elements of `n`, such that its `i`th element is the one that appears most frequently at the `i`th position of `s`' elements.
## Code Limit
```if:javascript
Less than `65` characters.
```
```if:python
Less than `55` characters.
```
## Example
For `n = 3, s = [[1,1,0], [1,0,0], [0,1,1]],`
the output should be `[1,1,0]`
```
1st 2nd 3rd
1 1 0
1 0 0
0 1 1
At the 1st position
there're two 1s and one 0,
so in the 1st element of the resulting array is 1.
At the 2nd position
there're two 1s and one 0,
so in the 2nd element of the resulting array is 1.
At the 3rd position
there're two 0s and one 1,
so in the 3rd element of the resulting array is 0.
```
|
games
|
def zero_or_one(n, s): return [sum(x) > n / 2 for x in zip(* s)]
|
One Line Task: Zero Or One
|
59031db02b0070a923000110
|
[
"Puzzles",
"Restricted"
] |
https://www.codewars.com/kata/59031db02b0070a923000110
|
4 kyu
|
Is it possible to write <a href="https://en.wikipedia.org/wiki/Gadsby_(novel)">a book without the letter 'e' ?</a>
### Task
Given String ```str```, return:
<li>How many "e" does it contain (case-insensitive) in string format.</li>
<li>If given String doesn't contain any "e", return:
"There is no "e"." </li>
<li>If given String is empty, return empty String.</li>
<li>If given String is `null`/`None`/`nil`, return `null`/`None`/`nil`</li>
|
reference
|
def find_e(s):
return s and str(s . count('e') + s . count('E') or 'There is no "e".')
|
Without the letter 'E'
|
594b8e182fa0a0d7fc000875
|
[
"Regular Expressions",
"Strings",
"Fundamentals"
] |
https://www.codewars.com/kata/594b8e182fa0a0d7fc000875
|
7 kyu
|
You are provided with an array of positive integers and an additional integer `n` (`n > 1`).
Calculate the sum of each value in the array to the `n`th power. Then subtract the sum of the original array.
## Examples
```
{1, 2, 3}, 3 --> (1^3 + 2^3 + 3^3 ) - (1 + 2 + 3) --> 36 - 6 --> 30
{1, 2}, 5 --> (1^5 + 2^5) - (1 + 2) --> 33 - 3 --> 30
```
|
games
|
def modified_sum(lst, p):
return sum(n * * p - n for n in lst)
|
Nth power rules them all!
|
58aed2cafab8faca1d000e20
|
[
"Fundamentals",
"Mathematics",
"Algorithms",
"Algebra"
] |
https://www.codewars.com/kata/58aed2cafab8faca1d000e20
|
7 kyu
|
# The learning game - Machine Learning #1
Growing up you would have learnt a lot of things like not to stand in fire, to drink food and eat water and not to jump off very tall things But Machines have it difficult they cannot learn for themselves we have to tell them what to do, why don't we give them a chance to learn it for themselves?
### Task
Your task is to finish the Machine object. What the machine object must do is learn from its mistakes! The Machine will be given a command and a number you will return a random action. After the command has returned you will be given a response (true/false) if the response is true then you have done good, if the response is false then the action was a bad one. You must program the machine to learn to apply an action to a given command using the reponse given. Note: It must take no more than 20 times to teach an action to a command also different commands can have the same action.
### Info
- In the preloaded section there is a constant called ```ACTIONS``` it is a function that returns the 5 possible actions.
- In Java, this a constant ```Actions.FUNCTIONS``` of type ```List<Function<Integer, Integer>>```.
- In C++, the actions can be accessed by ```get_action(i)(unsigned int num)``` where i chooses the function (and therefore can range from 0 to 4) and num is its argument.
- In python ```ACTIONS()``` returns a list of lambdas.
- In Golang ```Actions()``` retruns a function slice ```[]func(int) int```
|
reference
|
class Machine:
def __init__(self):
self . cmd = dict()
self . _actions = [lambda x: x + 1, lambda x: 0,
lambda x: x / 2, lambda x: x * 100, lambda x: x % 2]
def command(self, cmd, num):
self . last_cmd = cmd
if cmd in self . cmd:
return self . _actions[self . cmd[cmd]](num)
else:
self . cmd[cmd] = 0
return self . _actions[self . cmd[cmd]](num)
def response(self, res):
if res == False:
self . cmd[self . last_cmd] += 1
|
The learning game - Machine Learning #1
|
5695995cc26a1e90fe00004d
|
[
"Machine Learning",
"Algorithms"
] |
https://www.codewars.com/kata/5695995cc26a1e90fe00004d
|
4 kyu
|
As [breadcrumb menùs](https://en.wikipedia.org/wiki/Breadcrumb_%28navigation%29) are quite popular today, I won't digress much on explaining them, leaving the wiki link to do all the dirty work in my place.
What might not be so trivial is instead to get a decent breadcrumb from your current url. For this kata, your purpose is to create a function that takes a url, strips the first part (labelling it always `HOME`) and then builds it making each element but the last a `<a>` element linking to the relevant path; last has to be a `<span>` element getting the `active` `class`.
All elements need to be turned to uppercase and separated by a separator, given as the second parameter of the function; the last element can terminate in some common extension like `.html`, `.htm`, `.php` or `.asp`; if the name of the last element is `index`.something, you treat it as if it wasn't there, sending users automatically to the upper level folder.
A few examples can be more helpful than thousands of words of explanation, so here you have them:
```javascript
generateBC("mysite.com/pictures/holidays.html", " : ") == '<a href="/">HOME</a> : <a href="/pictures/">PICTURES</a> : <span class="active">HOLIDAYS</span>'
generateBC("www.codewars.com/users/GiacomoSorbi", " / ") == '<a href="/">HOME</a> / <a href="/users/">USERS</a> / <span class="active">GIACOMOSORBI</span>'
generateBC("www.microsoft.com/docs/index.htm", " * ") == '<a href="/">HOME</a> * <span class="active">DOCS</span>'
```
```python
generate_bc("mysite.com/pictures/holidays.html", " : ") == '<a href="/">HOME</a> : <a href="/pictures/">PICTURES</a> : <span class="active">HOLIDAYS</span>'
generate_bc("www.codewars.com/users/GiacomoSorbi", " / ") == '<a href="/">HOME</a> / <a href="/users/">USERS</a> / <span class="active">GIACOMOSORBI</span>'
generate_bc("www.microsoft.com/docs/index.htm", " * ") == '<a href="/">HOME</a> * <span class="active">DOCS</span>'
```
```ruby
generate_bc("mysite.com/pictures/holidays.html", " : ") == '<a href="/">HOME</a> : <a href="/pictures/">PICTURES</a> : <span class="active">HOLIDAYS</span>'
generate_bc("www.codewars.com/users/GiacomoSorbi", " / ") == '<a href="/">HOME</a> / <a href="/users/">USERS</a> / <span class="active">GIACOMOSORBI</span>'
generate_bc("www.microsoft.com/docs/index.htm", " * ") == '<a href="/">HOME</a> * <span class="active">DOCS</span>'
```
```java
Solution.generate_bc("mysite.com/pictures/holidays.html", " : ").equals( '<a href="/">HOME</a> : <a href="/pictures/">PICTURES</a> : <span class="active">HOLIDAYS</span>' );
Solution.generate_bc("www.codewars.com/users/GiacomoSorbi", " / ").equals( '<a href="/">HOME</a> / <a href="/users/">USERS</a> / <span class="active">GIACOMOSORBI</span>' );
Solution.generate_bc("www.microsoft.com/docs/index.htm", " * ").equals( '<a href="/">HOME</a> * <span class="active">DOCS</span>' );
```
```csharp
Kata.GenerateBC("mysite.com/pictures/holidays.html", " : ") == '<a href="/">HOME</a> : <a href="/pictures/">PICTURES</a> : <span class="active">HOLIDAYS</span>';
Kata.GenerateBC("www.codewars.com/users/GiacomoSorbi", " / ") == '<a href="/">HOME</a> / <a href="/users/">USERS</a> / <span class="active">GIACOMOSORBI</span>';
Kata.GenerateBC("www.microsoft.com/docs/index.htm", " * ") == '<a href="/">HOME</a> * <span class="active">DOCS</span>';
```
Seems easy enough?
Well, probably not so much, but we have one last extra rule: if one element (other than the root/home) is longer than 30 characters, you have to shorten it, acronymizing it (i.e.: taking just the initials of every word); url will be always given in the format `this-is-an-element-of-the-url` and you should ignore words in this array while acronymizing: `["the","of","in","from","by","with","and", "or", "for", "to", "at", "a"]`; a url composed of more words separated by `-` and equal or less than 30 characters long needs to be just uppercased with hyphens replaced by spaces.
Ignore anchors (`www.url.com#lameAnchorExample`) and parameters (`www.url.com?codewars=rocks&pippi=rocksToo`) when present.
Examples:
```javascript
generateBC("mysite.com/very-long-url-to-make-a-silly-yet-meaningful-example/example.htm", " > ") == '<a href="/">HOME</a> > <a href="/very-long-url-to-make-a-silly-yet-meaningful-example/">VLUMSYME</a> > <span class="active">EXAMPLE</span>'
generateBC("www.very-long-site_name-to-make-a-silly-yet-meaningful-example.com/users/giacomo-sorbi", " + ") == '<a href="/">HOME</a> + <a href="/users/">USERS</a> + <span class="active">GIACOMO SORBI</span>'
```
```python
generate_bc("mysite.com/very-long-url-to-make-a-silly-yet-meaningful-example/example.htm", " > ") == '<a href="/">HOME</a> > <a href="/very-long-url-to-make-a-silly-yet-meaningful-example/">VLUMSYME</a> > <span class="active">EXAMPLE</span>'
generate_bc("www.very-long-site_name-to-make-a-silly-yet-meaningful-example.com/users/giacomo-sorbi", " + ") == '<a href="/">HOME</a> + <a href="/users/">USERS</a> + <span class="active">GIACOMO SORBI</span>'
```
```ruby
generate_bc("mysite.com/very-long-url-to-make-a-silly-yet-meaningful-example/example.htm", " > ") == '<a href="/">HOME</a> > <a href="/very-long-url-to-make-a-silly-yet-meaningful-example/">VLUMSYME</a> > <span class="active">EXAMPLE</span>'
generate_bc("www.very-long-site_name-to-make-a-silly-yet-meaningful-example.com/users/giacomo-sorbi", " + ") == '<a href="/">HOME</a> + <a href="/users/">USERS</a> + <span class="active">GIACOMO SORBI</span>'
```
```java
Solution.generate_bc("mysite.com/very-long-url-to-make-a-silly-yet-meaningful-example/example.htm", " > ").equals( '<a href="/">HOME</a> > <a href="/very-long-url-to-make-a-silly-yet-meaningful-example/">VLUMSYME</a> > <span class="active">EXAMPLE</span>' );
Solution.generate_bc("www.very-long-site_name-to-make-a-silly-yet-meaningful-example.com/users/giacomo-sorbi", " + ").equals( '<a href="/">HOME</a> + <a href="/users/">USERS</a> + <span class="active">GIACOMO SORBI</span>' );
```
You will always be provided **valid url** to webpages **in common formats**, so you probably shouldn't bother validating them.
If you like to test yourself with actual work/interview related kata, please also consider this one about building [a string filter for Angular.js](http://www.codewars.com/kata/number-shortening-filter).
_Special thanks to [the colleague](http://www.codewars.com/users/jury89) that, seeing my code and commenting that I worked on that as if it was I was on CodeWars, made me realize that it could be indeed a good idea for a kata_ :)
|
algorithms
|
from re import sub
ignoreList = ["THE", "OF", "IN", "FROM", "BY",
"WITH", "AND", "OR", "FOR", "TO", "AT", "A"]
def generate_bc(url, separator):
# remove leading http(s):// and trailing /
url = sub("https?://", "", url . strip("/"))
# skip index files
url = sub("/index\..+$", "", url)
# split url for processing
url = url . split("/")
# remove file extensions, anchors and parameters
url[- 1] = sub("[\.#\?].*", "", url[- 1])
# first element is always "home"
menu = ["HOME"]
# generate breadcrumb items
for item in url[1:]:
# replace dashes and set to uppercase
item = sub("-", " ", item . upper())
# create acronym if too long
if len(item) > 30:
item = "" . join([w[0] for w in item . split() if w not in ignoreList])
menu . append(item)
# generate paths
path = ["/"]
for i in range(len(url) - 1):
path . append(path[i] + url[i + 1] + "/")
# generate html code
html = []
for i in range(len(url) - 1):
html . append("<a href=\"" + path[i] + "\">" + menu[i] + "</a>")
html . append("<span class=\"active\">" + menu[- 1] + "</span>")
return separator . join(html)
|
Breadcrumb Generator
|
563fbac924106b8bf7000046
|
[
"Parsing",
"Regular Expressions",
"Algorithms"
] |
https://www.codewars.com/kata/563fbac924106b8bf7000046
|
4 kyu
|
My 4th kata, define `puzzle` to pass all the tests by reading the error messages. Click ATTEMPT to start solving. The test will fail at first. The goal is to circumvent all test failures.
Do rank and provide feedback (not sure if this is a nice puzzle idea or a bad one!)
|
games
|
puzzle = []
puzzle . append(puzzle)
|
Recursion puzzle
|
587a58d008236e4951000197
|
[
"Puzzles",
"Recursion",
"Lists"
] |
https://www.codewars.com/kata/587a58d008236e4951000197
|
6 kyu
|
# Task
John and Alice have an appointment today.
In the morning, John starts from (`0,0`) and goes to the place (`a,b`) where he is dating. Unfortunately, John had no sense of direction at all, so he moved 1 step in a random direction(up, down, left or right) each time. For example, if John at (x,y), next step he may move to `(x+1,y), (x-1,y),(x,y+1) or (x,y-1)`.
Obviously, when he arrived at the destination, it was already too late and Alice had already left. It's a sadly story :(
The second day, Alice asked John why he didn't go to the dating place. John said he took `s` steps to his date yesterday.
Alice wants to know whether John is lying. Please help Alice to judge.
Given two coordinates `a, b` and the step `s`, return `true` if John tells the truth, `false` otherwise.
# Input/Output
`[input]` integer `a`
The x-coordinates of the dating site.
`-10^7 <= a <= 10^7`
`[input]` integer `b`
The y-coordinates of the dating site.
`-10^7 <= b <= 10^7`
`[input]` integer `s`
A positive integer. The steps John using.
`0 < s <= 10^9`
`[output]` a boolean value
return `true` if John tells the truth, `false` otherwise.
# Example
For `a = 3, b = 3, s = 6`, the output should be `true`.
A possible path is:
`(0,0) -> (0,1) -> (0,2) -> (0,3) -> (1,3) -> (2,3) -> (3,3)`
For `a = 3, b = 3, s = 8`, the output should be `true`.
A possible path is:
`(0,0) -> (0,1) -> (1,1) -> (1,2) -> (2,2) -> (2,1) -> (3,1) -> (3,2) -> (3,3)`
For `a = 4, b = 5, s = 10`, the output should be `false`.
John can't reach coordinates (a, b) using 10 steps, he's lying ;-)
|
games
|
def is_john_lying(a, b, s):
delta = abs(a) + abs(b) - s
return delta <= 0 and delta % 2 == 0
|
Simple Fun #324: Is John Lying?
|
594cd799c08247a55a000004
|
[
"Puzzles"
] |
https://www.codewars.com/kata/594cd799c08247a55a000004
|
7 kyu
|
# Task
There are `n` bears in the orchard and they picked a lot of apples.
They distribute apples like this:
```
The first bear divided the apple into n piles, each with the same number. leaving an apple at last, and the apple was thrown away. Then he took 1 pile and left the n-1 pile.
The second bear divided the apple into n piles, each with the same number. leaving an apple at last, and the apple was thrown away. Then he took 1 pile and left the n-1 pile.
and so on..
```
Hmm.. your task is coming, please calculate the minimum possible number of these apples (before they start distributing)
# Input/Output
`[input]` integer `n`
The number of bears.
`2 <= n <= 9` (JS, Crystal and C)
`2 <= n <= 50` (Ruby and Python)
`[output]` an integer
The minimum possible number of apples.
# Example
For `n = 5`, the output should be `3121`.
```
5 bears distribute apples:
1st bear divided the apples into 5 piles, each pile has 624 apples, and 1 apple was thrown away.
3121 - 1 = 624 x 5
1st bear took 1 pile of apples, 2496 apples left.
3121 - 1 - 624 = 2496
2nd bear divided the apples into 5 piles, each pile has 499 apples, and 1 apple was thrown away.
2496 - 1 = 499 x 5
2nd bear took 1 pile of apples, 1996 apples left.
2496 - 1 - 499 = 1996
3rd bear divided the apples into 5 piles, each pile has 399 apples, and 1 apple was thrown away.
1996 - 1 = 399 x 5
3rd bear took 1 pile of apples, 1596 apples left.
1996 - 1 - 399 = 1596
4th bear divided the apples into 5 piles, each pile has 319 apples, and 1 apple was thrown away.
1596 - 1 = 319 x 5
4th bear took 1 pile of apples, 1276 apples left.
1596 - 1 - 319 = 1276
5th bear divided the apples into 5 piles, each pile has 255 apples, and 1 apple was thrown away.
1276 - 1 = 255 x 5
5th bear took 1 pile of apples, 1020 apples left.
1276 - 1 - 255 = 1020
```
|
games
|
def how_many_apples(n):
return n * * n - n + 1 if n != 2 else 7
|
Simple Fun #323: Bears And Apples
|
594cc999d3cc8c883a00003b
|
[
"Puzzles"
] |
https://www.codewars.com/kata/594cc999d3cc8c883a00003b
|
6 kyu
|
One of the services provided by an operating system is memory management. The OS typically provides an API for allocating and releasing memory in a process's address space. A process should only read and write memory at addresses which have been allocated by the operating system. In this kata you will implement a simulation of a simple memory manager.
The language you will be using has no low level memory API, so for our simulation we will simply use an array as the process address space. The memory manager constructor will accept an array (further referred to as `memory`) where blocks of indices will be allocated later.
___
# Memory Manager Contract
## allocate(size)
`allocate` reserves a sequential block (sub-array) of `size` received as an argument in `memory`. It should return the index of the first element in the allocated block, or throw an exception if there is no block big enough to satisfy the requirements.
## release(pointer)
`release` accepts an integer representing the start of the block allocated ealier, and frees that block. If the released block is adjacent to a free block, they should be merged into a larger free block. Releasing an unallocated block should cause an exception.
## write(pointer, value)
To support testing this simulation our memory manager needs to support read/write functionality. Only elements within allocated blocks may be written to. The `write` method accepts an index in `memory` and a `value`. The `value` should be stored in `memory` at that index if it lies within an allocated block, or throw an exception otherwise.
## read(pointer)
This method is the counterpart to `write`. Only indices within allocated blocks may be read. The `read` method accepts an index. If the `index` is within an allocated block, the value stored in `memory` at that index should be returned, or an exception should be thrown otherwise.
|
algorithms
|
'''
some useful information about memory allocation in operating system
->There are various algorithms which are implemented by the Operating System in order to find out the holes(continuous empy blocks) \
in the linked list(array in this kata) and allocate them to the processes.
->various algorithms used by operating system:
1. First Fit Algorithm => First Fit algorithm scans the linked list and whenever it finds the first big enough hole to store a process, it stops scanning and load the process into that hole.
2. Next Fit Algorithm => Next Fit algorithm is similar to First Fit algorithm except the fact that, Next fit scans the linked list from the node where it previously allocated a hole.
( if i have allocated memory of size 8 in previous turn and initial pointer is 3 \
then in next turn os will start searching for next empty hole from position 11(3+8=11) )
3. Best Fit Algorithm => The Best Fit algorithm tries to find out the smallest hole possible in the list that can accommodate the size requirement of the process.
4. Worst Fit Algorithm => it is opposite of Best Fit Algorithm meaning that \
(The worst fit algorithm scans the entire list every time and tries to find out the biggest hole in the list which can fulfill the requirement of the process.)
The first fit and best fit algorithms are the best algorithm among all
PS. I HAVE IMPLEMENTED Best Fit Algorithm IN JAVASCRIPT AND IMPLEMENTED Next Fit Algorithm in PYTHON :)
'''
# Next fit Algorithm
class MemoryManager:
def __init__(self, memory):
self . storage = [True] * len(memory)
self . previous_allocated_index = 0
self . allocated = {}
self . data = memory
def allocate(self, size):
find_next = self . process_allocate(self . previous_allocated_index, len(
self . data) - size + 1, size) # start searching from previously allocated block
if find_next is not None:
return find_next
# if we cant find from last index then start searching from starting to previously allocated index
from_start = self . process_allocate(
0, self . previous_allocated_index - size + 1, size)
if from_start is not None:
return from_start
raise IndexError('caused by insufficient space in storage')
def process_allocate(self, initial, end, size):
for i in range(initial, end):
if all(self . storage[i: i + size]):
self . previous_allocated_index = i
self . storage[i: i + size] = [False] * size
self . allocated[i] = i + size
return i
def release(self, pointer):
if self . storage[pointer]:
raise RuntimeError(
'caused by providing incorrect pointer for releasing memory')
size = self . allocated[pointer] - pointer
self . storage[pointer: size] = [True] * size
self . data[pointer: size] = [None] * size
del self . allocated[pointer]
def read(self, pointer):
if self . storage[pointer]:
raise RuntimeError(
'caused by providing incorrect pointer for reading memory')
return self . data[pointer]
def write(self, pointer, value):
if self . storage[pointer]:
raise RuntimeError(
'caused by providing incorrect pointer for writing memory')
self . data[pointer] = value
|
Simple Memory Manager
|
536e7c7fd38523be14000ca2
|
[
"Linked Lists",
"Data Structures",
"Algorithms"
] |
https://www.codewars.com/kata/536e7c7fd38523be14000ca2
|
4 kyu
|
<p>Write a method that takes a field for well-known board game "Battleship" as an argument and returns true if it has a valid disposition of ships, false otherwise. Argument is guaranteed to be 10*10 two-dimension array. Elements in the array are numbers, 0 if the cell is free and 1 if occupied by ship.</p>
<p><b>Battleship</b> (also Battleships or Sea Battle) is a guessing game for two players.
Each player has a 10x10 grid containing several "ships" and objective is to destroy enemy's forces by targetting individual cells on his field. The ship occupies one or more cells in the grid. Size and number of ships may differ from version to version. In this kata we will use Soviet/Russian version of the game.</p>
<img src="http://i.imgur.com/IWxeRBV.png"><br>
Before the game begins, players set up the board and place the ships accordingly to the following rules:<br>
<ul>
<li>There must be single battleship (size of 4 cells), 2 cruisers (size 3), 3 destroyers (size 2) and 4 submarines (size 1). Any additional ships are not allowed, as well as missing ships.</li>
<li>Each ship must be a straight line, except for submarines, which are just single cell.<br>
<img src="http://i.imgur.com/FleBpT9.png"></li>
<li>The ship cannot overlap or be in contact with any other ship, neither by edge nor by corner.<br>
<img src="http://i.imgur.com/MuLvnug.png"></li>
</ul>
This is all you need to solve this kata. If you're interested in more information about the game, visit <a href="http://en.wikipedia.org/wiki/Battleship_(game)">this link</a>.
|
algorithms
|
from scipy . ndimage . measurements import label, find_objects, np
def validate_battlefield(field):
field = np . array(field)
return sorted(
ship . size if min(ship . shape) == 1 else 0
for ship in (field[pos] for pos in find_objects(label(field, np . ones((3, 3)))[0]))
) == [1, 1, 1, 1, 2, 2, 2, 3, 3, 4]
|
Battleship field validator
|
52bb6539a4cf1b12d90005b7
|
[
"Games",
"Arrays",
"Algorithms"
] |
https://www.codewars.com/kata/52bb6539a4cf1b12d90005b7
|
3 kyu
|
Consider a "word" as any sequence of capital letters A-Z (not limited to just "dictionary words"). For any word with at least two different letters, there are other words composed of the same letters but in a different order (for instance, STATIONARILY/ANTIROYALIST, which happen to both be dictionary words; for our purposes "AAIILNORSTTY" is also a "word" composed of the same letters as these two).
We can then assign a number to every word, based on where it falls in an alphabetically sorted list of all words made up of the same group of letters. One way to do this would be to generate the entire list of words and find the desired one, but this would be slow if the word is long.
Given a word, return its number. Your function should be able to accept any word 25 letters or less in length (possibly with some letters repeated), and take no more than 500 milliseconds to run. To compare, when the solution code runs the 27 test cases in JS, it takes 101ms.
For very large words, you'll run into number precision issues in JS (if the word's position is greater than 2^53). For the JS tests with large positions, there's some leeway (.000000001%). If you feel like you're getting it right for the smaller ranks, and only failing by rounding on the larger, submit a couple more times and see if it takes.
Python, Java and Haskell have arbitrary integer precision, so you must be precise in those languages (unless someone corrects me).
C# is using a `long`, which may not have the best precision, but the tests are locked so we can't change it.
Sample words, with their rank:<br />
ABAB = 2<br />
AAAB = 1<br />
BAAA = 4<br />
QUESTION = 24572<br />
BOOKKEEPER = 10743
|
algorithms
|
from collections import Counter
def listPosition(word):
l, r, s = len(word), 1, 1
c = Counter()
for i in range(l):
x = word[(l - 1) - i]
c[x] += 1
for y in c:
if (y < x):
r += s * c[y] / / c[x]
s = s * (i + 1) / / c[x]
return r
|
Alphabetic Anagrams
|
53e57dada0cb0400ba000688
|
[
"Mathematics",
"Logic",
"Strings",
"Algorithms"
] |
https://www.codewars.com/kata/53e57dada0cb0400ba000688
|
3 kyu
|
## Build a pyramid
You will get a string `s` with an even length, and an integer `n` which represents the height of the pyramid and your task is to draw the following pattern. Each line is seperated with `"\n"`.
* `n` will always be greater than 3. No need to check for invalid parameters
* There are no whitespaces at the end of the lines
## Example
`build_pyramid("00-00..00-00", 7)` should return:
```
00-00..00-00
0000--0000....0000--0000
000000---000000......000000---000000
00000000----00000000........00000000----00000000
0000000000-----0000000000..........0000000000-----0000000000
000000000000------000000000000............000000000000------000000000000
00000000000000-------00000000000000..............00000000000000-------00000000000000
```
#### Serie: ASCII Fun
<li><a href="https://www.codewars.com/kata/ascii-fun-number-1-x-shape">ASCII Fun #1: X-Shape</a></li>
<li><a href="https://www.codewars.com/kata/ascii-fun-number-2-funny-dots">ASCII Fun #2: Funny Dots</a></li>
<li><a href="https://www.codewars.com/kata/ascii-fun-number-3-puzzle-tiles">ASCII Fun #3: Puzzle Tiles</a></li>
<li><a href="https://www.codewars.com/kata/ascii-fun-number-4-build-a-pyramid">ASCII Fun #4: Build a pyramid</a></li>
|
reference
|
def build_pyramid(s: str, n: int) - > str:
w = len(s) * n
return '\n' . join('' . join(c * i for c in s). center(w). rstrip() for i in range(1, n + 1))
|
ASCII Fun #4: Build a pyramid
|
594a5d8f704e4d5561000019
|
[
"ASCII Art"
] |
https://www.codewars.com/kata/594a5d8f704e4d5561000019
|
6 kyu
|
<style type="text/css">
table, tr, td {
border: 0px;
}
</style>
In a grid of 4 by 4 squares you want to place a skyscraper in each square with only some clues:
<ul>
<li>The height of the skyscrapers is between 1 and 4</li>
<li>No two skyscrapers in a row or column may have the same number of floors</li>
<li>A clue is the number of skyscrapers that you can see in a row or column from the outside</li>
<li>Higher skyscrapers block the view of lower skyscrapers located behind them</li>
</ul>
<br />
Can you write a program that can solve this puzzle?
<br />
<br />
<b style='font-size:16px'>Example:</b>
<br />
<br />
To understand how the puzzle works, this is an example of a row with 2 clues. Seen from the left side there are 4 buildings visible while seen from the right side only 1:
<br />
<br />
<table style="width: 236px">
<tr>
<td style='text-align:center; height:16px;'> 4</td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; height:16px;'> 1</td>
</tr>
</table>
<br />
There is only one way in which the skyscrapers can be placed. From left-to-right all four buildings must be visible and no building may hide behind another building:
<br />
<br />
<table style="width: 236px">
<tr>
<td style='text-align:center; height:16px;'> 4</td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> 1</td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> 2</td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> 3</td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> 4</td>
<td style='text-align:center; height:16px;'> 1</td>
</tr>
</table>
<br />
Example of a 4 by 4 puzzle with the solution:
<br />
<br />
<table style="width: 236px">
<tr>
<td style='text-align:center; border: 0px;height:16px;'> </td>
<td style='text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;'> 1</td>
<td style='text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;'> 2</td>
<td style='text-align:center; border: 0px;height:16px;'> </td>
</tr>
<tr>
<td style='text-align:center; border: 0px;height:16px;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: 0px;height:16px;'> </td>
</tr>
<tr>
<td style='text-align:center; border: 0px;height:16px;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: 0px;height:16px;'> 2</td>
</tr>
<tr>
<td style='text-align:center; border: 0px;height:16px;'> 1</td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: 0px;height:16px;'> </td>
</tr>
<tr>
<td style='text-align:center; border: 0px;height:16px;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: 0px;height:16px;'> </td>
</tr>
<tr>
<td style='text-align:center; border: 0px;height:16px;'> </td>
<td style='height:16px;'> </td>
<td style='height:16px;'> </td>
<td style='text-align:center; height:16px;'> 3</td>
<td style='height:16px;'> </td>
<td style='text-align:center; border: 0px;height:16px;'> </td>
</tr>
</table>
<br />
<table style="width: 236px">
<tr>
<td style='text-align:center; border: 0px;height:16px;'> </td>
<td style='text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;'> 1</td>
<td style='text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;'> 2</td>
<td style='text-align:center; border: 0px;height:16px;'> </td>
</tr>
<tr>
<td style='text-align:center; border: 0px;height:16px;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> 2</td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> 1</td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> 4</td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> 3</td>
<td style='text-align:center; border: 0px;height:16px;'> </td>
</tr>
<tr>
<td style='text-align:center; border: 0px;height:16px;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> 3</td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> 4</td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> 1</td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> 2</td>
<td style='text-align:center; border: 0px;height:16px;'> 2</td>
</tr>
<tr>
<td style='text-align:center; border: 0px;height:16px;'> 1</td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> 4</td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> 2</td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> 3</td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> 1</td>
<td style='text-align:center; border: 0px;height:16px;'> </td>
</tr>
<tr>
<td style='text-align:center; border: 0px;height:16px;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> 1</td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> 3</td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> 2</td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> 4</td>
<td style='text-align:center; border: 0px;height:16px;'> </td>
</tr>
<tr>
<td style='text-align:center; border: 0px;height:16px;'> </td>
<td style='height:16px;'> </td>
<td style='height:16px;'> </td>
<td style='text-align:center; height:16px;'> 3</td>
<td style='height:16px;'> </td>
<td style='text-align:center; border: 0px;height:16px;'> </td>
</tr>
</table>
<br />
<b style='font-size:16px'>Task:</b>
<br />
<br />
<ul>
<li>Finish:</li>
</ul>
```javascript
function solvePuzzle(clues)
```
```csharp
public static int[][] SolvePuzzle(int[] clues)
```
```c
int** SolvePuzzle (int *clues);
```
```cpp
int** SolvePuzzle (int *clues);
```
```java
public static int[][] solvePuzzle (int[] clues)
```
```java
def solve_puzzle (clues)
```
```haskell
solve :: [Int] -> [[Int]]
```
```ruby
def solve_puzzle(clues)
```
```go
func SolvePuzzle(clues []int) [][]int
```
```clojure
defn solve-puzzle [clues]
```
```fsharp
solvePuzzle (clues : int[]) : int[][]
```
<ul>
<li>
Pass the clues in an array of 16 items. This array contains the clues around the clock, index:
<br />
<table style="width: 236px">
<tr>
<td style='text-align:center; border: 0px;height:16px;'> </td>
<td style='text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;'> 0</td>
<td style='text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;'> 1</td>
<td style='text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;'> 2</td>
<td style='text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;'> 3</td>
<td style='text-align:center; border: 0px;height:16px;'> </td>
</tr>
<tr>
<td style='text-align:center; border: 0px;height:16px;'> 15</td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: 0px;height:16px;'> 4</td>
</tr>
<tr>
<td style='text-align:center; border: 0px;height:16px;'> 14</td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: 0px;height:16px;'> 5</td>
</tr>
<tr>
<td style='text-align:center; border: 0px;height:16px;'> 13</td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: 0px;height:16px;'> 6</td>
</tr>
<tr>
<td style='text-align:center; border: 0px;height:16px;'> 12</td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: solid 1px;height:16px;border-color:gray;'> </td>
<td style='text-align:center; border: 0px;height:16px;'> 7</td>
</tr>
<tr>
<td style='text-align:center; border: 0px;height:16px;'> </td>
<td style='text-align:center; height:16px;'>11</td>
<td style='text-align:center; height:16px;'>10</td>
<td style='text-align:center; height:16px;'> 9</td>
<td style='text-align:center; height:16px;'> 8</td>
<td style='text-align:center; border: 0px;height:16px;'> </td>
</tr>
</table>
</li>
<li>If no clue is available, add value `0`</li>
<li>Each puzzle has only one possible solution</li>
<li>`SolvePuzzle()` returns matrix `int[][]`. The first indexer is for the row, the second indexer for the column. (Python: returns 4-tuple of 4-tuples, Ruby: 4-Array of 4-Arrays)
</li>
</ul>
<b style='font-size:16px'><i>If you finished this kata you can use your solution as a base for the more challenging kata: <a href="https://www.codewars.com/kata/6-by-6-skyscrapers">6 By 6 Skyscrapers</a></i></b>
|
games
|
from itertools import permutations
def check_row(I, x):
if len(set(I)) < len(I):
return False
v, h = 1, I [0]
for i in I [1:]:
if i > h:
h = i
v += 1
return v == x or x == 0
def check_grid (a, b, c , d , x , y ):
# a, b, c, d: 4 rows/ 4 columns
# x, y: pair of clues
for i in range(len (a)):
col = [a [i ], b [i ], c [i ], d [ i ]]
if not check_row (col , x [i ]) or not check_row (col [:: - 1 ], y [:: - 1 ][i ]):
return False
return True
def gen_arr (a, b ):
# generate possible rows based on pair of clues
L = [1, 2, 3 , 4 ]
return [o for o in permutations (L)
if check_row (o, a) and check_row (o [:: - 1 ], b )]
def solve_puzzle(clues):
Rows = [gen_arr (clues [15 - i ], clues [i + 4 ]) for i in range ( 0 , 4 )]
return [tuple ([a , b , c , d ]) for a in Rows [0 ] for b in Rows [1 ] for c in Rows [ 2 ] for d in Rows [ 3 ] if check_grid ( a , b , c , d , clues [: 4 ], clues [ 8 : 12 ])][ 0 ]
|
4 By 4 Skyscrapers
|
5671d975d81d6c1c87000022
|
[
"Puzzles",
"Algorithms"
] |
https://www.codewars.com/kata/5671d975d81d6c1c87000022
|
4 kyu
|
# Task
You know the slogan `p`, which the agitators have been chanting for quite a while now. Roka has heard this slogan a few times, but he missed almost all of them and grasped only their endings. You know the string `r` that Roka has heard.
You need to determine what is the `minimal number` of times agitators repeated the slogan `p`, such that Roka could hear `r`.
It is guaranteed the Roka heard nothing but the endings of the slogan P repeated several times.
# Example
For `p = "glorytoukraine", r = "ukraineaineaine"`, the output should be `3`.
The slogan was `"glorytoukraine"`, and Roka heard `"ukraineaineaine"`.
He could hear it as follows: `"ukraine"` + `"aine"` + `"aine"` = `"ukraineaineaine"`.
# Input/Output
- `[input]` string `p`
The slogan the agitators chanted, a string of lowecase Latin letters.
- `[input]` string `r`
The string of lowercase Latin letters Roka has heard.
- `[output]` an integer
The `minimum number` of times the agitators chanted.
|
games
|
def slogans(p, r):
i, s = 0, ''
for x in r:
s += x
if s not in p:
i += 1
s = x
return i + 1
|
Simple Fun #188: Slogans
|
58bf79fdc8bd4432d6000029
|
[
"Puzzles"
] |
https://www.codewars.com/kata/58bf79fdc8bd4432d6000029
|
5 kyu
|
Take a look to the kata ```Maximum Subarray Sum```
```https://www.codewars.com/kata/maximum-subarray-sum```
In that kata (if you solved it), you had to give the maximum value of the elements of all the subarrays.
In this kata, we have a similar task but you have to find the sub-array or sub-arrays having this maximum value for their corresponding sums of elements. Let's see some examples:
~~~if:python,ruby,javascript
```python
[-2, 1, -3, 4, -1, 2, 1, -5, 4] returns [[4, -1, 2, 1], 6]
```
If in the solution we have two or more arrays having the maximum sum value, the result will have an array of arrays in the corresponding order of the array, from left to right.
```python
[4, -1, 2, 1, -40, 1, 2, -1, 4]) returns [[[4, -1, 2, 1], [1, 2, -1, 4]], 6] # From left to right [4, -1, 2, 1] appears in the array before than [1, 2, -1, 4].
```
If the array does not have any sub-array with a positive sum of its terms, the function will return ```[[], 0]```.
~~~
~~~if-not:python,ruby,javascript
```
[-2, 1, -3, 4, -1, 2, 1, -5, 4] returns ([[4, -1, 2, 1]], 6)
[4, -1, 2, 1, -40, 1, 2, -1, 4]) returns ([[4, -1, 2, 1], [1, 2, -1, 4]], 6)
(From left to right [4, -1, 2, 1] appears in the array before than [1, 2, -1, 4])
If the array does not have any sub-array with a positive sum of its terms, the function will return ```([], 0)```.
```
~~~
See more cases in the Example Test Cases Window.
Enjoy it!
Thanks to smile67 (Matthias Metzger from Germany for his important observations in the javascript version)
|
reference
|
def find_subarr_maxsum(arr):
subarrs = [arr[i: j + 1]
for i in range(len(arr)) for j in range(i, len(arr))]
maxsum = max((sum(subarr) for subarr in subarrs))
if maxsum < 0:
return [[], 0]
maxes = [subarr for subarr in subarrs if sum(subarr) == maxsum]
if len(maxes) == 1:
maxes = maxes[0]
return [maxes, maxsum]
|
Maximum Subarray Sum II
|
56e3cbb5a28956899400073f
|
[
"Fundamentals",
"Data Structures",
"Algorithms",
"Mathematics",
"Logic",
"Sorting"
] |
https://www.codewars.com/kata/56e3cbb5a28956899400073f
|
5 kyu
|
The internet is a very confounding place for some adults. Tom has just joined an online forum and is trying to fit in with all the teens and tweens. It seems like they're speaking in another language! Help Tom fit in by translating his well-formatted English into n00b language.
The following rules should be observed:
- "to" and "too" should be replaced by the number 2, even if they are only part of a word (E.g. today = 2day)
- Likewise, "for" and "fore" should be replaced by the number 4
- Any remaining double o's should be replaced with zeros (E.g. noob = n00b)
- "be", "are", "you", "please", "people", "really", "have", and "know" should be changed to "b", "r", "u", "plz", "ppl", "rly", "haz", and "no" respectively (even if they are only part of the word)
- When replacing words, always maintain case of the first letter unless another rule forces the word to all caps.
- The letter "s" should always be replaced by a "z", maintaining case
- "LOL" must be added to the beginning of any input string starting with a "w" or "W"
- "OMG" must be added to the beginning (after LOL, if applicable,) of a string 32 characters<sup>1</sup> or longer
- All evenly numbered words<sup>2</sup> must be in ALL CAPS (<b>Example:</b> ```Cake is very delicious.``` becomes ```Cake IZ very DELICIOUZ```)
- If the input string starts with "h" or "H", the entire output string should be in ALL CAPS
- Periods ( . ), commas ( , ), and apostrophes ( ' ) are to be removed
- <sup>3</sup>A question mark ( ? ) should have more question marks added to it, equal to the number of words<sup>2</sup> in the sentence (<b>Example:</b> ```Are you a foo?``` has 4 words, so it would be converted to ```r U a F00????```)
- <sup>3</sup>Similarly, exclamation points ( ! ) should be replaced by a series of alternating exclamation points and the number 1, equal to the number of words<sup>2</sup> in the sentence (<b>Example:</b> ```You are a foo!``` becomes ```u R a F00!1!1```)
<sup>1</sup> Characters should be counted <b>After:</b> any word conversions, adding additional words, and removing punctuation. <b>Excluding:</b> All punctuation and any 1's added after exclamation marks ( ! ). Character count <b>includes</b> spaces.
<sup>2</sup> For the sake of this kata, "words" are simply a space-delimited substring, regardless of its characters. Since the output may have a different number of words than the input, words should be counted based on the output string.
<b>Example:</b> ```whoa, you are my 123 <3``` becomes ```LOL WHOA u R my 123 <3``` = 7 words
<sup>3</sup>The incoming string will be punctuated properly, so punctuation does not need to be validated.
|
reference
|
import re
dict = {"[\.,']": "", "too?": "2", "fore?": "4", "oo": "00", "be": "b",
"are": "r", "you": "u", "please": "plz", "people": "ppl",
"really": "rly", "have": "haz", "know": "no", "s": "z"}
def n00bify(text):
for word in dict:
text = re . sub(word, dict[word], text, flags=re . IGNORECASE)
if text[0] in "hH":
text = text . upper()
if text[0] in "wW":
text = "LOL " + text
if len(re . sub("[\?!]*", "", text)) >= 32:
text = re . sub("\A(LOL |)", "\g<1>OMG ", text)
text = " " . join(w . upper() if i % 2 != 0 else w for i,
w in enumerate(text . split()))
text = re . sub("(\?|!)", "\g<1>" * len(text . split()),
text). replace("!!", "!1")
return text
|
N00bify - English to n00b Translator
|
552ec968fcd1975e8100005a
|
[
"Fundamentals",
"Strings"
] |
https://www.codewars.com/kata/552ec968fcd1975e8100005a
|
5 kyu
|
Given a string of arbitrary length with any ascii characters. Write a function to determine whether the string contains the whole word "English".
The order of characters is important -- a string "abcEnglishdef" is correct but "abcnEglishsef" is not correct.
Upper or lower case letter does not matter -- "eNglisH" is also correct.
Return value as boolean values, true for the string to contains "English", false for it does not.
|
reference
|
def sp_eng(sentence):
return 'english' in sentence . lower()
|
Do you speak "English"?
|
58dbdccee5ee8fa2f9000058
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/58dbdccee5ee8fa2f9000058
|
8 kyu
|
# Task
You got a `scratch lottery`, you want to know how much money you win.
There are `6` sets of characters on the lottery. Each set of characters represents a chance to win. The text has a coating on it. When you buy the lottery ticket and then blow it off, you can see the text information below the coating.
Each set of characters contains three animal names and a number, like this: `"tiger tiger tiger 100"`. If the three animal names are the same, Congratulations, you won the prize. You will win the same bonus as the last number.
Given the `lottery`, returns the total amount of the bonus.
# Input/Output
`[input]` string array `lottery`
A string array that contains six sets of characters.
`[output]` an integer
the total amount of the bonus.
# Example
For
```
lottery = [
"tiger tiger tiger 100",
"rabbit dragon snake 100",
"rat ox pig 1000",
"dog cock sheep 10",
"horse monkey rat 5",
"dog dog dog 1000"
]```
the output should be `1100`.
`"tiger tiger tiger 100"` win $100, and `"dog dog dog 1000"` win $1000.
`100 + 1000 = 1100`
|
games
|
def scratch(lottery):
return sum(int(n) for lot in lottery for a, b, c, n in [lot . split()] if a == b == c)
|
Simple Fun #320: Scratch lottery I
|
594a1822a2db9e93bd0001d4
|
[
"Puzzles",
"Regular Expressions"
] |
https://www.codewars.com/kata/594a1822a2db9e93bd0001d4
|
7 kyu
|
You have to give the number of different integer triangles with one angle of 120 degrees which perimeters are under or equal a certain value. Each side of an integer triangle is an integer value.
```
give_triang(max. perimeter) --------> number of integer triangles,
```
with sides a, b, and c integers such that:
a + b + c <= max. perimeter
See some of the following cases
```
give_triang(5) -----> 0 # No Integer triangles with perimeter under or equal five
give_triang(15) ----> 1 # One integer triangle of (120 degrees). It's (3, 5, 7)
give_triang(30) ----> 3 # Three triangles: (3, 5, 7), (6, 10, 14) and (7, 8, 13)
give_triang(50) ----> 5 # (3, 5, 7), (5, 16, 19), (6, 10, 14), (7, 8, 13) and (9, 15, 21) are the triangles with perim under or equal 50.
```
|
reference
|
def give_triang(per):
cnt = 0
for a in range(3, per):
if (2 * a > per):
break
for b in range(a, per):
if (a + 2 * b > per):
break
c = (a * a + a * b + b * b) * * 0.5
if (c == int(c) and a + b + c <= per):
cnt += 1
return cnt
|
Integer triangles
|
55db7b239a11ac71d600009d
|
[
"Algorithms",
"Mathematics",
"Data Structures",
"Geometry"
] |
https://www.codewars.com/kata/55db7b239a11ac71d600009d
|
5 kyu
|
For a given pair of `a` and `b` : Consider a Chess board of `a × b` squares. Now, for each of the squares; Imagine a Queen standing on that square and compute the number of squares under the queen's attack. Add all the numbers you get for each of the `a × b` possible queen's position and return it.
__Examples :__
* For `a = 2` and `b = 2` : squaresUnderQueenAttack(2,2) => 12.
* For `a = 2` and `b = 3` : squaresUnderQueenAttack(2,3) => 26.
Explaination : <br>
<img src="http://i.imgur.com/QMgd2Pf.png" style="width:760px; height:400px;">
__Constraints :__
* `1 ≤ a ≤ 20`.
* `1 ≤ b ≤ 20`.
|
reference
|
from math import comb
'''
Consider each square in the board; how many times does it get covered by a Queen across
all a*b possible positions of the Queens:
First let m be the large dimension of the board, m>=n, n the smaller dimension, and say
that m is "horizontal" and n is "vertical".
- Each Queen placement will cover m-1 horizontal squares and n-1 vertical squares, for
a total of (m-1+n-1) = (m+n-2) squares. Since there are m*n Queen positions, the Queen
placements will cover in total m*n(m+n-2) squares due to horizontal and vertical moves.
- Now need to consider diagonal moves: There are 2 possible diagonals in the board, NW-SE and
SW-NE. They are identical by symmetry so consider one only. There are a total of (m-n+1) "full size"
diagonals that each contain n squares; e.g. for 9x4 board there are (9-4+1)=6 diagonals from NW to SE
that each contain n=4 squares. Each such diagonal therefore has n positions to place a Queen
and with each placement the Queen will cover n-1 such diagonal squares. Thus for the "full diagonals"
we get (m-n+1)*n*(n-1) squares covered.
-Then there are 2 sets of "partial" diagonals one at each end of the board. These contain diagonals
containing n-1, n-2, ..., 1 square. For example in 9x4 board, we have 1 diagonal of length 3, 1 of length
2, 1 of length 1, reaching into the bottom left and top right corners.
Each placement of a queen in such diagonal will cover k-1 squares diagonally, i.e. in diagonal of size 3
there are 3 positions for a queen and 3-1 = 2 squares covered by each queen. Therefore each of the 2 "partial"
diagonal blocks will contribute 3*(3-1) + 2*(2-1) + 1*(1-1) squares. In general, this is (n-1)*(n-1-1)... series
which evaluates to 2*math.comb(n,3) by hockey stick formula. Remember there are 2 such regions for a given diagonal
direction.
-So for *EACH* diagonal direction we get: (m-n+1)*n*(n-1) + 2*2*math.comb(n,3) and since
there are 2 diagonal directions we get 2* above result.
-Hence adding everything horizontal, vertical, 2*diagonals we get:
m*n(m+n-2) + 2 * [ (m-n+1)*n*(n-1) + 2*2*math.comb(n,3) ]
= m*n*(m+n-2) + 2*(m-n+1)*n*(n-1) + 8*math.comb(n,3)
'''
def chessboard_squares_under_queen_attack(a, b):
m, n = max(a, b), min(a, b)
return m * n * (m + n - 2) + 2 * (m - n + 1) * n * (n - 1) + 8 * comb(n, 3)
|
Chessboard Squares Under Queen's Attack
|
578e55c275ffd11cb3001045
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/578e55c275ffd11cb3001045
|
6 kyu
|
### Task:
Given a list of integers, determine whether the sum of its elements is odd or even.
Give your answer as a string matching `"odd"` or `"even"`.
If the input array is empty consider it as: `[0]` (array with a zero).
### Examples:
```
Input: [0]
Output: "even"
Input: [0, 1, 4]
Output: "odd"
Input: [0, -1, -5]
Output: "even"
```
Have fun!
|
reference
|
def oddOrEven(arr):
return 'even' if sum(arr) % 2 == 0 else 'odd'
|
Odd or Even?
|
5949481f86420f59480000e7
|
[
"Fundamentals",
"Arrays"
] |
https://www.codewars.com/kata/5949481f86420f59480000e7
|
7 kyu
|
<style>
.firstRow {
vertical-align:-60px;
}
</style>
<h4 style="color:brown">Task</h4>
Write function which validates an input string. If the string is a perfect square return true,false otherwise.
<h4 style="color:brown">What is perfect square?</h4>
* We assume that character '.' (dot) is a perfect square (1x1)
* Perfect squares can only contain '.' (dot) and optionally '\n' (line feed) characters.<br>
* Perfect squares must have same width and height -> cpt.Obvious<br>
* Squares of random sizes will be tested!
<h4 style="color:brown">Function input:</h4>
```javascript
perfectSquare = "...\n...\n...";
// This represents the following Perfect Square:
`...
...
...`
notPerfect = "..,\n..\n...";
// This is not a Perfect Square:
`..,
..
...`
```
|
reference
|
def perfect_square(square):
l = len(square . split("\n"))
return all("." * l == x for x in square . split("\n"))
|
Perfect Square.
|
584e93a70f60247eb8000132
|
[
"Regular Expressions",
"Fundamentals"
] |
https://www.codewars.com/kata/584e93a70f60247eb8000132
|
6 kyu
|
You have a number `x` in base `m` (x<sub>m</sub>). Count the number of digits `d` after converting x<sub>m</sub> to base `n`.
## Representation of numbers
```
base = 2: 0, 1
base = 3: 0, 1, 2
...
base = 10: 0, 1, ... 8, 9
base = 11: 0 ... , 8, 9, a
base = 12: 0 ... , 8, 9, a, b
...
base = 16: 0 ... , 8, 9, a, ..., e, f
base = 36: 0 ..., 8, 9, a, ..., y, z
```
## Preconditions
1. `2 <= m <= 36`
2. `2 <= n <= 36`
3. x<sub>m</sub> is always a valid _non-negative_ m-based number.
4. `d` is always a valid digit for base `n`
## Examples
```python
# Function defintion
count_digit(number, digit, base=10, from_base=10)
# number -> xm (str)
# digit -> d (str)
# base -> n (int)
# from_base -> m (int)
count_digit("133", "3") == 2
count_digit("10", "a", base=11) == 1
count_digit("1100101110101", "d", base=15, from_base=2) == 1
```
```ruby
# Function defintion
count_digit(number, digit, base=10, from_base=10)
# number -> xm (str)
# digit -> d (str)
# base -> n (int)
# from_base -> m (int)
count_digit("133", "3") == 2
count_digit("10", "a", base=11) == 1
count_digit("1100101110101", "d", base=15, from_base=2) == 1
```
```javascript
// Function defintion
countDigits(number, digit, base=10, from_base=10)
// number -> xm (str)
// digit -> d (str)
// base -> n (int)
// from_base -> m (int)
countDigits("133", "3") == 2
countDigits("10", "a", base=11) == 1
countDigits("1100101110101", "d", base=15, from_base=2) == 1
```
```coffeescript
# Function defintion
countDigits = (number, digit, base=10, from_base=10) -> ...
# number -> xm (str)
# digit -> d (str)
# base -> n (int)
# from_base -> m (int)
countDigits("133", "3") == 2
countDigits("10", "a", base=11) == 1
countDigits("1100101110101", "d", base=15, from_base=2) == 1
```
```typescript
// Function defintion
countDigits(number: string, digit: string, base: number=10, fromBase:number=10)
// number -> xm (string)
// digit -> d (string)
// base -> n (number)
// from_base -> m (number)
countDigits("133", "3") == 2
countDigits("10", "a", base=11) == 1
countDigits("1100101110101", "d", base=15, from_base=2) == 1
```
|
reference
|
from numpy import base_repr
def count_digit(number, digit, base=10, from_base=10):
return base_repr(int(number, from_base), base). lower(). count(digit)
|
Number of Digit d in m-based Number Converted to Base n
|
57c18a16c82ce75f4b000020
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/57c18a16c82ce75f4b000020
|
6 kyu
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.