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 |
---|---|---|---|---|---|---|---|
# Background
I have stacked some pool balls in a triangle.
Like this,
<img src="https://i.imgur.com/RuDkTCH.png" title="pool balls" />
# Kata Task
Given the number of `layers` of my stack, what is the total height?
Return the height as multiple of the ball diameter.
## Example
The image above shows a stack of 5 layers.
## Notes
* `layers` >= 0
* approximate answers (within 0.001) are good enough
---
*See Also*
* [Stacked Balls - 2D](https://www.codewars.com/kata/stacked-balls-2d)
* [Stacked Balls - 3D with square base](https://www.codewars.com/kata/stacked-balls-3d-square-base)
* [Stacked Balls - 3D with triangle base](https://www.codewars.com/kata/stacked-balls-3d-triangle-base)
| reference | def stack_height_2d(layers):
return round((1 + 3 * * 0.5 * (layers - 1) / 2), 3) if layers > 0 else 0
| Stacked Balls - 2D | 5bb804397274c772b40000ca | [
"Fundamentals"
]
| https://www.codewars.com/kata/5bb804397274c772b40000ca | 7 kyu |
Given a non-negative number, sum all its digits using the following rules:
1. If the number of digits is even, remove the last digit
2. a. If the middle digit is odd, subtract it instead of adding
b. If both the middle digit and the last digit are even, subtract the last digit instead of adding
c. If the middle digit is even but the last digit is odd, the first digit must be squared
Repeat this process until only 1 digit is left.
**Note**: if at some point the number becomes negative, remove the minus sign.
## Examples
```
5 => 5
214 => 2 - 1 + 4 = 5 => 5
126 => 1 + 2 - 6 = -3 => 3
2234 => 223 => 2^2 + 2 + 3 = 9 => 9
``` | games | def crazy_formula(n):
while n > 9:
a = list(map(int, str(n)))
if not len(a) % 2:
a . pop()
if a[len(a) / / 2] % 2:
a[len(a) / / 2] *= - 1
elif a[- 1] % 2:
a[0] * *= 2
else:
a[- 1] *= - 1
n = abs(sum(a))
return n
| Give me a Crazy Formula! | 5661cde807c4e28efa0000d0 | [
"Mathematics",
"Algorithms",
"Puzzles"
]
| https://www.codewars.com/kata/5661cde807c4e28efa0000d0 | 7 kyu |
# Task
The game starts with `n` people standing in a circle. The presenter counts `m` people starting with the first one, and gives `1` coin to each of them. The rest of the players receive `2` coins each. After that, the last person who received `1` coin leaves the circle, giving everything he had to the next participant (who will also be considered "the first in the circle" in the next round). This process continues until only 1 person remains.
Determine the `number` of this person and how many `coins` he has at the end of the game.
The result should be a pair of values in the format: `[person, coins]`.
## Example:
```
n = 8, m = 3
People
1 2 3 1 2 β 1 2 β β 2 β β 2 β β β β β β β
8 4 => 8 4 => 8 4 => 8 4 => 8 4 => 8 4 => β 4 => 7
7 6 5 7 6 5 7 β 5 7 β 5 7 β β 7 β β 7 β β
Coins
0 0 0 1 1 β 3 3 β β 9 β β 10 β β β β β β β
0 0 => 2 3 => 4 4 => 5 6 => 7 7 => 8 20 => β 30 => 51
0 0 0 2 2 2 7 β 3 8 β 5 16 β β 17 β β 18 β β
```
## Notes:
* The presenter can do several full circles during one counting.
* In this case, the same person will receive `1` coin multiple times, i.e. no matter how many people are left in the circle, at least `m` coins will always be distributed among the participants during the round.
* If a person had already received `1` coin (possibly multiple times), he won't receive any additional `2` coins **at once(!)** during that round.
* People are counted starting with `1`.
* `m` can be **bigger** than `n` at start | algorithms | def find_last(n, m):
num = 0
for i in range(2, n + 1):
num = (num + m) % i
return num + 1, n * (n + 1) + m * (m - 2) - n * m
| Last and rich in circle | 5bb5e174528b2908930005b5 | [
"Fundamentals",
"Algorithms"
]
| https://www.codewars.com/kata/5bb5e174528b2908930005b5 | 6 kyu |
We have the integer `9457`.
We distribute its digits in two buckets having the following possible distributions (we put the generated numbers as strings and we add the corresponding formed integers for each partition):
```
- one bucket with one digit and the other with three digits
[['9'], ['4','5','7']] --> ['9','457'] --> 9 + 457 = 466
[['9','5','7'], ['4']] --> ['957','4'] --> 957 + 4 = 961
[['9','4','7'], ['5']] --> ['947','5'] --> 947 + 5 = 952
[['9','4','5'], ['7']] --> ['945','7'] --> 945 + 7 = 952
- two buckets with 2 digits each:
[['9','4'], ['5','7']] --> ['94','57'] --> 94 + 57 = 151
[['9','5'], ['4','7']] --> ['95','47'] --> 95 + 47 = 142
[['9','7'], ['4','5']] --> ['97','45'] --> 97 + 45 = 142
```
Now we distribute the digits of that integer in three buckets, and we do the same presentation as above:
```
one bucket of two digits and two buckets with one digit each:
[['9'], ['4'], ['5','7']] --> ['9','4','57'] --> 9 + 4 + 57 = 70
[['9','4'], ['5'], ['7']] --> ['94','5','7'] --> 94 + 5 + 7 = 106
[['9'], ['4', '5'], ['7']] --> ['9','45','7'] --> 9 + 45 + 7 = 61
[['9'], ['5'], ['4','7']] --> ['9','5','47'] --> 9 + 5 + 47 = 61
[['9','5'], ['4'], ['7']] --> ['95','4','7'] --> 95 + 4 + 7 = 106
[['9','7'], ['4'], ['5']] --> ['97','4','5'] --> 97 + 4 + 5 = 106
```
Finally we distribute the digits in the maximum possible amount of buckets for this integer, four buckets, with an unique distribution:
```
One digit in each bucket.
[['9'], ['4'], ['5'], ['7']] --> ['9','4','5','7'] --> 9 + 4 + 5 + 7 = 25
```
In the distribution we can observe the following aspects:
- the order of the buckets does not matter
- the order of the digits in each bucket matters; the available digits have the same order than in the original number.
- the amount of buckets varies from two up to the amount of digits
The function, `f =` `bucket_digit_distributions_total_sum`, gives for each integer, the result of the big sum of the total addition of generated numbers for each distribution of digits.
```python
bucket_digit_distributions_total_sum(9457) === 4301 # 466 + 961 + 952 + 952 + 151 + 142 + 142 + 70 + 106 + 61 + 61 + 106 + 106 + 25 = 4301
```
It is interesting to see the value of this function for a number that has one or more zeroes as digits, for example:
```python
bucket_digit_distributions_total_sum(10001) === 5466
```
Given an integer `n`, with its corresponding value of the above function, `f(n)`, and another integer `z`, find the closest and higher integer to n, `nf`, such `f(nf) > f(n) + z`.
Example:
```python
find(10001,100) === 10003
find(30000, 1000) === 30046
```
Features of the random tests:
```
100 <= n <= 1500000
50 <= z <= 6000
```
Enjoy it!
Javascript and Ruby versions will be released soon! | reference | def subsets(collection):
if len(collection) == 1:
yield [collection]
return
first = collection[0]
for smaller in subsets(collection[1:]):
yield [first] + smaller
for n, subset in enumerate(smaller):
yield smaller[: n] + [first + subset] + smaller[n + 1:]
def bucket_digit_distributions_total_sum(n):
return sum(sum(map(int, sub)) for sub in subsets(str(n))) - n
def find(n, z):
f_nf = bucket_digit_distributions_total_sum(n) + z
while 1:
n += 1
if bucket_digit_distributions_total_sum(n) > f_nf:
return n
| Next Higher Value #2 | 5b74e28e69826c336e00002a | [
"Fundamentals",
"Data Structures",
"Arrays",
"Mathematics",
"Algebra",
"Combinatorics",
"Algorithms"
]
| https://www.codewars.com/kata/5b74e28e69826c336e00002a | 5 kyu |
Your `distributeEvenly` function will take an array as an argument and needs to return a new array with the values distributed evenly.
Example:
Argument:
`['one', 'one', 'two', 'two', 'three', 'three', 'four', 'four']`
Result:
`['one', 'two', 'three', 'four', 'one', 'two', 'three', 'four']`
The underlying order will stay the same as in the original array. So in the case of our argument above, `one` comes before `two` so it stays this way in the returned array.
---
The aim is to have the longest possible chain of evenly distributed values (from the left to right), this means that an argument with many of the same elements might have many which are repeated at the end.
Example:
Argument:
`['one', 'one', 'one', 'one', 'one', 'two', 'three']`
Result:
`[ 'one', 'two', 'three', 'one', 'one', 'one', 'one' ]` | algorithms | from collections import Counter
def distribute_evenly(lst):
count, result = Counter(lst), []
while count:
result . extend(count)
count -= Counter(count . keys())
return result
| Evenly distribute values in array | 5bb50eb68f8bbdb4b300021d | [
"Arrays",
"Sorting",
"Algorithms"
]
| https://www.codewars.com/kata/5bb50eb68f8bbdb4b300021d | 7 kyu |
Meet the Ackermann function:
> <h3> A(m, n, f) = <br>
>   n + f         if m <= 0 <br>
>   A(m - f, 1, f)       if m > 0 and n <= 0 <br>
>   A(m - f, A(m, n - f, f), f)  if m > 0 and n > 0
The Ackermann function is proven to be total recursive, which means that it cannot be implemented in iteration alone. What blasphemy! The challenge for this kata is to implement the Ackermann function without recursion.
The ranges for the inputs are as follows:
> 0 <= n <= 3 <br>
> 0 <= m <= 8 <br>
> 0.9 <= f <= 1.1
https://en.wikipedia.org/wiki/Ackermann_function | games | def hackermann(m, n, f):
stack = []
stack . append(m)
while stack:
m = stack . pop()
if m <= 0:
n = n + f
elif n <= 0:
n = 1
stack . append(m - f)
else:
n = n - f
stack . append(m - f)
stack . append(m)
return n
| Hackermann | 5bb3a707945bd500450001cb | [
"Recursion",
"Puzzles"
]
| https://www.codewars.com/kata/5bb3a707945bd500450001cb | 6 kyu |
Remember the triangle of balls in billiards? To build a classic triangle (5 levels) you need 15 balls. With 3 balls you can build a 2-level triangle, etc.
For more examples,
```
pyramid(1) == 1
pyramid(3) == 2
pyramid(6) == 3
pyramid(10) == 4
pyramid(15) == 5
```
Write a function that takes number of balls (β₯ 1) and calculates how many levels you can build a triangle.
| reference | def pyramid(n):
i = 1
while i <= n:
n = n - i
i += 1
return i - 1
| Billiards triangle | 5bb3e299484fcd5dbb002912 | [
"Mathematics",
"Fundamentals"
]
| https://www.codewars.com/kata/5bb3e299484fcd5dbb002912 | 7 kyu |
# Idea
In the world of graphs exists a structure called "spanning tree". It is unique because it's created not on its own, but based on other graphs. To make a spanning tree out of a given graph you should remove all the edges which create cycles, for example:
```
This can become this or this or this
A A A A
|\ | \ |\
| \ ==> | \ | \
|__\ |__ __\ | \
B C B C B C B C
```
Each *edge* (line between 2 *vertices*, i.e. points) has a weight, based on which you can build minimum and maximum spanning trees (sum of weights of vertices in the resulting tree is minimal/maximal possible).
[Wikipedia article](https://en.wikipedia.org/wiki/Spanning_tree) on spanning trees, in case you need it.
___
# Task
You will receive an array like this: `[["AB", 2], ["BC", 4], ["AC", 1]]` which includes all edges of an arbitrary graph and a string `"min"`/`"max"`. Based on them you should get and return a new array which includes only those edges which form a minimum/maximum spanning trees.
```python
edges = [("AB", 2), ("BC", 4), ("AC", 1)]
make_spanning_tree(edges, "min") ==> [("AB", 2), ("AC", 1)]
make_spanning_tree(edges, "max") ==> [("AB", 2), ("BC", 4)]
```
```javascript
edges = [["AB", 2], ["BC", 4], ["AC", 1]]
makeSpanningTree(edges, "min") ==> [["AB", 2], ["AC", 1]]
makeSpanningTree(edges, "max") ==> [["AB", 2], ["BC", 4]]
```
```ruby
input = [["AB", 2], ["BC", 4], ["AC", 1]]
make_spanning_tree(edges, "min") ==> [["AB", 2], ["AC", 1]]
make_spanning_tree(edges, "max") ==> [["AB", 2], ["BC", 4]]
```
___
# Notes
* All vertices will be connected with each other
* You may receive cycles, for example - `["AA", n]`
* The subject of the test are these 3 values: number of vertices included, total weight, number of edges, but **you should not return them**, there's a special function which will analyze your output instead | algorithms | def make_spanning_tree(edges, t):
edges = sorted(edges, key=lambda x: x[1], reverse=t == 'max')
span, vert = [], {}
for edge in edges:
((a, b), _), (subA, subB) = edge, map(vert . get, edge[0])
if a == b or subA is not None and subA is subB:
continue
if subA and subB:
subA |= subB
for v in subB:
vert[v] = subA
else:
subSpan = subA or subB or set()
for v in (a, b):
subSpan . add(v)
vert[v] = subSpan
span . append(edge)
return span
| Make a spanning tree | 5ae8e14c1839f14b2c00007a | [
"Algorithms",
"Trees",
"Graph Theory"
]
| https://www.codewars.com/kata/5ae8e14c1839f14b2c00007a | 6 kyu |
There are pillars near the road. The distance between the pillars is the same and the width of the pillars is the same.
Your function accepts three arguments:
1. number of pillars (β₯ 1);
2. distance between pillars (10 - 30 meters);
3. width of the pillar (10 - 50 centimeters).
Calculate the distance between the first and the last pillar in centimeters (without the width of the first and last pillar). | reference | def pillars(num_pill, dist, width):
return dist * 100 * (num_pill - 1) + width * (num_pill - 2) * (num_pill > 1)
| Pillars | 5bb0c58f484fcd170700063d | [
"Fundamentals",
"Mathematics"
]
| https://www.codewars.com/kata/5bb0c58f484fcd170700063d | 8 kyu |
# Your Task
Before bridges were common, ferries were used to transport cars across rivers. River ferries, unlike their larger cousins, run on a guide line and are powered by the riverβs current. Cars drive onto the ferry from one end, the ferry crosses the river, and the cars exit from the other end of the ferry.
There is a `length`-meter-long ferry that crosses the river. A car may arrive at either river bank to be transported by the ferry to the opposite bank. The ferry travels continuously back and forth between the banks so long as it is carrying a car or there is at least one car waiting at either bank. Whenever the ferry arrives at one of the banks, it unloads its cargo and loads up cars that are waiting to cross as long as they fit on its deck. The cars are loaded in the order of their arrival; ferryβs deck accommodates only one lane of cars. The ferry is initially on the left bank where it broke and it took quite some time to fix it. In the meantime, lines of cars formed on both banks that await to cross the river.
# Input
Each test case receives an integer `length` and a vector pairs of integers and strings `loads`. Each loads<sub>i</sub> has the length of a
car (in centimeters), and the bank at which the car arrives (βleftβ or βrightβ).
# Output
Return the number of times the ferry has to cross the river in order
to serve all waiting cars.
# Example
```cpp
ferryLoading(20, {{380, "left"},{720, "left"},{1340, "right"},{1040, "left"}}) == 3;
ferryLoading(15, {{380, "left"},{720, "left"},{1340, "left"},{1040, "left"}}) == 5;
```
```python
ferry_loading(20, [(380, "left"), (720, "left"), (1340, "right"), (1040, "left")]) == 3
ferry_loading(10, [(340, "right"), (550, "right"), (420, "left"), (510, "left")]) == 2
```
| reference | def ferry_loading(length, loads):
n, (l, r) = 0, ([t for t, side in loads if side == s]
for s in ['left', 'right'])
while l or r:
n += 1
loaded = 0
while l and loaded + l[0] <= length * 100:
loaded += l . pop(0)
l, r = r, l
return n
| Ferry Loading | 5b9a6d77d16ffeea92000102 | [
"Fundamentals"
]
| https://www.codewars.com/kata/5b9a6d77d16ffeea92000102 | 6 kyu |
In this kata, you're required to simulate the movement of a snake in a given 2D field following a given set of moves. The simulation ends when either of the following conditions is satisfied:
+ All moves have been executed
+ Snake collides with the boundary or with itself.
### Concepts:
+ #### Growth
When the snake encounters a `$` it will grow a segment at its tail, and `$` will disappear from there.
For example
-------- --------
--ooo$-- ===> --oooo--
-------- --------
+ #### Collision
(Here tail is the last segment of the body)
It should be considered that the snake moves successively, that is its head moves to the next cell, then the cell which followed head will move to the cell which was occupied by the head, and so on.
Keeping this in mind, a collision can occur when:
+ Snake collides with the wall of the field
+ Snake collides with itself
+ Snake's head moves into a place which is occupied by its tail after the last move was made.
Example:
Here's a demonstrative example: `H` : head of the snake, `T`: the tail of the snake
```
--------------
---Toooo------ If the snake is directed to move up, it would be considered
---H---o------ a collision
---o---o------
---ooooo------
```
+ #### Movement
The snake will be directed by commands, which can either direct the snake to turns its head or to perform translational motion in the direction of its head.
For controlling the direction of the head, there are 4 commands: `U`, `R`, `L` and `D` which stand for up, right, left, and down respectively, and translation motion which is quantized by steps, which is given as a whole number.
Initially, the snake would be pointing in the right direction `R`.
For example:
`12 D 2 R 2` would translate to
```
move 12 steps right
turn head in the downward direction
move 2 steps downward
turn head in the rightward direction
move 2 steps rightward
```
## Task
```if:python
Write a function `snake_collision` having
```
```if:javascript
Write a function `snakeCollision` having
```
#### Input:
+ `field`: A list/array of strings, in which each string consists of
+ `o`: snake's cell
+ `-`: empty cell
+ `$`: snake's food
Provided fields will abide by the following rules:
+ Height : `13`, Width: `21`
+ Initial size of snake would be always `3`
+ Initially, snake would occupy: `(0, 0), (0, 1), (0, 2)`, snake's head would be at `(0, 2)` and it would be facing in rightward direction `R`
(Here the first element of tuple is the row index and the second element is the column index)
Example of a field:
```
[
'ooo------$--$$$------',
'-----$$$--$--$---$--$',
'-$-----$--$-$---$----',
'------$$$----$---$---',
'--$$--$---------$$---',
'-----$$---$$$--$$--$-',
'----$-----$-$----$--$',
'$-----$-$$---$$---$--',
'$--------------------',
'-------$---$------$-$',
'----$-$$----------$$-',
'--$-$$$--$-$--$-----$',
'$------$--$----------'
]
```
+ `moves`: String which consists of whole numbers and commands `U`, `R`, `L` and `D` separated by spaces.
#### Output
```if:python
You are to return the output in the format: `((row, col), N)`.
```
```if:javascript
You are to return the output in the format: `[[row, col], N]`.
```
Where:
- `row`: Row index of the last location of snake's head
- `col`: Column index of the last location of snake's head
- `N`: Number of steps leading up to and including the collision
| games | from collections import deque
d = {'U': (- 1, 0), 'D': (1, 0), 'L': (0, - 1), 'R': (0, 1)}
def snake_collision(field, moves):
field = [list(x) for x in field]
moves = ['R'] + moves . split()
current_snake = deque([(0, 0), (0, 1), (0, 2)])
HEIGHT, WIDTH = 13, 21
cur_head, step = (0, 2), 0
for token in moves:
if token . isalpha():
facing = d[token]
else:
x, y = cur_head
dx, dy = facing
for i in range(1, int(token) + 1):
xx = x + (dx * i)
yy = y + (dy * i)
if not (0 <= xx < HEIGHT and 0 <= yy < WIDTH) or (xx, yy) in current_snake:
return current_snake . pop(), step + 1
if field[xx][yy] == '$':
field[xx][yy] = '-'
else:
current_snake . popleft()
cur_head = (xx, yy)
current_snake . append(cur_head)
step += 1
return cur_head, step
| Snake Collision | 5ac616ccbc72620a6a000096 | [
"Arrays",
"Games",
"Algorithms",
"Simulation",
"Puzzles"
]
| https://www.codewars.com/kata/5ac616ccbc72620a6a000096 | 5 kyu |
<center><img src="https://i.imgur.com/VE4Jstv.png"></center>
One of my favorite games I played in elementary school (that I may or may not still sometimes play) was <a href= "https://en.wikipedia.org/wiki/Heroes_of_Might_and_Magic_II">Heroes of Might and Magic II: The Succession Wars</a>, a 2D, turn-based RPG. One of the most powerfully offensive spells in the game was chain lightning; striking up to four targets, its first hit does 25 times the caster's spell power, each strike doing half the damage of the previous one.
In the game, the player (or the opponent AI) casts the spell on the enemy creature of their choosing, and it then jumps to the three nearest creatures (the owner doesn't matter after the first strike; your creatures may be struck as well). For simplicity's sake, we're not going to have to calculate distances. Maybe in the next kata :)
# <img src="https://i.imgur.com/pf8JFQu.png"> Instructions:
1) You will be given a 2D array of monster objects, a pair of coordinates indicating the location of the monster the spell is cast at, and your spell power. Each monster group has:
* a type
* an owner (either `'player'` or `'opponent'`)
* a number of hitpoints
* the number of units in the group
* a resistance to lightning spells as a percentage (can be either positive or negative)
```javascript
{type: "Steel Golem", owner: "player", hitpoints: 35, number: 9, resistance: 50}
```
```python
{"type": "Steel Golem", "owner": "player", "hitpoints": 35, "number": 9, "resistance": 50}
```
**NOTE:** A "monster" is merely a container. The example above means there is a group in the player's army which includes 9 'Steel Golem' units (indicated by the `number` property), with a total of 315 hitpoints (9 x 35).
For example, say after resitance checks, the group is hit for 100 damage. The group is left with 215 HP (315-100), representing six unhurt golems and one golem with 5 HP. Looked at another way, 100 damage = 100dmg/35hp, enough damage to kill two (2x35hp), with 30 damage taken by a third golem (which is left with 5hp).
2) After the lightning has struck the first creature, it moves to the next index of the array (left to right). If it finds a target **with resistance less than 100**, it will strike for half the damage of its previous hit, rounded down to the nearest integer. If it doesn't find a target or the target has a resistance of 100, it should pass over it as though it weren't there.
3) If the lightning reaches the end of the row/beginning of the row, it should drop down, at the same column index, and start moving in the opposite direction. For example:
```
-----------------
| > | > | > | V |
-----------------
| V | < | < | < |
-----------------
| > | > | > | > |
-----------------
```
If the lightning runs out of targets, or has struck 3 targets already, it stops. It also never loops back to the top of the array.
Your function should return two arrays of monsters that were killed: the first listing your ones, the other listing your opponent's ones. Each entry in a given array should be a string saying how many troops of a certain type were lost. If no monster dies from a hit, you should not include it.
**NOTE:** you don't have to bother with proper pluralization (`'1 Battle Dwarfs'` is "correct").
___
## Example (properties abbreviated for readability):
```javascript
coordinates = [0,1]
spellpower = 10
monsterArr = [
[ null, { type: "Mage", own: 'you', HP: 30, n: 9, res: 0}, null, { type: "Steel Golem", own: 'opp', HP: 35, n: 6, res: 50 } ],
[ null, null, { type: "Roc", own: 'you', HP: 40, n: 17, res: 0 }, { type: "Sprite", own: 'opp', HP: 2, n: 97, res: 0 } ] ]
// hit "Mage" - 250 dmg
// skip null
// hit "Steel Golem" - 62 dmg (because additional 50% resistance)
// hit "Sprite" - 62 dmg (uninfluenced by Steel Golem's resistance)
// hit "Roc" - 31 dmg
Return [ ['8 Mages'], ['1 Steel Golems', '31 Sprites'] ]
```
```python
coordinates = [0,1]
spellpower = 10
arr = [
[ None, { "type": "Mage", "own": "you", "HP": 30, "n": 9, "res": 0}, None, { "type": "Steel Golem", "own": "opp", "HP": 35, "n": 6, "res": 50 } ],
[ None, None, { "type": "Roc", "own": "you", "HP": 40, "n": 17, "res": 0 }, { "type": "Sprite", "own": "opp", "HP": 2, "n": 97, "res": 0 } ] ]
# hit "Mage" - 250 dmg
# skip None
# hit "Steel Golem" - 62 dmg (because additional 50% resistance)
# hit "Sprite" - 62 dmg (uninfluenced by Steel Golem's resistance)
# hit "Roc" - 31 dmg
Return [ ["8 Mages"], ["1 Steel Golems", "31 Sprites"] ]
``` | reference | from itertools import chain, cycle, islice
def chain_lightning(monsters, coordinates, spellpower):
r, c = coordinates
ms = chain . from_iterable(
row[slice_] for row, slice_ in zip(
islice(monsters, r, None),
chain([slice(c, None)], cycle(
[slice(None, None, - 1), slice(None)]))
)
)
ms = (m for m in ms if m and m['resistance'] < 100)
killed = [[], []]
for i, m in enumerate(islice(ms, 4)):
q = min((25 * spellpower * (100 - m['resistance']) / (2 * * i)) / / (m['hitpoints'] * 100), m['number'])
if q:
killed[m['owner'] != 'player']. append(f' { int ( q )} { m [ "type" ]} s')
return killed
| Heroes of Might & Magic II: Chain Lightning | 5b09cd44ee196bf290000082 | [
"Arrays",
"Games",
"Fundamentals"
]
| https://www.codewars.com/kata/5b09cd44ee196bf290000082 | 6 kyu |
In a factory a printer prints labels for boxes. The printer uses colors which, for the sake of simplicity, are named with letters from a to z (except letters `u`, `w`, `x` or `z` that are for errors).
The colors used by the printer are recorded in a control string. For example a control string would be `aaabbbbhaijjjm` meaning that the printer used three times color a, four times color b, one time color h then one time color a... and so on.
Sometimes there are problems: lack of colors, technical malfunction and a control string is produced e.g. `uuaaaxbbbbyyhwawiwjjjwwxym` where errors are reported with letters `u`, `w`, `x` or `z`.
You have to write a function `hist` which given a string will output the errors as a string representing a histogram of the encountered errors.
Format of the output string:
letter (error letters are sorted in alphabetical order) in a field of 2 characters, a white space, number of error for that letter in a field of 6, as many "*" as the number of errors for that letter and "\r" (or "\n" depending on the langauge).
The string has a length greater or equal to one and contains only letters from `a` to `z`.
#### Examples
```
s="uuaaaxbbbbyyhwawiwjjjwwxym"
hist(s) => "u 2 **\rw 5 *****\rx 2 **"
```
*or with dots to see white spaces:*
```
hist(s) => "u..2.....**\rw..5.....*****\rx..2.....**"
s="uuaaaxbbbbyyhwawiwjjjwwxymzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
hist(s) => "u..2.....**\rw..5.....*****\rx..2.....**\rz..31....*******************************"
```
#### Notes
- Unfortunately most often Codewars compresses all white spaces into one.
- See other examples in the "Sample tests".
| reference | from collections import Counter
ERRORS = 'uwxz'
def hist(s):
cnts = Counter(s)
return '\r' . join(f' { c } { cnts [ c ]: < 6 }{ "*" * cnts [ c ]} ' for c in ERRORS if cnts[c])
| Errors : histogram | 59f44c7bd4b36946fd000052 | [
"Fundamentals",
"Strings"
]
| https://www.codewars.com/kata/59f44c7bd4b36946fd000052 | 6 kyu |
Inspired by another Kata - <a href="http://www.codewars.com/kata/heroes-of-might-and-magic-ii-chain-lightning">Heroes of Might & Magic II: Chain Lightning</a> by Firefly2002, I thought I might have a go at another Kata related to this game.
___
In this Kata, two groups of monsters will attack each other, and your job is to find out who wins. Each group will have a stat for each of the following: number of units, hitpoints per unit, damage per unit, and monster type.
If you are not familiar with the game, just think of each group as standing in a line so that when they are attacked the unit at the front of the line takes the hit before the others, and if he dies the remaining damage will hit the next unit and so on. Therefore multiple units (or even the whole group) can die in one attack.
Each group takes turns attacking, and does so until only one remains. In this kata, the first entry in the input array is the first to attack.
The inputs for this game will be two dictionaries, each with the stats of each monster. Using these stats, calculate which group wins, and how many units in that group stay alive (unless they are undead :P), and return it as a string - formatted as below:
```python
Input:
mon1 = {"type": "Roc", "hitpoints": 40, "number": 6, "damage" : 8 }
mon2 = {"type": "Unicorn", "hitpoints": 40, "number": 4, "damage" : 13}
Output:
"[NUMBER] [TYPE](s) won" # in this case "5 Roc(s) won"
```
```ruby
Note: These are Ruby Objects, not hashes.
Input:
mon1 = Monster.new(type = "Roc", hitpoints = 40, number = 6, damage = 8)
mon2 = Monster.new(type = "Unicorn", hitpoints = 40, number = 4, damage = 13)
Output:
"[NUMBER] [TYPE](s) won" # in this case "5 Roc(s) won"
```
```javascript
Input:
mon1 = {"type": "Roc", "hitpoints": 40, "number": 6, "damage" : 8 };
mon2 = {"type": "Unicorn", "hitpoints": 40, "number": 4, "damage" : 13};
Output:
"[NUMBER] [TYPE](s) won" // in this case "5 Roc(s) won"
```
The damage of each attack is calculated simply as `(number of units) * (damage per unit)`.
You must also take into account that the first unit in the group may injured **BUT** he still attacks with full strength.
___
Fighting mechanics explanation:
```
mon1 = {"type": "Roc", "hitpoints": 40, "number": 6, "damage":8 }
mon2 = {"type": "Unicorn", "hitpoints": 40, "number": 4, "damage":13}
1) The Rocs attack the Unicorns for 48 damage (6 * 8),
killing one and damaging the next - leaving it with 32/40 hitpoints.
2) The remaining 3 Unicorns attack the Rocs for 39 damage (3 * 13),
killing 0 but leaving the first one with only 1/40 hitpoints.
3) Repeat until one of the groups is left with 0 units in total.
``` | reference | from math import ceil
def who_would_win(mon1, mon2):
mon1['allhit'] = mon1['hitpoints'] * mon1['number']
mon2['allhit'] = mon2['hitpoints'] * mon2['number']
while True:
mon2['allhit'] = mon2['allhit'] - mon1['number'] * mon1['damage']
mon2['number'] = ceil(mon2['allhit'] / mon2['hitpoints'])
if not mon2['number'] > 0:
return f" { mon1 [ 'number' ]} { mon1 [ 'type' ]} (s) won"
mon1['allhit'] = mon1['allhit'] - mon2['number'] * mon2['damage']
mon1['number'] = ceil(mon1['allhit'] / mon1['hitpoints'])
if not mon1['number'] > 0:
return f" { mon2 [ 'number' ]} { mon2 [ 'type' ]} (s) won"
| Heroes of Might & Magic II: One-on-One | 5b114e854de8651b6b000123 | [
"Fundamentals"
]
| https://www.codewars.com/kata/5b114e854de8651b6b000123 | 6 kyu |
<style>
#sb {
width: 200px;
margin-bottom: 20px;
}
#sb #sbtd, #sbtitle {
text-align: right;
}
#sb #sbth, #sbtd {
background-color: #0a290a;
color: gold;
}
#sbtitle {
background-color: #0a290a;
color: white;
font-size: 1em;
border-collapse: collapse;
border: 2px solid gray;
padding: 0px 15px 0px 0px;
}
#sb, #sbth, #sbtd {
border-collapse: collapse;
border: 2px solid gray;
padding: 3px 15px 3px 15px;
}
</style>
# Background
Oh No! You have tripped over the power cord of the **Wimbledon Scoreboard** during the Men's Final and all of the numbers have reset to zeroes. You idiot!
<table id="sb">
<tr><th id='sbth'><td id='sbtitle'>Games<td id='sbtitle'>Points</tr>
<tr><th id="sbth">P1<td id="sbtd">0<td id="sbtd">0</tr>
<tr><th id="sbth">P2<td id="sbtd">0<td id="sbtd">0</tr>
</table>
To put things right you need to re-calculate the correct scores for the match, but for some unexplained reason all you have at your disposal is an array representing all the balls the players have hit and whether they landed in or out...
Still, that should be enough... You start coding your solution. But hurry! It needs to be finished before anybody notices.
# Recap of Tennis Scoring
Games (with advantage)
* Tennis scores are `0`, `15`, `30`, `40`, win
* The score of *Deuce* is denoted `40`-`40`
* Player *Advantage* (i.e. after deuce) is denoted `AD`-`40` or `40`-`AD`
https://en.wikipedia.org/wiki/Tennis_scoring_system
# Kata Task
There are two players (P1 and P2).
Return the scoreboard as it stands after all the balls (from input array) are accounted for.
## Input
* `balls` - a boolean array representing if each ball hit landed in (`true`), or out (`false`). Which player hit which ball is something you will need to work out somehow.
## Output
* String arrays representing
* P1 games won, and P1 points in the current game
* P2 games won, and P2 points in the current game
# Notes
* This Kata is **only** about **games**. Do not worry about **sets**
* There are 2 players (P1 and P2)
* Player P1 serves the first game, and thereafter the server will alternate
* If the last known ball landed in, then assume the opponent failed to return it and record the points accordingly
* Don't forget to consider service *Faults*!
* There are no *Lets* or *Line-ball* decisions
# Examples
Ex1. `balls` = [true,false]
<table id="sb">
<tr><th id='sbth'><td id='sbtitle'>Games<td id='sbtitle'>Points</tr>
<tr><th id="sbth">P1<td id="sbtd">0<td id="sbtd">15</tr>
<tr><th id="sbth">P2<td id="sbtd">0<td id="sbtd">0</tr>
</table>
Ex2. `balls` = [true,false,true,false,true,false,true,false,true,false,false,false,false,false]
<table id="sb">
<tr><th id='sbth'><td id='sbtitle'>Games<td id='sbtitle'>Points</tr>
<tr><th id="sbth">P1<td id="sbtd">1<td id="sbtd">30</tr>
<tr><th id="sbth">P2<td id="sbtd">0<td id="sbtd">15</tr>
</table>
Ex3. `balls` = [true,false,true,false,true,false,false,false,false,false,false,false,false,false]
<table id="sb">
<tr><th id='sbth'><td id='sbtitle'>Games<td id='sbtitle'>Points</tr>
<tr><th id="sbth">P1<td id="sbtd">0<td id="sbtd">40</tr>
<tr><th id="sbth">P2<td id="sbtd">0<td id="sbtd">AD</tr>
</table>
<hr>
<div style='color:orange'>
Good Luck!<br>
DM
</div>
| algorithms | PTS = ["0", "15", "30", "40", "AD"]
def formatScores(who, pts, games):
iScore = min(3, pts[who]) + (pts[who] > 3 and pts[who]
> pts[who ^ 1]) # Take care of "AD"
return [str(games[who]), PTS[iScore]]
def wimbledon(balls):
games, pts = [0, 0], [0, 0] # Games score / "in game" score
server, who, isServ = 0, 0, 1 # Server index, player index, is first service?
for i, isIn in enumerate(balls, 1):
if not isIn and isServ:
isServ = 0
continue # Missing first service, keep current player
isServ = isIn ^ 1 # Next move will be or not a first service?
who ^= 1 # Permute players (before counting)
# Last player missed or isIn and last ball: count the points
if not isIn or isIn and i == len(balls):
if isIn:
who ^= 1 # If "is in", this is the last ball and the current player wins the points
pts[who] += 1 # Update point of winner
# Game won: upadte games, pts and change server
if pts[who] > 3 and pts[who] - pts[who ^ 1] > 1:
server ^= 1
games[who] += 1
pts = [0, 0]
who = server # New service to the "current" server
return [formatScores(i, pts, games) for i in range(2)]
| Wimbledon Scoreboard - Game | 5b4bccfabeb865730d000062 | [
"Algorithms"
]
| https://www.codewars.com/kata/5b4bccfabeb865730d000062 | 5 kyu |
Given a random bingo card and an array of called numbers, determine if you have a bingo!
*Parameters*: `card` and `numbers` arrays.
*Example input*:
```
card = [
['B', 'I', 'N', 'G', 'O'],
[1, 16, 31, 46, 61],
[3, 18, 33, 48, 63],
[5, 20, 'FREE SPACE', 50, 65],
[7, 22, 37, 52, 67],
[9, 24, 39, 54, 69]
]
numbers = ['B1', 'I16', 'N31', 'G46', 'O61']
```
*Output*: ```true``` if you have a bingo, ```false``` if you do not.
You have a bingo if you have a complete row, column, or diagonal - each consisting of 5 numbers, or 4 numbers and the FREE SPACE.
### Constraints:
Each column includes 5 random numbers within a range (inclusive):
`'B': 1 - 15`
`'I': 16 - 30`
`'N': 31 - 45`
`'G': 46 - 60`
`'O': 61 - 75`
### Notes:
* All numbers will be within the above ranges.
* `FREE SPACE` will not be included in the numbers array but always counts towards a bingo.
* The first array of the card is the column headers.
* `numbers` array will include only tiles present in the card, without duplicates.
___
## Examples:
```
card:
------------------------------
| B | I | N | G | O |
==============================
| 2 | 17 | 32 | 47 | 74 |
------------------------------
| 14 | 25 | 44 | 48 | 62 |
------------------------------
| 5 | 22 | 'FREE' | 49 | 67 |
------------------------------
| 10 | 23 | 45 | 59 | 73 |
------------------------------
| 1 | 30 | 33 | 58 | 70 |
------------------------------
numbers: ['N32', 'N45', 'B7', 'O75', 'N33', 'N41, 'I18', 'N44']
// return true - you have bingo at ['N32', 'N44', 'FREE', 'N45', 'N33']
```
The inspiration for this kata originates from completing the [Bingo Card](http://www.codewars.com/kata/566d5e2e57d8fae53c00000c) by FrankK.
| reference | def bingo(card, numbers):
# rows count, columns count, diag counts
rc, cc, dc = [0] * 5, [0] * 5, [1] * 2
rc[2] = cc[2] = 1 # preaffect 'FREE SPACE'
s = set(numbers)
for x, line in enumerate(card[1:]):
for y, (c, n) in enumerate(zip(card[0], line)):
tile = f' { c }{ n } '
if tile in s:
rc[x] += 1
cc[y] += 1
if x == y:
dc[0] += 1 # main diag
if x + y == 4:
dc[1] += 1 # secundary diag
return 5 in rc + cc + dc
| Bingo! | 5af304892c5061951e0000ce | [
"Fundamentals",
"Games",
"Arrays"
]
| https://www.codewars.com/kata/5af304892c5061951e0000ce | 6 kyu |
Yup!! The problem name reflects your task; just add a set of numbers. But you may feel yourselves condescended, to write a program just to add a set of numbers. Such a problem will simply question your erudition. So, let's add some flavor of ingenuity to it. Addition operation requires cost now, and the cost is the summation of those two to be added. So, to add `1` and `10`, you need a cost of `11`. If you want to add `1`, `2` and `3`, there are several ways:
```cpp
1 + 2 = 3, cost = 3,
3 + 3 = 6, cost = 6,
Total = 9.
```
```cpp
1 + 3 = 4, cost = 4,
2 + 4 = 6, cost = 6,
Total = 10.
```
```cpp
2 + 3 = 5, cost = 5,
1 + 5 = 6, cost = 6,
Total = 11.
```
I hope you have understood already your mission: to add a set of integers so that the cost is minimal.
# Your Task
Given a vector of integers, return the minimum total cost of addition.
~~~if:lambdacalc
# Encodings
purity: `LetRec`
numEncoding: `Scott`
export constructors `nil, cons` for your `List` encoding
~~~
| reference | from heapq import *
def add_all(lst):
heapify(lst)
total = 0
while len(lst) > 1:
s = heappop(lst) + heappop(lst)
total += s
heappush(lst, s)
return total
| Add All | 5b7d7ce57a0c9d86c700014b | [
"Fundamentals",
"Mathematics"
]
| https://www.codewars.com/kata/5b7d7ce57a0c9d86c700014b | 6 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;
1a. Or take the stairs to m floor;
2. Waiting the elevator open the door and go in;
3. Waiting the elevator close the door;
4. Waiting the elevator down to 0 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(0-based).
m: An integer. The floor of the elevator(0-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 or n+1 floor
```
Please help John to calculate the shortest time to go downstairs.
# Example
For `n = 4, m = 5 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 = 0, m = 5 and speeds = [1,2,3,10]`, the output should be `0`.
John is already at `0` floor, so the output is `0`.
For `n = 4, m = 3 and speeds = [2,3,4,5]`, the output should be `20`.
John go downstairs by walking:
`5 x 4 = 20`
For `n = 7, m = 6 and speeds = [3,1,1,4]`, the output should be `25`.
John walks down 1 floor and takes the elevator from there.
`1Γ4 + 1 + 1 + 6Γ3 + 1 = 25`
Pure walk would have taken `7Γ4 = 28`; pure elevator would have taken `1Γ3 + 1 + 1 + 7Γ3 + 1 = 27`.
# Note
These are Dutch floors. They are numbered 0-based. (`0` is usually called "begane grond".) | reference | def shorterest_time(n, m, speeds):
if n == 0:
return 0
a, b, c, d = speeds
return min(
n * d,
abs(n - m) * d + b * 2 + c + m * a,
abs(n - m) * a + b * 2 + c + n * a
)
| Simple Fun #326a: The Shorterest Time | 5953c6f8af7ac14fd4000021 | [
"Puzzles",
"Games",
"Fundamentals"
]
| https://www.codewars.com/kata/5953c6f8af7ac14fd4000021 | 6 kyu |
# History
This kata is a sequel of my [Mixbonacci](https://www.codewars.com/kata/mixbonacci/python) kata. Zozonacci is a special integer sequence named after [**ZozoFouchtra**](https://www.codewars.com/users/ZozoFouchtra), who came up with this kata idea in the [Mixbonacci discussion](https://www.codewars.com/kata/mixbonacci/discuss/python).
This sequence combines the rules for computing the n-th elements of fibonacci, jacobstal, pell, padovan, tribonacci and tetranacci sequences according to a given pattern.
# Task
Compute the first `n` elements of the Zozonacci sequence for a given pattern `p`.
## Rules
1. `n` is given as integer and `p` is given as a list of as abbreviations as strings (e.g. `["fib", "jac", "pad"]`)
2. When `n` is 0 or `p` is empty return an empty list.
3. The first four elements of the sequence are determined by the first abbreviation in the pattern (see the table below).
4. Compute the fifth element using the formula corespoding to the first element of the pattern, the sixth element using the formula for the second element and so on. (see the table below and the examples)
5. If `n` is more than the length of `p` repeat the pattern.
```
+------------+--------------+------------------------------------------+---------------------+
| sequence | abbreviation | formula for n-th element | first four elements |
+------------|--------------+------------------------------------------|---------------------|
| fibonacci | fib | a[n] = a[n-1] + a[n-2] | 0, 0, 0, 1 |
| jacobsthal | jac | a[n] = a[n-1] + 2 * a[n-2] | 0, 0, 0, 1 |
| padovan | pad | a[n] = a[n-2] + a[n-3] | 0, 1, 0, 0 |
| pell | pel | a[n] = 2 * a[n-1] + a[n-2] | 0, 0, 0, 1 |
| tetranacci | tet | a[n] = a[n-1] + a[n-2] + a[n-3] + a[n-4] | 0, 0, 0, 1 |
| tribonacci | tri | a[n] = a[n-1] + a[n-2] + a[n-3] | 0, 0, 0, 1 |
+------------+--------------+------------------------------------------+---------------------+
```
## Example
```
zozonacci(["fib", "tri"], 7) == [0, 0, 0, 1, 1, 2, 3]
Explanation:
b d
/-----\/----\
[0, 0, 0, 1, 1, 2, 3]
\--------/
| \--------/
a c
a - [0, 0, 0, 1] as "fib" is the first abbreviation
b - 5th element is 1 as the 1st element of the pattern is "fib": 1 = 0 + 1
c - 6th element is 2 as the 2nd element of the pattern is "tri": 2 = 0 + 1 + 1
d - 7th element is 3 as the 3rd element of the pattern is "fib" (see rule no. 5): 3 = 2 + 1
```
## Sequences
* [fibonacci](https://oeis.org/A000045) : 0, 1, 1, 2, 3 ...
* [padovan](https://oeis.org/A000931): 1, 0, 0, 1, 0 ...
* [jacobsthal](https://oeis.org/A001045): 0, 1, 1, 3, 5 ...
* [pell](https://oeis.org/A000129): 0, 1, 2, 5, 12 ...
* [tribonacci](https://oeis.org/A000073): 0, 0, 1, 1, 2 ...
* [tetranacci](https://oeis.org/A000078): 0, 0, 0, 1, 1 ...
| reference | from itertools import cycle
ROOT = {'fib': [0, 0, 0, 1],
'jac': [0, 0, 0, 1],
'pad': [0, 1, 0, 0],
'pel': [0, 0, 0, 1],
'tet': [0, 0, 0, 1],
'tri': [0, 0, 0, 1]}
GEN = {'fib': lambda a: a[- 1] + a[- 2],
'jac': lambda a: a[- 1] + 2 * a[- 2],
'pad': lambda a: a[- 2] + a[- 3],
'pel': lambda a: 2 * a[- 1] + a[- 2],
'tet': lambda a: a[- 1] + a[- 2] + a[- 3] + a[- 4],
'tri': lambda a: a[- 1] + a[- 2] + a[- 3]}
def zozonacci(pattern, n):
if not pattern or not n:
return []
lst = ROOT[pattern[0]][:]
cycl = cycle(map(GEN . get, pattern))
for f, _ in zip(cycl, range(n - 4)):
lst . append(f(lst))
return lst[: n]
| Zozonacci | 5b7c80094a6aca207000004d | [
"Fundamentals",
"Algorithms"
]
| https://www.codewars.com/kata/5b7c80094a6aca207000004d | 6 kyu |
You are in the capital of Far, Far Away Land, and you have heard about this museum where the royal family's crown jewels are on display. Before you visit the museum, a friend tells you to bring some extra money that you'll need to bribe the guards. You see, he says, the crown jewels are in one of 10 rooms numbered from 1 to 10. The doors to these room are kept closed, and each is guarded by a very intimidating guard.
For security purposes, the jewels are moved every night to a different room. To find out which room they are in, you'll have to ask one of the guards. But first you have to pay him a bribe. After paying him:
1. If the jewels are behind the door he's guarding, he'll let you in.
2. Otherwise, he'll point you in the direction of the correct room by telling you if the room has a higher or lower room number than the room he's guarding.
The guards have a special rank system, and, depending on rank, the size of the bribe that you'll need to pay to each guard may vary. For example, you may have to pay $1 to the guard at room 1, $2 to the guard at room 2, and so on, up to $10 to the guard at room 10. The bribe amounts are specified by an array/list sorted by room number in ascending order. Hence, in this example, the bribes are given by `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]`.
The problem you need to solve is to determine the minimum amount you may need _in the worst case_ to get into the room with the crown jewels. As a seasoned programmer, you might try doing a binary search. Let's assume that the bribes are as specified in the example above. You first go to the guard standing in front of room 5, and pay him $5. In the worst case the crown jewels are in room 10 and you'll end up paying: $5 + $8 + $9 + $10 = $32. It turns out that a regular binary search is not optimal in this case. You are better off if you first go to room 7. In the worst case the guard will direct you to the right(i.e., higher numbered rooms) and then you go to room 9. Again, in the worst case the guard will direct you to the right, and you go to room 10. In all, you'll have to pay $7 + $9 + $10 = $26. You can easily verify that if the first guard (at room 7) had directed you to the left, you would have ended up paying less than $26. So for this problem, the maximum you will need to pay is $26. There are no other solutions where you would need less in the worst case, so 26 is the solution to this problem instance.
You are asked to define function `least_bribes(bribes)` that takes as argument an array that contains the bribes that each guard will accept in ascending room number and returns the minumum amount you'll need to spend on bribes _in the worst case_. The problem is not limited to 10 rooms only, so the array `bribes` can be of any length greater or equal to 1. Your code will have to handle arrays up to 100 in length and bribes between $1 and $1000.
| reference | def least_bribes(bribes):
mem = {}
def s(n1, n2):
if n1 >= n2:
return 0
if (n1, n2) in mem:
return mem[n1, n2]
r = min(bribes[i] + max(s(n1, i), s(i + 1, n2)) for i in range(n1, n2))
mem[n1, n2] = r
return r
return s(0, len(bribes))
| Bribe the Guards of the Crown Jewels | 56d5078e945d0d5d35001b74 | [
"Dynamic Programming",
"Algorithms"
]
| https://www.codewars.com/kata/56d5078e945d0d5d35001b74 | 4 kyu |
SHA-1 is arguably the most widely used hash algorithm in the world at the moment. However, due to speculation that the hash algorithm will be broken soon, it will be eventually phased out (It has been broken; see https://www.theverge.com/2017/2/23/14712118/google-sha1-collision-broken-web-encryption-shattered). Nonetheless, it is definitely worth learning since it is extremely similar to its successor, SHA-2, which is still believed to be secure. If you would like to learn more about SHA-1, I'd recommend scanning the [Wikipedia page](https://en.wikipedia.org/wiki/SHA-1) but even better is [this lecture](https://www.youtube.com/watch?v=5q8q4PhN0cw) on how SHA-1 works.
Here is a general outline of the algorithm:
Initial constants/variables:
* H0 = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0], these will serve as the initial hash values, also called registers. They will also be reffered to individually as A, B, C, D, and E, respectively.
* K = [0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6], these will serve as constants used in the compression phase
The Four Functions:
* F1(B, C, D) = (B & C) | ((~B) & D)
* F2(B, C, D) = B ^ C ^ D
* F3(B, C, D) = (B & C) | (B & D) | (C & D)
* F4(B, C, D) = B ^ C ^ D
_Note_: & is the bitwise AND operator, | is the bitwise OR operator, ^ is the bitwise XOR (exclusive OR) operator, and ~ is the bitwise NOT operator.
Pre-Processing:
1. Given an input M, determine its length in bits.
2. Break the input M into 512-bit chunks, maintaining the original order.
3. At the end of the last chunk, add a 1-bit (unless the chunk is already 512-bits, in which case start a new chunk with a 1 bit).
4. Pad this chunk with enough 0 bits so that the chunk has exactly 64 bits left at the end. In other words, fill the chunk until it is 448 bits long.
5. Complete the last chunk by appending a 64-bit representation of the original bit length measured at the beginning.
Compression:
Repeat the following steps for each chunk in order:
1. Split the current chunk into 16 32-bit words. However, you will need a total of 80 words. Compute the following 64 words using the following formula where leftrotate is a function that rotates the bits of its first argument by an amount specified in its second:
w[i] = leftrotate(w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16], 1)
2. Save the current values of H0 aka A, B, C, D, and E.
3. The compression function consists of 80 rounds, which is split into four equal 20-round stages. A, B, C, D, and E are fed into the compression function and are modified. Parts of the compression function depend on what stage it is.
4. At the end of 80 rounds, add the new A, B, C, D, and E values to their values from the start of the 80 rounds, applying modulo 2^32. The following is a depiction of a round in the compression function:

The F represents one of the F functions (F1 for stage 1, F2 for stage 2, etc.), the <<<n represents a left bit rotation by n bits, the red crossed squares represent addition modulo 2^32, Kt represents the K constant for the t'th stage, and Wt stands for the Wth word of the chunk.
Completion:
1. Once every chunk has been processed, concatenate the bits of A, B, C, D, and E together and the resulting value is the hash value. You can also convert the 5 registers into hex strings and concatenate those, since hash values are often given in hex string format.
Implement this without cheating! No using built-in hash libraries/modules! Assume that message input is always of type `bytes`, and return `bytes` too. | algorithms | class SHA1:
def __init__(self):
self . message = []
self . H = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]
self . K = [0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6]
self . F = [lambda b, c, d: (b & c) | ((~ b) & d),
lambda b, c, d: b ^ c ^ d,
lambda b, c, d: (b & c) | (b & d) | (c & d),
lambda b, c, d: b ^ c ^ d]
def update(self, message):
self . message . extend(SHA1 . to_bits(message))
def digest(self):
chunks = SHA1 . pre_process(self . message)
for chunk in chunks:
self . process_chunk(chunk)
return str . encode('' . join(hex(h)[2:]. zfill(8) for h in self . H))
def to_bits(bytes):
bits = []
for b in bytes:
bits . extend(int(x) for x in bin(b)[2:]. zfill(8))
return bits
def pre_process(message):
original_message_length = len(message)
message . append(1)
message . extend([0] * ((448 - len(message) % 512) % 512))
size = SHA1 . to_bits([original_message_length])
message . extend([0] * (64 - len(size)) + size)
chunks = [message[i: i + 512] for i in range(0, len(message), 512)]
return chunks
def left_rotate(n, m):
return (n << m | n >> (32 - m)) % 2 * * 32
def process_chunk(self, chunk):
a, b, c, d, e = self . H
W = [chunk[i: i + 32] for i in range(0, 512, 32)]
W = list(map(lambda x: int('' . join(map(str, x)), 2), W))
for i in range(16, 80):
W . append(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16])
W[i] = SHA1 . left_rotate(W[i], 1)
for i in range(80):
temp = e + self . F[i / / 20](b, c, d) + SHA1 . left_rotate(a, 5) + W[i] + self . K[i / / 20]
e = d
d = c
c = SHA1 . left_rotate(b, 30)
b = a
a = temp % 2 * * 32
self . H = [(self . H[i] + [a, b, c, d, e][i]) % (2 * * 32) for i in range(5)]
| Implementing SHA-1 | 56f2f3dfe40b70a005001389 | [
"Cryptography",
"Algorithms"
]
| https://www.codewars.com/kata/56f2f3dfe40b70a005001389 | 4 kyu |
In this Kata, you will be given boolean values and boolean operators. Your task will be to return the number of arrangements that evaluate to `True`.
`t,f` will stand for `true, false` and the operators will be `Boolean AND (&), OR (|), and XOR (^)`.
For example, `solve("tft","^&") = 2`, as follows:
* `"((t ^ f) & t)" = True`
* `"(t ^ (f & t))" = True`
Notice that the order of the boolean values and operators does not change. What changes is the position of braces.
More examples in the test cases.
Good luck!
| algorithms | from functools import lru_cache
from operator import and_, or_, xor
FUNCS = {'|': or_, '&': and_, '^': xor}
def solve(s, ops):
@ lru_cache(None)
def evaluate(s, ops):
c = [0, 0]
if not ops:
c[s == 't'] += 1
else:
for i in range(len(ops)):
for v, n in enumerate(evaluate(s[: i + 1], ops[: i])):
for w, m in enumerate(evaluate(s[i + 1:], ops[i + 1:])):
c[FUNCS[ops[i]](v, w)] += n * m
return c
return evaluate(s, ops)[True]
| The boolean order | 59eb1e4a0863c7ff7e000008 | [
"Strings",
"Algorithms"
]
| https://www.codewars.com/kata/59eb1e4a0863c7ff7e000008 | 3 kyu |
# Telephone numbers
When you start to enter a phone number, the smartphone proposes you some choices of possible phone numbers from your repertory.
The goal of this kata is to save the phone numbers by keeping in common the same parts of the phone numbers thus reducing the total size of the repertory.
# Goal
Your function will take in arguments an array of phone numbers. (Of at least one element);
A phone number contains at least one digit and can contains up to 20 digits.
You must return the number of elements your graph contains.
You must not modify the input array.
# Example :
We have the following phone numbers :
0123456789
0123987654
0123987456
2365498756
2365498765
This gives the following graphs :
```
4 - 5 - 6 - 7 - 8 - 9
0 - 1 - 2 - 3 <
\ 4 - 5 - 6
9 - 8 - 7 <
6 - 5 - 4
6 - 5
2 - 3 - 6 - 5 - 4 - 9 - 8 - 7 <
5 - 6
```
The graphs contains 31 elements.
So the function must return 31 | games | def phone_number(phone_numbers):
return len({num[: i] for num in phone_numbers for i in range(1, len(num) + 1)})
| Phone numbers | 582b59f45ad9526ae6000249 | [
"Puzzles",
"Graph Theory"
]
| https://www.codewars.com/kata/582b59f45ad9526ae6000249 | 5 kyu |
Your wizard cousin works at a Quidditch stadium and wants you to write a function that calculates the points for the Quidditch scoreboard!
# Story
Quidditch is a sport with two teams. The teams score goals by throwing the Quaffle through a hoop, each goal is worth **10 points**.
The referee also deducts 30 points (**- 30 points**) from the team who are guilty of carrying out any of these fouls: Blatching, Blurting, Bumphing, Haverstacking, Quaffle-pocking, Stooging
The match is concluded when the Snitch is caught, and catching the Snitch is worth **150 points**. Let's say a Quaffle goes through the hoop just seconds after the Snitch is caught, in that case the points of that goal should not end up on the scoreboard seeing as the match is already concluded.
You don't need any prior knowledge of how Quidditch works in order to complete this kata, but if you want to read up on what it is, here's a link: https://en.wikipedia.org/wiki/Quidditch
# Task
You will be given a string with two arguments, the first argument will tell you which teams are playing and the second argument tells you what's happened in the match. Calculate the points and return a string containing the teams final scores, with the team names sorted in the same order as in the first argument.
# Examples:
# Given an input of:
```javascript
quidditchScoreboard("Ilkley vs Yorkshire", "Ilkley: Quaffle goal, Yorkshire: Haverstacking foul, Yorkshire: Caught Snitch")
```
# The expected output would be:
```javascript
"Ilkley: 10, Yorkshire: 120"
```
Separate the team names from their respective points with a colon and separate the two teams with a comma.
Good luck!
| reference | def quidditch_scoreboard(teams, actions):
teams = {i: 0 for i in teams . split(' vs ')}
for i in actions . split(', '):
team, action = i . split(': ')
if 'goal' in action:
teams[team] += 10
elif 'foul' in action :
teams [ team ] -= 30
elif 'Snitch' in action :
teams [ team ] += 150
break
return ', ' . join ( '{}: {}' . format ( i , teams [ i ]) for i in teams ) | Quidditch Scoreboard | 5b62f8a5b17883e037000136 | [
"Fundamentals",
"Strings",
"Algorithms"
]
| https://www.codewars.com/kata/5b62f8a5b17883e037000136 | 6 kyu |
We are interested in obtaining two scores from a given integer:
**First score**: The sum of all the integers obtained from the power set of the digits of the given integer that have the same order
E.g:
```
integer = 1234 ---> (1 + 2 + 3 + 4) + (12 + 13 + 14 + 23 + 24 + 34) +
(123 + 124 + 134 + 234) + 1234 = 10 + 120 + 615 + 1234 = 1979
```
**Second score**: The sum of all the integers obtained from the all the contiguous substrings of the given integer as a string.
E.g.
```
integer = 1234 ---> (1 + 2 + 3 + 4) + (12 + 23 + 34) + (123 + 234) + 1234 = 10 + 69 + 357 + 1234 = 1670
```
The first integer, higher than ```100```, that has both scores with ```3``` common divisors is ```204```. Its first score is ```258``` and the second one ```234```. The common divisors for both scores are ```2, 3, 6```.
In fact the integers ```294``` and ```468``` are the ones in the range ```[100, 500]```, that have both scores with ```7``` common divisors, the maximum amount of common factors in that range.
Your task in this kata is to create a function that may find the integer or integers that have the maximum amount of common divisors for the scores described above.
The example given above will be:
```python
find_int_inrange(100, 500) == [7, 294, 468]
```
As you can see, the function should receive the limits of a range [a, b], and outputs an array with the maximum amount of factors, ```max_am_div``` and the found numbers sorted
```
find_int_inrange(a, b) ----> [max_am_div, k1, k2, ...., kn] # k1 < k2 < ...< kn
```
The function may output only one number.
```python
find_int_inrange(100, 300) == [7, 294]
```
Enjoy it!
Features of the random tests:
```
100 < a < b < 55000
```
| reference | def score(sub_gen): return lambda n: sum(int('' . join(sub))
for length in range(1, len(str(n)) + 1) for sub in sub_gen(str(n), length))
score1 = score(__import__('itertools'). combinations)
score2 = score(lambda s, r: (s[i: i + r] for i in range(len(s) - r + 1)))
def divs(n): return set . union(* ({d, n / / d} for d in range(1, int(n * * .5) + 1) if not n % d)) - {1, n}
def find_int_inrange(a, b):
div_range = [0]
for n in range(a, b + 1):
common_divisors = divs(score1(n)) & divs(score2(n))
if len(common_divisors) > div_range[0]:
div_range = [len(common_divisors)]
if len(common_divisors) == div_range[0]:
div_range . append(n)
return div_range
| What Would They Have in Common? | 58e8561f06db4d4cc600008c | [
"Mathematics",
"Strings",
"Data Structures",
"Sorting",
"Performance",
"Algorithms",
"Fundamentals"
]
| https://www.codewars.com/kata/58e8561f06db4d4cc600008c | 5 kyu |
Based on [this kata, Connect Four.](https://www.codewars.com/kata/connect-four-1)
In this kata we play a modified game of connect four. It's connect X, and there can be multiple players.
Write the function ```whoIsWinner(moves,connect,size)```.
```2 <= connect <= 10```
```2 <= size <= 52```
Each column is identified by a character, A-Z a-z:
``` ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ```
Moves come in the form:
```
['C_R','p_Y','s_S','I_R','Z_Y','d_S']
```
* Player R puts on C
* Player Y puts on p
* Player S puts on s
* Player R puts on I
* ...
The moves are in the order that they are played.
The first player who connect ``` connect ``` items in same color is the winner.
Note that a player can win before all moves are done. You should return the first winner.
If no winner is found, return "Draw".
A board with size 7, where yellow has connected 4:
All inputs are valid, no illegal moves are made.
 | algorithms | from string import ascii_lowercase, ascii_uppercase
char_to_index = {c: i for i, c in enumerate(ascii_uppercase + ascii_lowercase)}
# assumes a space character isn't used to represent a player
def who_is_winner(moves, connect_size, size):
board, winner = [[' ' for i in range(size)] for j in range(size)], ''
def check_for_winner(i, j):
char = board[i][j]
def count_length(delta_x, delta_y):
x, y, count = i + delta_x, j + delta_y, 0
while 0 <= x < size and 0 <= y < size and board[x][y] == char:
x, y, count = x + delta_x, y + delta_y, count + 1
return count
search_pairs = (((- 1, 0), (1, 0)), ((0, 1), (0, - 1)),
((1, 1), (- 1, - 1)), ((- 1, 1), (1, - 1)))
for a, b in search_pairs:
if count_length(a[0], a[1]) + 1 + count_length(b[0], b[1]) >= connect_size:
return char
return ''
for m in moves:
char, player = m . split('_')
i = char_to_index[char]
j = board[i]. index(' ')
board[i][j] = player
winner = check_for_winner(i, j)
if winner:
break
return winner if winner else "Draw"
| NxN Connect X | 5b442a063da310049b000047 | [
"Games",
"Arrays",
"Algorithms"
]
| https://www.codewars.com/kata/5b442a063da310049b000047 | 5 kyu |
Given an array of integers, find the minimum number of elements to remove from the array so that the square root of the largest integer in the array is less or equal to the smallest number in the same array.
`x` = smallest integer in the array
`y` = largest integer in the array
Find the minimum number of elements to remove so, βy β€ x.
### Example
```cpp
A = {3, 6, 5, 9, 16}
```
```python
A = [3, 6, 5, 9, 16]
```
`min=3`
`max=16`
`β16 > 3`
remove 16, so largest element becomes 9.
`β9 β€ 3`
so
```cpp
minRemove(A) = 1
```
```python
min_remove(A) = 1
```
since only `16` was removed.
## Note
- If all integers in the array are equal, then it wouldnt make any sense to reduce the array any further, so return 0.
<br>
<br>
```cpp
minRemove({2}) //=> 0
minRemove({6,6,6,6}) //=> 0
minRemove({6,6,6,2}) //=> 1
```
```python
min_remove([2]) #=> 0
min_remove([6,6,6,6]) #=> 0
min_remove([6,6,6,2]) #=> 1
```
## Constraints
```if:cpp
### 1 <= |A| <= 10<sup>5</sup>
```
```if:python
### 1 <= |A| <= 10<sup>4</sup>
```
| algorithms | from bisect import bisect_left
from math import sqrt
def min_remove(xs):
xs = sorted(xs)
return min(bisect_left(xs, sqrt(x)) + nr for nr, x in enumerate(reversed(xs)))
| Minimum Reduction | 5ba47374b18e382069000052 | [
"Algorithms"
]
| https://www.codewars.com/kata/5ba47374b18e382069000052 | 6 kyu |
This kata was seen in programming competitions with a wide range of variations.
A strict bouncy array of numbers, of length three or longer, is an array that each term (neither the first nor the last element) is strictly higher or lower than its neighbours.
For example, the array:
```
arr = [7,9,6,10,5,11,10,12,13,4,2,5,1,6,4,8] (length = 16)
```
The two longest bouncy subarrays of arr are
```
[7,9,6,10,5,11,10,12] (length = 8) and [4,2,5,1,6,4,8] (length = 7)
```
According to the given definition, the arrays ```[8,1,4,6,7]```, ```[1,2,2,1,4,5]```, are not bouncy.
For the special case of length 2 arrays, we will consider them strict bouncy if the two elements are different.
The arrays ```[-1,4]``` and ```[0,-10]``` are both bouncy, while ```[0,0]``` is not.
An array of length 1 will be considered strict bouncy itself.
You will be given an array of integers and you should output the longest strict bouncy subarray.
In the case of having more than one bouncy subarray of same length, it should be output the subarray with its first term of lowest index in the original array.
Let's see the result for the first given example.
```
arr = [7,9,6,10,5,11,10,12,13,4,2,5,1,6,4,8]
longest_bouncy_list(arr) === [7,9,6,10,5,11,10,12]
```
See more examples in the example tests box.
Features of the random tests
```
length of the array inputs up to 1000
-500 <= arr[i] <= 500
```
Enjoy it!
| reference | def longest_bouncy_list(arr):
sub, maxSub = [], []
for v in arr:
if not sub or v != sub[- 1] and (len(sub) == 1 or (sub[- 1] - sub[- 2]) * (sub[- 1] - v) > 0):
sub . append(v)
else:
sub = sub[- 1:] + [v] if v != sub[- 1] else [v]
if len(sub) > len(maxSub):
maxSub = sub
return maxSub
| Longest Strict Bouncy Subarray | 5b483e70a4bc16eda40000f9 | [
"Performance",
"Algorithms",
"Mathematics",
"Data Structures",
"Arrays"
]
| https://www.codewars.com/kata/5b483e70a4bc16eda40000f9 | 6 kyu |
Implement a function which takes a string, and returns its hash value.
Algorithm steps:
* `a` := sum of the ascii values of the input characters
* `b` := sum of every difference between the consecutive characters of the input (second char minus first char, third minus second, ...)
* `c` := (`a` OR `b`) AND ((NOT `a`) shift left by 2 bits)
* `d` := `c` XOR (32 * (`total_number_of_spaces` + 1))
* return `d`
**Note**: OR, AND, NOT, XOR are bitwise operations.
___
### Examples
```
input = "a"
a = 97
b = 0
result = 64
input = "ca"
a = 196
b = -2
result = -820
```
___
Give an example why this hashing algorithm is bad? | reference | def string_hash(s):
a = sum(ord(c) for c in s)
b = sum(ord(b) - ord(a) for a, b in zip(s, s[1:]))
c = (a | b) & (~ a << 2)
return c ^ (32 * (s . count(" ") + 1))
| BAD Hash - String to Int | 596d93bd9b6a5df4de000049 | [
"Fundamentals"
]
| https://www.codewars.com/kata/596d93bd9b6a5df4de000049 | 7 kyu |
# Your Task
You have a cuboid with dimensions x,y,z β β. The values of x, y, and z are between 1 and 10^9. A subcuboid of this cuboid has dimensions length, width, height β β where 1β€lengthβ€x, 1β€widthβ€y, 1β€heightβ€z. If two subcuboids have the same length, width, and height, but they are at different positions within the cuboid, they are distinct. Find the total number of subcuboids for the given cuboid.
# Examples
See sample tests and the image below
### 27 subcuboids for a 2Γ2Γ2 cuboid

| games | def subcuboids(x, y, z):
return x * y * z * (x + 1) * (y + 1) * (z + 1) / / 8
| Subcuboids | 5b9e29dc1d5ed219910000a7 | [
"Mathematics",
"Puzzles",
"Performance"
]
| https://www.codewars.com/kata/5b9e29dc1d5ed219910000a7 | 7 kyu |
Find the most adjacent integers of the same value in a grid (2D array). Integers are only considered adjacent to their neighbors vertically and horizontally, not diagonally.
If there are different integers with the same amount of adjacent neighbors, choose the smallest integer for the answer.
Input:
N x N 2D array of integers
Output:
Tuple with the first item being the integer with the most adjacent neighbors of the same value and the second item being the amount of that integer and its neighbors of the same value.
Example:
```python
# Input:
grid = [
[1,2,1],
[1,1,0],
[0,0,0],
]
# Output:
(0, 4)
```
| algorithms | from collections import defaultdict
def find_most_adjacent(grid):
seeds, seens, N = defaultdict(list), set(), len(grid)
for x, row in enumerate(grid):
for y, v in enumerate(row):
if (x, y) in seens:
continue # Already filled, go to the next
seeds[v]. append(0) # Initiate the new seed count
bag = {(x, y)} # New flood-fill seed
while bag:
seens |= bag # Archive
seeds[v][- 1] += len(bag) # Update domain count
bag = {(xx, yy) for xx, yy in ((x + dx, y + dy) for x, y in bag # Get neighbours
for dx, dy in [(0, 1), (0, - 1), (1, 0), (- 1, 0)])
if 0 <= xx < N and 0 <= yy < N # Neighbours in the grid...
and v == grid[xx][yy] and (xx, yy) not in seens} # ...with the seed value and not already filled
# Seek for the highest count of the lowest seed integer
return max(((k, max(lst)) for k, lst in seeds . items()), key=lambda t: (t[1], - t[0]))
| Find the most adjacent integers of the same value in a grid | 5b258cf6d74b5b7105000035 | [
"Algorithms"
]
| https://www.codewars.com/kata/5b258cf6d74b5b7105000035 | 5 kyu |
You are given a (small) check book as a - sometimes - cluttered (by non-alphanumeric characters) string:
```
"1000.00
125 Market 125.45
126 Hardware 34.95
127 Video 7.45
128 Book 14.32
129 Gasoline 16.10"
```
The first line shows the original balance.
Each other line (when not blank) gives information: check number, category, check amount.
(Input form may change depending on the language).
First you have to clean the lines keeping only letters, digits, dots and spaces.
Then return a report as a string (underscores show spaces -- don't put them in your solution. They are there so you can see them and how many of them you need to have):
```
"Original_Balance:_1000.00
125_Market_125.45_Balance_874.55
126_Hardware_34.95_Balance_839.60
127_Video_7.45_Balance_832.15
128_Book_14.32_Balance_817.83
129_Gasoline_16.10_Balance_801.73
Total_expense__198.27
Average_expense__39.65"
```
On each line of the report you have to add the new balance and then in the last two lines the total expense and the average expense.
So as not to have a too long result string we don't ask for a properly formatted result.
#### Notes
- See input examples in Sample Tests.
- It *may* happen that one (or more) line(s) is (are) blank.
- Round to 2 decimals your calculated results (Elm: without traling 0)
- The line separator of results may depend on the language `\n` or `\r\n`. See examples in the "Sample tests".
- R language: Don't use R's base function "mean()" that could give results slightly different from expected ones.
| reference | import re
PATTERN = re . compile(r'([\d.]+)[^\w\n]*([a-zA-Z]+)[^\w\n]*([\d.]+)')
def balance(book):
balance, lst, (b, s) = 0, [], book . split('\n', 1)
iBal = balance = float(next(re . finditer(r'[\d.]+', b)). group())
lst . append("Original Balance: {:.2f}" . format(balance))
for num, item, amount in PATTERN . findall(s):
amount = float(amount)
balance -= amount
lst . append("{} {} {:.2f} Balance {:.2f}" . format(
num, item, amount, balance))
lst . append("Total expense {:.2f}\r\nAverage expense {:.2f}" . format(
iBal - balance, (iBal - balance) / (len(lst) - 1)))
return '\r\n' . join(lst)
| Easy Balance Checking | 59d727d40e8c9dd2dd00009f | [
"Fundamentals",
"Strings"
]
| https://www.codewars.com/kata/59d727d40e8c9dd2dd00009f | 6 kyu |

The walker
The walker starts from point O, walks along OA, AB and BC. When he is in C (C will be in the upper half-plane), what is the distance `CO`? What is the angle `tOC` in positive degrees, minutes, seconds?
Angle `tOA` is `alpha` (here 45 degrees), angle `hAB` is `beta` (here 30 degrees), angle `uBC` is `gamma`(here 60 degrees).
#### Task
`function solve(a, b, c, alpha, beta, gamma)` with parameters
- a, b, c: positive integers in units of distance (stand for OA, AB, BC)
- alpha, beta, gamma: positive integers in degrees (positive angles are anticlockwise)
returns an array:
- first element: distance CO (rounded to the nearest integer)
- then angle tOC with the third following elements:
- second element of the array: number of degrees in angle tOC (truncated positive integer)
- third element of the array: number of minutes in angle tOC (truncated positive integer)
- fourth element of the array: number of seconds in angle tOC (truncated positive integer)
#### Example:
```
print(solve(12, 20, 18, 45, 30, 60)) -> [15, 135, 49, 18]
- CO is 14.661... rounded to 15
- angle tOC is 135.821...
so
- degrees = 135
- minutes = 49.308...
- seconds = 18.518...
hence [15, 135, 49, 18]
```
#### Note
If you need the constant `pi` you can use `pi = 3.14159265358979323846` | reference | from cmath import rect, polar
from math import degrees, radians
def solve(a, b, c, alpha, beta, gamma):
dist, angle = polar(rect(a, radians(alpha)) + rect(b,
radians(beta + 90)) + rect(c, radians(gamma + 180)))
degree, temp = divmod(degrees(angle) * 60, 60)
minute, temp = divmod(temp * 60, 60)
return [round(dist), degree, minute, int(temp)]
| The Walker | 5b40b666dfb4291ad9000049 | [
"Fundamentals",
"Geometry"
]
| https://www.codewars.com/kata/5b40b666dfb4291ad9000049 | 6 kyu |
You are given a *small* extract of a catalog:
```
s = "<prod><name>drill</name><prx>99</prx><qty>5</qty></prod>
<prod><name>hammer</name><prx>10</prx><qty>50</qty></prod>
<prod><name>screwdriver</name><prx>5</prx><qty>51</qty></prod>
<prod><name>table saw</name><prx>1099.99</prx><qty>5</qty></prod>
<prod><name>saw</name><prx>9</prx><qty>10</qty></prod>
...
```
(`prx` stands for `price`, `qty` for `quantity`) and an article i.e "saw".
The `function catalog(s, "saw")` returns the line(s) corresponding to the article
with `$` before the prices:
```
"table saw > prx: $1099.99 qty: 5\nsaw > prx: $9 qty: 10\n..."
```
If the article is not in the catalog return "Nothing".
#### Notes
- There is a blank line between two lines of the catalog.
- The same article may appear more than once. If that happens return all the lines concerned by the article (in the same order as in the catalog; however see below a note for Prolog language).
- The line separator of results may depend on the language `\n`or `\r\n`.
In **Pascal** `\n` is replaced by `LineEnding`.
- in Perl use "Β£" instead of "$" before the prices.
- You can see examples in the "Sample tests".
#### Note for Prolog language
- If the article is not in the catalog then R equals "".
- R substrings (separated by "\n") must be in alphabetic order.
| reference | import xml . etree . ElementTree as ET
def catalog(s, article):
root = ET . fromstring('<cat>' + s + '</cat>')
resp = []
for child in root:
name = child . find('name'). text
price = child . find('prx'). text
quantity = child . find('qty'). text
if article in name:
resp . append(name + ' > prx: $' + price + ' qty: ' + quantity)
if resp:
return '\r\n' . join(resp)
else:
return 'Nothing'
| Catalog | 59d9d8cb27ee005972000045 | [
"Fundamentals",
"Strings"
]
| https://www.codewars.com/kata/59d9d8cb27ee005972000045 | 6 kyu |
A wildlife study involving ducks is taking place in North America. Researchers are visiting some wetlands in a certain area taking a survey of what they see. The researchers will submit reports that need to be processed by your function.
## Input
The input for your function will be an array with a list of common duck names along with the counts made by the researchers. The names and counts are separated by spaces in one array element. The number of spaces between the name and the count could vary; but, there will always be at least one. A name may be repeated because a report may be a combination of surveys from different locations.
An example of an input array would be:
```
["Redhead 3", "Gadwall 1", "Smew 4", "Greater Scaup 10", "Redhead 3", "Gadwall 9", "Greater Scaup 15", "Common Eider 6"]
```
## Processing
Your function should change the names of the ducks to a six-letter code according to given rules (see below). The six-letter code should be in upper case. The counts should be summed for a species if it is repeated.
## Output
The final data to be returned from your function should be an array sorted by the species codes and the total counts as integers. The codes and the counts should be individual elements.
An example of an array to be returned (based on the example input array above) would be:
```
["COMEID", 6, "GADWAL", 10, "GRESCA", 25, "REDHEA", 6, "SMEW", 4]
```
The codes are strings in upper case and the totaled counts are integers.
### Special Note
If someone has `"Labrador Duck"` in their list, the whole list should be thrown out as this species has been determined to be extinct. The person who submitted the list is obviously unreliable. Their lists will not be included in the final data. In such cases, return an array with a single string element in it: `"Disqualified data"`
Rules for converting a common name to a six-letter code:
* Hyphens should be considered as spaces.
* If a name has only one word, use the first six letters of the name. If that name has less than six letters, use what is there.
* If a name has two words, take the first three letters of each word.
* If a name has three words, take the first two letters of each word.
* If a name has four words, take the first letters from the first two words, and the first two letters from the last two words.
| reference | def create_report(names):
result = {}
for name in names:
if name . startswith("Labrador Duck"):
return ["Disqualified data"]
name = name . upper(). replace("-", " "). split()
count = int(name . pop())
if len(name) == 1:
code = name[0][: 6]
elif len(name) == 2:
code = name[0][: 3] + name[1][: 3]
elif len(name) == 3:
code = name[0][: 2] + name[1][: 2] + name[2][: 2]
elif len(name) == 4:
code = name[0][0] + name[1][0] + name[2][: 2] + name[3][: 2]
if code in result:
result[code] += count
else:
result[code] = count
return sum([[name, result[name]] for name in sorted(result)], [])
| Process Waterfowl Survey Data Results | 5b0737c724c0686bf8000172 | [
"Arrays",
"Regular Expressions",
"Fundamentals",
"Data Science"
]
| https://www.codewars.com/kata/5b0737c724c0686bf8000172 | 6 kyu |
I got lots of files beginning like this:
```
Program title: Primes
Author: Kern
Corporation: Gold
Phone: +1-503-555-0091
Date: Tues April 9, 2005
Version: 6.7
Level: Alpha
```
Here we will work with strings like the string data above and not with files.
The function `change(s, prog, version)` given:
`s=data, prog="Ladder" , version="1.1"` will return:
`"Program: Ladder Author: g964 Phone: +1-503-555-0090 Date: 2019-01-01 Version: 1.1"`
Rules:
- The date should always be `"2019-01-01"`.
- The author should always be `"g964"`.
- Replace the current `"Program Title"` with the prog argument supplied to your function.
Also remove `"Title"`, so in the example case `"Program Title: Primes"` becomes `"Program: Ladder"`.
- Remove the lines containing `"Corporation"` and `"Level"` completely.
- Phone numbers and versions must be in valid formats.
A valid version in the *input* string data is one or more digits followed by a dot, followed by one or more digits. So `0.6, 5.4, 14.275 and 1.99` are all valid, but versions like `.6, 5, 14.2.7 and 1.9.9` are invalid.
A valid *input* phone format is +1-xxx-xxx-xxxx, where each `x` is a digit.
- If the phone or version format is not valid, return `"ERROR: VERSION or PHONE"`.
-
If the version format is valid and the version is anything other than `2.0`, replace it with the version parameter supplied to your function.
If itβs `2.0`, donβt modify it.
- If the phone number is valid, replace it with `"+1-503-555-0090"`.
#### Note
- You can see other examples in the "Sample tests".
| reference | import re
def change(data, new_program, new_version):
try:
curr_phone = re . search(
r'^Phone\: (\+1-\d{3}-\d{3}-\d{4})$', data, re . M). group(1)
curr_version = re . search(
r'^Version\: (\d+\.\d+)$', data, re . M). group(1)
except:
return 'ERROR: VERSION or PHONE'
return 'Program: {} Author: g964 Phone: +1-503-555-0090 Date: 2019-01-01 Version: {}' . format(new_program, new_version if curr_version != '2.0' else curr_version)
| Matching And Substituting | 59de1e2fe50813a046000124 | [
"Fundamentals"
]
| https://www.codewars.com/kata/59de1e2fe50813a046000124 | 5 kyu |
Removed due to copyright infringement.
<!---
 You are given a set of `n` sections on a number line, each segment has integer endpoints between `0` and `m` inclusive.<br>
 Sections may intersect, overlap or even coincide with each other. Each section is characterized by two integers l<sub>i</sub> and r<sub>i</sub> β coordinates of the left and of the right endpoints.
 Consider all integer points between `0` and `m` inclusive. Your task is to print all such points that **don't** belong to any segment. The point x belongs to the segment `[l;r]` if and only if `l β€ x β€ r`.
**Input:**<br>
 `m` β the upper bound for coordinates;<br>
 array of coordinates l<sub>i</sub> and r<sub>i</sub> `0 β€ li β€ ri β€ m` β the endpoints of the `i`-th segment. Segments may intersect, overlap or even coincide with each other.
**Output:**<br>
 All points from `0` to `m` that don't belong to any segment.
**Examples:**
```javascript
segments(5, [[2,2],[1,2],[5,5]]) => [0,3,4]
segments(7, [[0,7]]) => []
```
```c
segments(5, {{2,2},{1,2},{5,5}}) => {0,3,4}
segments(7, {{0,7}}) => {}
```
```cpp
segments(5, {{2,2},{1,2},{5,5}}) => {0,3,4}
segments(7, {{0,7}}) => {}
```
```java
PointsInSegments.segments(5, {{2,2},{1,2},{5,5}}) => {0,3,4}
PointsInSegments.segments(7, {{0,7}}) => {}
```
```python
segments(5, [(2,2),(1,2),(5,5)]) => [0,3,4]
segments(7, [(0,7)]) => []
```
---> | algorithms | def segments(m, arr):
return [i for i in range(m + 1) if not any(a <= i <= b for a, b in arr)]
| Points in Segments | 5baa25f3246d071df90002b7 | [
"Algorithms",
"Logic"
]
| https://www.codewars.com/kata/5baa25f3246d071df90002b7 | 7 kyu |
Remove the duplicates from a list of integers, keeping the last ( rightmost ) occurrence of each element.
### Example:
For input: `[3, 4, 4, 3, 6, 3]`
* remove the `3` at index `0`
* remove the `4` at index `1`
* remove the `3` at index `3`
Expected output: `[4, 6, 3]`
More examples can be found in the test cases.
Good luck! | reference | def solve(arr):
re = []
for i in arr[:: - 1]:
if i not in re:
re . append(i)
return re[:: - 1]
| Simple remove duplicates | 5ba38ba180824a86850000f7 | [
"Fundamentals"
]
| https://www.codewars.com/kata/5ba38ba180824a86850000f7 | 7 kyu |
In the web we have many available colours that we may use with html. The different variations or arrangements, for a design in the web may climb up if we increase the amount of used colours, specially because the order matters for the different designs.
An "expert" uses a formula that relates the amount of designs with the number of colours, and even though he has a developed intiution, his results are not exact.
We explain the problem to you and see if you can help.
Let's see the amount of arrangements of colours that we may produce with the set: <span style="color:red">red</span>, <span style="color:#EEBB00">yellow</span>, <span style="color:DodgerBlue">blue</span>.
<span style="color:red">red</span>
<span style="color:#EEBB00">yellow</span>
<span style="color:DodgerBlue">blue</span>
<span style="color:red">red</span><span style="color:#EEBB00">yellow</span>
<span style="color:#EEBB00">yellow</span><span style="color:red">red</span>
<span style="color:red">red</span><span style="color:DodgerBlue">blue</span>
<span style="color:DodgerBlue">blue</span><span style="color:red">red</span>
<span style="color:#EEBB00">yellow</span><span style="color:DodgerBlue">blue</span>
<span style="color:DodgerBlue">blue</span><span style="color:#EEBB00">yellow</span>
<span style="color:red">red</span><span style="color:#EEBB00">yellow</span><span style="color:DodgerBlue">blue</span>
<span style="color:red">red</span><span style="color:DodgerBlue">blue</span><span style="color:#EEBB00">yellow</span>
<span style="color:#EEBB00">yellow</span><span style="color:red">red</span><span style="color:DodgerBlue">blue</span>
<span style="color:#EEBB00">yellow</span><span style="color:DodgerBlue">blue</span><span style="color:red">red</span>
<span style="color:DodgerBlue">blue</span><span style="color:red">red</span><span style="color:#EEBB00">yellow</span>
<span style="color:DodgerBlue">blue</span><span style="color:#EEBB00">yellow</span><span style="color:red">red</span>
We have a total of 15 arrangements. Six, will be the minimum value for the unique colours set size that surpasses the amount of **1.000** arrangements or variations.
## Task
Given an integer, ```limit```, and an array with different and unique colours, ```cols```, make a code that may calculate:
- the minimum size the set should have so that it generates more arrangements than the limit value, ```limit ```
- the number of variations that we may obtain with the current set, ```cols ```.
This pair of values should output in an array.
See sample cases in the examples box.
### Features of the random tests:
* `0 <= limit <= 10**150`
* `0 <= amount_of_colours < 100`
* Number of random tests: 90
<br>
_Have a good and productive time! (Performance matters)_ | reference | from bisect import bisect
a = [0]
for n in range(1, 150):
a . append((a[- 1] + 1) * n)
total_var = lambda n , c : [bisect (a , n ), a [len (c )]] | Counting the Webdesigns based on Used Colours | 5b3cdb419c9a75664e00013e | [
"Performance",
"Algorithms",
"Mathematics",
"Machine Learning",
"Combinatorics",
"Number Theory"
]
| https://www.codewars.com/kata/5b3cdb419c9a75664e00013e | 5 kyu |
<a href="https://imgur.com/Z7HiIU4"><img src="https://i.imgur.com/Z7HiIU4.jpg?1" title="source: imgur.com" /></a>
Cramer (1704 -1752), the swiss mathematician that created a method to solve systems of n linear equations with n variables.
We have a linear system of ```n Equations``` with ```n Variables``` like the following:
<a href="https://imgur.com/IK2keV7"><img src="https://i.imgur.com/IK2keV7.jpg?1" title="source: imgur.com" /></a>
The subindexed values ```a11```, ```a12```, .....```ann```, are the coefficients of the different variables ```x1```, ```x2```, .....,``` xn```.
We define ```Ξ``` (delta), the determinant of the matrix of the coefficients as it follows:
<a href="https://imgur.com/zvVIYVB"><img src="https://i.imgur.com/zvVIYVB.png?1" title="source: imgur.com" /></a>
You may calculate the determinant also by the way is explained at the kata Matrix Determinant. See at: http://www.codewars.com/kata/matrix-determinant
You may learn also to calculate the determinant: https://en.wikipedia.org/wiki/Determinant
Then, we define the vector, ```V```, with the independent terms ```b1```, ```b2```, ...., ```bn```:
<a href="https://imgur.com/m6m20id"><img src="https://i.imgur.com/m6m20id.png?1" title="source: imgur.com" /></a>
We will obtain the determinants for each variable replacing the vector V for a column in the position of the variable. ```Ξx1```, the determinant for the variable ```x1```, ```Ξx2```, the determinant for the variable ```x2``` and so on. It is as follows:
<a href="https://imgur.com/GaEIFJV"><img src="https://i.imgur.com/GaEIFJV.png?1" title="source: imgur.com" /></a>
So the values of the variables are:
<a href="https://imgur.com/GMANk3Y"><img src="https://i.imgur.com/GMANk3Y.png?1" title="source: imgur.com" /></a>
We should know that a linear equation system may be solvable, unsolvable or indeterminate as the following chart shows below:
* If Ξ β 0 , the equation system is ***solvable***. Each
variable will have a value.
* If Ξ = 0: the system will be ***Unsolvable*** if one of the variables Ξx<sub>i</sub> is not 0 or the system will be ***Indeterminate or Unsolvable*** if all the values of Ξx<sub>i</sub> are 0.
For that purpose we need a function ```cramer_solver()```, that will accept two arguments, ```matrix``` and ```vector```.
The function will output the array with the following results and order:
```
[Ξ, Ξx1, Ξx2,........,Ξxn]
```
But if Ξ = 0 and all the Ξx<sub>i</sub> are 0, the code will output "Indeterminate or Unsolvable".
If Ξ = 0 and at least only one Ξx<sub>i</sub> β 0, the code will output "Unsolvable".
If matrix is not square (equal amount of rows and columns) or the lengths of matrix and vector V are different, the code will "Check entries".
Let's see how to solve some example using maths and how the results would be.
We want to solve the following system of equations:
```
4x - 6y - 3z = 12
x + y - 2z = 3
4x -20y - 4z = 6
```
So the function will receive the following matrix and vector:
```python
matrix =[[4,-6, -3], [ 1 , 1, -2], [4, -20, -4]]
vector = [12, 3, 6]
cramer_solver(matrix, vector) == [-80, -330, -30, -60]
```
```javascript
var matrix =[[4,-6, -3], [ 1 , 1, -2], [4, -20, -4]];
var vector = [12, 3, 6];
cramerSolver(matrix, vector) == [-80, -330, -30, -60];
```
Another case:
```
x + y - 3z = -10
x + y - 2z = 3
x + y - 4z = -6
```
So our solver will receive our matrix and vector:
```python
matrix = [[1, 1, -3], [1, 1, -2], [1, 1, -4]]
vector = [-10, 3, -6]
cramer_solver(matrix, vector) == "Unsolvable"
```
```javascript
var matrix = [[1, 1, -3], [1, 1, -2], [1, 1, -4]];
var vector = [-10, 3, -6];
cramerSolver(matrix, vector) == "Unsolvable"
```
Let's see another more:
```
x + y - 3z = 0
x + y - 2z = 0
x + y - 4z = 0
```
The matrix and vector for this case:
```python
matrix = [[1, 1, -3], [1, 1, -2], [1, 1, -4]]
vector = [0, 0, 0]
cramer_solver(matrix, vector) == "Indeterminate or Unsolvable"
```
```javascript
var matrix = [[1, 1, -3], [1, 1, -2], [1, 1, -4]];
var vector = [0, 0, 0];
cramerSolver(matrix, vector) == "Indeterminate or Unsolvable"
```
If we introduce a matrix that is not square, the function should detect it.
```python
matrix = [[1, 1, -3, 4], [1, 1, -2, 3], [1, 1, -4, 2]]
vector = [0, 0, 0]
cramer_solver(matrix, vector) == "Check entries"
```
```javascript
var matrix = [[1, 1, -3, 4], [1, 1, -2, 3], [1, 1, -4, 2]];
var vector = [0, 0, 0];
cramer_solver(matrix, vector) == "Check entries"
```
Also cases where one (or more) row(s) has (have) different lengths.
```python
matrix = [[1, 1, -3], [1, 1], [1, 1, -4]]
vector = [-10, 3, -6]
cramer_solver(matrix, vector) == "Check entries"
```
```javascript
var matrix = [[1, 1, -3], [1, 1], [1, 1, -4]];
var vector = [-10, 3, -6];
cramerSolver(matrix, vector) == "Check entries"
```
The cases when the dimension of matrix is different than the length of vector should be detected, too.
```python
matrix = [[1, 1, -3, 4], [1, 1, -2, 3], [1, 1, -4, 2], [6, 4, 2, 1]]
vector = [1, 1, 1]
cramer_solver(matrix, vector) == "Check entries"
```
```javascript
var matrix = [[1, 1, -3, 4], [1, 1, -2, 3], [1, 1, -4, 2], var [6, 4, 2, 1]];
vector = [1, 1, 1];
cramerSolver(matrix, vector) == "Check entries"
```
The coefficients of the equation will be integer values for all the cases, so the array output should have only integers
The tests will challenge your code for linear equations systems up to 8 variables (and 8 equations obviously)
Enjoy it!!
(Javascript and Ruby versions will be released soon) | reference | import numpy as np
def cramer_solver(* args):
m, v = map(np . array, args)
if set(m . shape) != {len(v)}:
return "Check entries"
det = round(np . linalg . det(m))
subDets = []
for y in range(len(v)):
stored = list(m[:, y])
m[:, y] = v
subDets . append(round(np . linalg . det(m)))
m[:, y] = stored
return ("Indeterminate or Unsolvable" if set(subDets) == {0} else
"Unsolvable" if 0 in subDets else
[det] + subDets)
| Cramer, thanks for your contribution! | 5b4a9158f1d553b3be0000c0 | [
"Fundamentals",
"Data Structures",
"Arrays",
"Mathematics",
"Algebra"
]
| https://www.codewars.com/kata/5b4a9158f1d553b3be0000c0 | 6 kyu |
If we multiply the integer `717 (n)` by `7 (k)`, the result will be equal to `5019`.
Consider all the possible ways that this last number may be split as a string and calculate their corresponding sum obtained by adding the substrings as integers. When we add all of them up,... surprise, we got the original number `717`:
```
Partitions as string Total Sums
['5', '019'] 5 + 19 = 24
['50', '19'] 50 + 19 = 69
['501', '9'] 501 + 9 = 510
['5', '0', '19'] 5 + 0 + 19 = 24
['5', '01', '9'] 5 + 1 + 9 = 15
['50', '1', '9'] 50 + 1 + 9 = 60
['5', '0', '1', '9'] 5 + 0 + 1 + 9 = 15
____________________
Big Total: 717
____________________
```
In fact, `717` is one of the few integers that has such property with a factor `k = 7`.
Changing the factor `k`, for example to `k = 3`, we may see that the integer `40104` fulfills this property.
Given an integer `start_value` and an integer `k`, output the smallest integer `n`, but higher than `start_value`, that fulfills the above explained properties.
If by chance, `start_value`, fulfills the property, do not return `start_value` as a result, only the next integer. Perhaps you may find this assertion redundant if you understood well the requirement of the kata: "output the smallest integer `n`, but higher than `start_value`"
The values for `k` in the input may be one of these: `3, 4, 5, 7`
### Features of the random tests
If you want to understand the style and features of the random tests, see the *Notes* at the end of these instructions.
The random tests are classified in three parts.
- Random tests each with one of the possible values of `k` and a random `start_value` in the interval `[100, 1300]`
- Random tests each with a `start_value` in a larger interval for each value of `k`, as follows:
- for `k = 3`, a random `start value` in the range `[30000, 40000]`
- for `k = 4`, a random `start value` in the range `[2000, 10000]`
- for `k = 5`, a random `start value` in the range `[10000, 20000]`
- for `k = 7`, a random `start value` in the range `[100000, 130000]`
- More challenging tests, each with a random `start_value` in the interval `[100000, 110000]`.
<p></p>
See the examples tests.
Enjoy it.
# Notes:
- As these sequences are finite, in other words, they have a maximum term for each value of k, the tests are prepared in such way that the `start_value` will always be less than this maximum term. So you may be confident that your code will always find an integer.
- The values of `k` that generate sequences of integers, for the constrains of this kata are: 2, 3, 4, 5, and 7. The case `k = 2` was not included because it generates only two integers.
- The sequences have like "mountains" of abundance of integers but also have very wide ranges like "valleys" of scarceness. Potential solutions, even the fastest ones, may time out searching the next integer due to an input in one of these valleys. So it was intended to avoid these ranges.
Javascript and Ruby versions will be released soon. | reference | def sum_part(n):
m, p, q, r, s = 1, 1, 1, 0, n
while n > 9:
n, d = divmod(n, 10)
r += d * p
p *= 10
if d:
m = 1
else:
m *= 2
s += q * n + m * memo[r]
q *= 2
return s
from collections import defaultdict
qualified = defaultdict(list)
memo = {n: n for n in range(10)}
for n in range(10, 10 * * 6):
memo[n] = sum_part(n)
if memo[n] > n:
k, r = divmod(n, memo[n] - n)
if not r:
qualified[k]. append(memo[n] - n)
from bisect import bisect
def next_higher(n, k):
return qualified[k][bisect(qualified[k], n + 1)]
| Next Higher Value # 1 | 5b713d7187c59b53e60000b0 | [
"Fundamentals",
"Data Structures",
"Arrays",
"Mathematics",
"Algebra"
]
| https://www.codewars.com/kata/5b713d7187c59b53e60000b0 | 5 kyu |
You are given the head node of a singly-linked list. Write a method that swaps each pair of nodes in the list, then returns the head node of the list.
You have to swap the nodes themselves, not their values.
Example:
`(A --> B --> C --> D) => (B --> A --> D --> C)`
The swapping should be done left to right, so if the list has an odd length, the last node stays in place:
`(A --> B --> C) => (B --> A --> C)`
___
The list will be composed of `Node`s of the following specification:
```java
public class Node {
private String value;
public Node next;
public Node(String value) { this.value = value; }
public String getValue() { return value; }
// returns a String representation of the whole list:
public String printList() {}
}
```
```javascript
class Node {
constructor(value, next = null) {
this.value = value;
this.next = next;
}
}
```
```c
struct Node {
struct Node *next;
};
```
```python
class Node:
def __init__(self, next=None):
self.next = next
``` | algorithms | from preloaded import Node
def swap_pairs(head):
if head == None or head . next == None:
return head
A, B, C = head, head . next, head . next . next
B . next = A
A . next = swap_pairs(C)
return B
| Swap Node Pairs In Linked List | 59c6f43c2963ecf6bf002252 | [
"Algorithms",
"Data Structures",
"Linked Lists"
]
| https://www.codewars.com/kata/59c6f43c2963ecf6bf002252 | 5 kyu |
We define a range with two positive integers ```n1``` and ```n2``` and an integer factor ```k```, ```[n1, n1 + k*n2]```, the bounds of the defined range are included.
~~~if:ruby,rust,python
We will be given two arrays: ```prime_factors``` and ```digits```.
```
prime_factors = [p1, p2, ..., pl] # p1, p2, ... and pl are prime factors
digits = [d1, d2, ..., dj] # d1, d2, ..., dj are digits from 0 to 9 included
We want to find all the numbers, ```mi``` such that: ```n1 β€ m1 < m2 < ....mi β€ n1 + k*n2```, and are divisible for all the prime numbers present in ```prime_factors``` and have all the digits present in ```digits```.
```
~~~
~~~if:javascript,d,go
We will be given two arrays: ```primeFactors``` and ```digits```.
```
primeFactors = [p1, p2, ..., pl] # p1, p2, ... and pl are prime factors
digits = [d1, d2, ..., dj] # d1, d2, ..., dj are digits from 0 to 9 included
```
We want to find all the numbers, ```mi``` such that: ```n1 β€ m1 < m2 < ....mi β€ n1 + k*n2```, and are divisible for all the prime numbers present in ```primeFactors``` and have all the digits present in ```digits```.
~~~
Let's see an example showing the function that will solve these challenge.
```python
n1 = 30
n2 = 90
k = 4
factors = [2, 3]
digits = [6, 2]
--> return [126, 162, 216, 246, 264, 276] # result should be a sorted list with the found numbers.
```
An empty list means that the are no numbers that may fulfill the given conditions.
### Range of inputs
```
100 <= n1 <= 500,
1000 <= n2 <= 8000
180 <= k <= 2500
Prime factors will be inferior or equal to 31
```
Happy coding!! | algorithms | from math import lcm
def find_us(n1, n2, k, prime_factors, digits):
step, digits, end = 1, '' . join(map(str, digits)), 1 + n1 + k * n2
for p in prime_factors:
step = lcm(step, p)
while n1 % step:
n1 += 1
return [i for i in range(n1, end, step) if all(j in str(i) for j in digits)]
| Find a Very Special Set Of Numbers In a Certain Range | 569df0bc5565b243d500002b | [
"Fundamentals",
"Mathematics",
"Algorithms"
]
| https://www.codewars.com/kata/569df0bc5565b243d500002b | 6 kyu |
We are given a sequence of coplanar points and see all the possible triangles that may be generated which all combinations of three points.
We have the following list of points with the cartesian coordinates of each one:
```
Points [x, y]
A [1, 2]
B [3, 3]
C [4, 1]
D [1, 1]
E [4, -1]
```
With these points we may have the following triangles: ```ABC, ABD, ABE, ACD, ACE, ADE, BCD, BCE, BDE, CDE.``` There are three special ones: ```ABC, ACD and CDE```, that have an angle of 90Β°. All is shown in the picture below:
<a href="https://imgur.com/Kq0dAU1"><img src="https://i.imgur.com/Kq0dAU1.jpg?1" title="source: imgur.com" /></a>
We need to count all the rectangle triangles that may be formed by a given list of points. Note that possible duplicate points should be counted only once to form a triangle.
The case decribed above will be:
```python
count_rect_triang([[1, 2],[3, 3],[4, 1],[1, 1],[4, -1]]) == 3
```
Observe this case:
```python
count_rect_triang([[1, 2],[4, -1],[3, 3],[4, -1],[4, 1],[1, 1],[4, -1], [4, -1], [3, 3], [1, 2]]) == 3
```
If no rectangle triangles may be generated the function will output ```0```.
Enjoy it! | reference | from itertools import combinations
def isRect(a, b, c):
X, Y, Z = sorted(sum((q - p) * * 2 for p, q in zip(p1, p2)) for p1, p2 in [(a, b), (a, c), (b, c)])
return X + Y == Z
def count_rect_triang(points):
return sum(isRect(* c) for c in combinations(set(map(tuple, points)), 3))
| Counting Rectangle Triangles | 57d99f6bbfcdc5b3b0000286 | [
"Fundamentals",
"Mathematics",
"Geometry",
"Algorithms",
"Logic"
]
| https://www.codewars.com/kata/57d99f6bbfcdc5b3b0000286 | 6 kyu |
**1. - You are given an array of positive integers as argument. You must generate all the possible divisions between each pair of its elements that outputs an integer value.**
For example:
```
arr = [2, 4, 27, 16, 9, 15, 25, 6, 12, 83, 24, 49, 7, 5, 94, 12, 6]
```
You must then create a list, sorted by the quotient value, containing the corresponding numerator and denominator taken from the given array.
```python
Format: (quotient, (numerator, denominator))
[(2, (4, 2)), (2, (12, 6)), (2, (12, 6)), (2, (12, 6)), (2, (12, 6)), (2, (24, 12)), (2, (24, 12)), (3, (6, 2)), (3, (6, 2)), (3, (12, 4)), (3, (12, 4)), (3, (15, 5)), (3, (27, 9)), (4, (16, 4)), (4, (24, 6)), (4, (24, 6)), (5, (25, 5)), (6, (12, 2)), (6, (12, 2)), (6, (24, 4)), (7, (49, 7)), (8, (16, 2)), (12, (24, 2)), (47, (94, 2))]
```
```ruby
Format: [quotient, [numerator, denominator]]
[[2, [4, 2]], [2, [12, 6]], [2, [12, 6]], [2, [12, 6]], [2, [12, 6]], [2, [24, 12]], [2, [24, 12]], [3, [6, 2]], [3, [6, 2]], [3, [12, 4]], [3, [12, 4]], [3, [15, 5]], [3, [27, 9]], [4, [16, 4]], [4, [24, 6]], [4, [24, 6]], [5, [25, 5]], [6, [12, 2]], [6, [12, 2]], [6, [24, 4]], [7, [49, 7]], [8, [16, 2]], [12, [24, 2]], [47, [94, 2]]]
```
**2. - Eliminate all the duplicated cases giving it only once.**
```(2, (12, 6))``` occurs four times, for example (we have more cases)
The data is reduced to:
```python
[(2, (4, 2)), (2, (12, 6)), (2, (24, 12)), (3, (6, 2)), (3, (12, 4)), (3, (15, 5)), (3, (27, 9)), (4, (16, 4)), (4, (24, 6)), (5, (25, 5)), (6, (12, 2)), (6, (24, 4)), (7, (49, 7)), (8, (16, 2)), (12, (24, 2)), (47, (94, 2))]
```
```ruby
[[2, [4, 2]], [2, [12, 6]], [2, [24, 12]], [3, [6, 2]], [3, [12, 4]], [3, [15, 5]], [3, [27, 9]], [4, [16, 4]], [4, [24, 6]], [5, [25, 5]], [6, [12, 2]], [6, [24, 4]], [7, [49, 7]], [8, [16, 2]], [12, [24, 2]], [47, [94, 2]]]
```
**3. - Select the quotients that are higher or equal than a certain given value.**
If the given value is 6 will reduce even more our cases:
```python
[(6, (12, 2)), (6, (24, 4)), (7, (49, 7)), (8, (16, 2)), (12, (24, 2)), (47, (94, 2))]
```
```ruby
[[6, [12, 2]], [6, [24, 4]], [7, [49, 7]], [8, [16, 2]], [12, [24, 2]], [47, [94, 2]]]
```
**4. - Select the results by even or odd quotient value.**
Supose that we are interested in odd values only, we will finally have:
```python
[(7, (49, 7)), (47, (94, 2))]
```
```ruby
[[7, [49, 7]], [47, [94, 2]]]
```
So our function ```sel_quot()``` may receive the following the arguments in the following order outputting the corresponding result:
```python
# same array as above, arr
dir_str = 'odd'
sel_quot(arr, 6, dir_str) == [(7, (49, 7)), (47, (94, 2))] #
```
```ruby
# same array as above, arr
sel_quot(arr, 6, 'odd') == [[7, [49, 7]], [47, [94, 2]]]
```
Our function should be able to receive only an array and the integer value. (Without doing the even/odd selection)
```python
# same array, arr
sel_quot(arr, 6) == [(6, (12, 2)), (6, (24, 4)), (7, (49, 7)), (8, (16, 2)), (12, (24, 2)), (47, (94, 2))]
```
```ruby
# same array, arr
sel_quot(arr, 6) == [[6, [12, 2]], [6, [24, 4]], [7, [49, 7]], [8, [16, 2]], [12, [24, 2]], [47, [94, 2]]]
```
Assumptions:
All integer values in the array, including ```m```, will be >= 2.
The strings will be exactly given as 'even' and 'odd' or 'Even' and 'Odd'.
Have a good time!
| reference | def sel_quot(a, m, s=0): return sorted((n / d, (n, d)) for d, n in __import__('itertools'). combinations(
sorted(set(a)), 2) if n % d == 0 and n / d >= m and (not s or n / d % 2 == (s[1] == "d")))
| Selecting Quotients From an Array | 569f6ad962ff1dd52f00000d | [
"Fundamentals",
"Data Structures",
"Algorithms",
"Sorting",
"Mathematics",
"Logic"
]
| https://www.codewars.com/kata/569f6ad962ff1dd52f00000d | 6 kyu |
The ```digit root``` of a number ```(dr)``` is the sum of the digits of a number.
For example, the integer ```749```, has a digit root equals to ```20```.
In effect: ```7 + 4 + 9 = 20```.
We define here the ```deeper square double digit root``` of an integer ```n```, ```(dsddr)```, the sum of the squares of every digit of the digit root of ```n```.
The ```dsddr``` of ```749``` will be ```4```:
2<sup>2</sup> + 0<sup>2</sup> = 4
We define the function ```f```, like:
```
f(n) = dr(n) + dsddr(n)
```
Now we receive two arrays of positive integers, ``` arr1``` , ```arr2``` of different lengths. They have common elements. The task is to output an array, res, with the common elements occurring once and sorted by their corresponding value of f in descending order. If there is a coincidence in the value of f(res[i]), the lowest number goes first.
Example:
```
arr1 = [5, 56, 28, 35, 12, 27, 64, 99, 18, 31, 14, 6]
arr2 = [28, 17, 31, 63, 64, 5, 18, 17, 95, 56, 37, 5, 28, 16]
```
The common elements of arr1 and arr2 are:
```[64, 5, 18, 56, 28, 31]```
The table for their corresponding value of f is:
```
n f(n)
64 11
5 30
18 90
56 13
28 11
31 20
```
So the output will be:
```[18, 5, 31, 56, 28, 64]```
You do not have to worry about the inputs, arr1 and arr2, will be always valid arrays and all of their terms, positive integers.
Features of the random tests:
```
lengths of arrays for the input up to 500.000.
The values of the integers between 1 and 1.500.000
Amount of tests almost 150
```
See more examples in the Example tests | reference | def f(n):
dr = sum(map(int, str(n)))
deep = sum(d * d for d in map(int, str(dr)))
return (- dr - deep, n)
def sorted_comm_by_digs(arr1, arr2):
return sorted(set(arr1) & set(arr2), key=f)
| Warm Up for Speed. | 5b4dee5d05f04bba43000138 | [
"Performance",
"Algorithms",
"Mathematics",
"Data Structures",
"Arrays",
"Sorting",
"Fundamentals"
]
| https://www.codewars.com/kata/5b4dee5d05f04bba43000138 | 6 kyu |
# Your task
X and Y are playing a game. A list will be provided which contains `n` pairs of strings and integers. They have to add the integer<sub>i</sub> to the ASCII values of the string<sub>i</sub> characters. Then they have to check if any of the new added numbers is prime or not. If for any character of the word the added number is prime then the word will be considered as prime word.
Can you help X and Y to find the prime words?
___
## Example:
```cpp
prime_word({{"Emma",30},{"Liam",30}}) = {1,1};
```
```python
prime_word([["Emma", 30], ["Liam", 30]]) -> [1, 1]
```
* For the first word `"Emma"` ASCII values are: `69 109 109 97`
* After adding `30` the values will be: `99 139 139 127`
* As `139` is prime number so `"Emma"` is a Prime Word. | reference | from gmpy2 import is_prime as ip
def ok(w):
a, b = w
return any(ip(ord(j) + b) for j in a)
def prime_word(a):
return [1 if ok(i) else 0 for i in a]
| Prime Word | 5b1e2c04553292dacd00009e | [
"Fundamentals"
]
| https://www.codewars.com/kata/5b1e2c04553292dacd00009e | 6 kyu |
We have got a gun that shoots little balls of painting of different colours. We want to calculate the probability in having a certain number of shots with certain colours in a specific order.
Before start shooting, the balls are mixed in such way that each ball has the same probabilty of being selected to be shot. This action is repeated after each shot.
For example the gun will be feed with a total of `18` balls: `9` yellow, `4` red and `5` blue. Like the sets we have below.
<a href="https://imgur.com/wV5abKp"><img src="https://i.imgur.com/wV5abKp.png?1" title="source: imgur.com" /></a>
We want to know the probabilty for this set of balls (`balls_set`) in having the following event that has 4 consecutive shots: ```e1 = ["RD", "YL", "YL", "BL"]```.
RD means Red, YL means Yellow and BL means Blue
The probability will be:
```
p(e1) = 4/18 * 9/17 * 8/16 * 5/15 = 1440/73440 = 1/51
```
But the following event, for the same balls_set, is impossible for this event of 5 shots:
`e2 = ["RD", "YL", "YL", "BL", "GN"]`
`p(e2) = 0`. The new one here is GN, GN means green. There are no green balls in the set given above.
You will be given an unordered set of balls with different colours and a desired event. The balls_set has full words for the names of the colours (first letter in Capital letters) as an array. The event is an array, too, but has the corresponding abbreviation for the color. (see the table bellow). You should output the probability of the desired event as a non-reducible fraction with its numerator and denominator in an array, `[num, den]` (num and den should be co-primes).
The examples given above will be:
``` python
set_balls = ["Red","Red","Blue","Yellow","Yellow","Yellow","Red", "Yellow","Yellow","Blue","Yellow","Red","Blue","Yellow","Blue","Yellow","Blue",Yellow"]
e = ["RD", "YL", "YL", "BL"]
find_prob(set_balls, e1) === [1,51]
```
And the above case when the probability is 0, the function will output an array with the word "Impossible" in it.
``` python
set_balls = ["Red","Red","Blue","Yellow","Yellow","Yellow","Red", "Yellow","Yellow","Blue","Yellow","Red","Blue","Yellow","Blue","Yellow","Blue",Yellow"]
e = ["RD", "YL", "YL", "BL,"GN"]
find_prob(set_balls, e1) === ['Impossible']
```
You sould have in mind that events with very low probability very close to 0 are **improbable**, but events with probability equals to 0 are **impossible**
The following table shows the correspondent abreviations with all the possible colours of balls that are available for this kata.
```
Abbreviation Color
AL Aluminum
AM Amber
BG Beige
BK Black
BL Blue
BN Brown
BZ Bronze
CH Charcoal
CL Clear
GD Gold
GN Green
GY Gray
GT Granite
IV Ivory
LT Light
OL Olive
OP Opaque
OR Orange
PK Pink
RD Red
SM Smoke
TL Translucent
TN Tan
TP Transparent
VT Violet
WT White
YL Yellow
```
The dictionary ABBREVIATIONS (in Ruby $ABBREVIATIONS) has been preloaded for you to speed up the creation of your solution.
Features of the Random Tests:
```
length of balls_set (total amount of balls) between 20 and 100000
amount of events according to the amount of total balls
```
More cases in the example tests.
The gun has a huge deposit to charge incredible amount of painting balls.
Enjoy it! | reference | from collections import Counter
from math import gcd
def find_prob(balls_set, event):
cntr = Counter(balls_set)
nm, dn, ln = 1, 1, len(balls_set)
for vtn in map(ABBREVIATIONS . get, event):
nm *= cntr[vtn]
dn *= ln
cntr[vtn] -= 1
ln -= 1
g = gcd(nm, dn)
return [nm / / g, dn / / g] if nm else ['Impossible']
| "Shoot But As I've Seen It In My Imagination" | 5b8ea6bbcc7c0335f80001a9 | [
"Arrays",
"Mathematics",
"Algebra",
"Probability",
"Data Science"
]
| https://www.codewars.com/kata/5b8ea6bbcc7c0335f80001a9 | 6 kyu |
We have two consecutive integers k<sub>1</sub> and k<sub>2</sub>, k<sub>2</sub> = k<sub>1</sub> + 1
We need to calculate the lowest strictly positive integer `n`, such that:
the values nk<sub>1</sub> and nk<sub>2</sub> have the same digits but in different order.
E.g.# 1:
```
k1 = 100
k2 = 101
n = 8919
#Because 8919 * 100 = 891900
and 8919 * 101 = 900819
```
E.g.# 2:
```
k1 = 325
k2 = 326
n = 477
#Because 477 * 325 = 155025
and 477 * 326 = 155502
```
Your task is to prepare a function that will receive the value of `k` and outputs the value of `n`.
The examples given above will be:
```python
find_lowest_int(100) === 8919
find_lowest_int(325) === 477
```
Features of the random tests
```
10 < k < 10.000.000.000.000.000 (For Python, Ruby and Haskell)
10 < k < 1.000.000.000 (For Javascript and D 1e9)
```
Enjoy it!!
| reference | def find_lowest_int(k1):
k2, n = k1 + 1, 1
def digits(n):
return sorted(str(n))
while digits(n * k1) != digits(n * k2):
n += 1
return n
| Multiples By Permutations II | 5ba178be875de960a6000187 | [
"Fundamentals",
"Data Structures",
"Strings",
"Mathematics",
"Algebra",
"Sorting",
"Combinatorics"
]
| https://www.codewars.com/kata/5ba178be875de960a6000187 | 7 kyu |
# Your Task
You have a Petri dish with bacteria, and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them.
You know that you have `n` bacteria in the Petri dish and size of the i-th bacteria is bacteria<sub>i</sub>. Also you know intergalactic positive integer constant `K`.
The i-th bacteria can swallow the j-th bacteria if and only if bacteria<sub>i</sub> > bacteria<sub>j</sub> and bacteria<sub>i</sub> β€ bacteria<sub>j</sub> + K. The j-th bacteria disappear, but the i-th bacteria doesn't change its size.
Since you don't have a microscope, you can only guess the minimal possible number of bacteria that will remain in your Petri dish when you finally find a microscope.
```cpp
microWorld({101, 53, 42, 102, 101, 55, 54} , 1) == 3
microWorld({20, 15, 10, 15, 20, 25} , 5) == 1
```
```python
micro_world([101, 53, 42, 102, 101, 55, 54], 1) == 3
micro_world([20, 15, 10, 15, 20, 25], 5) == 1
```
```ruby
micro_world([101, 53, 42, 102, 101, 55, 54], 1) == 3
micro_world([20, 15, 10, 15, 20, 25], 5) == 1
```
```javascript
microWorld([101, 53, 42, 102, 101, 55, 54], 1) === 3
microWorld([20, 15, 10, 15, 20, 25], 5) === 1
```
___
# Explanation
```cpp
bacteria = {101, 53, 42, 102, 101, 55, 54}
K = 1
```
```python
bacteria = [101, 53, 42, 102, 101, 55, 54]
K = 1
```
```ruby
bacteria = [101, 53, 42, 102, 101, 55, 54]
K = 1
```
```javascript
bacteria = [101, 53, 42, 102, 101, 55, 54]
K = 1
```
```if:cpp
The one of possible sequences of swallows is: {101,53,42,102,<s>101</s>,55,54} β {101,<s>53</s>,42,102,55,54} β {<s>101</s>,42,102,55,54} β {42,102,55,<s>54</s>} β {42,102,55}. In total there are 3 bacteria remaining.
```
```if:python,ruby,javascript
The one of possible sequences of swallows is: [101,53,42,102,<s>101</s>,55,54] β [101,<s>53</s>,42,102,55,54] β [<s>101</s>,42,102,55,54] β [42,102,55,<s>54</s>] β [42,102,55]. In total there are 3 bacteria remaining.
``` | reference | def micro_world(bacteria, k):
return sum(1 for e in bacteria if not [j for j in bacteria if e < j <= e + k])
| Micro-World | 5ba068642ab67b95da00011d | [
"Fundamentals"
]
| https://www.codewars.com/kata/5ba068642ab67b95da00011d | 6 kyu |
## Welcome
In this kata, we'll play a mini-game `Flou`.

## Task
You are given a `gameMap`, like this:
```
+----+
|.B..| +,-,| --> The boundary of game map
|....| B --> The initial color block
|....| . --> The empty block
|..B.| It is always a rectangular shape
+----+
```
In the test cases, it displayed like this:
<img src="
https://files.gitter.im/myjinxin2015/u5EQ/thumb/blob.png">
The goal of the game is: move the initial color blocks, let each empty block became to color block.
## Moving Rules
- Each color block MUST/ONLY move once. The block should move at least one grid, otherwise, it is not a valid movement.
- You need to specify the direction of the movement for each color block, the direction can be `Left, Right, Up and Down`.
- The color block begins to move in the direction you specify, and each empty block on the path will turn into color. If an obstacle(border or another color block) is encountered, the moving direction will turn right 90 degrees, and the block will stop moving if there is still an obstacle after the turn.
For the `gameMap` above, we can let the purple block moving down:
<img src="
https://files.gitter.im/myjinxin2015/v4g8/blob">
Then, let the green block moving up:
<img src="
https://files.gitter.im/myjinxin2015/qeT2/thumb/blob.png">
In Python, the solution will be displayed in the console like this:
```
+----+
|aAbb| # First colered block is designated 'A'
|aabb|
|aabb|
|aaBb| # Second colored block is designated 'B', etc.
+----+
```
Ok, now all the blocks are colored. You win ;-)
So easy, right? ;-) Please write a nice solution to solve this kata. I'm waiting for you, code warrior `^_^`
## Output
Your output should be a 2D array, each subarray should contains 3 elements: [`rowIndex, columnIndex, diretion`]. `rowIndex` and `columnIndex` are 0-based, diretion should be one of `"Left", "Right", "Up" and "Down"`.
For the `gameMap` above, the output should be `[[0,1,"Down"],[3,2,"Up"]]`.
Not all test cases have a solution, if there is no solution, please return a boolean value `false`.
## Examples and Note
You can submit the `example solution`(preloaded in the initial code) to see how it works ;-)
You also can play this game on the Web, [here is the game link](http://www.4399.com/flash/193270_3.htm).
## Play Games series:
- [Play Tetris : Shape anastomosis](http://www.codewars.com/kata/56c85eebfd8fc02551000281)
- [Play FlappyBird : Advance Bravely](http://www.codewars.com/kata/play-flappybird-advance-bravely)
- [Play PingPong : Precise control](http://www.codewars.com/kata/57542b169a4524d7d9000b68)
- [Play PacMan : Devour all](https://www.codewars.com/kata/575c29d5fcee86cb8b000136)
- [Play PacMan 2: The way home](https://www.codewars.com/kata/575ed46e23891f67d90000d8)
- [Ins and Outs](https://www.codewars.com/kata/576bbb41b1abc47b3900015e)
- [Three Dots](https://www.codewars.com/kata/three-dots-play-game-series-number-8)
| games | from itertools import permutations
def play_flou(game_map):
flou = Flou(parse_grid(game_map))
moves = flou . solve()
return format_moves(moves) if moves else False
def format_moves(moves):
dirs = {1: 'Right', 1j: 'Down', - 1: 'Left', - 1j: 'Up'}
return [[int(pos . imag), int(pos . real), dirs[dir_]] for pos, dir_ in moves]
def parse_grid(game_map):
map_ = game_map . splitlines()
return [[int(map_[y][x] == 'B') for x in range(1, len(map_[0]) - 1)] for y in range(1, len(map_) - 1)]
class Flou:
def __init__(self, map_):
self . map_ = map_
self . set_grid()
self . rotations = {1: 1j, 1j: - 1, - 1: - 1j, - 1j: 1}
def solve(self):
all_blocks = permutations(self . blocks)
for blocks in all_blocks:
solved = self . dfs(blocks, 0, ())
if solved:
return solved
return False
def dfs(self, blocks, i, all_moves):
if i == len(blocks):
return all_moves if all(v for v in self . grid . values()) else False
block = blocks[i]
for move in self . rotations:
if self . valid_move(move, block):
moves = self . get_moves(move, block)
valid_moves = self . dfs(blocks, i + 1, all_moves + ((block, move),))
if valid_moves:
return valid_moves
else:
self . set_moves(moves, 0)
return False
def get_moves(self, move, block):
moves = []
running = True
while running:
block += move
moves . append(block)
self . grid[block] = 1
if not self . valid_move(move, block):
next_move = self . rotations[move]
if self . valid_move(next_move, block):
move = next_move
else:
running = False
return moves
def set_moves(self, moves, val):
for move in moves:
self . grid[move] = val
def valid_move(self, move, block):
return not self . grid . get(block + move, 1)
def set_grid(self):
self . blocks = []
self . grid = {}
for y, row in enumerate(self . map_):
for x, sq in enumerate(row):
pos = x + 1j * y
self . grid[pos] = sq
if sq:
self . blocks . append(pos)
| Flou--Play game Series #9 | 5a93754d0025e98fde000048 | [
"Puzzles",
"Games",
"Game Solvers"
]
| https://www.codewars.com/kata/5a93754d0025e98fde000048 | 2 kyu |
You are Cody Block, pro skater, and you are about to enter the competition that will define your career. You must decide what tricks will make up your "run," or routine, to **maximize its expected point value**.
You will be given a list of tricks, and you must return a dictionary indicating how many times each trick should be performed. Each trick is a dictionary with a **name**, a **point value**, a **multiplier base**, and a **success probability**. When you perform a trick, you gain a number of points determined by the formula
## point value \* multiplier base<sup>number of times already performed</sup>
For example, this trick:
```
[
{
'name': 'kickflip',
'points': 100,
'mult_base': .8,
'probability': .85,
},
]
```
The first time you perform it, it will be worth 100 points (100 \* .8<sup>0</sup>), the second time it will be worth 80 points (100 \* .8<sup>1</sup>), the third time will be worth 64 points (100 \* .8<sup>2</sup>), and so on. Judges get tired of seeing the same thing over and over.
However! **If you fail a single trick during your run, your entire run will be worth zero points.** Our kickflip has an 85% chance of success, so the expected value of runs consisting of only kickflips actually looks like:
* one kickflip = 85 expected points (.85<sup>1</sup> * 100)
* two kickflips = 130.05 expected points (.85<sup>2</sup> * (100 + 80))
* three kickflips = 149.8465 expected points (.85<sup>3</sup> * (100 + 80 + 64))
* four kickflips = 154.096245 expected points (.85<sup>4</sup> * (100 + 80 + 64 + 51.2))
* five kickflips = 149.15597785 expected points (.85<sup>5</sup> * (100 + 80 + 64 + 51.2 + 40.96))
We can see that after the fourth kickflip, its point value has become so low that the risk of performing it again starts to bring the expected score down. It's only going to get worse from here. In this case, we would return the dictionary:
```
{
'kickflip': 4,
}
```
With more tricks at our disposal, though, we could string together different ones for huge points. **Most test cases will have multiple tricks available**; you will have to figure out how many repetitions of each is optimal. Variety is important, and a single attempt at a risky, high-value trick is likely to increase the expected score more than a fourth β or tenth β kickflip. Check the example tests for more advanced cases.
If there are multiple runs with the maximum possible expected score, any will be accepted. | reference | def run(tricks):
def score(attempt):
total_points = 0
total_probability = 1
for trick in tricks:
points = trick["points"]
mult_base = trick["mult_base"]
quantity = attempt[trick["name"]]
probability = trick["probability"]
total_points += points * (mult_base * * quantity - 1) / (mult_base - 1)
total_probability *= probability * * quantity
return total_points * total_probability
def best(attempt):
return max([{k: max(0, v + i) if k == trick else v for k, v in attempt . items()} for trick in attempt for i in (1, - 1)], key=score)
current_attempt = {trick["name"]: 0 for trick in tricks}
next_attempt = best(current_attempt)
while True:
if score(next_attempt) > score(current_attempt):
current_attempt = next_attempt
next_attempt = best(current_attempt)
else:
return {k: v for k, v in current_attempt . items() if v}
| Cody Block's Pro Skater | 5ba0adafd6b09fd23c000255 | [
"Statistics",
"Probability",
"Fundamentals",
"Data Science"
]
| https://www.codewars.com/kata/5ba0adafd6b09fd23c000255 | 6 kyu |
<h1><u>Theory</u></h1>
<p> <i>This section does not need to be read and can be skipped, but it does provide some clarity into the inspiration behind the problem.</i></p>
<p>In music theory, <a href = "https://en.wikipedia.org/wiki/Major_scale">a major scale</a> consists of seven notes, or <a href = "https://en.wikipedia.org/wiki/Degree_(music)">scale degrees</a>, in order (with tonic listed twice for demonstrative purposes):</p>
<ol>
<li>Tonic, the base of the scale and the note the scale is named after (for example, C is the tonic note of the C major scale)</li>
<li>Supertonic, 2 semitones (or one tone) above the tonic</li>
<li>Mediant, 2 semitones above the supertonic and 4 above the tonic</li>
<li>Subdominant, 1 semitone above the median and 5 above the tonic</li>
<li>Dominant, 2 semitones above the subdominant and 7 above the tonic</li>
<li>Submediant, 2 semitones above the dominant and 9 above the tonic</li>
<li>Leading tone, 2 semitones above the mediant and 11 above the tonic</li>
<li value = 1>Tonic (again!), 1 semitone above the leading tone and 12 semitones (or one octave) above the tonic
</ol>
<p>An <a href = "https://en.wikipedia.org/wiki/Octave">octave</a> is an <a href = "https://en.wikipedia.org/wiki/Interval_(music)">interval</a> of 12 semitones, and the <a href = "https://en.wikipedia.org/wiki/Pitch_class">pitch class</a> of a note consists of any note that is some integer
number of octaves apart from that note. Notes in the same pitch class sound different but share similar properties. If a note is in a major scale, then any note in that note's pitch class is also in that major scale.
<h1><u> Problem </u></h1>
<p>Using integers to represent notes, the <b>major scale</b> of an integer <code>note</code> will be an array (or list) of integers that follows the major scale pattern <code>note</code>, <code>note + 2</code>, <code>note + 4</code>, <code>note + 5</code>, <code>note + 7</code>, <code>note + 9</code>, <code>note + 11</code>. For example, the array of integers <code>[1, 3, 5, 6, 8, 10, 12]</code> is the major scale of <code>1</code>.</p>
<p>Secondly, the <b>pitch class</b> of a note will be the set of all integers some multiple of 12 above or below the note. For example, <code>1</code>, <code>13</code>, and <code>25</code> are all in the same pitch class.</p>
<p>Thirdly, an integer <code>note1</code> is considered to be <b>in the key of</b> an integer <code>note2</code> if <code>note1</code>, or some integer in <code>note1</code>'s pitch class, is in the <b>major scale</b> of <code>note2</code>. More mathematically, an integer <code>note1</code> is <b>in the key of</b> an integer <code>note2</code> if there exists an integer <code>i</code> such that <code>note1 + i × 12</code> is in the <b>major scale</b> of <code>note2</code>. For example, <code>22</code> is <b>in the key of</b> of 1 because, even though <code>22</code> is not in 1's major scale (<code>[1, 3, 5, 6, 8, 10, 12]</code>), <code>10</code> is and is also a multiple of 12 away from <code>22</code>. Likewise, <code>-21</code> is also <b>in the key of</b> <code>1</code> because <code>-21 + (2 × 12) = 3</code> and <code>3</code> is present in the <b>major scale</b> of 1. An array is in the key of an integer if all its elements are in the key of the integer.
<p>Your job is to create a function <code>is_tune</code> that will return whether or not an array (or list) of integers is a <b>tune</b>. An array will be considered a <b>tune</b> if there exists a single integer <code>note</code> all the integers in the array are <b>in the key of</b>. The function will accept an array of integers as its parameter and return <code>True</code> if the array is a <b>tune</b> or <code>False</code> otherwise. Empty and null arrays are not considered to be tunes. Additionally, the function should not change the input array.</p>
<h1><u> Examples </u></h1>
```python
is_tune([1, 3, 6, 8, 10, 12]) # Returns True, all the elements are in the major scale
# of 1 ([1, 3, 5, 6, 8, 10, 12]) and so are in the key of 1.
is_tune([1, 3, 6, 8, 10, 12, 13, 15]) # Returns True, 14 and 15 are also in the key of 1 as
# they are in the major scale of 13 which is in the pitch class of 1 (13 = 1 + 12 * 1).
is_tune([1, 6, 3]) # Returns True, arrays don't need to be sorted.
is_tune([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) # Returns False, this array is not in the
# key of any integer.
is_tune([2, 4, 7, 9, 11, 13]) # Returns True, the array is in the key of 2 (the arrays
# don't need to be in the key of 1, just some integer)
``` | algorithms | def is_tune(notes):
return bool(notes) and any(
all((n + i) % 12 in {0, 2, 4, 5, 7, 9, 11} for n in notes)
for i in range(12)
)
| intTunes | 5b8dc84b8ce20454bd00002e | [
"Arrays",
"Lists",
"Fundamentals",
"Algorithms"
]
| https://www.codewars.com/kata/5b8dc84b8ce20454bd00002e | 7 kyu |
# Your Task
The city of Darkishland has a strange hotel with infinite rooms. The groups that come to this hotel follow the following rules:
* At the same time only members of one group can rent the hotel.
* Each group comes in the morning of the check-in day and leaves the hotel in the evening of the check-out day.
* Another group comes in the very next morning after the previous group has left the hotel.
* A very important property of the incoming group is that it has one more member than its previous group unless it is the starting group. You will be given the number of members of the starting group.
* A group with n members stays for n days in the hotel. For example, if a group of four members comes on 1st August in the morning, it will leave the hotel on 4th August in the evening and the next group of five members will come on 5th August in the morning and stay for five days and so on.
Given the initial group size you will have to find the group size staying in the hotel on a specified day.
# Input
S denotes the initial size of the group and D denotes that you will have to find the group size staying in the hotel on D-th day (starting from 1). A group size S
means that on the first day a group of S members comes to the hotel and stays for S days. Then comes a group of S + 1 members according to the previously described rules and so on.
| reference | from math import sqrt, ceil
# 1st group spends in the hotel s days,
# 2nd group - s + 1 days,
# 3rd group - s + 2 days,
# ...,
# nth group - s + n - 1 days.
#
# The total number of days for n groups: n * (s + s + n - 1) / 2
# (by the formula of arithmetic series).
# Let d be the last day of the nth group. Then
# n * (s + s + n - 1) / 2 = d,
# n**2 + (2*s-1)*n - 2*d = 0,
# The only possible root of this quadratic equation equals
# 1/2 * (-p + sqrt(p**2 - 4*q), where p = 2*s - 1, q = 2*d.
# Thus, n = (1 - 2*s + sqrt((2*s - 1)**2 + 8*d)) / 2.
# But if d is not the last day of the group n, then n will be fractional,
# and we have to round it up (get the ceiling of n).
def group_size(s, d):
n = ceil((1 - 2 * s + sqrt((2 * s - 1) * * 2 + 8 * d)) / 2)
return s + n - 1
| The Hotel with Infinite Rooms | 5b9cf881d6b09fc9ee0002b1 | [
"Fundamentals",
"Mathematics",
"Performance"
]
| https://www.codewars.com/kata/5b9cf881d6b09fc9ee0002b1 | 7 kyu |
## Welcome
In this kata, we'll playing with a mini game `Switch the Bulb`.
<div style="max-width: 800px; margin: 0 auto;">
<img alt="Switch the Bulb" src="https://files.gitter.im/myjinxin2015/XP36/blob" style="max-width: 480px; margin: 0 auto;">
</div>
## Rule
<!--

-->
> Aim of the game is to switch on the bulbs. But circuit will be the path of power supply.
> The circuit can transfer power to bulbs in straight or diagonal bulbs only.
> Watch out the circuit boxes use the box pattern to switch on the bulbs.
> Switch all the bulbs to complete the levels.
## Task
You are given a `gameMap`, like this:
```
+--------+
|........|
|...B....| +,-,| --> The boundary of game map
|........|
|........| B --> The bulb
|........|
|...B....| . --> The empty places
|........|
|........|
+--------+
```
In the testcase, it displayed like this:

## Output
Your output should be a 2D array, each subarray should contains 2 elements: [`rowIndex, columnIndex`]. `rowIndex` and `columnIndex` are 0-based.
For the `gameMap` above, the output should be `[[1,3],[5,3]]` (for python, return a list of tuples: `[(1,3),(5,3)]`).
It means that we starting from `bulb(1,3)`, then link to `bulb(5,3)`, like this:

```if:javascript
Not all testcases have a solution, if there is no solution, please return a boolean value `false`.
```
```if:java
Not all testcases have a solution, if there is no solution, please return `null`.
```
```if:python
Not all testcases have a solution, if there is no solution, please return `None`.
```
## Examples and Notes
You can submit the `example solution` (preloaded in the initial code) to see how it works ;-)
You also can play this game on the Web, [here is the game link](http://www.4399.com/flash/180138_1.htm).
In the random tests, some game map will be very large and the number of bulbs will be `10 to 30` like this:

So, your code should be fast enough, otherwise, you'll get timeout.
## Play Games Series
- [Play Tetris : Shape anastomosis](http://www.codewars.com/kata/56c85eebfd8fc02551000281)
- [Play FlappyBird : Advance Bravely](http://www.codewars.com/kata/play-flappybird-advance-bravely)
- [Play PingPong : Precise control](http://www.codewars.com/kata/57542b169a4524d7d9000b68)
- [Play PacMan : Devour all](https://www.codewars.com/kata/575c29d5fcee86cb8b000136)
- [Play PacMan 2: The way home](https://www.codewars.com/kata/575ed46e23891f67d90000d8)
- [Ins and Outs](https://www.codewars.com/kata/576bbb41b1abc47b3900015e)
- [Three Dots](https://www.codewars.com/kata/three-dots-play-game-series-number-8)
- [Flou](https://www.codewars.com/kata/5a93754d0025e98fde000048) | games | from itertools import count
class Bulb (set):
def __init__(self, x, y): super(). __init__(); self . pos = x, y
def __hash__(self): return hash(self . pos)
def __eq__(self, o): return self . pos == o . pos
def __str__(self): return "({},{})" . format(* self . pos)
def switch_bulbs(s):
def findNeighs(x, y):
for dx, dy in moves:
for n in count(1):
i, j = pos = x + n * dx, y + n * dy
if not (0 <= i < X and 0 <= j < Y):
break
if pos in bulbs:
yield bulbs[pos]
break
def solveDFS():
if len(path) == len(bulbs):
return 1
cnds = set(path[- 1] if path else bulbs . values())
while cnds:
b = min(cnds, key=len)
if not b and len(path) != len(bulbs) - 1:
break
cnds . discard(b)
path . append(b)
for neigh in b:
neigh . discard(b)
if solveDFS():
return 1
for neigh in b:
neigh . add(b)
path . pop()
# ---------------------------------------------------------------
moves = [(dx, dy) for dx in range(- 1, 2)
for dy in range(- 1, 2) if dx or dy]
board = list(map(list, re . sub(r'[-+|]+', '', s). strip(). splitlines()))
X, Y = len(board), len(board[0])
bulbs = {(x, y): Bulb(x, y) for x, r in enumerate(board)
for y, c in enumerate(r) if c == 'B'}
for b in bulbs . values():
b . update(findNeighs(* b . pos))
path = []
return solveDFS() and [b . pos for b in path]
| Switch the Bulb--Play game Series #10 | 5a96064cfd57777828000187 | [
"Puzzles",
"Games",
"Game Solvers"
]
| https://www.codewars.com/kata/5a96064cfd57777828000187 | 3 kyu |
The King and Queen of FarFarAway are going to pay Shrek and Fiona a visit at their swamp. However, Shrek is afraid that Donkey is going to be naughty *again*, so he decides to tie him up so he will not disturb the royal dinner. Shrek grows a circular patch of delicious grass, and decides to rope Donkey to a fence post on its border. However he's afraid that when Donkey gets hungry, he will eat all the grass, and Shrek needs the grass to prepare a dish of tasty ogre grass salad for the dinner. The rope needs to be short, so Donkey won't be able to eat (or, even worse, fertilize) too much grass.

Given the diameter of the circular grass patch (measured in ogre steps), calculate the maximum length of the rope so Donkey won't be able to eat more than given percentage of grass (given as ratio in range `0 <= percentage <= 1`, i.e. `0.5` means 50%). As Shrek is just an ogre and is not really familiar with fractions, the length should be returned as whole ogre steps. Beware: in the Fairy Land, grass patches can grow very large! | reference | from math import acos, pi, sqrt
def area(r, R):
# http://mathworld.wolfram.com/Circle-CircleIntersection.html
return (
r * * 2 * acos(r / 2 / R)
+ R * * 2 * acos(1 - r * r / 2 / R / R)
- sqrt(r * r * (R + R - r) * (R + R + r)) / 2
)
def get_rope_length(diameter, ratio):
if ratio == 1:
return diameter
elif ratio * diameter == 0:
return 0
R = diameter / 2
wanted = pi * R * R * ratio
lo, hi = 0, diameter + 1
while lo < hi - 1:
m = (lo + hi) / / 2
a = area(m, R)
if a < wanted:
lo = m
else:
hi = m
return lo
| Grazing Donkey | 5b5ce2176d0db7331f0000c0 | [
"Geometry",
"Performance"
]
| https://www.codewars.com/kata/5b5ce2176d0db7331f0000c0 | 4 kyu |
You've just entered a programming contest and have a chance to win a million dollars. This is the last question you have to solve, so your victory (and your vacation) depend on it. Can you guess the function just by looking at the test cases? There are two numerical inputs and one numerical output. Goodluck!
hint: go
<abbr title="digits"> here </abbr> | games | TABLE = str . maketrans('0123456789', '9876543210')
def code(* args):
return sum(map(lambda n: int(str(n). translate(TABLE)), args))
| can you guess what it is ? | 5b1fa8d92ae7540e700000f0 | [
"Puzzles"
]
| https://www.codewars.com/kata/5b1fa8d92ae7540e700000f0 | 6 kyu |
Suppose you have 4 numbers: `0, 9, 6, 4` and 3 strings composed with them:
```
s1 = "6900690040"
s2 = "4690606946"
s3 = "9990494604"
```
Compare `s1` and `s2` to see how many positions they have in common:
`0` at index 3, `6` at index 4, `4` at index 8 : 3 common positions out of ten.
Compare `s1` and `s3` to see how many positions they have in common:
`9` at index 1, `0` at index 3, `9` at index 5 : 3 common positions out of ten.
Compare `s2` and `s3`. We find 2 common positions out of ten.
So for the 3 strings we have 8 common positions out of 30 ie 0.2666... or 26.666...%
Given `n` substrings (n >= 2) in a string `s` our function `pos_average` will calculate the average percentage of positions that are the same
between the `(n * (n-1)) / 2` sets of substrings taken amongst the given `n` substrings. It can happen that some substrings are duplicate but since their ranks are not the same in `s` they are considered as different substrings.
The function returns the percentage formatted as a float with 10 decimals but the result is tested at 1e.-9 (see function assertFuzzy in the tests).
#### Example:
Given string s = "444996, 699990, 666690, 096904, 600644, 640646, 606469, 409694, 666094, 606490"
composing a set of n = 10 substrings (hence 45 combinations), `pos_average` returns `29.2592592593`.
In a set the `n` substrings will have the same length ( > 0 ).
#### Notes
- You can see other examples in the "Sample tests".
| reference | from statistics import mean
from itertools import combinations
def pos_average(s):
return mean(a == b for combo in combinations(s . split(', '), 2) for a, b in zip(* combo)) * 100.
| Positions Average | 59f4a0acbee84576800000af | [
"Fundamentals",
"Strings"
]
| https://www.codewars.com/kata/59f4a0acbee84576800000af | 6 kyu |
Given a two-dimensional array of non negative integers ```arr```, a value ```val```, and a coordinate ```coord``` in the form ```(row, column)```, return an iterable (depending on the language) of all of the coordinates that contain the given value and are connected to the original coordinate by the given value. Connections may be made horizontally, vertically, and diagonally. If the value of ```arr``` at ```coord``` is not equal to ```val```, return an empty iterable. The coordinates must include the original coordinate and may be in any order.
## Examples:
With the following array:
```
[1,0,2,0,2,1]
[1,0,2,1,5,7]
[4,1,1,0,1,9]
```
With val `1` and coord `(0, 0)`, the output should contain (the order doesn't matter and the actual data structure depends on the language):
```
[(2, 4), (2, 1), (0, 0), (2, 2), (1, 0), (1, 3)]
```
With value `2` and coord `(0, 2)`:
```
[(0, 2), (1, 2)]
```
With value `0` and coord `(0, 0)`, the output should be empty.
| algorithms | def connected_values(mat, val, coord):
if mat[coord[0]][coord[1]] != val:
return set()
Q, seen = [coord], {coord}
while Q:
r, c = Q . pop()
for i, j in ((0, 1), (1, 0), (0, - 1), (- 1, 0), (1, 1), (1, - 1), (- 1, 1), (- 1, - 1)):
if (0 <= r + i <= len(mat) - 1) and (0 <= c + j <= len(mat[0]) - 1) and \
mat[r + i][c + j] == val and (r + i, c + j) not in seen:
Q . append((r + i, c + j))
seen . add((r + i, c + j))
return seen
| Connecting Values | 5562aa03004710f3ab0001d5 | [
"Arrays",
"Algorithms"
]
| https://www.codewars.com/kata/5562aa03004710f3ab0001d5 | 5 kyu |
> If you've finished this kata, you can try the [more difficult version](https://www.codewars.com/kata/5b256145a454c8a6990000b5).
## Taking a walk
A promenade is a way of uniquely representing a fraction by a succession of βleft or rightβ choices.
For example, the promenade `"LRLL"` represents the fraction `4/7`.
Each successive choice (`L` or `R`) changes the value of the promenade by combining the values of the
promenade before the most recent left choice with the value before the most recent right choice. If the value before the most recent left choice was *l/m* and the value before the most recent right choice
was r/s then the new value will be *(l+r) / (m+s)*.
If there has never been a left choice we use *l=1* and *m=0*;
if there has never been a right choice we use *r=0* and *s=1*.
So let's take a walk.
* `""` An empty promenade has never had a left choice nor a right choice. Therefore we use *(l=1 and m=0)* and *(r=0 and s=1)*.
So the value of `""` is *(1+0) / (0+1) = 1/1*.
* `"L"`. Before the most recent left choice we have `""`, which equals *1/1*. There still has never been a right choice, so *(r=0 and s=1)*. So the value of `"L"` is *(1+0)/(1+1) = 1/2*
* `"LR"` = 2/3 as we use the values of `""` (before the left choice) and `"L"` (before the right choice)
* `"LRL"` = 3/5 as we use the values of `"LR"` and `"L"`
* `"LRLL"` = 4/7 as we use the values of `"LRL"` and `"L"`
Fractions are allowed to have a larger than b.
## Your task
Implement the `promenade` function, which takes an promenade as input (represented as a string), and returns
the corresponding fraction (represented as a tuple, containing the numerator and the denominator).
```Python
promenade("") == (1,1)
promenade("LR") == (2,3)
promenade("LRLL") == (4,7)
```
```Java
Return the Fraction as an int-Array:
promenade("") == [1,1]
promenade("LR") == [2,3]
promenade("LRLL") == [4,7]
```
*adapted from the 2016 British Informatics Olympiad* | games | def promenade(choices):
def compute(): return l + r, m + s
l, m, r, s = 1, 0, 0, 1
for c in choices:
if c == 'L':
l, m = compute()
else:
r, s = compute()
return compute()
| Promenade Fractions (from BIO 2016) | 5b254b2225c2bb99c500008d | [
"Puzzles"
]
| https://www.codewars.com/kata/5b254b2225c2bb99c500008d | 6 kyu |
Imagine you run a business selling some products. Every evening, you run a program that generates a report on the day's sales. The products are grouped into product groups and the report tells you the day's revenue for each product, group, and the grand total. The program takes as input a sequence of tuples `(product_id, group_id, value)`, where `value` is the value sold for for each of the given products. The input is subject to the following constraints:
1. Each product has a unique `product_id` consisting of a string of four digits.
2. Each product belongs to a unique group.
3. Each group has a unique `group_id` consisting of a string of three digits.
4. The input may contain multiple tuples with the same `product_id`.
5. The value reported for a product is the sum of the values of all tuples that have the product's `product_id`.
6. The input is sorted by `group_id` and then by `product_id`
7. The value is given as a positive integer.
8. The type of the input is unknown other than that it is _iterable_.
The output of the program is a string that, when printed, follows the format of the following example:
```
Group: 001
Product: 0001 Value: 12
Product: 0012 Value: 1032
Group total: 1044
Group: 007
Product: 0027 Value: 207
Product: 0112 Value: 12119
Product: 1009 Value: 200
Group total: 12526
Total: 13570
```
Do not use tabs in the output, but make sure to insert the correct amount of spaces. Do not include any whitespace at the end of a line. The values may have up to six digits and a single space separates each column. The groups must appear in ascending order of their `group_id`. The products within each group must appear in ascending order of their `product_id`.
Write a function `generate_report(records)` that generates the report for given input `records`.
Example: Let the input be `[('0001', '001', 12), ('0012', '001', 1000), ('0012', '001', 32), ('0027', '007', 207), ('0112', '007', 12119), ('1009', '007', 200)]`. Then the output shall be as shown in the example above. | reference | PRODUCT_STRING = " Product: {} Value: {:>6}"
TOTAL_STRING = "Total:{:>32}"
GROUP_STRING = """Group: {}
{}
Group total:{:>22}
"""
def generate_report(records):
ansLst, cGrp, cProd, cTot = [], 0, 0, 0
grpLst, records = [], list(records)
for (prod, grp, val), (nextProd, nextGrp, _) in zip(records, list(records[1:]) + [("", "", 0)]):
cGrp += val
cProd += val
cTot += val
if (prod, grp) != (nextProd, nextGrp): # Change of product or group after this one
grpLst += [PRODUCT_STRING . format(prod, cProd)]
cProd = 0
if grp != nextGrp: # end of a group after this one
ansLst += [GROUP_STRING . format(grp, '\n' . join(grpLst), cGrp)]
grpLst, cGrp, cProd = [], 0, 0
ansLst += [TOTAL_STRING . format(cTot)]
ans = '\n' . join(ansLst)
return ans
| Sales report | 577f57d7e555335c0d0003a9 | [
"Fundamentals"
]
| https://www.codewars.com/kata/577f57d7e555335c0d0003a9 | 6 kyu |
In this Kata, you will be given a series of times at which an alarm sounds. Your task will be to determine the maximum time interval between alarms. Each alarm starts ringing at the beginning of the corresponding minute and rings for exactly one minute. The times in the array are not in chronological order. Ignore duplicate times, if any.
```Haskell
For example:
solve(["14:51"]) = "23:59". If the alarm sounds now, it will not sound for another 23 hours and 59 minutes.
solve(["23:00","04:22","18:05","06:24"]) == "11:40". The max interval that the alarm will not sound is 11 hours and 40 minutes.
```
In the second example, the alarm sounds `4` times in a day.
More examples in test cases. Good luck! | algorithms | from datetime import datetime
def solve(arr):
dts = [datetime(2000, 1, 1, * map(int, x . split(':')))
for x in sorted(arr)]
delta = max(int((b - a). total_seconds() - 60)
for a, b in zip(dts, dts[1:] + [dts[0]. replace(day=2)]))
return '{:02}:{:02}' . format(* divmod(delta / / 60, 60))
| Simple time difference | 5b76a34ff71e5de9db0000f2 | [
"Algorithms",
"Date Time",
"Strings"
]
| https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2 | 6 kyu |
# Background
My TV remote control has arrow buttons and an `OK` button.
I can use these to move a "cursor" on a logical screen keyboard to type words...
# Keyboard
The screen "keyboard" layout looks like this
<style>
#tvkb {
width : 400px;
border: 5px solid gray; border-collapse: collapse;
}
#tvkb td {
color : orange;
background-color : black;
text-align : center;
border: 3px solid gray; border-collapse: collapse;
}
</style>
<table id = "tvkb">
<tr><td>a<td>b<td>c<td>d<td>e<td>1<td>2<td>3</tr>
<tr><td>f<td>g<td>h<td>i<td>j<td>4<td>5<td>6</tr>
<tr><td>k<td>l<td>m<td>n<td>o<td>7<td>8<td>9</tr>
<tr><td>p<td>q<td>r<td>s<td>t<td>.<td>@<td>0</tr>
<tr><td>u<td>v<td>w<td>x<td>y<td>z<td>_<td>/</tr>
<tr><td>aA<td>SP<td style="background-color: orange"><td style="background-color: orange"><td style="background-color: orange"><td style="background-color: orange"><td style="background-color: orange"><td style="background-color: orange"></tr>
</table>
* `aA` is the SHIFT key. Pressing this key toggles alpha characters between UPPERCASE and lowercase
* `SP` is the space character
* The other blank keys in the bottom row have no function
# Kata task
How many button presses on my remote are required to type the given `words`?
## Hint
This Kata is an extension of the earlier ones in this series. You should complete those first.
## Notes
* The cursor always starts on the letter `a` (top left)
* The alpha characters are initially lowercase (as shown above)
* Remember to also press `OK` to "accept" each letter
* Take the shortest route from one letter to the next
* <span style="color:red;">The cursor wraps,</span> so as it moves off one edge it will reappear on the opposite edge
* Although the blank keys have no function, you may navigate through them if you want to
* Spaces may occur anywhere in the `words` string
* Do not press the SHIFT key until you need to. For example, with the word `e.Z`, the SHIFT change happens **after** the `.` is pressed (not before)
# Example
words = `Code Wars`
* C => `a`-`aA`-OK-`A`-`B`-`C`-OK = 6
* o => `C`-`B`-`A`-`aA`-OK-`u`-`v`-`w`-`x`-`y`-`t`-`o`-OK = 12
* d => `o`-`j`-`e`-`d`-OK = 4
* e => `d`-`e`-OK = 2
* space => `e`-`d`-`c`-`b`-`SP`-OK = 5
* W => `SP`-`aA`-OK-`SP`-`V`-`W`-OK = 6
* a => `W`-`V`-`U`-`aA`-OK-`a`-OK = 6
* r => `a`-`f`-`k`-`p`-`q`-`r`-OK = 6
* s => `r`-`s`-OK = 2
Answer = 6 + 12 + 4 + 2 + 5 + 6 + 6 + 6 + 2 = 49
<hr style="background-color:orange;height:2px;width:75%;margin-top:30px;margin-bottom:30px;"/>
<span style="color:orange;">
*Good Luck!<br/>
DM.*
</span>
<hr>
Series
* <a href=https://www.codewars.com/kata/tv-remote>TV Remote</a>
* <a href=https://www.codewars.com/kata/tv-remote-shift-and-space>TV Remote (shift and space)</a>
* TV Remote (wrap)
* <a href=https://www.codewars.com/kata/tv-remote-symbols>TV Remote (symbols)</a>
| algorithms | import re
H, W = 6, 8
KEYBOARD = "abcde123fghij456klmno789pqrst.@0uvwxyz_/* "
MAP = {c: (i / / W, i % W) for i, c in enumerate(KEYBOARD)}
def manhattan(* pts):
dxy = [abs(z2 - z1) for z1, z2 in zip(* pts)]
return 1 + sum(min(dz, Z - dz) for dz, Z in zip(dxy, (H, W)))
def toggle(m):
ups, end = m . groups()
# Toggle Shift ON if uppercase presents, and then OFF if lowercase after (or end of the string)
return f'* { ups . lower ()} * { end } '
def tv_remote(words):
# Strip any useless toggle OFF at the end
reWords = re . sub(r'([A-Z][^a-z]*)([a-z]?)', toggle, words). rstrip('*')
return sum(manhattan(MAP[was], MAP[curr]) for was, curr in zip('a' + reWords, reWords))
| TV Remote (wrap) | 5b2c2c95b6989da552000120 | [
"Algorithms"
]
| https://www.codewars.com/kata/5b2c2c95b6989da552000120 | 6 kyu |
# Background
My TV remote control has arrow buttons and an `OK` button.
I can use these to move a "cursor" on a logical screen keyboard to type words...
# Keyboard
The screen "keyboard" layout looks like this
<style>
#tvkb {
width : 400px;
border: 5px solid gray; border-collapse: collapse;
}
#tvkb td {
color : orange;
background-color : black;
text-align : center;
border: 3px solid gray; border-collapse: collapse;
}
</style>
<table id = "tvkb">
<tr><td>a<td>b<td>c<td>d<td>e<td>1<td>2<td>3</tr>
<tr><td>f<td>g<td>h<td>i<td>j<td>4<td>5<td>6</tr>
<tr><td>k<td>l<td>m<td>n<td>o<td>7<td>8<td>9</tr>
<tr><td>p<td>q<td>r<td>s<td>t<td>.<td>@<td>0</tr>
<tr><td>u<td>v<td>w<td>x<td>y<td>z<td>_<td>/</tr>
<tr><td>aA<td>SP<td style="background-color: orange"><td style="background-color: orange"><td style="background-color: orange"><td style="background-color: orange"><td style="background-color: orange"><td style="background-color: orange"></tr>
</table>
* `aA` is the SHIFT key. Pressing this key toggles alpha characters between UPPERCASE and lowercase
* `SP` is the space character
* The other blank keys in the bottom row have no function
# Kata task
How many button presses on my remote are required to type the given `words`?
## Notes
* The cursor always starts on the letter `a` (top left)
* The alpha characters are initially lowercase (as shown above)
* Remember to also press `OK` to "accept" each letter
* Take a direct route from one letter to the next
* The cursor does not wrap (e.g. you cannot leave one edge and reappear on the opposite edge)
* Although the blank keys have no function, you may navigate through them if you want to
* Spaces may occur anywhere in the `words` string.
* Do not press the SHIFT key until you need to. For example, with the word `e.Z`, the SHIFT change happens **after** the `.` is pressed (not before)
# Example
words = `Code Wars`
* C => `a`-`f`-`k`-`p`-`u`-`aA`-OK-`U`-`P`-`K`-`F`-`A`-`B`-`C`-OK = 14
* o => `C`-`H`-`M`-`R`-`W`-`V`-`U`-`aA`-OK-`SP`-`v`-`q`-`l`-`m`-`n`-`o`-OK = 16
* d => `o`-`j`-`e`-`d`-OK = 4
* e => `d`-`e`-OK = 2
* space => `e`-`d`-`c`-`b`-`g`-`l`-`q`-`v`-`SP`-OK = 9
* W => `SP`-`aA`-OK-`SP`-`V`-`W`-OK = 6
* a => `W`-`V`-`U`-`aA`-OK-`u`-`p`-`k`-`f`-`a`-OK = 10
* r => `a`-`f`-`k`-`p`-`q`-`r`-OK = 6
* s => `r`-`s`-OK = 2
Answer = 14 + 16 + 4 + 2 + 9 + 6 + 10 + 6 + 2 = 69
<hr style="background-color:orange;height:2px;width:75%;margin-top:30px;margin-bottom:30px;"/>
<span style="color:orange;">
*Good Luck!<br/>
DM.*
</span>
<hr>
Series
* <a href=https://www.codewars.com/kata/tv-remote>TV Remote</a>
* TV Remote (shift and space)
* <a href=https://www.codewars.com/kata/tv-remote-wrap>TV Remote (wrap)</a>
* <a href=https://www.codewars.com/kata/tv-remote-symbols>TV Remote (symbols)</a>
| algorithms | import re
def tv_remote(words):
letters = {c: (x, y)
for y, row in enumerate((
"abcde123",
"fghij456",
"klmno789",
"pqrst.@0",
"uvwxyz_/",
"β§ "))
for x, c in enumerate(row)}
words = re . sub(r'((?:^|[a-z])[^A-Z]*)([A-Z])', r'\1β§\2', words)
words = re . sub(r'([A-Z][^a-z]*)([a-z])', r'\1β§\2', words)
words = words . lower()
return sum(
abs(letters[c1][0] - letters[c2][0]) +
abs(letters[c1][1] - letters[c2][1]) + 1
for c1, c2 in zip("a" + words, words))
| TV Remote (shift and space) | 5b277e94b6989dd1d9000009 | [
"Algorithms"
]
| https://www.codewars.com/kata/5b277e94b6989dd1d9000009 | 6 kyu |
In this Kata, you will be given a number and your task will be to rearrange the number so that it is divisible by `25`, but without leading zeros. Return the minimum number of digit moves that are needed to make this possible. If impossible, return `-1` ( `Nothing` in Haskell ).
For example:
```c
solve(521) = 3 because:
a) Move the digit '1' to the front: 521 -> 512 -> 152. The digit '1' is moved two times.
b) Move '5' to the end: 152 -> 125. The digit '5' is moved one time, so total movement = 3.
Of all the ways to accomplish this, the least digit moves = 3.
solve(100) = 0. Number already divisible by 25.
solve(1) = -1. Not possible to make number divisible by 25.
solve(0) is not tested.
```
More examples in test cases.
Good luck! | reference | def solve(n):
moves = []
for a, b in ["25", "75", "50", "00"]:
s = str(n)[:: - 1]
x = s . find(a)
y = s . find(b, x + 1 if a == "0" else 0)
if x == - 1 or y == - 1:
continue
moves . append(x + y - (x > y) - (a == b))
s = s . replace(a, "", 1). replace(b, "", 1)
l = len(s . rstrip("0"))
if l:
moves[- 1] = moves[- 1] + (len(s) - l)
elif s:
moves . pop()
return min(moves, default=- 1)
| Simple number divisibility | 5b165654c8be0d17f40000a3 | [
"Fundamentals"
]
| https://www.codewars.com/kata/5b165654c8be0d17f40000a3 | 6 kyu |
<!--Range of Integers in an Unsorted String-->
<p>In this kata, your task is to write a function that returns the smallest and largest integers in an unsorted string. In this kata, a range is considered a finite sequence of consecutive integers.</p>
<h2 style='color:#f88'>Input</h2>
Your function will receive two arguments:
<ul>
<li>A <code>string</code> comprised of integers in an unknown range; think of this string as the result when a range of integers is shuffled around in random order then joined together into a string</li>
<li>An <code>integer</code> value representing the size of the range</li>
</ul>
<h2 style='color:#f88'>Output</h2>
<p>Your function should return the starting (minimum) and ending (maximum) numbers of the range in the form of an array/list comprised of two integers.</p>
<h2 style='color:#f88'>Test Example</h2>
```python
input_string = '1568141291110137'
mystery_range(input_string, 10) # [6, 15]
# The 10 numbers in this string are:
# 15 6 8 14 12 9 11 10 13 7
# Therefore the range of numbers is from 6 to 15
```
```javascript
let inputString = '1568141291110137';
mysteryRange(inputString, 10) // [6, 15]
// The 10 numbers in this string are:
// 15 6 8 14 12 9 11 10 13 7
// Therefore the range of numbers is from 6 to 15
```
```go
inputString := "1568141291110137"
MysteryRange(inputString, 10) // [6 15]
// The 10 numbers in this string are:
// 15 6 8 14 12 9 11 10 13 7
// Therefore the range of numbers is from 6 to 15
```
```elixir
# For Elixir, return a tuple
input_string = "1568141291110137"
KataSolution.mystery_range(input_string, 10) # {6, 15}
# The 10 numbers in this string are:
# 15 6 8 14 12 9 11 10 13 7
# Therefore the range of numbers is from 6 to 15
```
```csharp
string input_string = "1568141291110137";
KataSolution.MysteryRange(input_string, 10); // [6, 15]
// The 10 numbers in this string are:
// 15 6 8 14 12 9 11 10 13 7
// Therefore the range of numbers is from 6 to 15
```
```ruby
input_string = '1568141291110137'
mystery_range(input_string, 10) # [6, 15]
# The 10 numbers in this string are:
# 15 6 8 14 12 9 11 10 13 7
# Therefore the range of numbers is from 6 to 15
```
```kotlin
// return a Pair for Kotlin
val inputString = "1568141291110137"
mysteryRange(inputString, 10) // Pair(6, 15)
// The 10 numbers in this string are:
// 15 6 8 14 12 9 11 10 13 7
// Therefore the range of numbers is from 6 to 15
```
```rust
let actual = mystery_range("1568141291110137", 10);
assert_eq!(actual, (6,15));// OK
// The 10 numbers in this string are:
// 15 6 8 14 12 9 11 10 13 7
// Therefore the range of numbers is from 6 to 15
```
<h2 style='color:#f88'>Technical Details</h2>
<ul>
<li>The maximum size of a range will be <code>100</code> integers</li>
<li>The starting number of a range will be: <code>0 < n < 100</code></li>
<li>Full Test Suite: <code>21</code> fixed tests, <code>100</code> random tests</li>
<li>Use Python 3+ for the Python translation</li>
<li>For JavaScript, <code>require</code> has been disabled and most built-in prototypes have been frozen (prototype methods can be added to <code>Array</code> and <code>Function</code>)</li>
<li>All test cases will be valid</li>
</ul>
<p>If you enjoyed this kata, be sure to check out <a href='https://www.codewars.com/users/docgunthrop/authored' style='color:#9f9;text-decoration:none'>my other katas</a></p> | games | from collections import Counter
def mystery_range(s, n):
counts = Counter(s)
for num in range(1, 100):
if counts == Counter('' . join(map(str, range(num, num + n)))):
if all(str(i) in s for i in range(num, num + n)):
return [num, num + n - 1]
| Range of Integers in an Unsorted String | 5b6b67a5ecd0979e5b00000e | [
"Algorithms",
"Puzzles"
]
| https://www.codewars.com/kata/5b6b67a5ecd0979e5b00000e | 5 kyu |
# Background
Every time you photocopy something the quality of the copy is never quite as good as the original.
But then you make a copy of copy, and then a copy of that copy, et cetera... And the results get worse each time.
This kind of degradation is called <a href="https://en.wikipedia.org/wiki/Generation_loss">Generation Loss</a>.
<a href="https://www.youtube.com/watch?v=G8GOcB6H0uQ">Here</a> is a fun example of generation loss copying VHS tapes.
# Kata task
In this Kata you will be given 2 sheets of paper.
The first one is the original, and the second one is the result of copying many times. Let's call these papers `orig` and `copy`.
Only a small % of generation loss happens at each copy, but the effect is cummulative and the copies quickly become more like gibberish.
Your task is to return true/false if `orig` is a possible ancestor of `copy`.
# Notes
* The `orig` document may include any kind of character
* Copied characters will degrade as follows: `A`-`Z` <span style='color:orange'>⇒</span> `a`-`z` <span style='color:orange'>⇒</span> `#` <span style='color:orange'>⇒</span> `+` <span style='color:orange'>⇒</span> `:` <span style='color:orange'>⇒</span> `.` <span style='color:orange'>⇒</span> ` `
* Any other character not mentioned above (e.g. digits) do not degrade
* For the uppercase to lowercase degradation the letters must be the same (i.e. `A` <span style='color:orange'>⇒</span> `a` ... `Z` <span style='color:orange'>⇒</span> `z`)
# Example
(5% error rate)
<div>
<table style='width:50%;'>
<tr style='color:orange'><th>Original<th>After 20 copies...<th>After 75 copies...</tr>
<tr>
<td><pre style='color:black;background-color:white;'>
THE QUICK BROWN FOX JUMPS OVER A LAZY DOG.
THE QUICK BROWN FOX JUMPS OVER A LAZY DOG.
THE QUICK BROWN FOX JUMPS OVER A LAZY DOG.
THE QUICK BROWN FOX JUMPS OVER A LAZY DOG.
THE QUICK BROWN FOX JUMPS OVER A LAZY DOG.
THE QUICK BROWN FOX JUMPS OVER A LAZY DOG.
THE QUICK BROWN FOX JUMPS OVER A LAZY DOG.
THE QUICK BROWN FOX JUMPS OVER A LAZY DOG.
THE QUICK BROWN FOX JUMPS OVER A LAZY DOG.
THE QUICK BROWN FOX JUMPS OVER A LAZY DOG.
</pre></td>
<td><pre style='color:black;background-color:white;'>
TH# Q+#Ck BRow# F+x J#MPS over A Laz# #+#
:He Qui#k #rO#n foX Ju#Ps oVer a la+y Do+
THe QUiC# b:OWn #oX ##m#s #Ver + lAZ# D#G
##E #uIcK BROWn Fox #UMPS o#Er A LaZY doG.
#H+ Qui## BROW# +ox jUMPs OV#r a lAzy ###.
##e +UICK #ROWn fo# +#mPs #Ve+ a lazY dOg
### ##IC+ Br### f#x Jump# oVE+ A La## dOg.
th+ qUI#k bRO#n fOX #umP# o#ER A La+Y #O.
tH# #U:#k +r+## F+# +#mP+ #VeR A ###Y DOg.
#H# QUIcK #ROwN #o+ juM#s #V#+ A #aZy dog
</pre></td>
<td><pre style='color:black;background-color:white;'>
## q :c+ +r# . ..# #. #+ #+ a #:+: .
.+ Q#:## +::: +++ :::+. .#.# . :. + #:
:: q#.c# . ..# : :.: :v:+ +a.+ .+#
:++ :.+k +:+:# f.. .:m: o:# . :+#y #+
+# :::. +::++ :: #:.+: #+ +:z. .:
. e .:#c# ##:+# : .p# +v: . #++: #++
..: ..:. ++++ +++ ++:p: +ve A L+.. # +
::. :ui :## : +Ox +#::: :::+ + ++ + :#
+# + + + .+ f . : + :. : ++ y +.+
++ .u#+k +r#.. +: :::+. ## # :+# +##
</pre></td>
</tr>
</table>
</div>
| algorithms | from string import ascii_uppercase, ascii_lowercase
s, D = "#+:. ", {}
for i, c in enumerate(s):
D[c] = s[i:]
for c in ascii_uppercase:
D [c] = c + c . lower () + s
for c in ascii_lowercase:
D[c] = c + s
def generation_loss (orig, copy):
return len (orig ) == len (copy ) and all (y in D . get (x , x ) for x , y in zip (orig , copy )) | Photocopy decay | 5b6fcd9668cb2e282d00000f | [
"Strings",
"Algorithms"
]
| https://www.codewars.com/kata/5b6fcd9668cb2e282d00000f | 6 kyu |
# Your task
Oh no... more lemmings!! And in Lemmings Planet a huge battle
is being fought between the two great rival races: the green
lemmings and the blue lemmings. Everybody was now assigned
to battle and they will fight until one of the races completely
dissapears: the Deadly War has begun!
Every single lemming has a power measure that describes its
ability to fight. When two single lemmings fight with each one,
the lemming with more power survives and the other one dies.
However, the power of the living lemming gets smaller after the
fight, exactly in the value of the power of the lemming that died.
For example, if we have a green lemming with power ``50`` and a
blue lemming with power ``40``, the blue one dies and the green one
survives, but having only power 10 after the battle ``(50-40=10)``.
If two lemmings have the same power when they fight, both of
them die.
In the fight between the two races, there are a certain number of battlefields. Each race assigns one
lemming for each battlefield, starting with the most powerful. So for example, if a race has 5 lemmings
with power ```{50, 50, 40, 40, 30}``` and we have `3` battlefields, then a lemming with power `50` will be assigned
to battlefield 1, another with `50` power will be assigned to battlefield 2 and last a lemming with power `40` will go to battlefield 3. The other race will do the same.
The Deadly War is processed by having each race send its best soldiers as described to the battle-
fields, making a battle round. Then, all battles process at the same time, and some of the lemmings
will emerge victorious (but with less power) and some of them will die. The surviving ones will return to their raceβs army and then a new round will begin, with each race sending again its best remaining soldiers to the battlefields. If at some point a race does not have enough soldiers to fill all battlefields, then only the ones with soldiers from both races will have a fight.
The Deadly War ends when one of the races has no more lemmings or when both of them disappear
at the same time. For example, imagine a war with 2 battlefields and a green army with powers `{20,10}` and a blue army with powers `{10, 10, 15}`. The first round will have `20 vs 15` in battlefield 1 and `10 vs 10` in battlefield 2. After these battles, green race will still have a power `5` lemming (that won on battlefield 1) and blue race will have one with power 10 (that did not fight). The ones in battlefield 2
died, since they both had the same power. Afer that comes a second round, and only battlefield 1 will have a fight, being `5 vs 10`. The blue lemming wins, killing the last green soldier and giving the victory to the blue race!
But in the real battle, will victory be green or blue?
Given the number of battefields and the armies of both races, your task is to discover which race
will win the Deadly War and show the power of the surviving soldiers.
## Input
You are given B, SG and SB, representing respectively the number of battlefields available, a vector of integers size `n` of lemmings in the green army
and a vector of integers size `n` of lemmings in the blue army (1 β€ B, SG, SB β€ 100000).
The lemmings in each army do not need to come in any particular order.
## Output
For each test case you should return :
β’ "Green and Blue died" if both races died in the same round
β’ "Green wins : Each surviving soldier in descending order" if the green army won the Deadly War
β’ "Blue wins : Each surviving soldier in descending order" if the blue army won the Deadly War
## Example
```cpp
lemmings_battle(5, {10}, {10}) == "Green and Blue died"
lemmings_battle(2, {20,10}, {10,10,15}) == "Blue wins: 5"
lemmings_battle(3, {50,40,30,40,50}, {50,30,30,20,60}) == "Green wins: 10 10"
```
```python
lemming_battle(5, [10], [10]) == "Green and Blue died"
lemming_battle(2, [20,10], [10,10,15]) == "Blue wins: 5"
lemming_battle(3, [50,40,30,40,50], [50,30,30,20,60]) == "Green wins: 10 10"
```
```ruby
lemming_battle(5, [10], [10]) == "Green and Blue died"
lemming_battle(2, [20,10], [10,10,15]) == "Blue wins: 5"
lemming_battle(3, [50,40,30,40,50], [50,30,30,20,60]) == "Green wins: 10 10"
```
```javascript
lemmingBattle(5, [10], [10]) === "Green and Blue died"
lemmingBattle(2, [20,10], [10,10,15]) === "Blue wins: 5"
lemmingBattle(3, [50,40,30,40,50], [50,30,30,20,60]) === "Green wins: 10 10"
```
```swift
lemmingBattle(5, [10], [10]) == "Green and Blue died"
lemmingBattle(2, [20,10], [10,10,15]) == "Blue wins: 5"
lemmingBattle(3, [50,40,30,40,50], [50,30,30,20,60]) == "Green wins: 10 10"
```
| reference | from heapq import *
def lemming_battle(battlefield, green, blue):
hg, hb = ([- v for v in lst] for lst in (green, blue))
heapify(hg)
heapify(hb)
while hb and hg:
tmp_b, tmp_g = [], []
for _ in range(min(battlefield, len(hg), len(hb))):
cmp = heappop(hg) - heappop(hb)
if cmp < 0:
tmp_g . append(cmp)
elif cmp > 0:
tmp_b . append(- cmp)
for lem in tmp_b:
heappush(hb, lem)
for lem in tmp_g:
heappush(hg, lem)
winner, lst = ("Green", hg) if hg else ("Blue", hb)
survivors = ' ' . join(str(- v) for v in sorted(lst))
return ("Green and Blue died" if not hg and not hb else
f" { winner } wins: { survivors } ")
| Lemmings Battle! | 5b7d2cca7a2013f79f000129 | [
"Fundamentals",
"Games"
]
| https://www.codewars.com/kata/5b7d2cca7a2013f79f000129 | 6 kyu |
We have an array of unique elements. A special kind of permutation is the one that has all of its elements in a different position than the original.
Let's see how many of these permutations may be generated from an array of four elements. We put the original array with square brackets and the wanted permutations with parentheses.
```
arr = [1, 2, 3, 4]
(2, 1, 4, 3)
(2, 3, 4, 1)
(2, 4, 1, 3)
(3, 1, 4, 2)
(3, 4, 1, 2)
(3, 4, 2, 1)
(4, 1, 2, 3)
(4, 3, 1, 2)
(4, 3, 2, 1)
_____________
A total of 9 permutations with all their elements in different positions than arr
```
The task for this kata would be to create a code to count all these permutations for an array of certain length.
Features of the random tests:
```
l = length of the array
10 β€ l β€ 5000
```
See the example tests.
Enjoy it! | reference | def all_permuted(n):
a, b = 0, 1
for i in range(1, n):
a, b = b, (i + 1) * (a + b)
return a
| Shuffle It Up | 5b997b066c77d521880001bd | [
"Performance",
"Algorithms",
"Mathematics",
"Machine Learning",
"Combinatorics",
"Number Theory"
]
| https://www.codewars.com/kata/5b997b066c77d521880001bd | 5 kyu |
# Task
Write a function that accepts `msg` string and returns local tops of string from the highest to the lowest.
The string's tops are from displaying the string in the below way:
```
7891012
TUWvXY 6 3
ABCDE S Z 5
lmno z F R 1 4
abc k p v G Q 2 3
.34..9 d...j q....x H.....P 3......2
125678 efghi rstuwy IJKLMNO 45678901
```
The next top is always 1 character higher than the previous one.
For the above example, the solution for the `123456789abcdefghijklmnopqrstuwyxvzABCDEFGHIJKLMNOPQRSTUWvXYZ123456789012345678910123` input string is `7891012TUWvXYABCDElmnoabc34`.
- When the `msg` string is empty, return an empty string.
- The input strings may be very long. Make sure your solution has good performance.
- The (.)dots on the sample dispaly of string are only there to help you to understand the pattern
Check the test cases for more samples.
# Series
- [String tops](https://www.codewars.com/kata/59b7571bbf10a48c75000070)
- [Square string tops](https://www.codewars.com/kata/5aa3e2b0373c2e4b420009af) | reference | def tops(msg):
n = len(msg)
res, i, j, k = "", 2, 2, 7
while i < n:
res = msg[i: i + j] + res
i, j, k = i + k, j + 1, k + 4
return res
| Square string tops | 5aa3e2b0373c2e4b420009af | [
"Fundamentals",
"Strings"
]
| https://www.codewars.com/kata/5aa3e2b0373c2e4b420009af | 6 kyu |
Many years ago, Roman numbers were defined by only `4` digits: `I, V, X, L`, which represented `1, 5, 10, 50`. These were the only digits used. The value of a sequence was simply the sum of digits in it. For instance:
```
IV = VI = 6
IX = XI = 11
XXL = LXX = XLX = 70
```
It is easy to see that this system is ambiguous, and some numbers could be written in many different ways. Your goal is to determine how many distinct integers could be represented by exactly `n` Roman digits grouped together. For instance:
```Perl
solve(1) = 4, because groups of 1 are [I, V, X, L].
solve(2) = 10, because the groups of 2 are [II, VI, VV, XI, XV, XX, IL, VL, XL, LL] corresponding to [2,6,10,11,15,20,51,55,60,100].
solve(3) = 20, because groups of 3 start with [III, IIV, IVV, ...etc]
```
`n <= 10E7`
More examples in test cases. Good luck! | reference | INITIAL = [0, 4, 10, 20, 35, 56, 83, 116, 155, 198, 244, 292]
def solve(n):
return INITIAL[n] if n < 12 else 292 + (49 * (n - 11))
| Strange roman numbers | 5b983dcd660b1227d00002c9 | [
"Fundamentals"
]
| https://www.codewars.com/kata/5b983dcd660b1227d00002c9 | 6 kyu |
There are some perfect squares with a particular property.
For example the number ```n = 256``` is a perfect square, its square root is ```16```. If we change the position of the digits of n, we may obtain another perfect square``` 625``` (square root = 25).
With these three digits ```2```,```5``` and ```6``` we can get two perfect squares: ```[256,625]```
The number ```1354896``` may generate another ```4``` perfect squares, having with the number itself, a total of five perfect squares: ```[1354896, 3594816, 3481956, 5391684, 6395841]```, being the last one in the list, ```6395841```, the highest value of the set.
Your task is to find the first perfect square above the given lower_limit, that can generate the given k number of perfect squares, and it doesn't contain the digit 0. Then return the maximum perfect square that can be obtained from its digits.
Example with the cases seen above:
```
lower_limit = 200
k = 2 (amount of perfect squares)
result = 625
lower_limit = 3550000
k = 5 (amount of perfect squares)
result = 6395841
```
Features of the random tests:
```
100 <= lower_limit <= 1e6
2 <= k <= 5
number of tests = 45
```
Have a good time! | reference | from itertools import count, permutations
def next_perfectsq_perm(limit_below, k):
for n in count(int(limit_below * * .5) + 1):
s = str(n * * 2)
if '0' not in s:
sq_set = {x for x in (int('' . join(p)) for p in permutations(s)) if (x * * .5). is_integer()}
if len(sq_set) == k:
return max(sq_set)
| Highest Perfect Square with Same Digits | 5b2cd515553292a4ff0000c2 | [
"Fundamentals",
"Data Structures",
"Algorithms",
"Mathematics",
"Performance",
"Permutations"
]
| https://www.codewars.com/kata/5b2cd515553292a4ff0000c2 | 6 kyu |
In this Kata, you will be given directions and your task will be to find your way back.
```Perl
solve(["Begin on Road A","Right on Road B","Right on Road C","Left on Road D"]) = ['Begin on Road D', 'Right on Road C', 'Left on Road B', 'Left on Road A']
solve(['Begin on Lua Pkwy', 'Right on Sixth Alley', 'Right on 1st Cr']) = ['Begin on 1st Cr', 'Left on Sixth Alley', 'Left on Lua Pkwy']
```
More examples in test cases.
Good luck!
Please also try [Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7) | algorithms | DIRS = {'Left': 'Right', 'Right': 'Left'}
def solve(arr):
lst, prevDir = [], 'Begin'
for cmd in arr[:: - 1]:
d, r = cmd . split(' on ')
follow = DIRS . get(prevDir, prevDir)
prevDir = d
lst . append(f' { follow } on { r } ')
return lst
| Simple directions reversal | 5b94d7eb1d5ed297680000ca | [
"Algorithms"
]
| https://www.codewars.com/kata/5b94d7eb1d5ed297680000ca | 7 kyu |
Jack and Jill are playing a game. They have balls numbered from `0` to `n - 1`. Jack looks the other way and asks Jill to reverse the position of the balls, for instance, to change the order from say, `0,1,2,3` to `3,2,1,0`. He further asks Jill to reverse the position of the balls `n` times, each time starting from one position further to the right, till she reaches the last ball. So, Jill has to reverse the positions of the ball starting from position `0`, then from position `1`, then from position `2` and so on. At the end of the game, Jill will ask Jack to guess the final position of any ball numbered `k`.
You will be given `2` integers, the first will be `n`(balls numbered from `0` to `n-1`) and the second will be `k`. You will return the position of the ball numbered `k` after the rearrangement.
```Perl
solve(4,1) = 3. The reversals are [0,1,2,3] -> [3,2,1,0] -> [3,0,1,2] -> [3,0,2,1]. => 1 is in position 3.
```
More examples in the test cases. Good luck! | games | def solve(count, ball_number):
"""
Return the position of the `ball_number` after the game with `count` balls
:param count: Number of balls
:type count: int
:param ball_number: Number of ball to be found in the end
:type ball_number: int
:return: Return the index of the ball `ball_number` at the end of the game
:rtype: int
"""
assert isinstance(count, int)
assert isinstance(ball_number, int)
balls = list(range(count))
for idx in range(count):
balls = balls[: idx] + balls[idx:][:: - 1]
return balls . index(ball_number)
| Simple reversal game | 5b93636ba28ce032600000b7 | [
"Puzzles",
"Mathematics"
]
| https://www.codewars.com/kata/5b93636ba28ce032600000b7 | 7 kyu |
The snail crawls up the column. During the day it crawls up some distance. During the night she sleeps, so she slides down for some distance (less than crawls up during the day).
Your function takes three arguments:
1. The height of the column (meters)
2. The distance that the snail crawls during the day (meters)
3. The distance that the snail slides down during the night (meters)
Calculate number of day when the snail will reach the top of the column. | reference | from math import ceil
def snail(column, day, night):
return max(ceil((column - night) / (day - night)), 1)
| Snail crawls up | 5b93fecd8463745630001d05 | [
"Fundamentals",
"Mathematics"
]
| https://www.codewars.com/kata/5b93fecd8463745630001d05 | 7 kyu |
An eviternity number is a number which:
* contains only digits 8, 5 and 3, and
* the count of the digit `8` >= count of digit `5` >= count of digit `3`.
The first few eviternity numbers are as follows.
```Haskell
[8, 58, 85, 88, 358, 385, 538, 583, 588, 835, 853, 858, 885, 888]
```
You will be given two integers, `a` and `b`, and your task is to return the number of eviternity numbers in the range `>= a and < b`.
```
For example:
solve(0,1000) = 14, because they are [8, 58, 85, 88, 358, 385, 538, 583, 588, 835, 853, 858, 885, 888]
```
The upper bound will not exceed `500,000`.
More examples in test cases. Good luck! | reference | def ever(n):
s = str(n)
C = [s . count('3'), s . count('5'), s . count('8')]
if sum(C) == len(s) and sorted(C) == C:
return True
return False
D = {i for i in range(1000000) if ever(i)}
def solve(a, b):
return len({e for e in D if e >= a and e <= b})
| Simple eviternity numbers | 5b93f268563417c7ed0001bd | [
"Fundamentals"
]
| https://www.codewars.com/kata/5b93f268563417c7ed0001bd | 7 kyu |
<img src="https://upload.wikimedia.org/wikipedia/commons/d/d5/UPC-A.png" />
Your task is to convert a string representing the lines/spaces in a 12 digit barcode/UPC-A into a string of numbers 0-9.
A black line represents a `1` and a space represents `0`. The string you are returning is the decimal representation of those binary digits. NOTE: The digits 0-9 are not represented as bits the usual way, UPC has it's own tables which are preloaded as `LEFT_HAND` and `RIGHT_HAND` dictionaries.
The `LEFT_HAND` and `RIGHT_HAND` dictionaries contain 7 digit bit strings as keys and an integer for values. For example:
`'0011001'` = `1` in `LEFT_HAND`
`'1100110'` = `1` in `RIGHT_HAND`, left and right side bit strings are complements of each other.
The structure of a UPC-A is as follows:
* Starts with a guard pattern, always representing 101. Known as `left-hand` guard pattern.
* 6 groups of 7 bits each, eg: <code>' ββ β'</code> = '0011001' = 1(left-hand). The first group is the `number system digit.`
* A center guard pattern, always representing 01010. Divides "left-hand" groups and "right-hand" groups.
* 6 groups of 7 bits each, eg: <code>'ββ ββ '</code> = '1100110' = 1(right-hand). The last group is the `modulo check digit.`
* Ends with a guard pattern, always representing 101. Known as `right-hand` guard pattern.
The format for your returned string is:
```python
'(number_system) (left_hand) (right_hand) (modulo_check)'
```
Example barcode, sorry about number formatting:
```python
1. 'β β ββ β ββ β ββ β ββ β ββ β ββ β β β βββ β ββ ββ ββ ββ β βββ ββ ββ β β β β'
2. '(101)0001101,0110001,0011001,0001101,0001101,0001101(01010)1110010,1100110,1101100,1001110,1100110,1000100(101)'
3. (left_guard)0,5,1,0,0,0(center_guard)0,1,2,5,1,7(right_guard)
return '0 51000 01251 7'
```
For this kata there will be no tricks, no error checking, or reading backwards. Inputs will always be correct, left to right, and a single bar/space will always represent 1/0. The validity of modulo check digit is irrelevant here, we're just doing conversion and formatting. Guards are not part of the returned string but will be part of the input.
A bar in case you need to use it: `β`
[Further reading/details wiki](https://en.wikipedia.org/wiki/Universal_Product_Code), thanks to CODE by Charles Petzold.
| algorithms | tbl = str . maketrans('β ', '10')
def read_barcode(barcode):
txt = barcode . translate(tbl)
l = (LEFT_HAND['' . join(xs)]
for xs in zip(* [iter(txt[3: 7 * 6 + 3])] * 7))
r = (RIGHT_HAND['' . join(xs)]
for xs in zip(* [iter(txt[- 7 * 6 - 3: - 3])] * 7))
return '{} {}{}{}{}{} {}{}{}{}{} {}' . format(* l, * r)
| Read a UPC/Barcode | 5b7dfd8cbfae24e5f200004d | [
"Algorithms"
]
| https://www.codewars.com/kata/5b7dfd8cbfae24e5f200004d | 6 kyu |
Many items that are available for sale have a barcode somewhere on them - this allows them to be scanned at a checkout.
Your task is to create an algorithm to convert a series of ones and zeroes from the scanner into an Universal Product Code (UPC). You can learn more about UPC from [Wikipedia](https://en.wikipedia.org/wiki/Universal_Product_Code). We will be using the UPC-A formatting.
## Specifications
Each barcode follows the pattern: `SLLLLLLMRRRRRRE`
`S`, `M` and `E` are guard bars (start, middle, end). These are constants.
`L` and `R` are digits. They are 7 modules wide and are variables. They can be of 1 of 10 patterns.
Each item is described using the pattern below. The number indicates how many modules wide, the letter is the colour of the bar: `W` for white and `B` for black.
The guard bars:
```
S: 1B1W1B
M: 1W1B1W1B1W
E: 1B1W1B
```
These are the `L` digits:
```
0: 3W2B1W1B
1: 2W2B2W1B
2: 2W1B2W2B
3: 1W4B1W1B
4: 1W1B3W2B
5: 1W2B3W1B
6: 1W1B1W4B
7: 1W3B1W2B
8: 1W2B1W3B
9: 3W1B1W2B
```
You will be provided with a preloaded dictionary `DIGITS` which contains the above information (`L` digits and guard bar patterns).
`R` digits are the inverse of `L` digits, e.g.:
```
0: 3B2W1B1W
```
## Your task
Your function will receive a string consisting of ones (black) and zeroes (white), and should return the UPC as a string. Each one or zero will correspond to one *module* of width. **Only valid barcodes will be supplied**, and they will always be presented from left to right. They will start with the first black line of the guard bars.
## Example
```python
barcode_scanner("10101110110110111000101100010110101111011011101010111001011100101110010111001011011001000010101")
=> "789968000023"
because:
"101 0111011 0110111 0001011 0001011 0101111 0110111 01010 1110010 1110010 1110010 1110010 1101100 1000010 101"
" S 7 8 9 9 6 8 M 0 0 0 0 2 3 E "
``` | algorithms | import re
L_DIGITS = {
"0001101": "0",
"0011001": "1",
"0010011": "2",
"0111101": "3",
"0100011": "4",
"0110001": "5",
"0101111": "6",
"0111011": "7",
"0110111": "8",
"0001011": "9"}
def barcode_scanner(barcode):
leftized = barcode[3: 45] + barcode[50: -
3]. translate(str . maketrans("01", "10"))
return re . sub('|' . join(L_DIGITS . keys()), lambda m: L_DIGITS[m . group(0)], leftized)
| Simple Barcode Scanner | 55f4ad47ada1dd22f1000088 | [
"Regular Expressions",
"Algorithms"
]
| https://www.codewars.com/kata/55f4ad47ada1dd22f1000088 | 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
In this kata, No algorithms, only funny ;-)
# Description:
"All the people hurry up! We need to take a picture. The tallest standing in the middle, and then left and right descending...All the people, hand in hand..."
Give you an array `legs`. It recorded the length of the legs of all the people(we assume that their upper body is the same height), please follow the above rules to arrange these people, and then complete and return the photo:
```
legs = [1,2,3]
After arrange --> [2,3,1]
The photo should be:
+ +
+ + +o o+
+o o+ + u + + +
+ u + + ~ + +o o+
+ ~ + | + u +
| +-o-+ + ~ +
+-o-+ /| o |\ |
_/| o |\__/ +-o-+ \ +-o-+
+-o-+ | | \__/| o |\_
| | | | +-o-+
I I I I I I
legs = [1,1,1,2,3]
After arrange --> [1,2,3,1,1]
The photo should be:
+ +
+ + +o o+
+ + +o o+ + u + + + + +
+o o+ + u + + ~ + +o o+ +o o+
+ u + + ~ + | + u + + u +
+ ~ + | +-o-+ + ~ + + ~ +
| +-o-+ /| o |\ | |
+-o-+ /| o |\__/ +-o-+ \ +-o-+ +-o-+
_/| o |\__/ +-o-+ | | \__/| o |\__/| o |\_
+-o-+ | | | | +-o-+ +-o-+
I I I I I I I I I I
```
# Note:
- The length of array `legs` always be a positive odd integer, all elements are positive integers.
- The order is tallest in the middle, then left, then right, then left, then right..
- If necessary, please add some spaces on both sides.
- Please pay attention to "hand in hand". You can assume that their arms are retractable ;-) | algorithms | from collections import deque
from itertools import chain
blueprint = [* map('' . join, zip(* '''\
+ +
+o o+
+ u +
+ ~ +
|
+-o-+
/| o |\\
+-o-+
''' . splitlines()))]
def person(leg):
yield from (col + ('I' . rjust(leg, '|') if i in (2, 4) else ' ' * leg) for i, col in enumerate(blueprint))
def arms(x, y):
mini = min(x or y, y or x) + 1
if x:
if y:
yield from ('\\' . ljust(i) for i in range(x + 1, y + 1, - 1))
yield f"_ { ' ' * mini } "
if y:
yield f"_ { ' ' * mini } "
if x:
yield from ('/' . ljust(i) for i in range(x + 2, y + 2))
def pattern(legs):
q = deque()
for i, x in enumerate(sorted(legs, reverse=True)):
(deque . append, deque . appendleft)[i & 1](q, x)
it, res = iter(q), []
res . append(arms(None, next(it)))
for x, y in zip(q, chain(it, [None])):
res . append(person(x))
res . append(arms(x, y))
max_size = max(legs) + 8
return '\n' . join(map('' . join, zip(* (x . rjust(max_size) for x in chain . from_iterable(res)))))
| Complete the photo pattern | 58477f76ad2567b465000153 | [
"Algorithms",
"ASCII Art"
]
| https://www.codewars.com/kata/58477f76ad2567b465000153 | 4 kyu |
> When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said
# Description:
Give you two number `m` and `n`(two positive integer, m < n), make a triangle pattern with number sequence `m to n`. The order is clockwise, starting from the top corner, like this:
```
When m=1 n=10 triangle is:
1
9 2
8 0 3
7 6 5 4
```
Note: The pattern only uses the last digit of each number; Each row separated by "\n"; Each digit separated by a space; Left side may need pad some spaces, but don't pad the right side; If `m to n` can not make the triangle, return `""`.
# Some examples:
```
makeTriangle(1,3) should return:
1
3 2
makeTriangle(6,20) should return:
6
7 7
6 8 8
5 0 9 9
4 3 2 1 0
makeTriangle(1,12) should return ""
``` | games | from itertools import cycle
from math import sqrt
def make_triangle(start, end):
rows = sqrt(8 * (end - start) + 9) / 2 - .5
if not rows . is_integer():
return ''
rows = int(rows)
row, col, value = - 1, - 1, start
directions = cycle([(1, 0), (0, - 1), (- 1, 1)])
triangle = [[''] * n for n in range(1, rows + 1)]
for times in range(rows, 0, - 1):
cur_dir = next(directions)
for _ in range(times):
row += cur_dir[0]
col += cur_dir[1]
triangle[row][col] = str(value % 10)
value += 1
return "\n" . join(' ' * (rows - i - 1) + ' ' . join(r) for i, r in enumerate(triangle))
| Complete the triangle pattern | 58281843cea5349c9f000110 | [
"Puzzles"
]
| https://www.codewars.com/kata/58281843cea5349c9f000110 | 5 kyu |
The goal of this kata is to implement [trie](https://en.wikipedia.org/wiki/Trie) (or prefix tree) using dictionaries (aka hash maps or hash tables), where:
1. the dictionary keys are the prefixes
2. the value of a leaf node is `None` in Python, `nil` in Ruby, `null` in Groovy, JavaScript and Java, and `Nothing` in Haskell.
3. the value for empty input is `{}` in Python, Ruby, Javascript and Java (empty map), `[:]` in Groovy, and `Trie []` in Haskell.
**Examples:**
```python
>>> build_trie()
{}
>>> build_trie("")
{}
>>> build_trie("trie")
{'t': {'tr': {'tri': {'trie': None}}}}
>>> build_trie("tree")
{'t': {'tr': {'tre': {'tree': None}}}}
>>> build_trie("A","to", "tea", "ted", "ten", "i", "in", "inn")
{'A': None, 't': {'to': None, 'te': {'tea': None, 'ted': None, 'ten': None}}, 'i': {'in': {'inn': None}}}
>>> build_trie("true", "trust")
{'t': {'tr': {'tru': {'true': None, 'trus': {'trust': None}}}}}
```
```ruby
>> build_trie()
=> {}
>> build_trie("")
=> {}
>> build_trie("trie")
=> {"t" => {"tr" => {"tri" => {"trie" => nil}}}}
>> build_trie("tree")
=> {"t" => {"tr" => {"tre" => {"tree" => nil}}}}
>> build_trie("trie", "trie")
=> {"t" => {"tr" => {"tri" => {"trie" => nil}}}}
>> build_trie("A","to", "tea", "ted", "ten", "i", "in", "inn")
=> {"A" => nil, "t" => {"to" => nil, "te" => {"tea" => nil, "ted" => nil, "ten" => nil}}, "i" => {"in" => {"inn" => nil}}}
>> build_trie("true", "trust")
=> {"t" => {"tr" => {"tru" => {"true" => nil, "trus" => {"trust" => nil}}}}}
```
```groovy
Kata.buildTrie() == [:]
Kata.buildTrie("") == [:]
Kata.buildTrie("trie") == ["t": ["tr": ["tri": ["trie": null]]]]
Kata.buildTrie("tree") == ["t": ["tr": ["tre": ["tree": null]]]]
Kata.buildTrie("A", "to", "tea", "ted", "ten", "i", "in", "inn") == ["A": null, "t": ["to": null, "te": ["tea": null, "ted": null, "ten": null]], "i": ["in": ["inn": null]]]
Kata.buildTrie("true", "trust") == ["t": ["tr": ["tru": ["true": null, "trus": ["trust": null]]]]]
```
```haskell
-- Note that the trie format is a standard assoclist, but `newtype`d because of type recursion.
-- This type is Preloaded, and its Eq instance does not require equal ordering for equality.
buildTrie [] -> Trie []
buildTrie [""] -> Trie []
buildTrie ["trie"] -> Trie [("t",Just (Trie [("tr",Just (Trie [("tri",Just (Trie [("trie",Nothing)]))]))]))]
buildTrie ["tree"] -> Trie [("t",Just (Trie [("tr",Just (Trie [("tre",Just (Trie [("tree",Nothing)]))]))]))]
buildTrie ["A", "to", "tea", "ted", "ten", "i", "in", "inn"] -> Trie [ ("A",Nothing), ("t",Just (Trie [ ("to",Nothing), ("te",Just (Trie [ ("tea",Nothing), ("ted",Nothing), ("ten",Nothing) ])) ])), ("i",Just (Trie [ ("in",Just (Trie [ ("inn",Nothing) ])) ])) ]
buildTrie ["true", "trust"] -> Trie [("t",Just (Trie [("tr",Just (Trie [("tru",Just (Trie [("true",Nothing),("trus",Just (Trie [("trust",Nothing)]))]))]))]))]
```
```javascript
buildTrie() => {}
buildTrie("") => {}
buildTrie("trie") => {'t': {'tr': {'tri': {'trie': null}}}}
buildTrie("tree") => {'t': {'tr': {'tre': {'tree': null}}}}
buildTrie("A","to", "tea", "ted", "ten", "i", "in", "inn") => {'A': null, 't': {'to': null, 'te': {'tea': null, 'ted': null, 'ten': null}}, 'i': {'in': {'inn': null}}}
buildTrie("true", "trust") => {'t': {'tr': {'tru': {'true': null, 'trus': {'trust': null}}}}}
```
```coffeescript
buildTrie() => {}
buildTrie("") => {}
buildTrie("trie") => {'t': {'tr': {'tri': {'trie': null}}}}
buildTrie("tree") => {'t': {'tr': {'tre': {'tree': null}}}}
buildTrie("") => {'A': null, 't': {'to': null, 'te': {'tea': null, 'ted': null, 'ten': null}}, 'i': {'in': {'inn': null}}}
buildTrie("true", "trust") => {'t': {'tr': {'tru': {'true': null, 'trus': {'trust': null}}}}}
```
```java
Solution.buildTrie().toString() == "{}";
Solution.buildTrie("").toString() == "{}";
Solution.buildTrie("trie").toString() == "{t={tr={tri={trie=null}}}}";
Solution.buildTrie("tree").toString() == "{t={tr={tre={tree=null}}}}";
Solution.buildTrie("A", "to", "tea", "ted", "ten", "i", "in", "inn").toString() == "{A=null, t={te={tea=null, ted=null, ten=null}, to=null}, i={in={inn=null}}}";
Solution.buildTrie("true", "trust").toString() == "{t={tr={tru={true=null, trus={trust=null}}}}}";
```
Happy coding! :) | reference | def build_trie(* words):
root = {}
for word in words:
branch = root
length = len(word)
for i in range(1, length + 1):
length -= 1
key = word[: i]
if key not in branch:
branch[key] = None
if length and not branch[key]:
branch[key] = {}
branch = branch[key]
return root
| Build a Trie | 5b65c47cbedf7b69ab00066e | [
"Data Structures",
"Fundamentals"
]
| https://www.codewars.com/kata/5b65c47cbedf7b69ab00066e | 6 kyu |
## Task
Find the sum of the first `n` elements in the RecamΓ‘n Sequence.
Input range:
```javascript
1000 tests
0 <= n <= 1,000,000
```
```python
1000 tests
0 <= n <= 2,500,000
```
```haskell
0 <= n <= 1 000 000
1 000 tests
```
---
## Sequence
The sequence is formed using the next formula:
* We start with `0`
* At each step `i`, we subtract `i` from the previous number
* If the result is not negative, and not yet present in the sequence, it becomes the `i`th element of the sequence
* Otherwise the `i`th element of the sequence will be previous number plus `i`
The beginning of the sequence is `[0, 1, 3, 6, 2, ...]` because:
0) `0` <- we start with `0`
1) `1` <- `0 - 1` is negative, hence we choose `0 + 1`
2) `3` <- `1 - 2` is negative, hence we choose `1 + 2`
3) `6` <-`3 - 3` is not negative, but we already have a `0` in the sequence, hence we choose `3 + 3`
4) `2` <- `6 - 4` is positive, and is not present in the sequence yet, so we go for it
---
## Examples
```
rec(0) == 0
rec(1) == 0
rec(2) == 1
rec(3) == 4
rec(4) == 10
rec(5) == 12
``` | algorithms | S, SS, SUM = [0], {0}, [0]
def rec(n):
while len(S) <= n:
v = S[- 1] - len(S)
if v <= 0 or v in SS:
v += 2 * len(S)
S . append(v)
SS . add(v)
SUM . append(SUM[- 1] + v)
return SUM[n - 1]
| RecamΓ‘n Sequence Sum | 5b8c055336332fce3d00000e | [
"Algorithms"
]
| https://www.codewars.com/kata/5b8c055336332fce3d00000e | 5 kyu |
Consider the string `"1 2 36 4 8"`. Lets take pairs of these numbers, concatenate each pair and determine how many of them of divisible by `k`.
```Pearl
If k = 3, we get following numbers ['12', '18', '21', '24', '42', '48', '81', '84'], all divisible by 3.
Note:
-- 21 and 12 are different pairs.
-- Elements must be from different indices, so '3636` is not a valid.
```
Given a string of numbers and an integer `k`, return the number of pairs that when concatenated, are divisible by `k`.
```
solve("1 2 36 4 8", 3) = 8, because they are ['12', '18', '21', '24', '42', '48', '81', '84']
solve("1 3 6 3", 3) = 6. They are ['36', '33', '63', '63', '33', '36']
```
More examples in test cases. Good luck!
Please also try [Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7) | algorithms | from itertools import permutations
def solve(s, k):
return sum(not v % k for v in map(int, map('' . join, permutations(s . split(), 2))))
| Simple string division II | 5b8be3ae36332f341e00015e | [
"Algorithms"
]
| https://www.codewars.com/kata/5b8be3ae36332f341e00015e | 7 kyu |
You are given a string representing a website's address. To calculate the IP4 address you must convert all the characters into ASCII code, then calculate the sum of the values.
* the first part of the IP number will be the result mod 256
* the second part of the IP number will be the double of the sum mod 256
* the third will be the triple of the sum mod 256
* the fourth will be the quadruple of the sum mod 256
## Input
A string representing the website address
## Output
An array containing the four parts of the IP value
## Examples
```
"www.codewars.com" ---> [88, 176, 8, 96]
"www.starwiki.com" ---> [110, 220, 74, 184]
```
## Restrictions
```if:javascript
* Code length <= 77 characters
* `require` is forbidden
```
```if:python
* Code length <= 59 characters
* `import` is forbidden as a part of anti-cheat
```
```if:ruby
* Code length <= 60 characters
``` | games | def f(u): return [sum(map(ord, u)) * i % 256 for i in [1, 2, 3, 4]]
| IP address finder [Code-golf] | 5b883cdecc7c03c0fa00015a | [
"Strings",
"Arrays",
"Restricted",
"Puzzles"
]
| https://www.codewars.com/kata/5b883cdecc7c03c0fa00015a | 6 kyu |
Your function takes two arguments:
1. current father's age (years)
2. current age of his son (years)
Π‘alculate how many years ago the father was twice as old as his son (or in how many years he will be twice as old). The answer is always greater or equal to 0, no matter if it was in the past or it is in the future. | reference | def twice_as_old(dad_years_old, son_years_old):
return abs(dad_years_old - 2 * son_years_old)
| Twice as old | 5b853229cfde412a470000d0 | [
"Fundamentals",
"Mathematics"
]
| https://www.codewars.com/kata/5b853229cfde412a470000d0 | 8 kyu |
In this Kata, you will be given a number in form of a string and an integer `k` and your task is to insert `k` commas into the string and determine which of the partitions is the largest.
```
For example:
solve('1234',1) = 234 because ('1','234') or ('12','34') or ('123','4').
solve('1234',2) = 34 because ('1','2','34') or ('1','23','4') or ('12','3','4').
solve('1234',3) = 4
solve('2020',1) = 202
```
More examples in test cases. Good luck!
Please also try [Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7) | reference | def solve(st, k):
length = len(st) - k
return max(int(st[i: i + length]) for i in range(k + 1))
| Simple string division | 5b83c1c44a6acac33400009a | [
"Fundamentals"
]
| https://www.codewars.com/kata/5b83c1c44a6acac33400009a | 7 kyu |
While most devs know about [big/little-endianness](https://en.wikipedia.org/wiki/Endianness), only a selected few know the secret of real hard core coolness with mid-endians.
Your task is to take a number and return it in its mid-endian format, putting the most significant couple of bytes in the middle and all the others around it, alternating left and right.
For example, consider the number `9999999`, whose hexadecimal representation would be `98967F` in big endian (the classic you get converting); it becomes `7F9698` in little-endian and `96987F` in mid-endian.
Write a function to do that given a positive integer (in base 10) and remembering that you need to pad with `0`s when you get a single hex digit! | algorithms | import re
def mid_endian(n):
h = hex(n)[2:]. upper()
r = re . findall('..', '0' * (len(h) % 2) + h)
return "" . join(r[1:: 2][:: - 1] + r[0:: 2])
| Mid-Endian numbers | 5b3e3ca99c9a75a62400016d | [
"Algorithms"
]
| https://www.codewars.com/kata/5b3e3ca99c9a75a62400016d | 6 kyu |
Lets play some Pong!

For those who don't know what Pong is, it is a simple arcade game where two players can move their paddles to hit a ball towards the opponent's side of the screen, gaining a point for each opponent's miss. You can read more about it [here](https://en.wikipedia.org/wiki/Pong).
___
# Task:
You must finish the `Pong` class. It has a constructor which accepts the `maximum score` a player can get throughout the game, and a method called `play`. This method determines whether the current player hit the ball or not, i.e. if the paddle is at the sufficient height to hit it back. There're 4 possible outcomes: player successfully hits the ball back, player misses the ball, player misses the ball **and his opponent reaches the maximum score winning the game**, either player tries to hit a ball despite the game being over. You can see the input and output description in detail below.
### "Play" method input:
* ball position - The Y coordinate of the ball
* player position - The Y coordinate of the centre(!) of the current player's paddle
### "Play" method output:
One of the following strings:
* `"Player X has hit the ball!"` - If the ball "hits" the paddle
* `"Player X has missed the ball!"` - If the ball is above/below the paddle
* `"Player X has won the game!"` - If one of the players has reached the maximum score
* `"Game Over!"` - If the game has ended when the `play` method is called
### Important notes:
* Players take turns hitting the ball, always starting the game with the Player 1.
* The paddles are `7` pixels in height.
* The ball is `1` pixel in height.
___
## Example
```javascript
let game = new Pong(2); // Here we say that the score to win is 2
game.play(50, 53) -> "Player 1 has hit the ball!"; // Player 1 hits the ball
game.play(100, 97) -> "Player 2 has hit the ball!"; // Player 2 hits it back
game.play(0, 4) -> "Player 1 has missed the ball!"; // Player 1 misses so Player 2 gains a point
game.play(25, 25) -> "Player 2 has hit the ball!"; // Player 2 hits the ball
game.play(75, 25) -> "Player 2 has won the game!"; // Player 1 misses again. Having 2 points Player 2 wins, so we return the corresponding string
game.play(50, 50) -> "Game Over!"; // Another turn is made even though the game is already over
``` | algorithms | from itertools import cycle
class Pong:
def __init__(self, max_score):
self . max_score = max_score
self . scores = {1: 0, 2: 0}
self . players = cycle((1, 2))
def game_over(self):
return any(score >= self . max_score for score in self . scores . values())
def play(self, ball_pos, player_pos):
if self . game_over():
return "Game Over!"
player = next(self . players)
if abs(ball_pos - player_pos) <= 3:
return "Player {} has hit the ball!" . format(player)
else:
self . scores[player] += 1
if self . scores[player] == self . max_score:
return "Player {} has won the game!" . format(next(self . players))
else:
return "Player {} has missed the ball!" . format(player)
| Pong! [Basics] | 5b432bdf82417e3f39000195 | [
"Fundamentals",
"Games",
"Algorithms",
"Object-oriented Programming"
]
| https://www.codewars.com/kata/5b432bdf82417e3f39000195 | 6 kyu |
# Introduction
This kata is yet another version of Avanta's [Coloured Triangles](/kata/coloured-triangles), once again focused on performance.
It takes Bubbler's ["Insane" version](/kata/insane-coloured-triangles) a step further, hence the name "Ludicrous".
I highly recommend having a close look at these other versions first, and solving them if you haven't already: they are super nice kata, and the test cases are significantly less challenging than what you'll find here.
# Problem Description
> This section has been borrowed from Avanta's kata.
A coloured triangle is created from a row of colours, each of which is red, green or blue. Successive rows, each containing one fewer colour than the last, are generated by considering the two touching colours in the previous row. If these colours are identical, the same colour is used in the new row. If they are different, the missing colour is used in the new row. This is continued until the final row, with only a single colour, is generated.
For example, different possibilities are:
Colour here: G G B G R G B R
Becomes colour here: G R B G
With a bigger example:
R R G B R G B B
R B R G B R B
G G B R G G
G R G B G
B B R R
B G R
R B
G
You will be given the first row of the triangle as a string and its your job to return the final colour which would appear in the bottom row as a string. In the case of the example above, you would the given `'RRGBRGBB'` you should return `'G'`.
- The input string will only contain the uppercase letters `'B'`, `'G'` or `'R'` and there will be at least one letter so you do not have to test for invalid input.
- If you are only given one colour as the input, return that colour.
*Adapted from the 2017 British Informatics Olympiad*
# Challenge
The specificity of this kata resides in the very large size of the input strings that your function will have to crunch and digest.
As a reference, the test cases in Bubbler's *Insane* version go up to 100 000 characters. In this one, the limit is set to 1 000 000 000 characters. (That's 10 000 times more.)
With such large numbers, the challenge here will clearly not be about optimizing code execution, but about reducing algorithmic complexity.
Please note that the test cases are randomly generated, so the actual time it takes to complete the tests can vary from one attempt to the next. A good solution, though, should be able to beat the timeout 99% of the time.
```if:ruby
For `Ruby`: do __not__ _mutate the strings_!
(This could otherwise cause some tests to fail...)
``` | algorithms | import itertools
import operator
def triangle(row):
# Explanation of approach:
# We associate each of the 3 colours/characters with a unique code: 0, 1, or 2.
# With this encoding and the rules given,
# we see that a pair of neighbours in one row will give rise in the next row
# to a colour whose code is the negated sum of the two neighbours' codes, reduced modulo 3.
# Applying this repeatedly starting with a row of length m + 1,
# we find that the code of the colour at the bottom tip of the triangle
# is just the dot product of the mth row (zero-indexing, always) of Pascal's triangle
# with the codes of the initial row of colours,
# the result negated if m is odd, and reduced modulo 3.
# Working modulo 3, Lucas's Theorem says that (m choose n),
# the nth value/coefficient in the mth row of Pascal's triangle,
# is congruent to the product of all (m_i choose n_i),
# where m_i and n_i are the ith base-3 digits of m and n, respectively,
# and (m_i choose n_i) is taken to be zero if m_i < n_i.
# Therefore nonzero coefficients appear precisely
# when each base-3 digit of n is no greater than the corresponding base-3 digit of m.
# Now, for such a coefficient, the factor (m_i choose n_i) is 2 if m_i == 2 and n_i == 1.
# Otherwise, the factor is 1.
# Therefore, for such a coefficient, if k denotes the number of pairs of corresponding base-3 digits of m and n
# that are equal to 2 and 1, respectively,
# then the coefficient is congruent to 2**k, which reduces to 1 if k is even or 2 if k is odd.
# We map our three colours/characters to our three codes.
colours = 'RGB'
code_for_colour = {colour: code for code, colour in enumerate(colours)}
# We determine m and its base-3 digit sequence (starting with the least significant digit).
m = len(row) - 1
m_base_3_digits = []
q = m
while q:
q, r = divmod(q, 3)
m_base_3_digits . append(r)
# For later use, we locate all 2s in the base-3 digit sequence of m.
positions_of_2s_in_m_base_3_digits = tuple(
position for position, digit in enumerate(m_base_3_digits) if digit == 2)
# We collect the first powers of 3, so that we can later quickly compute a number from its base-3 digit sequence.
# (Note: The only difference between my solution for the "Insane Coloured Triangles" kata and this one occurs here.
# Unlike the current kata, that one allowed use of Python 3.8, where itertools.accumulate's initial parameter first appeared.)
powers_of_3 = (1, * itertools . accumulate(itertools . repeat(3,
len(m_base_3_digits) - 1), operator . mul))
# We will progressively compute the dot product of the vector of coefficients of the mth row of Pascal's triangle
# with the vector of codes of colours in the given initial row, reducing modulo 3.
reduced_dot_product = 0
# We need only consider the nonzero coefficients in the mth row of Pascal's triangle,
# so we visit all sequences of base-3 digits whose elements are no greater than the corresponding base-3 digits of m.
for n_base_3_digits in itertools . product(* (range(m_base_3_digit + 1) for m_base_3_digit in m_base_3_digits)):
# From the base-3 digit sequence we are now visiting, we compute the associated value of n.
# (m choose n) is nonzero.
n = sum(map(operator . mul, n_base_3_digits, powers_of_3))
# We look up the code of the colour at the nth position in the given initial row.
nth_code_in_row = code_for_colour[row[n]]
# Only nonzero codes will result in nonzero contributions to our dot product.
if nth_code_in_row:
# We determine the value of (m choose n) reduced modulo 3,
# multiply by the corresponding colour code in the given initial row,
# and update our partial reduced dot product.
nth_coefficient = sum(
n_base_3_digits[position] == 1 for position in positions_of_2s_in_m_base_3_digits) % 2 + 1
reduced_dot_product = (reduced_dot_product +
nth_coefficient * nth_code_in_row) % 3
# If m is even, the dot product is congruent to the code of the colour at the bottom tip of the triangle,
# while for odd m, the negated dot product is congruent to the desired code.
# We thus determine the final code and return the associated colour character.
return colours[(- reduced_dot_product) % 3 if m % 2 else reduced_dot_product]
| Ludicrous Coloured Triangles | 5b84d6d6b2f82f34d00000d7 | [
"Puzzles",
"Mathematics",
"Algorithms"
]
| https://www.codewars.com/kata/5b84d6d6b2f82f34d00000d7 | 2 kyu |
I advise you to do some of the previous katas from the: [Neighbourhood collection](https://www.codewars.com/collections/5b2f4db591c746349d0000ce).
___
This is the next step. We are going multidimensional.
You should build a function that return the neighbourhood of a cell within a matrix with the given distance and type. AND it should work for any dimension.
# Input
- `type` `"moore"` or `"von_neumann"`
- `matrix` a N-dimensional matrix. N >= 0 (the matrix is always rectangular; could be a list or a tuple)
- `coordinates` of the cell. It is a N-length tuple.
Order of the indices: The first index should be applied for the outer/first matrix layer. The last index for the most inner/last layer. `coordinates = (m, n, k)` should be apllied like `mat[m][n][k]`
- `distance`
# Task
construct `get_neighbourhood(n_type, matrix, coordinates, distance)`
# Ouput
The N dimension neighbours of the cell
# Performance
Your code should be performant.
- There will be two Tests with a very highdimensional matrix
- There will be 30 Tests with 9 <= distance <= 12
- There will be 200 Tests with N == 4, Dimension size == 5
- There will be 30 Tests with N == 8, Dimension size == 3
Note: you should return an empty array if any of these conditions is true:
* Index is outside the matrix (python: negative indexes are outside the matrix too)
* Matrix is empty
* Distance equals `0`
___
Translations are appreciated.^^
If you like matrices chekout [Array Hyperrectangularity](https://www.codewars.com/kata/5b33e9c291c746b102000290)
If you like puzzles chekout [Rubik's cube](https://www.codewars.com/kata/5b3bec086be5d8893000002e) | algorithms | def genNeigh(isNeum, arr, coords, d, var=0, idx=()):
depth = len(idx)
x = coords[depth]
if not (0 <= x < len(arr)):
raise IndexError()
low, up = - d + isNeum * var, d - isNeum * var + 1
for j in range(max(0, low + x), min(up + x, len(arr))):
indexes = idx + (j,)
if 0 <= j < len(arr) and indexes != coords:
if depth < len(coords) - 1:
yield from genNeigh(isNeum, arr[j], coords, d, var + abs(j - x), indexes)
else:
yield arr[j]
def get_neighbourhood(typ, arr, coords, d=1):
try:
return list(genNeigh(typ == 'von_neumann', arr, coords, d))
except IndexError:
return []
| Multidimensional Neighbourhood | 5b47ba689c9a7591e70001a3 | [
"Algorithms",
"Logic",
"Data Structures",
"Arrays",
"Performance"
]
| https://www.codewars.com/kata/5b47ba689c9a7591e70001a3 | 5 kyu |
```
NOTE: To solve this Kata you need a minimum knowlege of probability theory
https://en.wikipedia.org/wiki/Probability_theory
```
# Description
Alice and Bob decided to have a quick tennis match. The rules a simple:
```
A game consists of a sequence of points played with the same
player serving. A game is won by the first player to have won
at least four points in total and at least two points more
than the opponent.
```
https://en.wikipedia.org/wiki/Tennis#Manner_of_play
This means that Alice and Bob have potentially endless match till one of them exceed opponent at 2 points.
Examples:
```
Game ends:
Alice - 0, Bob - 4
Alice - 1, Bob - 4
Alice - 2, Bob - 4
Alice - 3, Bob - 5
Alice - 10, Bob - 8
Game continues:
Alice - 3, Bob - 3
Alice - 3, Bob - 4
Alice - 11, Bob - 10
Impossible scores:
Alice - 5, Bob - 10 # Bob would have won at 7
```
During the little warm-up Alice noticed that Bob wins only 30% of points, while Alice succeeded in 70%.
So, assuming Bob's probability to win a single point: `q = 0.3`, while Alice's is `p = 0.7`.
Therefore, Alice's chances to win a match by 4 wins in a row is `pow(p, 4) = 0.2401`, and Bob's `pow(q, 4) = 0.0081`. But remember about possible results without whitewash.
# Task
Your goal is to write a function that accepts two player's probabilities to win a single point: `p` and `q`, and returns a tuple of their probabilities to win the entire match `(P, Q)`.
# Examples
```python
>>> match_probability(0.7, 0.3)
(0.9007889655172411, 0.09921103448275892)
>>> match_probability(0.5, 0.5) # When chances to win point are equal, so will be chances to win the match
(0.5, 0.5)
>>> match_probability(1.0, 0.0) # When Bob can't score a single point, Alice will definitely win the match
(1.0, 0.0)
```
# Notes
* All inputs will be valid (p + q will equal to 1.0)
* Answers should be pretty precise (Up to 10 decimal places)
* Remember that there are different ways to get a score (Example: Alice - 1, Bob - 1 can be achieved with either Bob or Alice scoring the first point)
* Hint: Also, `match_probability(p, q) + match_probability(q, p)` also should be equal to 1, since one of them will win the game eventually.
| reference | def match_probability(p, q):
# 4 Ways to Win:
# 1st = 4 - 0
# 2nd = 4 - 1
# 3rd = 4 - 2
# 4th = two in a row during "overtime" after 3-3
# Chance of p winning 4 - 0
prob_1 = p * * 4
# Chance of p winning 4 - 1
prob_2 = (4 * p * * 4 * (1 - p))
# Chance of p winning 4 - 2
prob_3 = (10 * p * * 4 * (1 - p) * * 2)
# Chance of p winning "overtime"
num = (20 * p * * 5 * (1 - p) * * 3)
denom = (1 - 2 * p * (1 - p))
prob_4 = num / denom
# Total chance of p winning
chance = prob_1 + prob_2 + prob_3 + prob_4
return chance, 1 - chance
| Probability to Win an Infinite Tennis Game | 5b756dc4049416c24f000762 | [
"Mathematics",
"Fundamentals"
]
| https://www.codewars.com/kata/5b756dc4049416c24f000762 | 5 kyu |
We are interested in collecting the triples of positive integers ```(a, b, c)``` that fulfill the following equation:
```python
aΒ² + bΒ² = cΒ³
```
The first triple with the lowest values that satisfies the equation we have above is (2, 2 ,2).
In effect:
```python
2Β² + 2Β² = 2Β³
4 + 4 = 8
```
The first pair of triples that "shares" the same value of ```c``` is: ```(2, 11, 5)``` and ```(5, 10, 5)```.
Both triples share the same value of ```c``` is ```c = 5```.
```python
Triple (2, 11, 5) Triple(5, 10, 5)
2Β² + 11Β² = 5Β³ 5Β² + 10Β² = 5Β³
4 + 121 = 125 25 + 100 = 125
```
So, we say that the value ```c``` has two solutions because there are two triples sharing the same value of ```c```.
There are some values of ```c``` with no solutions.
The first value of ```c``` that have a surprising number of solutions is ```65``` with ```8``` different triples.
In order to avoid duplications you will consider that ```a <= b``` always.
Make the function ```find_abc_sumsqcube()```, that may give us the values of c for an specific number of solutions.
For that purpose the above required function will receive two arguments, ```c_max``` and ```num_sol```. It is understandable that ```c_max``` will give to our function the upper limit of ```c``` and ```num_sol```, the specific number of solutions.
The function will output a sorted list with the values of ```c``` that have a number of solutions equals to ```num_sol```
Let's see some cases:
```python
find_abc_sumsqcube(5, 1) == [2] # below or equal to c_max = 5 we have triple the (2, 2, 2) (see above)
find_abc_sumsqcube(5, 2) == [5] # now we want the values of ```c β€ c_max``` with two solutions (see above again)
find_abc_sumsqcube(10, 2) == [5, 10]
find_abc_sumsqcube(20, 8) == [] # There are no values of c equal and bellow 20 having 8 solutions.
```
Our tests will have the following ranges for our two arguments:
```python
5 β€ c_max β€ 1000
1 β€ num_sol β€ 10
```
Happy coding!! | reference | from bisect import bisect_right as bisect
RES = [[] for _ in range(11)]
for c in range(1, 1001):
c3 = c * * 3
nSol = sum(((c3 - a * * 2) * * .5). is_integer() for a in range(1, int((c3 / / 2) * * .5 + 1)))
if 0 < nSol < 11:
RES[nSol]. append(c)
def find_abc_sumsqcube(c_max, nSol):
return RES[nSol][: bisect(RES[nSol], c_max)]
| Square Cubic Triples | 5618716a738b95cee8000062 | [
"Fundamentals",
"Algorithms",
"Data Structures",
"Mathematics",
"Memoization"
]
| https://www.codewars.com/kata/5618716a738b95cee8000062 | 6 kyu |
You are given an input string.
For each symbol in the string if it's the first character occurrence, replace it with a '1', else replace it with the amount of times you've already seen it.
___
## Examples:
```
input = "Hello, World!"
result = "1112111121311"
input = "aaaaaaaaaaaa"
result = "123456789101112"
```
There might be some non-ascii characters in the string.
<hr>
~~~if:java
Note: there will be no int domain overflow (character occurrences will be less than 2 billion).
~~~
~~~if:c
(this does not apply to the C language translation)
~~~
Take note of **performance**
| algorithms | def numericals(s):
dictio = {}
t = ""
for i in s:
dictio[i] = dictio . get(i, 0) + 1
t += str(dictio[i])
return t
| Numericals of a String | 5b4070144d7d8bbfe7000001 | [
"Puzzles",
"Performance",
"Algorithms"
]
| https://www.codewars.com/kata/5b4070144d7d8bbfe7000001 | 6 kyu |
# Description
Write a function that accepts the current position of a knight in a chess board, it returns the possible positions that it will end up after 1 move. The resulted should be sorted.
## Example
"a1" -> ["b3", "c2"] | reference | def possible_positions(p):
r, c = ord(p[0]) - 96, int(p[1])
moves = [(- 2, - 1), (- 2, 1), (- 1, - 2), (- 1, 2),
(1, - 2), (1, 2), (2, - 1), (2, 1)]
return ['' . join((chr(r + i + 96), str(c + j))) for i, j in moves if 1 <= r + i <= 8 and 1 <= c + j <= 8]
| Knight position | 5b5736abf1d553f844000050 | [
"Fundamentals"
]
| https://www.codewars.com/kata/5b5736abf1d553f844000050 | 7 kyu |
# Parentheses are loud !
As a spy python object, you have been sent to a remote memory location to gather information about some anonymous functions. Unfortunately, they caught wind of this and are on the lookout for any parentheses to prevent you from making any calls for help. But you are a proffesional and you don't need parentheses to make calls. Help yourself out of this situation.
# Your Task
Write a code snippet that will make call to the `help_me` function.
Your code must NOT:
1. Contain any parentheses `(` or `)`
2. Assign any variables
3. Be longer than 50 characters
4. Have more than 2 lines
## Extra info
The `help_me` function is very flexible and doesn't care how may parameters you give it
#### Please Take time to give feedback on this kata. | games | @ help_me
class _:
pass
| Parentheses are loud ! | 5b6711e86d0db7519a000112 | [
"Logic",
"Puzzles"
]
| https://www.codewars.com/kata/5b6711e86d0db7519a000112 | 6 kyu |
## Task
Implement a function which finds the numbers less than `2`, and the indices of numbers greater than `1` in the given sequence, and returns them as a pair of sequences.
Return a nested array or a tuple depending on the language:
* The first sequence being only the `1`s and `0`s from the original sequence.
* The second sequence being the indexes of the elements greater than `1` in the original sequence.
## Examples
```javascript
[ 0, 1, 2, 1, 5, 6, 2, 1, 1, 0 ] => [ [ 0, 1, 1, 1, 1, 0 ], [ 2, 4, 5, 6 ] ]
```
```haskell
[ 0, 1, 2, 1, 5, 6, 2, 1, 1, 0 ] => ( [ 0, 1, 1, 1, 1, 0 ], [ 2, 4, 5, 6 ] )
```
```python
[ 0, 1, 2, 1, 5, 6, 2, 1, 1, 0 ] => ( [ 0, 1, 1, 1, 1, 0 ], [ 2, 4, 5, 6 ] )
```
Please upvote and enjoy! | reference | def binary_cleaner(seq):
res = ([], [])
for i, x in enumerate(seq):
if x < 2:
res[0]. append(x)
else:
res[1]. append(i)
return res
| Not above the one! | 5b5097324a317afc740000fe | [
"Arrays",
"Fundamentals"
]
| https://www.codewars.com/kata/5b5097324a317afc740000fe | 7 kyu |
You have a string of numbers; starting with the third number each number is the result of an operation performed using the previous two numbers.
Complete the function which returns a string of the operations in order and separated by a comma and a space, e.g. `"subtraction, subtraction, addition"`
The available operations are (in this order of preference):
```
1) addition
2) subtraction
3) multiplication
4) division
```
**Notes:**
* All input data is valid
* The number of numbers in the input string >= 3
* For a case like `"2 2 4"` - when multiple variants are possible - choose the first possible operation from the list (in this case `"addition"`)
* Integer division should be used
## Example
```
"9 4 5 20 25" --> "subtraction, multiplication, addition"
```
Because:
```
9 - 4 = 5 --> subtraction
4 * 5 = 20 --> multiplication
5 + 20 = 25 --> addition
```
| algorithms | def sayMeOperations(stringNumbers):
nums = [int(i) for i in stringNumbers . split()]
return ', ' . join({
a * b: 'multiplication',
a - b: 'subtraction',
a + b: 'addition',
}. get(c, 'division') for a, b, c in zip(nums, nums[1:], nums[2:]))
| Say Me Please Operations | 5b5e0c0d83d64866bc00001d | [
"Algorithms",
"Logic",
"Strings",
"Lists"
]
| https://www.codewars.com/kata/5b5e0c0d83d64866bc00001d | 7 kyu |
## Task
You will be given a list of objects. Each object has `type`, `material`, and possibly `secondMaterial`. The existing materials are: `paper`, `glass`, `organic`, and `plastic`.
Your job is to sort these objects across the 4 recycling bins according to their `material` (and `secondMaterial` if it's present), by listing the `type`'s of objects that should go into those bins.
### Notes
* The bins should come in the same order as the materials listed above
* All bins should be listed in the output, even if some of them are empty
* If an object is made of two materials, its `type` should be listed in both of the respective bins
* The order of the `type`'s in each bin should be the same as the order of their respective objects was in the input list
```if:python
* Contrary to the example below, the output in Python should be a tuple of 4 lists instead of a 2-dimensional list
```
### Example
```
input = [
{"type": "rotten apples", "material": "organic"},
{"type": "out of date yogurt", "material": "organic", "secondMaterial": "plastic"},
{"type": "wine bottle", "material": "glass", "secondMaterial": "paper"},
{"type": "amazon box", "material": "paper"},
{"type": "beer bottle", "material": "glass", "secondMaterial": "paper"}
]
output = [
["wine bottle", "amazon box", "beer bottle"],
["wine bottle", "beer bottle"],
["rotten apples", "out of date yogurt"],
["out of date yogurt"]
]
``` | reference | def recycle(a):
bins = {"paper": [], "glass": [], "organic": [], "plastic": []}
for i in a:
bins[i["material"]]. append(i["type"])
if "secondMaterial" in i:
bins[i["secondMaterial"]]. append(i["type"])
return tuple(bins . values())
| Let's Recycle! | 5b6db1acb118141f6b000060 | [
"Arrays",
"Fundamentals"
]
| https://www.codewars.com/kata/5b6db1acb118141f6b000060 | 6 kyu |
Do you have in mind the good old TicTacToe?
Assuming that you get all the data in one array, you put a space around each value, `|` as a columns separator and multiple `-` as rows separator, with something like `["O", "X", " ", " ", "X", " ", "X", "O", " "]` you should be returning this structure (inclusive of new lines):
```
O | X |
-----------
| X |
-----------
X | O |
```
Now, to spice up things a bit, we are going to expand our board well beyond a trivial `3` x `3` square and we will accept rectangles of big sizes, still all as a long linear array.
For example, for `"O", "X", " ", " ", "X", " ", "X", "O", " ", "O"]` (same as above, just one extra `"O"`) and knowing that the length of each row is `5`, you will be returning
```
O | X | | | X
-------------------
| X | O | | O
```
And worry not about missing elements, as the array/list/vector length is always going to be a multiple of the width. | reference | def display_board(board, width):
board = [c . center(3) for c in board]
rows = ["|" . join(board[n: n + width])
for n in range(0, len(board), width)]
return ("\n" + "-" * (4 * width - 1) + "\n"). join(rows)
| Tic-Tac-Toe-like table Generator | 5b817c2a0ce070ace8002be0 | [
"ASCII Art",
"Fundamentals"
]
| https://www.codewars.com/kata/5b817c2a0ce070ace8002be0 | 6 kyu |
## [Every](https://www.codewars.com/kata/every-possible-sum-of-two-digits/) [possible](https://www.codewars.com/kata/every-possible-sum-of-two-digits/) [sum](https://www.codewars.com/kata/every-possible-sum-of-two-digits/) [of](https://www.codewars.com/kata/every-possible-sum-of-two-digits/) [two](https://www.codewars.com/kata/every-possible-sum-of-two-digits/) [digits](https://www.codewars.com/kata/every-possible-sum-of-two-digits/)
Given a long number, return all the possible sum of two digits of it.
For example, `12345`: all possible sum of two digits from that number are:
[ 1 + 2, 1 + 3, 1 + 4, 1 + 5, 2 + 3, 2 + 4, 2 + 5, 3 + 4, 3 + 5, 4 + 5 ]
Therefore the result must be:
[ 3, 4, 5, 6, 5, 6, 7, 7, 8, 9 ]
<hr>
## <span style="color:magenta">We now interrupt your regularly scheduled programming</span>
Given the result, return the number!
###### ( if there is more than one possibility, just return any one of them ) | algorithms | def find_number(a): return int(str(l := a[0] + a[1] - a[n] >> 1 if ~ - (n := int((2 * len(a)) * * .5)) else (a[0] > 9) * 9) + '' . join(str(d - l) for d in a[: n]))
| Going backwards: Number from every possible sum of two digits | 5b4fd549bdd074f9a200005f | [
"Algorithms"
]
| https://www.codewars.com/kata/5b4fd549bdd074f9a200005f | 6 kyu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.