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 |
|---|---|---|---|---|---|---|---|
There are five workers : James,John,Robert,Michael and William.They work one by one and on weekends they rest.
Order is same as in the description(James works on mondays,John works on tuesdays and so on).You have to create a function **'task'** that will take 3 arguments(**w, n, c**):
1) Weekday
2) Number of trees that must be sprayed on that day
3) Cost of 1 litre liquid that is needed to spray tree,let's say one tree needs 1 litre liquid.
Let cost of all liquid be **x**
Your function should return string like this : `'It is (weekday) today, (name), you have to work, you must spray (number) trees and you need (x) dollars to buy liquid'`
**For example**:
```python
task('Monday', 15, 2) -> 'It is Monday today, James, you have to work, you must spray 15 trees and you need 30 dollars to buy liquid'
```
```cpp
task("Monday", 15, 2) -> "It is Monday today, James, you have to work, you must spray 15 trees and you need 30 dollars to buy liquid"
```
```ruby
task('Monday', 15, 2) -> 'It is Monday today, James, you have to work, you must spray 15 trees and you need 30 dollars to buy liquid'
```
|
reference
|
def task(w, n, c):
workers = {"Monday": "James", "Tuesday": "John",
"Wednesday": "Robert", "Thursday": "Michael", "Friday": "William"}
return f"It is { w } today, { workers [ w ]} , you have to work, you must spray { n } trees and you need { n * c } dollars to buy liquid"
|
Spraying trees
|
5981a139f5471fd1b2000071
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/5981a139f5471fd1b2000071
|
7 kyu
|
<video controls style='width:500px;' autoplay='autoplay' loop='loop'><source src="https://i.imgur.com/j36Kh64.mp4" type='video/mp4'></source></video>
Background Story:
=================
In the [*Dune* universe][1], a **spice harvester** is a large, heavy, mobile factory designed to harvest the spice *Melange*. It is dropped by carrier ships (known as Carryalls) onto spice fields. Harvesters harvest and process the spice off the top of the desert floor.
Because of the rhythmic sound they make, harvesters are regularly eaten by sandworms (on the planet *Arrakis*, sandworms were reported to range from 100 meters to up to 450 meters in length). That's why 2 or 3 ornithopters (called spotters) are deployed to scout from the skies to watch for wormsign. Upon detection of wormsign (ie. worm movement), the spotters then contact the nearest Carryall for pickup of the target harvester.
[1]:https://en.wikipedia.org/wiki/Dune_(novel)
Goal:
=====
As a spotter pilot, you are responsible for handling dispatch of Carryalls in your vicinity. Your goal is to determine whether a carryall should be sent for rescue, or if it must be forfeited because there is not enough time.
Each test input will consist of an object `data`, which has the following properties:
`harvester`: location of the spice harvester
`worm`: location and travel speed of the spotted sandworm in the form `[location, movement speed]`)
`carryall`: location and travel speed of the nearest carryall in the form `[location, movement speed]`)
Conditions / Restrictions:
==========================
- All coordinates (`location`) are in the form: `[x, y]` and may be positive or negative. For example: `[45,225]`
- Assume that the sandworm and Carryall each are moving toward the harvester in a straight line at a constant speed.
- A Carryall takes 1 minute to lift the harvester to a safe altitude in order to avoid being devoured by the sandworm. Take this into account when formulating your solution.
- Distance is measured in kilometers (*in the 213th century, the metric system is the universal standard*)
- Movement speed is measured in km/minute.
- Input argument is always valid.
- Return value should be a `String` type value.
- Do not mutate the input.
Output:
=======
If the harvester can be saved (that is, lifted to a safe altitude *before* the sandworm reaches the target location), the function should return `The spice must flow! Rescue the harvester!` otherwise, it should return `Damn the spice! I'll rescue the miners!`
Test Example:
=============
```javascript
let data1 = {harvester: [345,600], worm: [[200,100],25], carryall: [[350,200],32]};
harvesterRescue(data1); // returns 'The spice must flow! Rescue the harvester!'
```
```python
data1 = {'harvester': [345,600], 'worm': [[200,100],25], 'carryall': [[350,200],32]}
harvester_rescue(data1); # returns 'The spice must flow! Rescue the harvester!'
```
```java
// Harvester Position, Worm Position&Speed, Carryall Position&Speed
data = {{345, 600}, {200, 100, 25}, {350, 200, 32}}
harvester_rescue(data); // Returns "The spice must flow! Rescue the harvester!"
```
```elixir
# in Elixir you will be given a keyword list
data1 = [harvester: [345,600], worm: [[200,100],25], carryall: [[350,200],32]]
Save.harvester_rescue(data1) # returns "The spice must flow! Rescue the harvester!"
```
```go
// For Go, you'll be given a preloaded Data struct:
type Data struct {
Harvester [2]int
Worm [3]int
Carryall [3]int
}
data1 := Data{[2]int{345,600}, [3]int{200,100,25}, [3]int{350,200,32}}
HarvesterRescue(data1) // returns "The spice must flow! Rescue the harvester!"
```
If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored).
|
reference
|
import math
def harvester_rescue(data):
harvester = data['harvester']
worm, worm_speed = data['worm']
carryall, carryall_speed = data['carryall']
if distance(harvester, worm) / worm_speed > distance(harvester, carryall) / carryall_speed + 1:
return 'The spice must flow! Rescue the harvester!'
return 'Damn the spice! I\'ll rescue the miners!'
def distance(loc1, loc2):
return math . sqrt((loc1[0] - loc2[0]) * * 2 + (loc1[1] - loc2[1]) * * 2)
|
Save the Spice Harvester (Dune Universe)
|
587d7544f1be39c48c000109
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/587d7544f1be39c48c000109
|
6 kyu
|
Create a method **partition** that accepts a list and a method/block. It should return two arrays: the first, with all the elements for which the given block returned true, and the second for the remaining elements.
Here's a simple Ruby example:
animals = ["cat", "dog", "duck", "cow", "donkey"]
partition(animals){|animal| animal.size == 3}
#=> [["cat", "dog", "cow"], ["duck", "donkey"]]
The equivalent in Python would be:
animals = ['cat', 'dog', 'duck', 'cow', 'donkey']
partition(animals, lambda x: len(x) == 3)
# (['cat', 'dog', 'cow'], ['duck', 'donkey'])
If you need help, here's a reference:
http://www.rubycuts.com/enum-partition
|
reference
|
def partition(list, classifier_method):
listTrue = []
listFalse = []
for l in list:
if classifier_method(l):
listTrue . append(l)
else:
listFalse . append(l)
return listTrue, listFalse
|
Enumerable Magic #30 - Split that Array!
|
545b342082e55dc9da000051
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/545b342082e55dc9da000051
|
8 kyu
|
Given an unsorted array of integers, find the smallest number in the array, the largest number in the array, and the smallest number between the two array bounds that is not in the array.
For instance, given the array [-1, 4, 5, -23, 24], the smallest number is -23, the largest number is 24, and the smallest number between the array bounds is -22. You may assume the input is well-formed.
You solution should return an array `[smallest, minimumAbsent, largest]`
The `smallest` integer should be the integer from the array with the lowest value.
The `largest` integer should be the integer from the array with the highest value.
The `minimumAbsent` is the smallest number between the largest and the smallest number that is not in the array.
```javascript
minMinMax([-1, 4, 5, -23, 24]); //[-23, -22, 24]
minMinMax([1, 3, -3, -2, 8, -1]); //[-3, 0, 8]
minMinMax([2, -4, 8, -5, 9, 7]); //[-5, -3,9]
```
```php
minMinMax([-1, 4, 5, -23, 24]); //[-23, -22, 24]
minMinMax([1, 3, -3, -2, 8, -1]); //[-3, 0, 8]
minMinMax([2, -4, 8, -5, 9, 7]); //[-5, -3,9]
```
```c
min_min_max({-1, 4, 5, -23, 24}, 5); // {-23, -22, 24}
min_min_max({1, 3, -3, -2, 8, -1}, 6); // {-3, 0, 8}
min_min_max({2, -4, 8, -5, 9, 7}, 6); // {-5, -3, 9}
```
|
games
|
def minMinMax(arr):
s, mi, ma = set(arr), min(arr), max(arr)
return [mi, next(x for x in range(mi + 1, ma) if x not in s), ma]
|
MinMaxMin: Bounded Nums
|
58d3487a643a3f6aa20000ff
|
[
"Arrays"
] |
https://www.codewars.com/kata/58d3487a643a3f6aa20000ff
|
7 kyu
|
Remember the spongebob meme that is meant to make fun of people by repeating what they say in a mocking way?

You need to create a function that converts the input into this format, with the output being the same string expect there is a pattern of uppercase and lowercase letters.
Example:
```
input: "stop Making spongebob Memes!"
output: "StOp mAkInG SpOnGeBoB MeMeS!"
```
|
reference
|
def sponge_meme(seq):
return '' . join(
c . lower() if i % 2 else c . upper()
for i, c in enumerate(seq)
)
|
sPoNgEbOb MeMe
|
5982619d2671576e90000017
|
[
"Fundamentals",
"Strings"
] |
https://www.codewars.com/kata/5982619d2671576e90000017
|
7 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 arrays `arr1` and `arr2`. They have the same length(length>=2). The elements of two arrays always be integer.
Sort `arr1` according to the ascending order of arr2; Sort `arr2` according to the ascending order of arr1. Description is not easy to understand, for example:
```
arr1=[5,4,3,2,1],
arr2=[6,5,7,8,9]
```
Let us try to sorting arr1.
First, we need know the ascending order of arr2:
```
[5,6,7,8,9]
```
We can see, after sorting arr2 to ascending order, some elements' index are changed:
```
unsort arr2 ascending order arr2
[6,5,7,8,9]---> [5,6,7,8,9]
index0(6) ---> index1
index1(5) ---> index0
index2(7) index2(no change)
index3(8) index3(no change)
index4(9) index4(no change)
```
So, we need to sort arr1 according to these changes:
```
unsort arr1 sorted arr1
[5,4,3,2,1]---> [4,5,3,2,1]
index0(5) ---> index1
index1(4) ---> index0
index2(3) index2(no change)
index3(2) index3(no change)
index4(1) index4(no change)
So: sorted arr1= [4,5,3,2,1]
```
And then, we're sorting arr2 with the same process:
```
unsort arr1 ascending order arr1
[5,4,3,2,1]---> [1,2,3,4,5]
index0(5) ---> index4
index1(4) ---> index3
index2(3) index2(no change)
index3(2) ---> index1
index4(1) ---> index0
unsort arr2 sorted arr2
[6,5,7,8,9]---> [9,8,7,5,6]
index0(6) ---> index4
index1(5) ---> index3
index2(7) index2(no change)
index3(8) ---> index1
index4(9) ---> index0
So: sorted arr2= [9,8,7,5,6]
```
Finally, return sorted arrays as a 2D array: `[sorted arr1, sorted arr2]`
Note: In ascending order sorting process(not the final sort), if some elements have same value, sort them according to their index; You can modify the original array, but I advise you not to do that. ;-)
```if:haskell
Note: In Haskell, you are expected to return a tuple of arrays, and good luck trying to modifiy the original array. :]
```
```if:cobol
Note: In COBOL, use the two tables `result1` and `result2` for the result.
```
# Some Examples and explain
```
sortArrays([5,4,3,2,1],[6,5,7,8,9]) should return
[[4,5,3,2,1],[9,8,7,5,6]]
sortArrays([2,1,3,4,5],[5,6,7,8,9]) should return
[[2,1,3,4,5],[6,5,7,8,9]]
sortArrays([5,6,9,2,6,5],[3,6,7,4,8,1]) should return
[[5,5,2,6,9,6],[4,3,1,6,8,7]]
```
|
reference
|
def sort_two_arrays(arr1, arr2):
a1 = sorted([[arr1[i], i] for i in range(len(arr1))])
a2 = sorted([[arr2[i], i] for i in range(len(arr2))])
r1 = [arr1[a[1]] for a in a2]
r2 = [arr2[a[1]] for a in a1]
return [r1, r2]
|
Sort two arrays
|
5818c52e21a33314e00000cb
|
[
"Puzzles",
"Fundamentals",
"Sorting",
"Algorithms",
"Arrays"
] |
https://www.codewars.com/kata/5818c52e21a33314e00000cb
|
6 kyu
|
Todd is looking for the best place to park in the grocery store parking lot. Todd knows that there's a sequence of events that happens whenever he buys groceries:
* When he first arrives, he walks straight into the store (where the carts are kept).
* After completing shopping, he will return to his car with his cart to put the groceries away.
* He will walk with the now empty cart to the nearest cart corral, and deposit it.
* He will walk back to his car.
This particular parking lot is fairly simple. The store is located on the far left, there is a single row of parking, with some number of cart corrals interspersed within them. For example:
```python
["STORE", "TAKEN", "TAKEN", "CORRAL", "TAKEN", "OPEN", "OPEN", "TAKEN", "CORRAL"]
```
```javascript
["STORE", "TAKEN", "TAKEN", "CORRAL", "TAKEN", "OPEN", "OPEN", "TAKEN", "CORRAL"]
```
```haskell
[ STORE, TAKEN, TAKEN, CORRAL, TAKEN, OPEN, OPEN, TAKEN, CORRAL ]
```
Each index is one "space" of walking.
In this case, the best spot for Todd would be at index 5. He would take 5 steps to get to the store, then 5 steps to get back to his car, then 2 steps to get to a cart corral, then 2 steps to get back, for a total of 14 steps.
Return the index of the parking spot Todd should choose. Since Todd is driving in from the side without the store on it, if there's a tie in distance, pick the one that's the furthest from the store. (Less driving. Todd is incredibly lazy.)
|
algorithms
|
def best_parking_spot(arr):
if arr . count("OPEN") == 1:
return arr . index("OPEN")
corrals = [i for i, v in enumerate(arr) if v == 'CORRAL']
opens = [i for i, v in enumerate(arr) if v == 'OPEN']
result = {}
for i in range(0, len(opens)):
for j in range(0, len(corrals)):
result[opens[i] * 2 + abs(opens[i] - corrals[j]) * 2] = opens[i]
return result[min(result . keys())]
|
Best Parking Spot
|
5859aaf04facfeb0d4002051
|
[
"Algorithms"
] |
https://www.codewars.com/kata/5859aaf04facfeb0d4002051
|
6 kyu
|
<img src="https://i.imgur.com/ta6gv1i.png?1"/>
---
# Story
The <a href="https://en.wikipedia.org/wiki/Pied_Piper_of_Hamelin">Pied Piper</a> has been enlisted to play his magical tune and coax all the rats out of town.
But some of the rats are deaf and are going the wrong way!
# Kata Task
How many deaf rats are there?
# Legend
* ```P``` = The Pied Piper
* ```O~``` = Rat going left
* ```~O``` = Rat going right
# Example
* ex1 ```~O~O~O~O P``` has 0 deaf rats
* ex2 ```P O~ O~ ~O O~``` has 1 deaf rat
* ex3 ```~O~O~O~OP~O~OO~``` has 2 deaf rats
---
# Series
* [The deaf rats of Hamelin (2D)](https://www.codewars.com/kata/the-deaf-rats-of-hamelin-2d)
</span>
|
reference
|
def count_deaf_rats(town):
return town . replace(' ', '')[:: 2]. count('O')
|
The Deaf Rats of Hamelin
|
598106cb34e205e074000031
|
[
"Fundamentals",
"Strings",
"Algorithms",
"Queues",
"Data Structures"
] |
https://www.codewars.com/kata/598106cb34e205e074000031
|
6 kyu
|
#About Caesar Cipher
Caesar Cipher is a simple encryption technique based on shifting each character by a fixed number of positions in the alphabet.
For example, if the shift is 3, an encoded version of phrase "kata" will be:
```
k + 3 = n
a + 3 = d
t + 3 = w
a + 3 = d
```
In a case when "z" is reached, the algorithm wraps back to "a".
Example: "zen", key 3
```
z + 3 = c
e + 3 = h
n + 3 = q
```
The key for this cipher can be any non-negative integer. However, because there are 26 letters in English alphabet, any key larger than 26 can be thought about as key = key % 26.
#What to do
Your task is to write a function that will *encrypt* a phrase using Caesar Cipher and a given shift key and return it as a string. However, **the key should be increased by 1 with every word in a phrase**. For example, if the function is called with a phrase "divide et impera" and key 3, the encoding should be as follows:
```
- Shift the word "divide" by the key of 3
- Shift the word "et" by the key of 3 + 1 = 4
- Shift the word "impera" by the key of 3 + 2 = 5
```
#Important things to note:
- Guaranteed input will be of type string, **lowercase characters and spaces only**.
- Key can be any non-negative integer.
To read more about Caesar Cipher, visit https://en.wikipedia.org/wiki/Caesar_cipher
|
algorithms
|
def caesar_encode(s, n):
return ' ' . join('' . join(chr((ord(c) - 97 + n + i) % 26 + 97) for c in w) for i, w in enumerate(s . split(' ')))
|
Caesar Cipher Encryption - Variation
|
55ec55323c89fc5fbd000019
|
[
"Algorithms",
"Cryptography"
] |
https://www.codewars.com/kata/55ec55323c89fc5fbd000019
|
6 kyu
|
*** Nova polynomial multiply***
This kata is from a series on polynomial handling. ( [#1](http://www.codewars.com/kata/nova-polynomial-1-add-1) [#2](http://www.codewars.com/kata/570eb07e127ad107270005fe) [#3](http://www.codewars.com/kata/5714041e8807940ff3001140 ) [#4](http://www.codewars.com/kata/571a2e2df24bdfd4e20001f5))
Consider a polynomial in a list where each element in the list element corresponds to the factors. The factor order is the position in the list. The first element is the zero order factor (the constant).
p = [a0, a1, a2, a3] signifies the polynomial a0 + a1x + a2x^2 + a3*x^3
In this kata multiply two polynomials:
```python
poly_multiply([1, 2], [1] ) = [1, 2]
poly_multiply([2, 4], [4, 5] ) = [8, 26, 20]
```
The first kata of this series is preloaded in the code and can be used: [poly_add](http://www.codewars.com/kata/nova-polynomial-1-add-1)
|
algorithms
|
def poly_multiply(p1, p2):
if not p1 or not p2:
return []
n = len(p1) + len(p2) - 1
p = [0] * n
for i, a in enumerate(p1):
for j, b in enumerate(p2):
p[i + j] += a * b
return p
|
nova polynomial 2. multiply
|
570eb07e127ad107270005fe
|
[
"Algorithms"
] |
https://www.codewars.com/kata/570eb07e127ad107270005fe
|
6 kyu
|
Sort array by last character
Complete the function to sort a given array or list by last character of elements.
```if-not:haskell
Element can be an integer or a string.
```
### Example:
```
['acvd', 'bcc'] --> ['bcc', 'acvd']
```
The last characters of the strings are `d` and `c`. As `c` comes before `d`, sorting by last character will give `['bcc', 'acvd']`.
If two elements don't differ in the last character, then they should be sorted by the order they come in the array.
```if:haskell
Elements will not be empty (but the list may be).
```
|
reference
|
def sort_me(arr):
return sorted(arr, key=lambda elem: str(elem)[- 1])
|
sort array by last character
|
55aea0a123c33fa3400000e7
|
[
"Fundamentals",
"Sorting",
"Arrays",
"Strings"
] |
https://www.codewars.com/kata/55aea0a123c33fa3400000e7
|
7 kyu
|
## Description
This is your first potion class in Hogwarts and professor gave you a homework to figure out what color potion will turn into if he'll mix it with some other potion. All potions have some color that written down as RGB color from `[0, 0, 0]` to `[255, 255, 255]`. To make task more complicated teacher will do few mixing and after will ask you for final color. Besides color you also need to figure out what volume will have potion after final mix.
## Task
Based on your programming background you managed to figure that after mixing two potions colors will mix as if mix two RGB colors. For example, if you'll mix potion that have color `[255, 255, 0]` and volume `10` with one that have color `[0, 254, 0]` and volume `5`, you'll get new potion with color `[170, 255, 0]` and volume `15`. So you decided to create a class `Potion` that will have two properties: `color` (a list (a tuple in Python) with 3 integers) and `volume` (a number), and one method `mix` that will accept another `Potion` and return a mixed `Potion`.
## Example
```
felix_felicis = Potion([255, 255, 255], 7)
shrinking_solution = Potion([ 51, 102, 51], 12)
new_potion = felix_felicis.mix(shrinking_solution)
new_potion.color == [127, 159, 127]
new_potion.volume == 19
```
**Note**: Use ceiling when calculating the resulting potion's color.
|
algorithms
|
from math import ceil
class Potion:
def __init__(self, color, volume):
self . color = color
self . volume = volume
def mix(self, other):
ratio1 = self . volume / (self . volume + other . volume)
ratio2 = other . volume / (self . volume + other . volume)
r = ceil(self . color[0] * ratio1 + other . color[0] * ratio2)
g = ceil(self . color[1] * ratio1 + other . color[1] * ratio2)
b = ceil(self . color[2] * ratio1 + other . color[2] * ratio2)
volume = self . volume + other . volume
return Potion((r, g, b), volume)
|
Potion Class 101
|
5981ff1daf72e8747d000091
|
[
"Algorithms",
"Object-oriented Programming"
] |
https://www.codewars.com/kata/5981ff1daf72e8747d000091
|
6 kyu
|
In computer science and discrete mathematics, an [inversion](https://en.wikipedia.org/wiki/Inversion_%28discrete_mathematics%29) is a pair of places in a sequence where the elements in these places are out of their natural order. So, if we use ascending order for a group of numbers, then an inversion is when larger numbers appear before lower number in a sequence.
Check out this example sequence: ```(1, 2, 5, 3, 4, 7, 6)``` and we can see here three inversions
```5``` and ```3```; ```5``` and ```4```; ```7``` and ```6```.
You are given a sequence of numbers and you should count the number of inversions in this sequence.
```Input```: A sequence as a tuple of integers.
```Output```: The inversion number as an integer.
Example:
```python
count_inversion((1, 2, 5, 3, 4, 7, 6)) == 3
count_inversion((0, 1, 2, 3)) == 0
```
|
algorithms
|
def count_inversion(nums):
return sum(a > b for i, a in enumerate(nums) for b in nums[i + 1:])
|
Count inversions
|
5728a1bc0838ffea270018b2
|
[
"Algorithms"
] |
https://www.codewars.com/kata/5728a1bc0838ffea270018b2
|
7 kyu
|
*** Nova polynomial derivative***
This kata is from a series on polynomial handling. ( [#1](http://www.codewars.com/kata/nova-polynomial-1-add-1) [#2](http://www.codewars.com/kata/570eb07e127ad107270005fe) [#3](http://www.codewars.com/kata/5714041e8807940ff3001140 ) [#4](http://www.codewars.com/kata/571a2e2df24bdfd4e20001f5))
Consider a polynomial in a list where each element in the list element corresponds to the factors. The factor order is the position in the list. The first element is the zero order factor (the constant).
p = [a0, a1, a2, a3] signifies the polynomial a0 + a1x + a2x^2 + a3*x^3
In this kata return the derivative of a polynomial:
```python
poly_derivative([1, 2] ) = [2]
poly_derivative([9, 1, 3]) = [1, 6]
```
Previous Katas on Nova polynomial:
1. [poly_add](http://www.codewars.com/kata/nova-polynomial-1-add-1)
2. [poly_multiply](http://www.codewars.com/kata/570eb07e127ad107270005fe).
3. [poly_subtract](http://www.codewars.com/kata/5714041e8807940ff3001140 )
|
algorithms
|
def poly_derivative(p):
return [i * x for i, x in enumerate(p)][1:]
|
nova polynomial 4. derivative
|
571a2e2df24bdfd4e20001f5
|
[
"Algorithms",
"Recursion",
"Arrays"
] |
https://www.codewars.com/kata/571a2e2df24bdfd4e20001f5
|
7 kyu
|
*** Nova polynomial subtract***
This kata is from a series on polynomial handling. ( [#1](http://www.codewars.com/kata/nova-polynomial-1-add-1) [#2](http://www.codewars.com/kata/570eb07e127ad107270005fe) [#3](http://www.codewars.com/kata/5714041e8807940ff3001140 ) [#4](http://www.codewars.com/kata/571a2e2df24bdfd4e20001f5))
Consider a polynomial in a list where each element in the list element corresponds to the factors. The factor order is the position in the list. The first element is the zero order factor (the constant).
p = [a0, a1, a2, a3] signifies the polynomial a0 + a1x + a2x^2 + a3*x^3
In this kata subtract two polynomials:
```python
poly_subtract([1, 2], [1] ) = [0, 2]
poly_subtract([2, 4], [4, 5] ) = [-2, -1]
```
The first and second katas of this series are preloaded in the code and can be used:
* [poly_add](http://www.codewars.com/kata/nova-polynomial-1-add-1)
* [poly_multiply](http://www.codewars.com/kata/570eb07e127ad107270005fe).
|
algorithms
|
def poly_subtract(p, q): return poly_add(p, [- c for c in q])
|
nova polynomial 3. subtract
|
5714041e8807940ff3001140
|
[
"Algorithms",
"Recursion",
"Arrays"
] |
https://www.codewars.com/kata/5714041e8807940ff3001140
|
7 kyu
|
## Nova polynomial add
This kata is from a series on polynomial handling. ( [#1](http://www.codewars.com/kata/nova-polynomial-1-add-1) [#2](http://www.codewars.com/kata/570eb07e127ad107270005fe) [#3](http://www.codewars.com/kata/5714041e8807940ff3001140 ) [#4](http://www.codewars.com/kata/571a2e2df24bdfd4e20001f5) )
Consider a polynomial in a list where each element in the list element corresponds to a factor. The factor order is the position in the list. The first element is the zero order factor (the constant).
`p = [a0, a1, a2, a3]` signifies the polynomial `a0 + a1x + a2x^2 + a3*x^3`
In this kata add two polynomials:
```python
poly_add ( [1, 2], [1] ) = [2, 2]
```
```haskell
polyAdd [1, 2] [1] = [2, 2]
```
|
algorithms
|
from itertools import zip_longest
def poly_add(p1, p2):
return [x + y for x, y in zip_longest(p1, p2, fillvalue=0)]
|
nova polynomial 1. add
|
570ac43a1618ef634000087f
|
[
"Algorithms",
"Mathematics",
"Recursion",
"Arrays"
] |
https://www.codewars.com/kata/570ac43a1618ef634000087f
|
7 kyu
|
I forgot what system I'm running on. Can you help me find my hostname?
Each computer has a name associated with it. Your goal is to return a string version (case-sensitive) of the host that your kata code runs on.
|
games
|
def get_pid():
import socket
return socket . gethostname()
|
Where am I?
|
560b000f56b4d8be9e000018
|
[
"Puzzles"
] |
https://www.codewars.com/kata/560b000f56b4d8be9e000018
|
7 kyu
|
You are in a military mission in the middle of the jungle where your enemies are really hard to spot because of their camouflage. Luckily you have a device that shows the position of your enemies!
Your device is a radar that computes the ```x``` and ```y``` coordinates of an enemy in meters ```every 5 seconds```. You are always at the point ```(0, 0)``` and your enemies are always heading towards you.
<h2>Your task</h2>
The radar will give you two consecutive points ```P1(x, y)``` and ```P2(x, y)``` of an enemy and you should write a function that will return the estimated time in seconds that the enemy will take to reach you, so you can defend! <b>Python results should be rounded to 3 decimal places.</b>
<h2>Hints</h2>
<a href="https://en.wikipedia.org/wiki/Euclidean_distance" target="_blank">Distance between two points</a>. Remember that you are working with only 2 dimensions!
Tests will have a precision of 3 decimal points. Good luck!
|
games
|
def distance(p1, p2): return ((p2[0] - p1[0]) * * 2 + (p2[1] - p1[1]) * * 2) * * 0.5
def calculate_time(p1, p2):
return round(5 * distance(p2, [0, 0]) / distance(p1, p2), 3)
|
Approaching enemies
|
56d58a16e8f2d6957100093f
|
[
"Puzzles",
"Games"
] |
https://www.codewars.com/kata/56d58a16e8f2d6957100093f
|
7 kyu
|
Implement something called `str_repeat` that repeats a string n-times. That something _must not_ be a function.
Thanks `wichu` for the idea.
Enjoy! :)
|
games
|
from operator import mul as str_repeat
|
String Repetition without Function
|
57a110eee298a737e2000283
|
[
"Restricted",
"Puzzles"
] |
https://www.codewars.com/kata/57a110eee298a737e2000283
|
6 kyu
|
Your goal is to create something called `puzzle` which is equivalent to function `n_time2_power_x(n, x)` (see below) where `n` and `x` are positive integers.
__IMPORTANT__: `puzzle` must not be a `function` or `method` and your solution mustn't contain `return` keyword.
Enjoy! :)
```python
def n_time2_power_x(n, x):
return n * 2 ** x
```
|
games
|
puzzle = int . __lshift__
|
n times 2 to the power of x without function or class method and return
|
57b971f68f58135e840001cc
|
[
"Language Features",
"Restricted",
"Puzzles"
] |
https://www.codewars.com/kata/57b971f68f58135e840001cc
|
7 kyu
|
Imagine that you have an array of 3 integers each representing different person. Each number can be 0, 1, or 2 which represents the number of hands that person is holding up.
Now imagine there is a sequence which follows these rules:
* None of the people have their arms raised at first
* Firstly, a person raises 1 hand; then they raise the second hand; after that they put both hands down - these steps form a cycle
* Person #1 performs these steps all the time, person #2 advances only after person #1 puts their hands down, and person #3 advances only after person #2 puts their hands down
The first 10 steps of the sequence represented as a table are:
```
Step P1 P2 P3
--------------------
0 0 0 0
1 1 0 0
2 2 0 0
3 0 1 0
4 1 1 0
5 2 1 0
6 0 2 0
7 1 2 0
8 2 2 0
9 0 0 1
```
Given a number, return an array, containing 3 integers, each representing the number of hands raised by each person at that step, starting from `0`.
|
algorithms
|
def get_positions(n):
return n % 3, n / / 3 % 3, n / / 9 % 3
|
Hands Up
|
56d8f14cba01a83cdb0002a2
|
[
"Fundamentals",
"Algorithms"
] |
https://www.codewars.com/kata/56d8f14cba01a83cdb0002a2
|
7 kyu
|
Here your task is to <font size="+1">Create a (nice) Christmas Tree</font>.<br><br>
You don't have to check errors or incorrect input values, every thing is ok without bad tricks, only one int parameter as input and a string to return;-)...<br><br>
<u>So what to do?</u><br><br>First three easy examples:
<br>
````
Input: 3 and Output:
*
***
*****
###
Input 9 and Output:
*
***
*****
***
*****
*******
*****
*******
*********
###
Input 17 and Output:
*
***
*****
***
*****
*******
*****
*******
*********
*******
*********
***********
*********
***********
*************
###
Really nice trees, or what???! So merry Christmas;-)
````
You can see, always a root, always steps of hight 3, tree never smaller than 3 (return "") and no difference for input values like 15 or 17 (because (int) 15/3 = (int) 17/3). That's valid for every input and every tree. Lines are delimited by <code>\r\n</code> and no trailing white space allowed.
I think there's nothing more to say - perhaps look at the testcases too;-)!
There are some static tests at the beginning and many random tests if you submit your solution.<br> <br>
<h2><font color="red">Hope you have fun:-)!</font></h2>
|
reference
|
def christmas_tree(h):
return "" if h < 3 else "\r\n" . join(["\r\n" . join([" " * (((5 - y) / / 2) + (h / / 3) - i - 1) + "*" * (y + i * 2) for y in [1, 3, 5]]) for i in range(h / / 3)]) + "\r\n" + " " * (h / / 3) + "###"
|
Pattern 01: Merry Christmas (sometimes little bit out of time;-))
|
56c30eaef85696bf35000ccf
|
[
"Strings",
"ASCII Art",
"Fundamentals"
] |
https://www.codewars.com/kata/56c30eaef85696bf35000ccf
|
6 kyu
|
Create a function that finds the [integral](https://en.wikipedia.org/wiki/Integral) of the expression passed.
In order to find the integral all you need to do is add one to the `exponent` (the second argument), and divide the `coefficient` (the first argument) by that new number.
For example for `3x^2`, the integral would be `1x^3`: we added 1 to the exponent, and divided the coefficient by that new number).
Notes:
* The output should be a string.
* The coefficient and exponent is always a positive integer.
## Examples
```
3, 2 --> "1x^3"
12, 5 --> "2x^6"
20, 1 --> "10x^2"
40, 3 --> "10x^4"
90, 2 --> "30x^3"
```
|
reference
|
def integrate(coefficient, exponent):
return f' { coefficient / / ( exponent + 1 )} x^ { exponent + 1 } '
|
Find the Integral
|
59811fd8a070625d4c000013
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/59811fd8a070625d4c000013
|
8 kyu
|
A **bouncy number** is a positive integer whose digits neither increase nor decrease. For example, `1235` is an increasing number, `5321` is a decreasing number, and `2351` is a bouncy number. By definition, all numbers under `100` are non-bouncy, and `101` is the first bouncy number. To complete this kata, you must write a function that takes a number and determines if it is bouncy.
Input numbers will always be positive integers, but it never hurts to throw in some error handling : )
For clarification, the bouncy numbers between `100` and `125` are: `101, 102, 103, 104, 105, 106, 107, 108, 109, 120, and 121`.
|
reference
|
def is_bouncy(n):
return sorted(str(n)) != list(str(n)) and sorted(str(n)) != list(str(n))[:: - 1]
|
Bouncy Numbers
|
5769a78c6f2dea72b3000027
|
[
"Mathematics",
"Fundamentals"
] |
https://www.codewars.com/kata/5769a78c6f2dea72b3000027
|
7 kyu
|
**The scenario:** You have to complete a textbook assignment full of boring math problems as homework due in 5 days time. You want to find out how long you must spend on each of the 5 days to evenly spread the workload.
You will create a program, ```time_per_day```, that will take a list of tuples. Each tuple represents a section of the assignment and contains **two integer values**. The first value represents the complexity of each question and the second value represents the number of questions.
On average, you take:
* 0.75 minutes to complete a question of complexity value 1;
* 1.5 minutes to complete a question of complexity 2;
* 2.25 minutes to complete a question of complexity 3;
...and so on. You must return the amount of time to spend for each of the 5 days in **hours**, rounded to **2 decimal points**.
**Example:** If the parameter passed is ```[(1, 20), (2, 10), (3, 15), (4, 10)]```, the funtion should return 0.31 (If you are unsure about how to go about the solution, try working the example out on paper first before attempting to recreate it.)
**Try refining your code by writing it in one line.**
|
algorithms
|
def time_per_day(l):
sum = 0
for a in l:
sum += a[1] * a[0] * 0.75
return round(sum / 300, 2)
|
Managing Homework Time
|
58cbc48930bcf09b7a000117
|
[
"Algorithms"
] |
https://www.codewars.com/kata/58cbc48930bcf09b7a000117
|
7 kyu
|
If you have not ever heard the term **Arithmetic Progression**, refer to:
http://www.codewars.com/kata/find-the-missing-term-in-an-arithmetic-progression/python
And here is an unordered version. Try if you can survive lists of **MASSIVE** numbers (which means time limit should be considered). :D
Note: Don't be afraid that the minimum or the maximum element in the list is missing, e.g. [4, 6, 3, 5, 2] is missing 1 or 7, but this case is excluded from the kata.
Example:
```python
find([3, 9, 1, 11, 13, 5]) # => 7
```
|
algorithms
|
def find(seq):
return (min(seq) + max(seq)) * (len(seq) + 1) / 2 - sum(seq)
|
Missing number in Unordered Arithmetic Progression
|
568fca718404ad457c000033
|
[
"Algorithms",
"Mathematics",
"Performance"
] |
https://www.codewars.com/kata/568fca718404ad457c000033
|
5 kyu
|
In this exercise, you will create a function that takes an integer, ```i```. With it you must do the following:
- Find all of its multiples up to and including 100,
- Then take the digit sum of each multiple (eg. 45 -> 4 + 5 = 9),
- And finally, get the total sum of each new digit sum.
**Note:** If the digit sum of a number is more than 9 (eg. 99 -> 9 + 9 = 18) then you do **NOT** have to break it down further until it reaches one digit.
**Example** (if ```i``` is 25):
Multiples of 25 up to 100 --> ```[25, 50, 75, 100]```
Digit sum of each multiple --> ```[7, 5, 12, 1]```
Sum of each new digit sum --> ```25```
**If you can, try writing it in readable code.**
Edit (3/17/2017): Added random tests
|
algorithms
|
def procedure(n):
return sum(int(d) for i in range(n, 101, n) for d in str(i))
|
Multiples and Digit Sums
|
58ca77b9c0d640ecd2000b1e
|
[
"Algorithms"
] |
https://www.codewars.com/kata/58ca77b9c0d640ecd2000b1e
|
7 kyu
|
Build a function that can get all the integers between two given numbers.
Example:
`(2,9)`
Should give you this output back:
`[ 3, 4, 5, 6, 7, 8 ]`
~~~if:javascript,csharp
If startNum is the same as endNum, return an empty array.
~~~
~~~if:ruby,cpp
If start_num is the same as end_num, return an empty array.
~~~
~~~if:python
If start_num is the same as end_num, return an empty sequence.
~~~
~~~if:cobol
If start-num is the same as end-num, set result as an empty table.
~~~
|
algorithms
|
def function(start_num, end_num):
return list(range(start_num + 1, end_num))
|
Get the integers between two numbers
|
598057c8d95a04f33f00004e
|
[
"Algorithms"
] |
https://www.codewars.com/kata/598057c8d95a04f33f00004e
|
7 kyu
|
You have been hired by a company making speed cameras. Your mission is to write the controller software turning the picture taken by the camera into a license plate number.
# Specification
The sensor matrix outputs a 3-line string using pipes and underscores. We want to translate this into a string with regular digits when these are recognized, and a ? when they are not. See the input and output examples below.
* we plan to sell to various countries, so we make no assumption on length
* there are no 0s or 1s on license plates
* the input string sometimes misses one of the bottom two horizontal stripes. Since there is no ambiguity, we must return the digit instead of a question mark
# Input
A non-empty string with pipes and underscores. It will always have 3 lines of identical length (which will always be a multiple of 3).
```
_ _ _ _ _ _ \n
_| _||_||_ |_ || ||_|\n
|_ _| | _|| | ||_| _|
```
# Output
A string with regular digits and question marks.
```234?6789```
|
reference
|
table = {
' _ _||_ ': '2', ' _ ||_ ': '2', ' _ _|| ': '2',
' _ _| _|': '3', ' _ | _|': '3', ' _ _| |': '3',
' |_| |': '4', ' | | |': '4',
' _ |_ _|': '5', ' _ | _|': '5', ' _ |_ |': '5',
' _ |_ |_|': '6', ' _ | |_|': '6', ' _ |_ | |': '6',
' _ | |': '7',
' _ |_||_|': '8', ' _ | ||_|': '8', ' _ |_|| |': '8',
' _ |_| _|': '9', ' _ | | _|': '9', ' _ |_| |': '9',
}
def recognize(s):
rows = s . splitlines()
digits = ['' . join(r[k: k + 3] for r in rows)
for k in range(0, len(rows[0]), 3)]
return '' . join(table . get(d, '?') for d in digits)
|
License Plate Recognition
|
58db721b2f449efaf5000038
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/58db721b2f449efaf5000038
|
5 kyu
|
 Returns the bank account number parsed from specified string.
 You work for a bank, which has recently purchased an ingenious machine to assist in reading letters and faxes sent in by branch offices.<br>
 The machine scans the paper documents, and produces a string with a bank account that looks like this:
```
_ _ _ _ _ _ _ _
| | | _| _||_||_ |_ ||_||_|
|_| ||_ _| | _||_| ||_| _|
```
 Each string contains an account number written using pipes and underscores.<br>
 Each account number should have at least one digit, all of which should be in the range 0-9.
 Your task is to write a function that can take bank account string and parse it into actual account numbers.
```
@param {string} bankAccount
@return {number}
```
Examples:
```
' _ _ _ _ _ _ _ \n'+
' | _| _||_||_ |_ ||_||_|\n'+ => 123456789
' ||_ _| | _||_| ||_| _|\n'
' _ _ _ _ _ _ _ _ _ \n'+
'| | _| _|| ||_ |_ ||_||_|\n'+ => 23056789
'|_||_ _||_| _||_| ||_| _|\n',
' _ _ _ _ _ _ _ _ _ \n'+
'|_| _| _||_||_ |_ |_||_||_|\n'+ => 823856989
'|_||_ _||_| _||_| _||_| _|\n',
```
(c)RSS
|
games
|
def builder(s, isRef=0):
out = {}
for r in s . splitlines():
for i in range(len(r) / / 3):
out[i] = out . get(i, '') + r[i * 3: i * 3 + 3]
return {s: str(i) for i, s in out . items()} if isRef else out . values()
DIGS = builder('''\
_ _ _ _ _ _ _ _
| | | _| _||_||_ |_ ||_||_|
|_| ||_ _| | _||_| ||_| _|
''', 1)
def parse_bank_account(s):
return int('' . join(DIGS[d] for d in builder(s)))
|
Parse bank account number
|
597eeb0136f4ae84f9000001
|
[
"Strings",
"Puzzles"
] |
https://www.codewars.com/kata/597eeb0136f4ae84f9000001
|
6 kyu
|
 Return the most profit from stock quotes.
 Stock quotes are stored in an array in order of date. The stock profit is the difference in prices in buying and selling stock. Each day, you can either buy one unit of stock, sell any number of stock units you have already bought, or do nothing. Therefore, the most profit is the maximum difference of all pairs in a sequence of stock prices.
```
@param {array} quotes
@return {number} max profit
```
Example:
```
[ 1, 2, 3, 4, 5, 6 ] => 15 (buy at 1,2,3,4,5 and then sell all at 6)
[ 6, 5, 4, 3, 2, 1 ] => 0 (nothing to buy for profit)
[ 1, 6, 5, 10, 8, 7 ] => 18 (buy at 1,6,5 and sell all at 10)
[ 1, 2, 10, 3, 2, 7, 3, 2 ] => 26 (buy at 1,2 and sell them at 10. Then buy at 3,2 and sell them at 7)
```
(c)RSS
|
games
|
def get_most_profit_from_stock_quotes(quotes):
gain, top = 0, - float('inf')
for v in reversed(quotes):
if top < v:
top = v
else:
gain += top - v
return gain
|
Most profit from stock quotes
|
597ef546ee48603f7a000057
|
[
"Puzzles"
] |
https://www.codewars.com/kata/597ef546ee48603f7a000057
|
6 kyu
|
Given a positive integer `N`, return the largest integer `k` such that `3^k < N`.
For example,
```python
largest_power(3) == 0
largest_power(4) == 1
```
```haskell
largestPower 3 = 0
largestPower 4 = 1
```
```csharp
Kata.LargestPower(3) => 0
Kata.LargestPower(4) => 1
```
```ruby
largest_power(3) => 0
largest_power(4) => 1
```
```c
largest_power(3); // returns 0
largest_power(4); // returns 1
```
```go
LargestPower(3) // returns 0
LargestPower(4) // returns 1
```
You may assume that the input to your function is always a positive integer.
|
algorithms
|
from math import log, ceil
def largest_power(N):
return ceil(log(N, 3)) - 1
|
Powers of 3
|
57be674b93687de78c0001d9
|
[
"Mathematics",
"Algorithms"
] |
https://www.codewars.com/kata/57be674b93687de78c0001d9
|
7 kyu
|
Given a list of white pawns on a chessboard (any number of them, meaning from 0 to 64 and with the possibility to be positioned everywhere), determine how many of them have their backs covered by another.
Pawns attacking upwards since we have only white ones.
Please remember that a pawn attack(and defend as well) only the 2 square on the sides in front of him. https://en.wikipedia.org/wiki/Pawn_(chess)#/media/File:Pawn_(chess)_movements.gif
This is how the chess board coordinates are defined:
<table style='width: 215px; background-color:white; font-size: 10px; border-collapse: collapse;'><tr><td style='line-height: 1; padding: 0; height:15px; width: 15px;'></td><td style='line-height: 1; padding: 0; text-align: center; width: 25px; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>A</td><td style='line-height: 1; padding: 0; text-align: center; width: 25px; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>B</td><td style='line-height: 1; padding: 0; text-align: center; width: 25px; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>C</td><td style='line-height: 1; padding: 0; text-align: center; width: 25px; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>D</td><td style='line-height: 1; padding: 0; text-align: center; width: 25px; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>E</td><td style='line-height: 1; padding: 0; text-align: center; width: 25px; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>F</td><td style='line-height: 1; padding: 0; text-align: center; width: 25px; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>G</td><td style='line-height: 1; padding: 0; text-align: center; width: 25px; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>H</td></tr><tr><td style='line-height: 1; padding: 0; height: 25px; text-align: center; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>8</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♜</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♞</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♝</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♛</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♚</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♝</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♞</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♜</td></tr><tr><td style='line-height: 1; padding: 0; height: 25px; text-align: center; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>7</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♟</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♟</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♟</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♟</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♟</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♟</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♟</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♟</td></tr><tr><td style='line-height: 1; padding: 0; height: 25px; text-align: center; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>6</td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td></tr><tr><td style='line-height: 1; padding: 0; height: 25px; text-align: center; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>5</td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td></tr><tr><td style='line-height: 1; padding: 0; height: 25px; text-align: center; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>4</td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td></tr><tr><td style='line-height: 1; padding: 0; height: 25px; text-align: center; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>3</td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: #aaaaaa;'></td><td style='line-height: 1; padding: 0; border: 0; padding: 0; background-color: white;'></td></tr><tr><td style='line-height: 1; padding: 0; height: 25px; text-align: center; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>2</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♙</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♙</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♙</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♙</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♙</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♙</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♙</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♙</td></tr><tr><td style='line-height: 1; padding: 0; height: 25px; text-align: center; border: 0; padding: 0; background-color: black; color:white; font-size: 10px;'>1</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♖</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♘</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♗</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♕</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♔</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♗</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: #aaaaaa;'>♘</td><td style='line-height: 1; padding: 0; text-align: center; color: black; font-size: 20px; border: 0; background-color: white;'>♖</td></tr></table>
|
reference
|
def covered_pawns(pawns):
pawns = set(pawns)
return len({p for p in pawns for x, y in [map(ord, p)] if {chr(x - 1) + chr(y - 1), chr(x + 1) + chr(y - 1)} & pawns})
|
Covered pawns
|
597cfe0a38015079a0000006
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/597cfe0a38015079a0000006
|
6 kyu
|
### Introduction:
There are two ice-cream sellers, Emily and Danny. They sell one flavour, vanilla, and their prices are the same. No advertising, no difference between their products.
Emily and Danny can put their stall on any point in the town square, which is a five by five grid, with x and y coordinates. And is laid out like this:
<br>
```
(-2, 2) (-1, 2) (0, 2) (1, 2) (2, 2)
(-2, 1) (-1, 1) (0, 1) (1, 1) (2, 1)
(-2, 0) (-1, 0) (0, 0) (1, 0) (2, 0)
(-2,-1) (-1,-1) (0,-1) (1,-1) (2,-1)
(-2,-2) (-1,-2) (0,-2) (1,-2) (2,-2)
```
Their customers only care about one thing: walking the shortest distance to the stall. If the two shops are equal distance from their starting point, half will go to one, half go to the other.
<br><br>
People will come from any point on the edge and in equal amounts from each point ( to save time I've put the coordinates are at the *bottom of the page*). They can **only** move horizontally and vertically, not diagonally. E.g. going from (1,1) to (0,0) takes two steps, not one. <br>
### Task:
Danny gets to pick his coordinates first, Emily picks second. <br>
Write a function that takes Danny’s coordinates and returns the coordinates where Emily will get the most customers.
### Format:
Danny's choice will be given as coordinates [x, y] in an array e.g. ``` [2, 2] ```. <br>
Answers for Emily should be given in a nested array ``` [[-2, 1]]```.
If there is more than one answer you should list all possible pitches in a nested array e.g.``` [[2, 2],[2, 1]]```. <br> <br>
The pitches should be in order from lowest x coordinate to highest, any with the same x coordinates should be from lowest y coordinate to highest:
<br> e.g. ```[[1,1],[2,1],[2,2]]``` <br> not: ```[[2,1],[2,2],[1,1]]```
<br><br>
If Danny picks coordinates off the grid e.g. ``` [3,1] ``` you should return the centre coordinate to spread the walking distance equally ```[[0,0]]```. <br>
Enjoy!
<br>
```javascript
allEntranceCoordinates = [[2,2,],[1,2],[0,2],[-1,2],[-2,2],[-2,1],
[-2,0],[-2,-1],[-2,-2],[-1,-2],[0,-2],[1,-2],[2,-2],[2,-1],[2,0],
[2,1]];
```
|
games
|
def most_customers(dannys_pitch):
x, y = dannys_pitch
def sign(n): return int(n / abs(n)) if n != 0 else 0
if abs(x) > 2 or abs(y) > 2:
return [[0, 0]]
if x == 0 and y == 0:
return [[- 1, - 1], [- 1, 0], [- 1, 1], [0, - 1], [0, 1], [1, - 1], [1, 0], [1, 1]]
if abs(x) == abs(y):
return sorted([[x - sign(x), y], [x, y - sign(y)], [x - sign(x), y - sign(y)]])
if abs(x) > abs(y):
return [[x - sign(x), y]]
if abs(x) < abs(y):
return [[x, y - sign(y)]]
pass
# z.
|
The Ice Cream Vendors Dilema
|
597c82c5213e128eed000072
|
[
"Puzzles"
] |
https://www.codewars.com/kata/597c82c5213e128eed000072
|
6 kyu
|
<img src="https://i.imgur.com/ta6gv1i.png?1" title="source: imgur.com" />
# Story
You and a group of friends are earning some extra money in the school holidays by re-painting the numbers on people's letterboxes for a small fee.
Since there are 10 of you in the group each person just concentrates on painting one digit! For example, somebody will paint only the ```1```'s, somebody else will paint only the ```2```'s and so on...
But at the end of the day you realise not everybody did the same amount of work.
To avoid any fights you need to distribute the money fairly. That's where this Kata comes in.
# Kata Task
Given the ```start``` and ```end``` letterbox numbers, write a method to return the frequency of all 10 digits painted.
# Example
For ```start``` = 125, and ```end``` = 132
The letterboxes are
* 125 = ```1```, ```2```, ```5```
* 126 = ```1```, ```2```, ```6```
* 127 = ```1```, ```2```, ```7```
* 128 = ```1```, ```2```, ```8```
* 129 = ```1```, ```2```, ```9```
* 130 = ```1```, ```3```, ```0```
* 131 = ```1```, ```3```, ```1```
* 132 = ```1```, ```3```, ```2```
The digit frequencies are:
* `0` is painted <span style='color:red;'>1</span> time
* `1` is painted <span style='color:red;'>9</span> times
* `2` is painted <span style='color:red;'>6</span> times
* etc...
and so the method would return ```[1,9,6,3,0,1,1,1,1,1]```
# Notes
* 0 < ```start``` <= ```end```
* In C, the returned value will be free'd.
|
reference
|
def paint_letterboxes(start, finish):
xs = [0] * 10
for n in range(start, finish + 1):
for i in str(n):
xs[int(i)] += 1
return xs
|
Letterbox Paint-Squad
|
597d75744f4190857a00008d
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/597d75744f4190857a00008d
|
7 kyu
|
Conways game of life (https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life) is usually implemented without considering neigbouring cells that would be outside of the arrays range, but another way to do it is by considering the left and right edges of the array to be stitched together, and the top and bottom edges also, yielding a toroidal array and thus all cells get 8 neighbours.
Implement the function get_generation(cells, n) which takes a 2d-array cells an returns generation 'n' of game of life with the initial 'cells' and which considers the array as a toroidal array.
you can use the function `print2dArr(list)` to print out your array in a more readable format.
### Example:
The following pattern would be considered Still life (a pattern which does not change after a generation) on a toroidal array because each live element have exactly 3 neighbours at the toroids stiched edges.
```
[ 1, 0, 0, 1]
[ 0, 0, 0, 0]
[ 0, 0, 0, 0]
[ 1, 0, 0, 1]
```
|
games
|
# sumArround = 0 1 2 3 4 5 6 7 8
SURVIVAL_DICT = {0: [0, 0, 0, 1, 0, 0, 0, 0, 0],
1: [0, 0, 1, 1, 0, 0, 0, 0, 0]}
def get_generation(cells, generation):
maxI, maxJ = len(cells), len(cells[0])
def sumArround(i, j):
return sum(cells[(i + a) % maxI][(j + b) % maxJ] for a in range(- 1, 2) for b in range(- 1, 2)) - cells[i][j]
return cells if generation == 0 else get_generation([[SURVIVAL_DICT[cells[i][j]][sumArround(i, j)] for j in range(maxJ)] for i in range(maxI)], generation - 1)
|
Conways game of life on a toroidal array
|
57b988048f5813799600004f
|
[
"Puzzles",
"Cellular Automata"
] |
https://www.codewars.com/kata/57b988048f5813799600004f
|
5 kyu
|
You have to extract a portion of the file name as follows:
* Assume it will start with date represented as long number
* Followed by an underscore
* You'll have then a filename with an extension
* it will always have an extra extension at the end
Inputs:
---
```
1231231223123131_FILE_NAME.EXTENSION.OTHEREXTENSION
1_This_is_an_otherExample.mpg.OTHEREXTENSIONadasdassdassds34
1231231223123131_myFile.tar.gz2
```
Outputs
---
```
FILE_NAME.EXTENSION
This_is_an_otherExample.mpg
myFile.tar
```
Acceptable characters for random tests:
`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-0123456789`
The recommended way to solve it is using RegEx and specifically groups.
|
reference
|
class FileNameExtractor:
@ staticmethod
def extract_file_name(fname):
return fname . split('_', 1)[1]. rsplit('.', 1)[0]
|
extract portion of file name
|
597770e98b4b340e5b000071
|
[
"Regular Expressions",
"Fundamentals"
] |
https://www.codewars.com/kata/597770e98b4b340e5b000071
|
6 kyu
|
Given two words and a letter, return a single word that's a combination of both words, merged at the point where the given letter first appears in each word. The returned word should have the beginning of the first word and the ending of the second, with the dividing letter in the middle. You can assume both words will contain the dividing letter.
## Examples
```python
("hello", "world", "l") ==> "held"
("coding", "anywhere", "n") ==> "codinywhere"
("jason", "samson", "s") ==> "jasamson"
("wonderful", "people", "e") ==> "wondeople"
```
|
reference
|
def StringMerge(string1, string2, letter):
return string1[: string1 . index(letter)] + string2[string2 . index(letter):]
|
String Merge!
|
597bb84522bc93b71e00007e
|
[
"Strings",
"Fundamentals"
] |
https://www.codewars.com/kata/597bb84522bc93b71e00007e
|
7 kyu
|
# Story
Due to lack of maintenance the minute-hand has fallen off Town Hall clock face.
And because the local council has lost most of our tax money to an elaborate email scam there are no funds to fix the clock properly.
Instead, they are asking for volunteer programmers to write some code that tell the time by only looking at the remaining hour-hand!
What a bunch of cheapskates!
Can you do it?
# Kata
Given the ```angle``` (in degrees) of the hour-hand, return the time in 12 hour HH:MM format. Round _down_ to the nearest minute.
# Examples
* ```12:00``` = 0 degrees
* ```03:00``` = 90 degrees
* ```06:00``` = 180 degrees
* ```09:00``` = 270 degrees
* ```12:00``` = 360 degrees
# Notes
* 0 <= ```angle``` <= 360
* Do not make any AM or PM assumptions for the HH:MM result. They are indistinguishable for this Kata.
* 3 o'clock is ```03:00```, not ```15:00```
* 7 minutes past midnight is ```12:07```
* 7 minutes past noon is also ```12:07```
|
reference
|
def what_time_is_it(angle):
hr = int(angle / / 30)
mn = int((angle % 30) * 2)
if hr == 0:
hr = 12
return '{:02d}:{:02d}' . format(hr, mn)
|
Clocky Mc Clock-Face
|
59752e1f064d1261cb0000ec
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/59752e1f064d1261cb0000ec
|
6 kyu
|
# Task
Imagine that you are standing near a lake and watching frog John trying to get to the other bank. You can see some stones in front of him, and you know that John can make short jumps and long jumps. But that's not it. You also know that John is a magic frog: he is afraid of water, so he can cross the lake only by stones. Luckily, he can understand your words. Can you help him to get to the other side of lake?
You are given an array with coordinates of the stones ahead of John. Initially John is standing on a stone with coordinate `0`. If he stands on a stone with coordinate `x`, he can jump to the stones with coordinates `x + 1` (make a short jump), or `x + 2` (make a long jump).
Find the shortest path to the other side (to the last stone) and return the sequence of `'1's` and `'2's`, where `'1'` is a short jump and `'2'` is a long one. If there are several answers, return lexicographically smallest.
String A is lexicographically smaller than string B either if A is a prefix of B (and A ≠ B), or if there exists such index i (0 ≤ i < min(x.length, y.length)), that Ai < Bi, and for any j (0 ≤ j < i) Aj = Bj. The lexicographic comparison of strings is implemented by operator < in modern programming languages.
# Input/Output
- `[input]` integer array `stones`
A sorted array of stones' coordinates. It is guaranteed that `stones[0] = 0`.
- `[output]` a string
A sequence of `'1's` and `'2's` describing the shortest path to the other bank. It's guaranteed that the answer exists.
# Example:
For `stones = [0,1,2,3,5,6]`, the output should be `"1221"`.
Here are all possible paths:
`"11121"`, not the shortest one;
`"2121"`, one of the shortest ones, but not the lexicographically smallest;
`"1221"`, the shortest and the lexicographically smallest.
|
algorithms
|
def frogs_jumping(stones):
path = []
i = len(stones) - 1
while i > 0:
if i > 1 and stones[i] - stones[i - 2] == 2:
dist = jmp = 2
else:
dist, jmp = stones[i] - stones[i - 1], 1
i -= jmp
path . append(dist)
return "" . join(map(str, path[:: - 1]))
|
Simple Fun #211: Frog's Jumping
|
58fff63f4c5d026cc200000f
|
[
"Algorithms"
] |
https://www.codewars.com/kata/58fff63f4c5d026cc200000f
|
5 kyu
|
Given an array with 3 subarrays, each containing hexadecimal color codes loosely defining red, green and blue colors based on their predominant byte value, return a string description of which of the three colors each array contains.
Input is an array which contains 3 subarrays. These subarrays contain strings representing colors in RGB format, each string will contain one predominant color channel that is more saturated than the other two. Among all the strings in an subarray only 2 color channels will come up as predominant - the one that appears more often is "major" and the one that appears less often is "minor". Your task is to determine the major and minor colors inside each subarray and return them in the following format: `{Major1}+{Minor1},{Major2}+{Minor2},{Major3}+{Minor3}`.
Example:
```
input = [
["FFA07A", "FA8072", "8DC4DE"],
["7FFF00", "ADFF2F", "FF0000", "00FF7F", "00FF7F"],
["ADD8E6", "6B8E23", "9ACD32", "32CD32", "00FF00"]
]
result = "Red+Blue,Green+Red,Green+Blue"
```
Explanation:
* first subarray's predominant colors: `Red`, `Red`, `Blue` (`Red` is major, `Blue` is minor)
* second subarray's predominant colors: `Green`, `Green`, `Red`, `Green`, `Green` (`Green` is major, `Red` is minor)
* third subarray's predominant colors: `Blue`, `Green`, `Green`, `Green`, `Green` (`Green` is major, `Blue` is minor)
|
reference
|
from collections import Counter
COLORS = 'Red', 'Green', 'Blue'
IDX = 0, 1, 2
def get_major_minor(colors):
c = Counter(max(IDX, key=lambda i: c[i * 2: i * 2 + 2]) for c in colors)
return '+' . join(COLORS[i] for i, _ in c . most_common(2))
def get_colors(col_arr):
return ',' . join(map(get_major_minor, col_arr))
|
Arrays and hex color codes
|
597a660f59873cc353000061
|
[
"Fundamentals",
"Arrays"
] |
https://www.codewars.com/kata/597a660f59873cc353000061
|
6 kyu
|
On fictional islands of Matunga archipelage several different tribes use fictional currency - tung. One tung is a very small amount, so all payments are made with coins of different values. For example, one tribe use coins of 7 and 9 tungs, another - 6, 10 and 11 tungs. Every tribe has at least 2 different coins.
Also every tribe has a shop with remarkable feature: if you find an item N tungs worth, you always can find an item priced N+1 tungs in the same shop.
Your goal is to write the function min_price(coins) which finds out the minimum price of item which can be in sale in Matunga tribe shop, knowing the values of coins used there.
Function should return -1 if result is not accessible (i.e. coins of these values can't cover natural row from N to infinity without gaps).
For example, some tribe has coins of 3 and 5 tungs. They can't sell items of 4 or 7 tungs, because 4 and 7 can't be represented as a sum of 3's and 5's. But starting from 8 tungs you can do it with every sum: 8 is 5+3, 9 is 3+3+3, 10 is 5+5, 11 is 5+3+3 and so on. So the answer for this set of coins is 8.
|
algorithms
|
from functools import reduce
import math
# The Money Changing Problem Revisited: Computing the Frobenius Number in Time O(k a1)*
# https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.389.4933&rep=rep1&type=pdf
def min_price(coins):
# edge case
if 1 in coins:
return 1
if reduce(math . gcd, coins) != 1:
return - 1
coins = sorted(set(coins))
a1 = coins[0]
k = len(coins)
n_arr = [float("inf") for _ in range(a1)]
n_arr[0] = 0
for i in range(1, k):
d = math . gcd(a1, coins[i])
for r in range(d):
n = min(n_arr[q] for q in range(a1) if q % d == r)
if n < float("inf"):
for j in range(a1 / / d + 1):
n += coins[i]
p = n % a1
n = min(n, n_arr[p])
n_arr[p] = n
best = max(x for x in n_arr if x < float("inf"))
return best - a1 + 1
|
Matunga coins
|
59799cb9429e83b7e500010c
|
[
"Algorithms",
"Mathematics",
"Combinatorics",
"Performance"
] |
https://www.codewars.com/kata/59799cb9429e83b7e500010c
|
4 kyu
|
Implement a function to calculate the distance between two points in n-dimensional space. The two points will be passed to your function as arrays of the same length (tuples in Python).
Round your answers to two decimal places.
|
algorithms
|
def euclidean_distance(point1, point2):
return round(sum((b - a) * * 2 for a, b in zip(point1, point2)) * * 0.5, 2)
|
Euclidean distance in n dimensions
|
595877be60d17855980013d3
|
[
"Mathematics",
"Algorithms",
"Fundamentals"
] |
https://www.codewars.com/kata/595877be60d17855980013d3
|
7 kyu
|
You just got done with your set at the gym, and you are wondering how much weight you could lift if you did a single repetition. Thankfully, a few scholars have devised formulas for this purpose (from [Wikipedia](https://en.wikipedia.org/wiki/One-repetition_maximum)) :
### Epley
```math
\Large\text{1 RM} = w(1 + \frac{r}{30})
```
### McGlothin
```math
\Large\text{1 RM} = \frac{100w}{101.3 - 2.67123r}
```
### Lombardi
```math
\Large\text{1 RM} = wr^{0.10}
```
Your function will receive a weight `w` and a number of repetitions `r` and must return your projected one repetition maximum. Since you are not sure which formula to use and you are feeling confident, your function will return the largest value from the three formulas shown above, rounded to the nearest integer. However, if the number of repetitions passed in is `1` (i.e., it is already a one rep max), your function must return `w`. Also, if the number of repetitions passed in is `0` (i.e., no repetitions were completed), your function must return `0`.
```if:rust
**Note:** due to a loss of precision, it is advisable to use `f64` and not `f32`.
```
|
algorithms
|
def calculate_1RM(w, r):
if r == 0:
return 0
if r == 1:
return w
return round(max([
w * (1 + r / 30), # Epley
100 * w / (101.3 - 2.67123 * r), # McGlothin
w * r * * 0.10 # Lombardi
]))
|
1RM Calculator
|
595bbea8a930ac0b91000130
|
[
"Mathematics"
] |
https://www.codewars.com/kata/595bbea8a930ac0b91000130
|
6 kyu
|
For this kata you will be using some meta-programming magic to create a new `Thing` object. This object will allow you to define things in a descriptive **sentence like format**.
This challenge attempts to build on itself in an increasingly complex manner.
## Examples of what can be done with "Thing":
```ruby
jane = Thing.new('Jane')
jane.name # => 'Jane'
# can define boolean methods on an instance
jane.is_a.person
jane.is_a.woman
jane.is_not_a.man
jane.person? # => true
jane.man? # => false
# can define properties on a per instance level
jane.is_the.parent_of.joe
jane.parent_of # => 'joe'
# can define number of child things
# when more than 1, an array is created
jane.has(2).legs
jane.legs.size # => 2
jane.legs.first.is_a?(Thing) # => true
# can define single items
jane.has(1).head
jane.head.is_a?(Thing) # => true
# can define number of things in a chainable and natural format
jane.has(2).arms.each { having(1).hand.having(5).fingers }
jane.arms.first.hand.fingers.size # => 5
# can define properties on nested items
jane.has(1).head.having(2).eyes.each { being_the.color.blue.and_the.shape.round }
# can define methods
jane.can.speak('spoke') do |phrase|
"#{name} says: #{phrase}"
end
jane.speak("hello") # => "Jane says: hello"
# if past tense was provided then method calls are tracked
jane.spoke # => ["Jane says: hello"]
```
```javascript
const jane = new Thing('Jane')
jane.name // => 'Jane'
// can define boolean methods on an instance
jane.is_a.person
jane.is_a.woman
jane.is_not_a.man
jane.is_a_person // => true
jane.is_a_man // => false
// can define properties on a per instance level
jane.is_the.parent_of.joe
jane.parent_of // => 'joe'
// can define number of child things
// when more than 1, an array is created
jane.has(2).legs
jane.legs.length // => 2
jane.legs[0] instanceof Thing // => true
// can define single items
jane.has(1).head
jane.head instanceof Thing // => true
// can define number of things in a chainable and natural format
jane.has(2).arms.each(arm => having(1).hand.having(5).fingers )
jane.arms[0].hand.fingers.length // => 5
// can define properties on nested items
jane.has(1).head.having(2).eyes.each( eye => being_the.color.blue.having(1).pupil.being_the.color.black )
// can define methods
jane.can.speak('spoke', phrase =>
`${name} says: ${phrase}`)
jane.speak("hello") // => "Jane says: hello"
// if past tense was provided then method calls are tracked
jane.spoke // => ["Jane says: hello"]
```
```coffeescript
jane = new Thing 'Jane'
jane.name # => 'Jane'
# can define boolean methods on an instance
jane.is_a.person
jane.is_a.woman
jane.is_not_a.man
jane.is_a_person # => true
jane.is_a_man # => false
# can define properties on a per instance level
jane.is_the.parent_of.joe
jane.parent_of # => 'joe'
# can define number of child things
# when more than 1, an array is created
jane.has(2).legs
jane.legs.length # => 2
jane.legs[0] instanceof Thing # => true
# can define single items
jane.has(1).head
jane.head instanceof Thing # => true
# can define number of things in a chainable and natural format
jane.has(2).arms.each (arm)-> having(1).hand.having(5).fingers
jane.arms[0].hand.fingers.length # => 5
# can define properties on nested items
jane.has(1).head.having(2).eyes.each (eye) ->
being_the.color.blue.with(1).pupil.being_the.color.black
# can define methods
jane.can.speak 'spoke', (phrase)-> "#{name} says: #{phrase}"
jane.speak 'hello' # => 'Jane says: hello'
# if past tense was provided then method calls are tracked
jane.spoke # => ['Jane says: hello']
```
```python
jane = Thing('Jane')
jane.name # => 'Jane'
# can define boolean methods on an instance
jane.is_a.person
jane.is_a.woman.is_not_a.man
jane.is_a_person # => True
jane.is_a_man # => False
# can define properties on a per instance level
jane.is_the.parent_of.joe
jane.parent_of # => 'joe'
# can define number of child things
# when more than 1, the resulting Thing must be a sequence and must be an iterable
legs = jane.has(2).legs
len(legs) # => 2
isinstance(legs, Thing) # => True
isinstance(jane.legs[0], Thing) # => True
# can define single items
jane.has(1).head.is_the.on_top_of.body
isinstance(jane.head, Thing) # => True
jane.head.on_top_of # => "body"
# can define number of things in a chainable and natural format
jane.has(2).hands.each(lambda h:h.having(5).fingers)
len(jane.arms[0].hand.fingers) # => 5
# can define properties on nested items
jane.has(2).eyes.each(lambda thing: thing.being_the.color.green.having(1).pupil.being_the.color.black)
# can define methods: thing.can.verb(method, archive=None)
def method(self_:Thing, phrase:str):
return f"{self_.name} says: {phrase}"
jane.can.speak(method, "spoke")
jane.speak("hello") # => "Jane says: hello"
jane.speak("bye") # => "Jane says: bye"
# if archive was provided then method results are tracked
jane.spoke # => ["Jane says: hello", "Jane says: bye"]
```
> Note: Most of the test cases have already been provided for you so that you can see how the Thing object is supposed to work.
|
algorithms
|
from __future__ import annotations
from collections . abc import Sequence
import re
class Being:
def __init__(self, api):
self . api = api
def __getattr__(self, item):
return self . api(item)
class Relation:
def __init__(self, name: str, api):
self . name = name
self . api = api
def __getattr__(self, other):
return self . api(self . name, other)
class Related:
def __init__(self, api):
self . api = api
def __getattr__(self, name):
return Relation(name, self . api)
class Having:
def __init__(self, api):
self . n = 1
self . api = api
def __getattr__(self, name):
obj = Thing(name, length=self . n, being=f"is_ { name } ")
self . api(obj)
return obj
class Archive:
def __init__(self, name):
self . name = name
self . _history = []
def __call__(self, msg):
self . _history . append(msg)
class Ability:
def __init__(self, name, master, api):
self . name = name
self . master = master
self . api = api
self . method = None
self . archive = None
def _late_init(self, method, archive=None):
self . method = method
if archive:
self . archive = Archive(archive)
self . api(archive, self . archive)
return self . master
def __call__(self, * args, * * kwargs):
msg = self . method(self . master, * args, * * kwargs)
if self . archive:
self . archive(msg)
return msg
class Can:
def __init__(self, master, api_ability, api_archive):
self . master = master
self . api_ability = api_ability
self . api_archive = api_archive
def __getattr__(self, name):
ability = Ability(name, self . master, self . api_archive)
self . api_ability(name, ability)
return ability . _late_init
class Thing (Sequence):
def __init__(self, name: str, length: int = None, being: str = None):
self . name = name
self . _len = 1
self . _instances = [self]
if length and length > 1:
self . _len = length
self . _instances = []
name_single = name[: len(name) - 1]
for _ in range(length):
self . _instances . append(Thing(name_single))
if being:
being = being[: len(being) - 1]
self . _being = set()
self . _related = {}
self . _having = {}
self . _ability = {}
self . _archive = {}
self . is_a = Being(self . _add_being)
self . is_not_a = Being(self . _add_not_being)
self . is_the = Related(self . _add_relation)
self . being_the = self . is_the
self . and_the = self . is_the
self . _has = Having(self . _add_having)
self . can = Can(self, self . _add_ability, self . _add_archive)
if being:
for obj in self . _instances:
obj . _being . add(being)
def has(self, n: int):
self . _has . n = n
return self . _has
having = has
def each(self, func):
for obj in self . _instances:
func(obj)
return self
def _add_being(self, name: str):
self . _being . add(f"is_a_ { name } ")
return self
def _add_not_being(self, name: str):
self . _being . add(f"is_not_a_ { name } ")
return self
def _add_relation(self, name: str, other):
self . _related[name] = other
return self
def _add_having(self, obj):
self . _having[obj . name] = obj
def _add_ability(self, name, ability):
self . _ability[name] = ability
def _add_archive(self, name, archive):
self . _archive[name] = archive
def __getattr__(self, attr):
if attr . startswith('is_'):
if attr in self . _being:
return True
return False
if attr in self . _related:
return self . _related[attr]
if attr in self . _having:
return self . _having[attr]
if attr in self . _ability:
return self . _ability[attr]
if attr in self . _archive:
return self . _archive[attr]. _history
def __getitem__(self, idx: int):
assert idx < self . _len
return self . _instances[idx]
def __iter__(self):
return iter(self . _instances)
def __len__(self):
return self . _len
|
The builder of things
|
5571d9fc11526780a000011a
|
[
"Metaprogramming",
"Domain Specific Languages",
"Algorithms",
"Language Features"
] |
https://www.codewars.com/kata/5571d9fc11526780a000011a
|
3 kyu
|
Given a string containing a list of integers separated by commas, write the function string_to_int_list(s) that takes said string and returns a new list containing all integers present in the string, preserving the order.
For example, give the string "-1,2,3,4,5", the function string_to_int_list() should return [-1,2,3,4,5]
Please note that there can be one or more consecutive commas whithout numbers, like so: "-1,-2,,,,,,3,4,5,,6"
|
algorithms
|
def string_to_int_list(s):
return [int(n) for n in s . split(",") if n]
|
String to list of integers.
|
5727868888095bdf5c001d3d
|
[
"Strings",
"Algorithms"
] |
https://www.codewars.com/kata/5727868888095bdf5c001d3d
|
7 kyu
|
An NBA game runs 48 minutes (Four 12 minute quarters). Players do not typically play the full game, subbing in and out as necessary. Your job is to extrapolate a player's points per game if they played the full 48 minutes.
Write a function that takes two arguments, ppg (points per game) and mpg (minutes per game) and returns a straight extrapolation of ppg per 48 minutes rounded to the nearest tenth. Return 0 if 0.
Examples:
```javascript
pointsPer48(12, 20) // 28.8
pointsPer48(10, 10) // 48
pointsPer48(5, 17) // 14.1
pointsPer48(0, 0) // 0
```
```python
nba_extrap(12, 20) # 28.8
nba_extrap(10, 10) # 48
nba_extrap(5, 17) # 14.1
nba_extrap(0, 0) # 0
```
```csharp
Kata.NbaExtrap(12, 20) => 28.8
Kata.NbaExtrap(10, 10) => 48
Kata.NbaExtrap(5, 17) => 14.1
Kata.NbaExtrap(0, 0) => 0
```
```ruby
nba_extrap(12, 20) # 28.8
nba_extrap(10, 10) # 48
nba_extrap(5, 17) # 14.1
nba_extrap(0, 0) # 0
```
Notes:<br>
All inputs will be either be an integer or float.<br>
Follow your dreams!
|
reference
|
def nba_extrap(ppg, mpg):
return round(48.0 / mpg * ppg, 1) if mpg > 0 else 0
|
NBA full 48 minutes average
|
587c2d08bb65b5e8040004fd
|
[
"Fundamentals",
"Mathematics"
] |
https://www.codewars.com/kata/587c2d08bb65b5e8040004fd
|
8 kyu
|
In this challenge, we'll be learning about the pseudocode `Display` command, and how to translate it to Python. The pseudocode standard used in this challenge is based on the book [Starting Out with Programming Logic and Design, 3rd Edition](http://www.pearsonhighered.com/product?ISBN=0132805456) by Tony Gaddis. If you want to test code that uses x_print (described below) in Python 3 outside of the CodeWars site, add this line to the top of the code:
```
x_print = print
```
# Python 2.7 and Codewars
First, it's important to note that the Codewars site uses Python 2.7, which is an older version. One of the important differences between Python 2.7 and Python 3.4 is that the `print` statement is different.
In Python 2.7, `print` is called like this:
```
# Display "Hello World!"
print "Hello World!"
```
The `print` statement takes a single String argument. If you want to `print` multiple values, you need to either use multiple `print` statements (one per each line of output), or you need to create a single String from the values you want to `print` and `print` that single String (you can use the String concatenation operator `+` to do that). For example:
```
# Declare String student_name = "Fred"
# Declare String course_name = "Software Design"
#
# Display "Hello", student_name, ", welcome to", course_name, "!"
student_name = "Fred"
course_name = "Software Design"
print "Hello " + student_name + ", wecome to " + course_name + "!"
```
The output from running this program will be:
```
Hello Fred, wecome to Software Design!
```
Note the use of spaces inside the strings `"Hello "` and `", welcome to "` so that the resulting line is formatted correctly.
Converting the output to a single String becomes a little more complicated when you want to print numbers, because the following code produces an error:
```
# Declare String assignment = "Exam 1"
# Declare Real score = 85.5
#
# Display "Your grade on", assignment, "was", score
assignment = "Exam 1"
score = 85.5
print "Your grade on " + assignment + " was " + score
```
The text of the error is:
```
TypeError: cannot concatenate 'str' and 'float' objects
```
The reason for the error is that only Strings can be concatenated with other Strings, and Reals (floats in Python) are not Strings. The value of `score` is the Real number 85.5, not the String "85.5". To fix that, we need to convert the Real to a String ourselves, using the `str` function in Python:
```
# Declare String assignment = "Exam 1"
# Declare Real score = 85.5
#
# Display "Your grade on", assignment, "was", score
assignment = "Exam 1"
score = 85.5
print "Your grade on " + assignment + " was " + str(score)
```
Note that we don't need to put the call to `str` in our pseudocode, that's just a detail of our Python implementation.
This version of the program should produce the following output in Python 2.7:
```
Your grade on Exam 1 was 85.5
```
# Python 3
In Python 3, `print` is called like this:
```
# Display "Hello World!"
print("Hello World!")
```
The `print` statement takes multiple arguments within the `(...)`. If you want to `print` multiple values, you can include them all in a single print statement, separated by commas like `print(a, b, c, ..., n)`. For example:
```
# Declare String student_name = "Fred"
# Declare String course_name = "Software Design"
#
# Display "Hello", student_name, ", welcome to", course_name, "!"
student_name = "Fred"
course_name = "Software Design"
print("Hello", student_name, ", wecome to" + course_name + "!")
```
The output from running this program will be:
```
Hello Fred , wecome to Software Design !
```
Note that Python prints each argument in order, separated by a single space (" "). You can control what text the `print` command uses to separate values by supplying a `sep` argument, like this:
```
# Declare String student_name = "Fred"
# Declare String course_name = "Software Design"
#
# Display "Hello", student_name, ", welcome to", course_name, "!"
student_name = "Fred"
course_name = "Software Design"
print("Hello ", student_name, ", wecome to " + course_name + "!", sep="")
```
The output from running this program will be:
```
Hello Fred, wecome to Software Design!
```
With Python 3 print, each argument is automatically converted to a String, so there's no need to use the `str` function. This code should work properly:
```
# Declare String assignment = "Exam 1"
# Declare Real score = 85.5
#
# Display "Your grade on", assignment, "was", score
assignment = "Exam 1"
score = 85.5
print("Your grade on", assignment, "was", score)
```
This version of the program should produce the following output in Python 3:
```
Your grade on Exam 1 was 85.5
```
When you `print` text, each `print` statement will add one line of output to the display by default. It does this by automatically adding a linefeed character to the end of the output (in Python, the linefeed character is represented as "\n"). You can change this behavior by specifying a different value for the `end` argument like this:
```
print("Hello", end=" ")
print("World!")
```
Since the end-of-line string has been changed to a single space in the first print statement, the output displays as:
```
Hello World!
```
# x_print
Since `print` on Codewars is the Python 2.7 version of `print`, but we want to get practice with the Python 3 version, I have included a command called `x_print`. It works the same way as the print command works in Python 3. Use it like this:
```
# Declare String assignment = "Exam 1"
# Declare Real score = 85.5
#
# Display "Your grade on", assignment, "was", score
assignment = "Exam 1"
score = 85.5
x_print("Your grade on", assignment, "was", score)
```
# Challenge
To complete this challenge, supply both the Python 2.7 and Python 3 translations (using `x_print` for the Python 3 version) for the pseudocode provided in the comments.
|
reference
|
print "Hello World!"
course = "CIS 122"
name = "Intro to Software Design"
print "Welcome to " + course + ": " + name
a = 1.1
b = 3
c = a + b
print "The sum of %s and %s is %s" % (a, b, c)
x_print("Hello World!")
language = "Python"
adjective = "Fun"
x_print("Learning", language, "is", adjective)
pizzas = 10
slices_per_pizza = 8
total_slices = pizzas * slices_per_pizza
x_print("There are", total_slices, "slices in", pizzas, "pizzas.")
x_print(total_slices, ": It must be dinner time!", sep="")
|
CIS 122 #1 Simple Printing
|
55cd156ead636caae3000099
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/55cd156ead636caae3000099
|
8 kyu
|
Create a function that takes a string and separates it into a sequence of letters.
The array will be formatted as so:
```javascript,python
[['J','L','L','M']
,['u','i','i','a']
,['s','v','f','n']
,['t','e','e','']]
```
The function should separate each word into individual letters, with the first word in the sentence having its letters in the 0th index of each 2nd dimension array, and so on.
Shorter words will have an empty string in the place once the word has already been mapped out. (See the last element in the last part of the array.)
Examples:
```javascript
sepStr("Just Live Life Man")
// => [['J','L','L','M'],
// => ['u','i','i','a'],
// => ['s','v','f','n'],
// => ['t','e','e','']]);
sepStr("The Mitochondria is the powerhouse of the cell")
// => [ [ 'T', 'M', 'i', 't', 'p', 'o', 't', 'c' ],
// => [ 'h', 'i', 's', 'h', 'o', 'f', 'h', 'e' ],
// => [ 'e', 't', '', 'e', 'w', '', 'e', 'l' ],
// => [ '', 'o', '', '', 'e', '', '', 'l' ],
// => [ '', 'c', '', '', 'r', '', '', '' ],
// => [ '', 'h', '', '', 'h', '', '', '' ],
// => [ '', 'o', '', '', 'o', '', '', '' ],
// => [ '', 'n', '', '', 'u', '', '', '' ],
// => [ '', 'd', '', '', 's', '', '', '' ],
// => [ '', 'r', '', '', 'e', '', '', '' ],
// => [ '', 'i', '', '', '', '', '', '' ],
// => [ '', 'a', '', '', '', '', '', '' ]]
```
```python
sep_str("Just Live Life Man")
# => [['J','L','L','M'],
# => ['u','i','i','a'],
# => ['s','v','f','n'],
# => ['t','e','e','']]);
sep_str("The Mitochondria is the powerhouse of the cell")
# => [ [ 'T', 'M', 'i', 't', 'p', 'o', 't', 'c' ],
# => [ 'h', 'i', 's', 'h', 'o', 'f', 'h', 'e' ],
# => [ 'e', 't', '', 'e', 'w', '', 'e', 'l' ],
# => [ '', 'o', '', '', 'e', '', '', 'l' ],
# => [ '', 'c', '', '', 'r', '', '', '' ],
# => [ '', 'h', '', '', 'h', '', '', '' ],
# => [ '', 'o', '', '', 'o', '', '', '' ],
# => [ '', 'n', '', '', 'u', '', '', '' ],
# => [ '', 'd', '', '', 's', '', '', '' ],
# => [ '', 'r', '', '', 'e', '', '', '' ],
# => [ '', 'i', '', '', '', '', '', '' ],
# => [ '', 'a', '', '', '', '', '', '' ]]
```
|
reference
|
from itertools import zip_longest
def sep_str(st):
return [[* cs] for cs in zip_longest(* st . split(), fillvalue='')]
|
Separating Strings
|
5977ef1f945d45158d00011f
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/5977ef1f945d45158d00011f
|
6 kyu
|
Create a function that takes an array of letters, and combines them into words in a sentence.
The array will be formatted as so:
```javascript
[
['J','L','L','M'],
['u','i','i','a'],
['s','v','f','n'],
['t','e','e','']
]
```
The function should combine all the 0th indexed letters to create the word 'just', all the 1st indexed letters to create the word 'live', etc.
Shorter words will have an empty string in the place once the word has already been mapped out (see the last element in the last element in the array).
```if:c
In C we use nul characters (`'\0'`) instead of empty strings.
```
Examples:
```javascript
[
['J','L','L','M'],
['u','i','i','a'],
['s','v','f','n'],
['t','e','e','']
] // => "Just Live Life Man"
[
[ 'T', 'M', 'i', 't', 'p', 'o', 't', 'c' ],
[ 'h', 'i', 's', 'h', 'o', 'f', 'h', 'e' ],
[ 'e', 't', '', 'e', 'w', '', 'e', 'l' ],
[ '', 'o', '', '', 'e', '', '', 'l' ],
[ '', 'c', '', '', 'r', '', '', '' ],
[ '', 'h', '', '', 'h', '', '', '' ],
[ '', 'o', '', '', 'o', '', '', '' ],
[ '', 'n', '', '', 'u', '', '', '' ],
[ '', 'd', '', '', 's', '', '', '' ],
[ '', 'r', '', '', 'e', '', '', '' ],
[ '', 'i', '', '', '', '', '', '' ],
[ '', 'a', '', '', '', '', '', '' ]
] // => "The Mitochondria is the powerhouse of the cell"
```
|
reference
|
def arr_adder(arr):
return ' ' . join(map('' . join, zip(* arr)))
|
Adding Arrays
|
59778cb1b061e877c50000cc
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/59778cb1b061e877c50000cc
|
7 kyu
|
Help a fruit packer sort out the bad apples.
There are 7 varieties of apples, all packaged as pairs and stacked in a fruit box. Some of the apples are spoiled. The fruit packer will have to make sure the spoiled apples are either removed from the fruit box or replaced. Below is the breakdown:
Apple varieties are represented with numbers, `1 to 7`
A fruit package is represented with a 2 element array `[4,3]`
A fruit package with one bad apple, or a bad package, is represented with `[2,0]` or `[0,2]`
A fruit package with two bad apples, or a rotten package, is represented with `[0,0]`
A fruit box is represented with:
```
[ [ 1, 3 ],
[ 7, 6 ],
[ 7, 2 ],
[ 1, 3 ],
[ 0, 2 ],
[ 4, 5 ],
[ 0, 3 ],
[ 7, 6 ] ]
```
Write a program to clear the fruit box off bad apples.
The INPUT will be a fruit box represented with a 2D array: `[[1,3],[7,6],[7,2],[1,3],[0,2],[4,5],[0,3],[7,6]]`
The OUTPUT should be the fruit box void of bad apples: `[[1,3],[7,6],[7,2],[1,3],[2,3],[4,5],[7,6]]`
Conditions to be met:
1.A bad package should have the bad apple replaced if there is another bad package with a good apple to spare. Else, the bad package should be discarded.
2.The order of the packages in the fruit box should be preserved. Repackaging happens from the top of the fruit box `index = 0` to the bottom `nth index`. Also note how fruits in a package are ordered when repacking. Example shown in INPUT/OUPUT above.
3.Rotten packages should be discarded.
4.There can be packages with the same variety of apples, e.g `[1,1]`, this is not a problem.
|
algorithms
|
def bad_apples(apples):
lst, notFull = [], []
for a, b in apples:
if (bool(a) ^ bool(b)) and notFull:
# One bad and partially full box already present: fill it (as second element)
lst[notFull . pop()]. append(a or b)
elif a and b:
lst . append([a, b]) # 2 good ones: keep as they are
elif a or b:
notFull . append(len(lst))
lst . append([a or b]) # 1 good but no partial box: archive
if notFull:
lst . pop(notFull . pop()) # If 1 not full box remains: remove it
return lst
|
Bad Apples
|
59766edb9bfe7cd5b000006e
|
[
"Arrays",
"Algorithms"
] |
https://www.codewars.com/kata/59766edb9bfe7cd5b000006e
|
6 kyu
|
There is an implementation of quicksort algorithm. Your task is to fix it. All inputs are correct.
See also: https://en.wikipedia.org/wiki/Quicksort
|
bug_fixes
|
quicksort = sorted
|
Bug Fix - Quick Sort
|
56bdaa2cbe8f29257c000085
|
[
"Sorting",
"Algorithms",
"Fundamentals",
"Debugging"
] |
https://www.codewars.com/kata/56bdaa2cbe8f29257c000085
|
6 kyu
|
In this kata you must determine the lowest floor in a building from which you cannot drop an egg without it breaking. You may assume that all eggs are the same; if one egg breaks when dropped from floor `n`, all eggs will. If an egg survives a drop from some floor, it will survive a drop from any floor below too.
You are given `num_eggs` eggs and are allowed to make a maximum of `num_drops` drops. If an egg does not break when dropped, it may be reused. You may assume that it is feasible to determine the floor with the given number of eggs and drops.
Example 1:
You are given 1 egg and 10 drops. You start by dropping the egg from the first floor (floor numbering starts at 1). If it breaks, the answer is 1. If it does not break, you drop it from the second floor. If it breaks, the answer is 2. Otherwise you continue in the same manner until you reach a floor where the egg breaks. You may assume that you will reach that floor before you have exhausted your drops (i.e., in this example, the egg will break when dropped from floor 10 or lower).
Example 2: You are given 2 eggs and 10 drops. The highest floor for which this problem has a solution is floor 55, so you may assume that the answer is floor 55 or a lower floor. You will have to determine how the number 55 is derived and generalize it for any number of eggs and drops.
To solve this problem, you need to write a function `solve` that takes an argument `emulator` and returns the lowest floor from which an egg will break if dropped. The `emulator` object has the following properties and method which you may invoke:
1. `emulator.eggs` returns the number of eggs you have left. You may use this property to detemine the number of eggs you are given initially.
2. `emulator.drops` returns the the number of drops you have left. You may use this property to detemine the number of drops you are given initially.
3. `emulator.drop(n)` returns `True` if an egg dropped from floor `n` breaks and `False` if it does not break. The number of times that you may invoke this method is limited to the number of drops you were given. If invoked after no drops are left, it will throw an exception. Same happens if you invoke this method after all your eggs are broken.
You are not allowed to access any other method or state attribute of the `emulator` object, even if you can. This is considered cheating and is a very dishonorable thing to do! Note that `emulator.__dict__` has been disabled.
Note: [This kata](http://www.codewars.com/kata/faberge-easter-eggs-crush-test) is similar although not the same.
|
games
|
# THanks to easter eggs kata ;*
def height(n, m):
if n >= m:
return (2 * * (min(n, m)) - 1)
f = 1
res = 0
for i in range(n):
f = f * (m - i) / / (i + 1)
res += f
return res
def solve(emulator):
m = emulator . drops
n = emulator . eggs
h = 0
tryh = 0
while n and m:
tryh = height(n - 1, m - 1) + 1
if emulator . drop(h + tryh):
n -= 1
else:
h += tryh
m -= 1
return (h + 1)
# continue here
|
Egg Drops
|
56d3f1743323a8399200063f
|
[
"Recursion",
"Dynamic Programming",
"Puzzles"
] |
https://www.codewars.com/kata/56d3f1743323a8399200063f
|
4 kyu
|
You are given an array. Complete the function that returns the number of ALL elements within an array, including any nested arrays.
## Examples
```python
[] --> 0
[1, 2, 3] --> 3
["x", "y", ["z"]] --> 4
[1, 2, [3, 4, [5]]] --> 7
```
The input will always be an array.
```if:php
In PHP you may *not* assume that the array passed in will be non-associative.
Please note that `count()`, `eval()` and `COUNT_RECURSIVE` are disallowed - you should be able to implement the logic for `deep_c()` yourself ;)
```
|
reference
|
def deep_count(a):
result = 0
for i in range(len(a)):
if type(a[i]) is list:
result += deep_count(a[i])
result += 1
return result
|
Array Deep Count
|
596f72bbe7cd7296d1000029
|
[
"Arrays",
"Recursion",
"Fundamentals"
] |
https://www.codewars.com/kata/596f72bbe7cd7296d1000029
|
6 kyu
|
Your work is to write a method that takes a value and an index, and returns the value with the bit at given index flipped.
The bits are numbered from the least significant bit (index 1).
Example:
```cobol
flipBit(15,4) = 7
* 15 in binary is 1111, after flipping 4th bit, it becomes 0111, i.e. 7
flipBit(15,5) = 31
* 15 in binary is 1111, 5th bit is 0, after flipping, it becomes 11111, i.e., 31
```
```csharp
FlipBit(15,4) == 7 // 15 in binary is 1111, after flipping 4th bit, it becomes 0111, i.e. 7
FlipBit(15,5) == 31 // 15 in binary is 1111, 5th bit is 0, after flipping, it becomes 11111, i.e., 31
```
```cpp
flip_bit(15,4) == 7 // 15 in binary is 1111, after flipping 4th bit, it becomes 0111, i.e. 7
flip_bit(15,5) == 31 // 15 in binary is 1111, 5th bit is 0, after flipping, it becomes 11111, i.e., 31
```
```python
flip_bit(15, 4) == 7 # 15 in binary is 1111, after flipping 4th bit, it becomes 0111, i.e. 7
flip_bit(15, 5) == 31 # 15 in binary is 1111, 5th bit is 0, after flipping, it becomes 11111, i.e., 31
```
Note : index number can be out of number's range : e.g number is 3 (it has 2 bits) and index number is 8(for C# this number is up to 31) -> result will be 131
See more examples in test classes
Good luck!
|
reference
|
def flip_bit(value, bit_index):
return value ^ (1 << (bit_index - 1))
|
Binary operations #1
|
560e80734267381a270000a2
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/560e80734267381a270000a2
|
7 kyu
|
Write a comparator for a list of phonetic words for the letters of the [greek alphabet](https://en.wikipedia.org/wiki/Greek_alphabet).
A comparator is:
> *a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument*
*(source: https://docs.python.org/2/library/functions.html#sorted)*
The greek alphabet is preloded for you as `greek_alphabet`:
```python
greek_alphabet = (
'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta',
'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu',
'nu', 'xi', 'omicron', 'pi', 'rho', 'sigma',
'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega')
```
## Examples
```python
greek_comparator('alpha', 'beta') < 0
greek_comparator('psi', 'psi') == 0
greek_comparator('upsilon', 'rho') > 0
```
|
reference
|
def greek_comparator(lhs, rhs):
return greek_alphabet . index(lhs) - greek_alphabet . index(rhs)
|
Greek Sort
|
56bc1acf66a2abc891000561
|
[
"Fundamentals",
"Sorting"
] |
https://www.codewars.com/kata/56bc1acf66a2abc891000561
|
8 kyu
|
## Description
Welcome, Warrior! In this kata, you will get a message and you will need to get the frequency of each and every character!
## Explanation
Your function will be called `char_freq`/`charFreq`/`CharFreq` and you will get passed a string, you will then return a dictionary (object in JavaScript) with as keys the characters, and as values how many times that character is in the string. You can assume you will be given valid input.
## Example
```python
char_freq("I like cats") // Returns {'a': 1, ' ': 2, 'c': 1, 'e': 1, 'I': 1, 'k': 1, 'l': 1, 'i': 1, 's': 1, 't': 1}
```
```javascript
charFreq("I like cats") // Returns {'a': 1, ' ': 2, 'c': 1, 'e': 1, 'I': 1, 'k': 1, 'l': 1, 'i': 1, 's': 1, 't': 1}
```
```csharp
CharFreq("I like cats") => new Dictionary<char, int> {{'a', 1}, {' ', 2}, {'c', 1}, {'e', 1}, {'I', 1}, {'k', 1}, {'l', 1}, {'i', 1}, {'s', 1}, {'t', 1}}
```
|
reference
|
from collections import Counter
def char_freq(message):
return Counter(message)
|
Character Frequency
|
548ef5b7f33a646ea50000b2
|
[
"Fundamentals",
"Strings"
] |
https://www.codewars.com/kata/548ef5b7f33a646ea50000b2
|
8 kyu
|
Python is now supported on Codewars!
For those of us who are not very familiar with Python, let's handle the very basic challenge of creating a class named `Python`. We want to give our Pythons a name, so it should take a name argument that we can retrieve later.
For example:
```python
bubba = Python('Bubba')
bubba.name # should return 'Bubba'
```
|
reference
|
class Python:
def __init__(self, name):
self . name = name
|
Name Your Python!
|
53cf459503f9bbb774000003
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/53cf459503f9bbb774000003
|
8 kyu
|
This series of katas will introduce you to basics of doing geometry with computers.
~~~if:csharp
`Point` objects have fields `X` and `Y`.
~~~
~~~if-not:csharp
`Point` objects have attributes `x` and `y`.
~~~
Write a function calculating distance between `Point a` and `Point b`.
Input coordinates fit in range `$ -50 \leqslant x,y \leqslant 50 $`. Tests compare expected result and actual answer with tolerance of `1e-6`.
|
reference
|
def distance_between_points(a, b):
return ((b . x - a . x) * * 2 + (b . y - a . y) * * 2) * * 0.5
|
Geometry Basics: Distance between points in 2D
|
58dced7b702b805b200000be
|
[
"Geometry",
"Fundamentals"
] |
https://www.codewars.com/kata/58dced7b702b805b200000be
|
8 kyu
|
You are a biologist working on the amino acid composition of proteins. Every protein consists of a long chain of 20 different amino acids with different properties.
Currently, you are collecting data on the percentage, various amino acids make up a protein you are working on. As manually counting the occurences of amino acids takes too long (especially when counting more than one amino acid), you decide to write a program for this task:
Write a function that takes two arguments,
1. A (snippet of a) protein sequence
2. A list of amino acid residue codes
and returns the rounded percentage of the protein that the given amino acids make up.
If no amino acid list is given, return the percentage of hydrophobic amino acid residues ["A", "I", "L", "M", "F", "W", "Y", "V"].
|
reference
|
def aa_percentage(seq, residues=["A", "I", "L", "M", "F", "W", "Y", "V"]):
return round(sum(seq . count(r) for r in residues) / len(seq) * 100)
|
Percentage of amino acids
|
59759761e30a19cfe1000024
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/59759761e30a19cfe1000024
|
7 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:
There is a infinite string. You can imagine it's a combination of numbers from 1 to n, like this:
```
"123456789101112131415....n-2n-1n"
```
Please note: the length of the string is infinite. It depends on how long you need it(I can't offer it as a argument, it only exists in your imagination) ;-)
Your task is complete function `findPosition` that accept a digital string `num`. Returns the position(index) of the digital string(the first appearance).
For example:
```
findPosition("456") == 3
because "123456789101112131415".indexOf("456") = 3
^^^
```
Is it simple? No, It is more difficult than you think ;-)
```
findPosition("454") = ?
Oh, no! There is no "454" in "123456789101112131415",
so we should return -1?
No, I said, this is a string of infinite length.
We need to increase the length of the string to find "454"
findPosition("454") == 79
because "123456789101112131415...44454647".indexOf("454")=79
^^^
```
The length of argument `num` is 2 to 15. So now there are two ways: one is to create a huge own string to find the index position; Or thinking about an algorithm to calculate the index position.
Which way would you choose? ;-)
### Some examples:
```
findPosition("456") == 3
("...3456...")
^^^
findPosition("454") == 79
("...444546...")
^^^
findPosition("455") == 98
("...545556...")
^^^
findPosition("910") == 8
("...7891011...")
^^^
findPosition("9100") == 188
("...9899100101...")
^^^^
findPosition("99100") == 187
("...9899100101...")
^^^^^
findPosition("00101") == 190
("...99100101...")
^^^^^
findPosition("001") == 190
("...9899100101...")
^^^
findPosition("123456789") == 0
findPosition("1234567891") == 0
findPosition("123456798") == 1000000071
```
A bit difficulty, A bit of fun, happy coding ;-)
|
algorithms
|
from itertools import count
def num_index(n):
if (n < 10):
return n - 1
c = 0
for i in count(1):
c += i * 9 * 10 * * (i - 1)
if (n < 10 * * (i + 1)):
return c + (i + 1) * (n - 10 * * i)
def find_position(s):
if not int(s):
return num_index(int('1' + s)) + 1
for l in range(1, len(s) + 1):
poss = []
for i in range(0, l + 1):
sdt = s[0: l - i]
end = s[l - i: l]
for c in ([end + sdt, str(int(end) - 1) + sdt] if end and int(end) != 0 else [end + sdt]):
if (c[0] == '0'):
continue
ds = c
n = int(c)
while (len(ds) < len(s) + l):
n += 1
ds += str(n)
idx = ds . find(s)
if (idx != - 1):
poss . append(num_index(int(c)) + idx)
if (len(poss) > 0):
return min(poss)
|
The position of a digital string in a infinite digital string
|
582c1092306063791c000c00
|
[
"Algorithms",
"Puzzles"
] |
https://www.codewars.com/kata/582c1092306063791c000c00
|
2 kyu
|
-----
## CLEAR CUTTER'S NEEDS YOUR HELP!
-----
The logging company Clear Cutter's makes its money by optimizing the price-to-length of each log they cut before selling them. An example of one of their price tables is included:
```python
# So a price table p
p = [ 0, 1, 5, 8, 9, 10]
# Can be imagined as:
# length i | 0 1 2 3 4 5 *in feet*
# price pi | 0 1 5 8 9 10 *in money*
```
They hired an intern last summer to create a recursive function for them to easily calculate the most profitable price for a log of length _n_ using price table _p_ as follows:
```python
def cut_log(p, n):
if (n == 0):
return 0
q = -1
for i in range(1, n+1):
q = max(q, p[i] + cut_log(p, n-i))
return q
```
```javascript
function cutLog(p, n) {
if (n == 0) return 0;
let q = -1;
for (let i = 1; i <= n; i++) {
q = Math.max(q, p[i] + cutLog(p, n - i));
}
return q;
}
```
```haskell
cutLog _ 0 = 0
cutLog prices l = maximum $ zipWith ( \ i price -> price + cutLog prices (l-i) ) [1..l] (tail prices)
```
```dart
int cutLog(List<int> p, int n) {
if (n == 0) return 0;
int q = -1;
for (int i = 1; i <= n; i++) {
q = max(q, p[i] + cutLog(p, n - i));
}
return q;
}
```
An example of the working code:
```python
cut_log(p, 5) # => 13
# 5ft = $10, BUT 2ft + 3ft = 5ft -> $5 + $8 = $13 which is greater in value
```
```haskell
cutLog prices 5 -> 13
-- 5ft = $10, BUT 2ft + 3ft = 5ft -> $5 + $8 = $13 which is greater in value
```
However, their senior software engineer realized that the number of recursive calls in the function gives it an awful running time of 2^n (as this function iterates through ALL 2^n-1 possibilities for a log of length n).
Having discovered this problem just as you've arrived for your internship, he responsibly delegates the issue to you.
Using the power of Stack Overflow and Google, he wants you to create a solution that runs in Θ(n^2) time so that it doesn't take 5 hours to calculate the optimal price for a log of size 50. (He also suggests to research the problem using the keywords in the tags)
__(Be aware that if your algorithm is not efficient, it will attempt to look at 2^49 = 562949953421312 nodes instead of 49^2 = 2401... The solution will automatically fail if it takes longer than 6 seconds... which occurs at right around Log 23)__
|
refactoring
|
from functools import lru_cache
# Not gonna reinvent the wheel
# Now I can go on codewars while they think I'm still working on it
# Be a smart intern
def cut_log(p, n):
@ lru_cache(maxsize=None)
def rec(x):
if not x:
return 0
return max(p[i] + rec(x - i) for i in range(1, x + 1))
return rec(n)
|
Memoized Log Cutting
|
54b058ce56f22dc6fe0011df
|
[
"Dynamic Programming",
"Memoization",
"Refactoring"
] |
https://www.codewars.com/kata/54b058ce56f22dc6fe0011df
|
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:
Given some pieces of wood. It given by an integer array `woods`(argument 1), each element is the length of wood. Cut them into small pieces to guarantee you could have equal or more than `n`(argument 2) pieces with the same length(length should be integer). Your task is find what is the longest length you can get from these woods? Return the maximum length of the small pieces.
An example:
```
woods = [232, 124, 456], n = 7
That is: we have three woods, their length is 232, 124 and 456
We want cut them and get at least 7 small pieces(same length)
and we want the length of small piece is as long as possible
The result should be 114
Because:
232 can cut into 2 pieces and 4 excess wood
(The excess wood will be discarded)
124 can cut into 1 piece and 10 excess wood
456 can cut into 4 pieces and no excess wood
So we got total 7 pieces small pieces with length 114
Otherwise:
If we cut small pieces with length 115
We can only got 6 pieces
```
# Note:
- All numbers in `woods` are positive integers;
- `n` is an positive integer too;
- Result should be an integer length of small piece as long as possible;
- Please pay attention to optimizing the code to avoid time out
# Some Examples
```
woodCut([232, 124, 456], 7) === 114
woodCut([232, 124, 456], 20) === 38
woodCut([232, 124, 456], 1) === 456
woodCut([232, 124, 456], 2) === 232
woodCut([232, 124, 456], 3) === 228
woodCut([1, 1, 1], 4) === 0
woodCut([1, 1, 1], 3) === 1
```
|
games
|
def wood_cut(woods, n):
x = sum(woods) / / n
while x > 0 and sum(w / / x for w in woods) < n:
x = max([w / / (w / / x + 1) for w in woods])
return x
|
Wood Cut
|
583dbc028bbc0446f500032b
|
[
"Puzzles",
"Algorithms",
"Arrays"
] |
https://www.codewars.com/kata/583dbc028bbc0446f500032b
|
5 kyu
|
## Task
In your favorite game, you must shoot a target with a water-gun to gain points. Each target can be worth a different amount of points.
You are guaranteed to hit every target that you try to hit. You cannot hit consecutive targets though because targets are only visible for one second (one at a time) and it takes you a full second to reload your water-gun after shooting (you start the game already loaded).
Given an array `vals` with the order of each target's point value, determine the maximum number of points that you can win.
## Example
For `vals = [1, 2, 3, 4]`, the result should be `6`.
your optimal strategy would be to let the first one pass and shoot the second one with value 2 and the 4th one with value 4 thus:
`vals[1](2) + vals[3](4) = 6`
For `vals = [5, 5, 5, 5, 5]`, the result should be `15`.
your optimal strategy would be to shoot the 1st, 3rd and 5th value:
`5 + 5 + 5 = 15`
You haven't shoot the 2nd, 4th value because you are reloading your water-gun after shooting other values.
Note that the value can be zero or negative, don't shoot them ;-)
For `vals = [0, 0, -1, -1]`, the result should be `0`.
For `vals = [5, -2, -9, -4]`, the result should be `5`.
Shoot the first one is enough.
## Input/Output
- `[input]` integer array `vals`
The point values (negative or non-negative) of the targets (in order of appearance).
- `[output]` an integer
The maximum number of points that you can score.
|
algorithms
|
def target_game(values):
a = b = 0
for n in values:
a, b = b, max(a + n, b)
return max(a, b)
|
Challenge Fun #14: Target Game
|
58acf858154165363c00004e
|
[
"Algorithms",
"Arrays"
] |
https://www.codewars.com/kata/58acf858154165363c00004e
|
5 kyu
|
Create a function that differentiates a polynomial for a given value of `x`.
Your function will receive 2 arguments: a polynomial as a string, and a point to evaluate the equation as an integer.
## Assumptions:
* There will be a coefficient near each `x`, unless the coefficient equals `1` or `-1`.
* There will be an exponent near each `x`, unless the exponent equals `0` or `1`.
* All exponents will be greater or equal to zero
## Examples:
```python
differenatiate("12x+2", 3) ==> returns 12
differenatiate("x^2+3x+2", 3) ==> returns 9
```
```ruby
differenatiate("12x+2", 3) ==> returns 12
differenatiate("x^2+3x+2", 3) ==> returns 9
```
```javascript
differenatiate("12x+2", 3) ==> returns 12
differenatiate("x^2+3x+2", 3) ==> returns 9
```
```java
Equation.differenatiate("12x+2", 3) ==> 12
Equation.differenatiate("x^2+3x+2", 3) ==> 9
```
|
reference
|
from collections import defaultdict
import re
P = re . compile(r'\+?(-?\d*)(x\^?)?(\d*)')
def differentiate(eq, x):
derivate = defaultdict(int)
for coef, var, exp in P . findall(eq):
exp = int(exp or var and '1' or '0')
coef = int(coef != '-' and coef or coef and '-1' or '1')
if exp:
derivate[exp - 1] += exp * coef
return sum(coef * x * * exp for exp, coef in derivate . items())
|
Differentiate a polynomial
|
566584e3309db1b17d000027
|
[
"Algorithms",
"Strings",
"Fundamentals"
] |
https://www.codewars.com/kata/566584e3309db1b17d000027
|
4 kyu
|
**Steps**
1. Square the numbers that are greater than zero.
2. Multiply by 3 every third number.
3. Multiply by -1 every fifth number.
4. Return the sum of the sequence.
**Example**
`{ -2, -1, 0, 1, 2 }` returns `-6`
```
1. { -2, -1, 0, 1 * 1, 2 * 2 }
2. { -2, -1, 0 * 3, 1, 4 }
3. { -2, -1, 0, 1, -1 * 4 }
4. -6
```
P.S.: The sequence consists only of integers. And try not to use "for", "while" or "loop" statements.
|
reference
|
def calc(a):
return sum(x * * (1 + (x >= 0)) * (1 + 2 * (not i % 3)) * (- 1) * * (not i % 5) for i, x in enumerate(a, 1))
|
Operations with sequence
|
596ddaccdd42c1cf0e00005c
|
[
"Fundamentals",
"Arrays"
] |
https://www.codewars.com/kata/596ddaccdd42c1cf0e00005c
|
7 kyu
|
Given two strings, the first being a random string and the second being the same as the first, but with three added characters somewhere in the string (three same characters),
Write a function that returns the added character
### E.g
```
string1 = "hello"
string2 = "aaahello"
// => 'a'
```
The above is just an example; the characters could be anywhere in the string and string2 is actually **shuffled**.
### Another example
```
string1 = "abcde"
string2 = "2db2a2ec"
// => '2'
```
Note that the added character could also exist in the original string
```
string1 = "aabbcc"
string2 = "aacccbbcc"
// => 'c'
```
You can assume that string2 will aways be larger than string1, and there will always be three added characters in string2.
```if:c
Write the function `added_char()` that takes two strings and return the added character as described above.
```
```if:javascript
Write the function `addedChar()` that takes two strings and return the added character as described above.
```
|
games
|
from collections import Counter
def added_char(s1, s2):
return next((Counter(s2) - Counter(s1)). elements())
|
Three added Characters
|
5971b219d5db74843a000052
|
[
"Logic",
"Strings"
] |
https://www.codewars.com/kata/5971b219d5db74843a000052
|
6 kyu
|
My friend wants a new band name for her band. She like bands that use the formula: "The" + a noun with the first letter capitalized, for example:
`"dolphin" -> "The Dolphin"`
However, when a noun STARTS and ENDS with the same letter, she likes to repeat the noun twice and connect them together with the first and last letter, combined into one word (WITHOUT "The" in front), like this:
`"alaska" -> "Alaskalaska"`
Complete the function that takes a noun as a string, and returns her preferred band name written as a string.
|
reference
|
def band_name_generator(name):
return name . capitalize() + name[1:] if name[0] == name[- 1] else 'The ' + name . capitalize()
|
Band name generator
|
59727ff285281a44e3000011
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/59727ff285281a44e3000011
|
7 kyu
|
# Unflatten a list (Harder than easy)
This is the harder version of [Unflatten a list (Easy)](https://www.codewars.com/kata/57e2dd0bec7d247e5600013a)
So you have again to build a method, that creates new arrays, that can be flattened!
# Shorter: You have to unflatten a list/an array.
You get an array of integers and have to unflatten it by these rules:
```
- You have to do several runs. The depth is the number of runs, you have to do.
- In every run you have to switch the direction. First run from left, next run from right. Next left...
Every run has these rules:
- You start at the first number (from the direction).
- Take for every number x the remainder of the division by the number of still available elements (from
this position!) to have the number for the next decision.
- If the remainder-value is smaller than 3, take this number x (NOT the remainder-Value) direct
for the new array and continue with the next number.
- If the remainder-value (e.g. 3) is greater than 2, take the next remainder-value-number (e.g. 3)
elements/numbers (inclusive the number x, NOT the remainder-value) as a sub-array in the new array.
Continue with the next number/element AFTER this taken elements/numbers.
- Every sub-array in the array is independent and is only one element for the progress on the array.
For every sub-array you have to follow the same rules for unflatten it.
The direction is always the same as the actual run.
```
Sounds complicated? Yeah, thats why, this is the harder version...
Maybe an example will help.
```
Array: [4, 5, 1, 7, 1] Depth: 2 -> [[ 4, [ 5, 1, 7 ] ], 1]
Steps:
First run: (start from left side!)
1. The first number is 4. The number is smaller than the number of remaining elements, so it is the remainder-value (4 / 5 -> remainder 4).
So 4 numbers (4, 5, 1, 7) are added as sub-array in the new array.
2. The next number is 1. It is smaller than 3, so the 1 is added direct to the new array.
Now we have --> [[4, 5, 1, 7], 1]
Second run: (start from right side!)
1. The last number (first from other side) is 1. So the 1 is added direct to the new array.
2. The next element is the sub-array. So we use the rules for this.
2a.The last number is 7. There are 4 elements in the array. So for the next decision you have to
take the remainder from 7 / 4 -> 3. So 3 numbers (5, 1, 7) are added as sub-array in the
new array.
2b.Now there is the 4 and only one element last in this array. 4 / 1 -> remainder 0. It is smaller
than 3. So the 4 is added direct to the new array.
Now we have --> [[ 4, [ 5, 1, 7 ] ], 1]
```
The given array will always contain numbers. There will only be numbers > 0.
Have fun coding it and please don't forget to vote and rank this kata! :-)
I have created other katas. Have a look if you like coding and challenges.
|
algorithms
|
def unflatten(arr, depth, isLeft=1):
lst, it = [], enumerate(arr if isLeft else reversed(arr))
for i, x in it:
if isinstance(x, list):
lst . append(unflatten(x, 1, isLeft))
continue
n = x % (len(arr) - i)
if n < 3:
lst . append(x)
else:
gna = [x] + [next(it)[1] for _ in range(n - 1)]
lst . append(gna if isLeft else gna[:: - 1])
if not isLeft:
lst = lst[:: - 1]
return lst if depth == 1 else unflatten(lst, depth - 1, isLeft ^ 1)
|
Unflatten a list (Harder than easy)
|
57e5aa1d7fbcc988800001ae
|
[
"Mathematics",
"Arrays",
"Algorithms"
] |
https://www.codewars.com/kata/57e5aa1d7fbcc988800001ae
|
4 kyu
|
## Task
You will create an interpreter which takes inputs described below and produces outputs, storing state in between each input.
If you're not sure where to start with this kata, check out my [Simpler Interactive Interpreter](http://www.codewars.com/dojo/katas/53005a7b26d12be55c000243) kata, which greatly simplifies the interpreter by removing functions.
**Note that the** `eval` **command has been disabled.**
## Concepts
The interpreter will take inputs in the language described under the language header below. This section will give an overview of the language constructs.
### Variables
Any `identifier` which is not a keyword or a function name will be treated as a variable. If the identifier is on the left hand side of an assignment operator, the result of the right hand side will be stored in the variable. If a variable occurs as part of an expression, the value held in the variable will be substituted when the expression is evaluated.
Variables are implicitly declared the first time they are assigned to.
**Example:** Initializing a variable to a constant value and using the variable in another expression (Each line starting with a '>' indicates a separate call to the input method of the interpreter, other lines represent output)
```
>x = 7
7
>x + 6
13
```
Referencing a non-existent variable will cause the interpreter to throw an error. The interpreter should be able to continue accepting input even after throwing.
**Example:** Referencing a non-existent variable
```
>y + 7
ERROR: Invalid identifier. No variable with name 'y' was found."
```
### Assignments
An assignment is an expression that has an identifier on left side of an `=` operator, and any expression on the right. Such expressions should store the value of the right hand side in the specified variable and return the result.
**Example:** Assigning a constant to a variable
```
x = 7
7
```
You should also be able to chain and nest assignments. Note that the assignment operator is one of the few that is right associative.
**Example:** Chained assignments. The statement below should set both `x` and `y` to `7`.
```
x = y = 7
7
```
**Example:** Nested assignments. The statement below should set `y` to `3`, but it only outputs the final result.
```
x = 13 + (y = 3)
16
```
### Operator Precedence
Operator precedence will follow the common order. There is a table in the *Language* section below that explicitly states the operators and their relative precedence.
### Functions
Functions are declared by the `fn` keyword followed by a name, an optional arguments list, the `=>` operator, and finally an expression. All function variables are local to the function. That is, the only variable names allowed in the function body are those declared by the arguments list. If a function has an argument called 'x', and there is also a global variable called 'x', the function should use the value of the supplied argument, not the value of the global variable, when evaluating the expression. References to variables not found in the argument list should result in an error when the function is defined.
**Example:** declare a function to calculate the average of two variables and call it. (Each line starting with a '>' indicates a separate call to the input method of the interpreter, other lines represent output)
```
>fn avg => (x + y) / 2
ERROR: Unknown identifier 'x'
>fn avg x y => (x + y) / 2
>a = 2
2
>b = 4
4
>avg a b
3
```
**Example:** declare a function with an invalid variable name in the function body
```
>fn add x y => x + z
ERROR: Invalid identifier 'z' in function body.
```
**Example:** chain method calls (hint: function calls are right associative!)
```
>fn echo x => x
>fn add x y => x + y
>add echo 4 echo 3
7
```
### Name conflicts
Because variable and function names share the same grammar, conflicts are possible. Precedence will be given to the first object declared. That is, if a variable is declared, then subsequent declaration of a function with the same name should result in an error. Likewise, declaration of a function followed by the initialization of a variable with the same name should result in an error.
Declaration of function with the same name as an existing function should overwrite the old function with the new one.
**Example:** Overwriting a function
```
>fn inc x => x + 1
>a = 0
0
>a = inc a
1
>fn inc x => x + 2
>a = inc a
3
```
### Input
Input will conform to either the `function` production or the `expression` production in the grammar below.
### Output
* Output for a valid function declaration will be an empty string (null in Java).
* Output for a valid expression will be the result of the expression.
* Output for input consisting entirely of whitespace will be an empty string (null in Java).
* All other cases will throw an error.
```haskell
-- In Haskell that is:
Right (Nothing, Interpreter)
Right (Just Double, Interpreter)
Right (Nothing, Interpreter)
Left String
```
```rust
// In Rust that is:
Ok(None)
Ok(Some(f32))
Ok(None)
Err(String)
```
## Language
### Grammar
This section specifies the grammar for the interpreter language in [EBNF syntax](http://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_Form)
```
function ::= fn-keyword fn-name { identifier } fn-operator expression
fn-name ::= identifier
fn-operator ::= '=>'
fn-keyword ::= 'fn'
expression ::= factor | expression operator expression
factor ::= number | identifier | assignment | '(' expression ')' | function-call
assignment ::= identifier '=' expression
function-call ::= fn-name { expression }
operator ::= '+' | '-' | '*' | '/' | '%'
identifier ::= letter | '_' { identifier-char }
identifier-char ::= '_' | letter | digit
number ::= { digit } [ '.' digit { digit } ]
letter ::= 'a' | 'b' | ... | 'y' | 'z' | 'A' | 'B' | ... | 'Y' | 'Z'
digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
```
### Operator Precedence
The following table lists the language's operators grouped in order of precedence. Operators within each group have equal precedence.
Category | Operators
------------- | -------------
Multiplicative | *, /, %
Additive | +, -
Assignment | =
Function | =>
### Division
You should use float division instead of integer division.
|
algorithms
|
import operator as op
import re
import string
RE = re . compile(
"\s*(=>|[-+*\/\%=\(\)]|[A-Za-z_][A-Za-z0-9_]*|[0-9]*\.?[0-9]+)\s*")
def tokenize(e): return [s for s in RE . findall(e) if not s . isspace()]
def is_ident(t): return t[0] in "_ " + string . ascii_letters
class Interpreter:
def __init__(self):
self . vars = {}
self . functions = {}
def input(self, expression):
if "( fn " in ' ' . join(tokenize(expression)):
raise ValueError("Cannot declare function in an expression")
while "(" in expression:
if expression . startswith("fn "):
break
ptr = idx = expression . index("(")
start, tofind = expression[: idx] if idx else "", 1
while tofind:
ptr += 1
if expression[ptr] == ")":
tofind -= 1
if expression[ptr] == "(":
tofind += 1
expression = start + \
str(self . input(expression[idx + 1: ptr])) + expression[ptr + 1:]
return self . parse(expression)
def parse(self, expression):
if expression . startswith("fn "):
name, args, expr = expression . split()[1], expression . split(
"=>")[0]. split()[2:], expression . split("=>")[1]. strip()
self . functions[name] = {"expr": expr, "args": args}
if name in self . vars:
raise ValueError("Name alreday in use " + name)
elif len(args) > len(set(args)):
raise ValueError("Repeated argument " + expression)
elif any(t not in args and t not in self . functions for t in tokenize(expr) if is_ident(t)):
raise ValueError("Invalid function" + expression)
return ''
# Deal with other expressions, find rightmost =
left, expression = expression . rsplit(
"=", 1) if "=" in expression else ('', expression)
tokens = tokenize(expression)
if not tokens:
return ''
newtokens = []
while tokens:
token = tokens . pop()
if is_ident(token):
if token in self . functions:
args = {a: newtokens . pop() for a in self . functions[token]["args"]}
token = self . input(' ' . join(
[args . get(t, t) for t in tokenize(self . functions[token]["expr"])]))
elif token in self . vars:
token = self . vars[token]
else:
raise ValueError("Referenced before assignment : " + token)
newtokens . append(str(token))
result = evaluate(' ' . join(newtokens[:: - 1]))
if left:
vv = ' ' . join(left . split()). split("=")
if any(v in self . functions for v in vv):
raise ValueError("Identifier already in use : " + v)
for v in vv:
self . vars[v . strip()] = result
return result
def evaluate(s):
OP = {"*": op . mul, "/": op . truediv,
"+": op . add, "-": op . sub, "%": op . mod}
tokens, stack, result = [w if w in OP else float(
w) if '.' in w else int(w) for w in s . split()[:: - 1]], [], 0
while tokens:
t = tokens . pop()
stack . append(OP[t](stack . pop(), tokens . pop())
if str(t) in '/*%' else t)
while stack:
n = stack . pop()
result = OP[stack . pop() if stack else "+"](result, n)
return result
|
Simple Interactive Interpreter
|
52ffcfa4aff455b3c2000750
|
[
"Interpreters",
"Algorithms"
] |
https://www.codewars.com/kata/52ffcfa4aff455b3c2000750
|
1 kyu
|
# Simpler Interactive interpreter (or REPL)
You will create an interpreter which takes inputs described below and produces outputs, storing state in between each input. This is a simplified version of the [Simple Interactive Interpreter](http://www.codewars.com/dojo/katas/52ffcfa4aff455b3c2000750) kata with functions removed, so if you have fun with this kata, check out its big brother to add functions into the mix.
If you're not sure where to start with this kata, check out [ankr](http://www.codewars.com/users/ankr)'s [Evaluate Mathematical Expression](http://www.codewars.com/dojo/katas/52a78825cdfc2cfc87000005) kata.
**Note that the `eval` command has been disabled.**
## Concepts
The interpreter will take inputs in the language described under the language header below. This section will give an overview of the language constructs.
### Variables
Any `identifier` which is not a keyword will be treated as a variable. If the identifier is on the left hand side of an assignment operator, the result of the right hand side will be stored in the variable. If a variable occurs as part of an expression, the value held in the variable will be substituted when the expression is evaluated.
Variables are implicitly declared the first time they are assigned to.
**Example:** Initializing a variable to a constant value and using the variable in another expression (Each line starting with a '>' indicates a separate call to the input method of the interpreter, other lines represent output)
```
>x = 7
7
>x + 6
13
```
Referencing a non-existent variable will cause the interpreter to throw an error. The interpreter should be able to continue accepting input even after throwing.
**Example:** Referencing a non-existent variable
```
>y + 7
ERROR: Invalid identifier. No variable with name 'y' was found."
```
### Assignments
An assignment is an expression that has an identifier on left side of an `=` operator, and any expression on the right. Such expressions should store the value of the right hand side in the specified variable and return the result.
**Example:** Assigning a constant to a variable
```
x = 7
7
```
In this kata, all tests will contain only a single assignment. You do not need to consider chained or nested assignments.
### Operator Precedence
Operator precedence will follow the common order. There is a table in the *Language* section below that explicitly states the operators and their relative precedence.
### Name conflicts
Because variables are declared implicitly, no naming conflicts are possible. variable assignment will always overwrite any existing value.
### Input
Input will conform to the `expression` production in the grammar below.
### Output
Output for a valid expression will be the result of the expression.
Output for input consisting entirely of whitespace will be an empty string (`null` in case of Java).
All other cases will throw an error.
## Language
### Grammar
This section specifies the grammar for the interpreter language in [EBNF syntax](http://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_Form)
```
expression ::= factor | expression operator expression
factor ::= number | identifier | assignment | '(' expression ')'
assignment ::= identifier '=' expression
operator ::= '+' | '-' | '*' | '/' | '%'
identifier ::= letter | '_' { identifier-char }
identifier-char ::= '_' | letter | digit
number ::= { digit } [ '.' digit { digit } ]
letter ::= 'a' | 'b' | ... | 'y' | 'z' | 'A' | 'B' | ... | 'Y' | 'Z'
digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
```
### Operator Precedence
The following table lists the language's operators grouped in order of precedence. Operators within each group have equal precedence.
Category | Operators
------------- | -------------
Multiplicative | *, /, %
Additive | +, -
Assignment | =
|
algorithms
|
from ast import parse, Expr, Assign, BinOp, Name, Num
from operator import add, sub, mul, mod, truediv
class Interpreter:
def __init__(self):
self . vars = {}
def input(self, expression):
op = {'Sub': sub, 'Add': add, 'Mult': mul, 'Div': truediv, 'Mod': mod}
def _eval(node):
if isinstance(node, Expr):
return _eval(node . value)
if isinstance(node, Name):
return self . vars[node . id]
if isinstance(node, Num):
return node . n
if isinstance(node, BinOp):
return op[type(node . op). __name__](_eval(node . left), _eval(node . right))
if isinstance(node, Assign):
name = node . targets[0]. id
self . vars[name] = _eval(node . value)
return self . vars[name]
tree = parse(expression)
return _eval(tree . body[0]) if len(tree . body) else ''
|
Simpler Interactive Interpreter
|
53005a7b26d12be55c000243
|
[
"Interpreters",
"Parsing",
"Algorithms"
] |
https://www.codewars.com/kata/53005a7b26d12be55c000243
|
2 kyu
|
You will be given a sphere with radius `r`. Imagine that sphere gets cut with a plane, in this case the figure that is made with this cut is a circle. You will also be given the distance `h` between centres of sphere and circle.Your task is to return the surface area of the original sphere,area of circle and perimeter of circle, all of them rounded to 3 decimal places and order must be same as in the description.
<div style="display: grid; place-items: center;">
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="500"
height="500"
viewBox="0 0 132.29167 132.29167"
version="1.1"
id="svg1"
inkscape:version="1.3.2 (091e20ef0f, 2023-11-25)"
sodipodi:docname="sphereintersection.svg"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<sodipodi:namedview
id="namedview1"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1"
inkscape:document-units="mm"
inkscape:lockguides="false"
showgrid="true"
inkscape:zoom="1.9027095"
inkscape:cx="427.02263"
inkscape:cy="278.55014"
inkscape:window-width="2067"
inkscape:window-height="1304"
inkscape:window-x="477"
inkscape:window-y="16"
inkscape:window-maximized="0"
inkscape:current-layer="layer1" />
<defs
id="defs1">
<linearGradient
id="linearGradient10"
inkscape:collect="always">
<stop
style="stop-color:#ffffff;stop-opacity:0.49776787;"
offset="0"
id="stop10" />
<stop
style="stop-color:#00b7ff;stop-opacity:0.5;"
offset="1"
id="stop11" />
</linearGradient>
<linearGradient
id="linearGradient1"
inkscape:collect="always">
<stop
style="stop-color:#feffff;stop-opacity:0.50223213;"
offset="0"
id="stop1" />
<stop
style="stop-color:#00b6fd;stop-opacity:0.50223213;"
offset="1"
id="stop2" />
</linearGradient>
<radialGradient
inkscape:collect="always"
xlink:href="#linearGradient1"
id="radialGradient2"
cx="64.951904"
cy="52.5"
fx="64.951904"
fy="52.5"
r="50.717968"
gradientUnits="userSpaceOnUse" />
<radialGradient
inkscape:collect="always"
xlink:href="#linearGradient10"
id="radialGradient11"
cx="66.411091"
cy="21.191966"
fx="66.411091"
fy="21.191966"
r="46.982619"
gradientTransform="matrix(1,0,0,0.37110565,0,13.327508)"
gradientUnits="userSpaceOnUse" />
</defs>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1">
<path
style="fill:url(#radialGradient2);stroke-width:1.32292"
id="path1"
sodipodi:type="arc"
sodipodi:cx="64.951904"
sodipodi:cy="67.5"
sodipodi:rx="50.717968"
sodipodi:ry="50.717968"
sodipodi:start="5.8796643"
sodipodi:end="3.544925"
sodipodi:open="true"
sodipodi:arc-type="arc"
d="M 111.59642,47.585134 A 50.717968,50.717968 0 0 1 95.974517,107.62368 50.717968,50.717968 0 0 1 33.936862,107.62953 50.717968,50.717968 0 0 1 18.303637,47.593935" />
<path
style="fill:#d32c6f;fill-opacity:1;stroke-width:1.32292"
id="path4"
sodipodi:type="arc"
sodipodi:cx="85.150215"
sodipodi:cy="47.897724"
sodipodi:rx="0.1136852"
sodipodi:ry="0.30479777"
sodipodi:start="0"
sodipodi:end="0.4842336"
sodipodi:arc-type="slice"
d="m 85.2639,47.897724 a 0.1136852,0.30479777 0 0 1 -0.01307,0.141893 l -0.100615,-0.141893 z" />
<ellipse
style="fill:#e580aa;fill-opacity:1;stroke-width:1.32292"
id="path3-2"
ry="4.0813518"
rx="46.651325"
cy="34.567348"
cx="66.013329" />
<path
id="path10"
style="fill:url(#radialGradient11);stroke-width:0.264999;stroke-linecap:round;stroke-dasharray:1.05833, 0.264583"
d="m 112.70926,34.534481 c 0,2.323503 -20.313483,4.093 -46.215745,4.093 -25.902263,0 -47.129481,-1.741806 -47.129482,-4.065309 1e-6,-2.323503 21.227219,-4.348841 47.129482,-4.348841 25.902262,0 46.215745,1.997647 46.215745,4.32115 z m -93.358115,0.0148 C 27.358731,15.947908 45.741949,3.7643006 65.993679,3.7564545 86.245408,3.7486092 104.57318,15.825241 112.59518,34.420406"
sodipodi:nodetypes="ssssscsc" />
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:7.05556px;line-height:1.25;font-family:sans-serif;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.264583"
x="58.651443"
y="59.437603"
id="text6"><tspan
sodipodi:role="line"
id="tspan6"
style="font-size:7.05556px;stroke-width:0.264583"
x="58.651443"
y="59.437603">h</tspan></text>
<text
xml:space="preserve"
style="font-style:normal;font-weight:normal;font-size:7.05556px;line-height:1.25;font-family:sans-serif;fill:#000000;fill-opacity:1;stroke:none;stroke-width:0.264583"
x="87.354057"
y="63.514252"
id="text7"><tspan
sodipodi:role="line"
id="tspan7"
style="font-size:7.05556px;stroke-width:0.264583"
x="87.354057"
y="63.514252">r</tspan></text>
<path
style="fill:none;stroke:#000000;stroke-width:0.52916598;stroke-linecap:round;stroke-linejoin:miter;stroke-opacity:1;stroke-dasharray:none"
d="m 66.145832,66.145832 -8.9e-4,-13.794528"
id="path5"
sodipodi:nodetypes="cc" />
<ellipse
style="fill:#e581aa;fill-opacity:1;stroke-width:1.32292"
id="path3"
ry="4.7583737"
rx="46.651325"
cy="47.59293"
cx="64.951904" />
<path
style="fill:none;stroke:#000000;stroke-width:0.52999997;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;stroke-dasharray:2.11999988,0.52999997;stroke-dashoffset:0"
d="m 66.144941,52.351304 7.94e-4,-4.45358"
id="path8" />
<path
style="fill:none;stroke:#000000;stroke-width:0.52999997;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;stroke-dasharray:2.11999988,0.52999997;stroke-dashoffset:0"
d="m 66.14583,47.897724 45.4574,-0.304795"
id="path7" />
<path
style="fill:none;stroke:#000000;stroke-width:0.52999997;stroke-linecap:round;stroke-linejoin:miter;stroke-dasharray:none;stroke-opacity:1"
d="m 66.14583,66.14583 40.04435,-16.352948 v 0"
id="path6"
sodipodi:nodetypes="ccc" />
<path
style="fill:none;stroke:#000000;stroke-width:0.52916598;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1;stroke-dasharray:2.11666393,0.52916598;stroke-dashoffset:0"
d="m 106.19018,49.792881 5.41305,-2.199952"
id="path9" />
</g>
</svg>
</div>
|
reference
|
from math import pi
def stereometry(r, h):
area_of_sphere = round(4 * pi * r * * 2, 3)
area_of_circle = round(pi * (r * * 2 - h * * 2), 3)
perimeter_of_circle = round(2 * pi * (r * * 2 - h * * 2) * * 0.5, 3)
return (area_of_sphere, area_of_circle, perimeter_of_circle)
|
Some stereometry
|
5970915e54c27bd71000007b
|
[
"Mathematics",
"Fundamentals"
] |
https://www.codewars.com/kata/5970915e54c27bd71000007b
|
7 kyu
|
The alphabetized kata
---------------------
Re-order the characters of a string, so that they are concatenated into a new string in "case-insensitively-alphabetical-order-of-appearance" order. Whitespace and punctuation shall simply be removed!
The input is restricted to contain no numerals and only words containing the english alphabet letters.
Example:
```javascript
alphabetized("The Holy Bible") // "BbeehHilloTy"
```
```cpp
alphabetized("The Holy Bible") // "BbeehHilloTy"
```
```python
alphabetized("The Holy Bible") # "BbeehHilloTy"
```
```ruby
alphabetized("The Holy Bible") # "BbeehHilloTy"
```
```crystal
alphabetized("The Holy Bible") # "BbeehHilloTy"
```
```haskell
alphabetized "The Holy Bible" -- "BbeehHilloTy"
```
```c
alphabetized ("The Holy Bible") // "BbeehHilloTy"
```
_Inspired by [Tauba Auerbach](http://www.taubaauerbach.com/view.php?id=73)_
|
games
|
def alphabetized(s):
return "" . join(sorted(filter(str . isalpha, s), key=str . lower))
|
Alphabetized
|
5970df092ef474680a0000c9
|
[
"Strings",
"Sorting"
] |
https://www.codewars.com/kata/5970df092ef474680a0000c9
|
6 kyu
|
Calculate the product of all elements in an array.
```if:csharp
If the array is *null*, you should throw `ArgumentNullException` and if the array is empty, you should throw `InvalidOperationException`.
As a challenge, try writing your method in just one line of code. It's possible to have only 36 characters within your method.
```
```if:javascript
If the array is `null` or is empty, the function should return `null`.
```
```if:haskell
If the array is empty then return Nothing, else return Just product.
```
```if:php
If the array is `NULL` or empty, return `NULL`.
```
```if:python
If the array is empty or `None`, return `None`.
```
```if:ruby
If the array is `nil` or is empty, the function should return `nil`.
```
```if:crystal
If the array is `nil` or is empty, the function should return `nil`.
```
```if:groovy
If the array is `null` or `empty` return `null`.
```
```if:julia
If the input is `nothing` or an empty array, return `nothing`
```
|
reference
|
from functools import reduce
from operator import mul
def product(numbers):
return reduce(mul, numbers) if numbers else None
|
Product of Array Items
|
5901f361927288d961000013
|
[
"Mathematics",
"Fundamentals"
] |
https://www.codewars.com/kata/5901f361927288d961000013
|
7 kyu
|
Suzuki is preparing for a walk over fire ceremony high up in the mountains and the monks need coal for the fire. He must pack a basket of coal to the optimal level for each trip up the mountain. He must fit as much as possible into his basket. He can either take a piece of coal or leave it so he must chose which pieces will be optimal for the trip based on the weight in order to maximize the basket capacity.
10 ≤ basket ≤ 200
1 ≤ pile ≤ 100
You will be given a data structure similar to the one below:
```python
pile = 'dust 1 dust 4 dust 8 dust 100 dust'
basket = 43
Return the weight of the coal:
'The basket weighs 13 kilograms'
basket = 50
pile = 'dust83dust 45 25 22 46'
Returns:
'The basket weighs 47 kilograms'
```
Rake out the dust setting the pieces represented as integers for their weight aside. Take as much coal as possible filling the basket as close to its capacity as possible.
The size of the basket will change with each test as Suzuki exchanges it for an empty one on each trip up the mountain.
Return the weight of the coal as a string:
'The basket weighs 13 kilograms'
If there are no pieces of coal that will fit in the basket the solution returns:
'The basket weighs 0 kilograms'
Please also try the other Kata in this series..
* [Help Suzuki count his vegetables...](https://www.codewars.com/kata/56ff1667cc08cacf4b00171b)
* [Help Suzuki purchase his Tofu!](https://www.codewars.com/kata/57d4ecb8164a67b97c00003c)
* [Help Suzuki rake his garden!](https://www.codewars.com/kata/571c1e847beb0a8f8900153d)
* [Suzuki needs help lining up his students!](https://www.codewars.com/kata/5701800886306a876a001031)
* [How many stairs will Suzuki climb in 20 years?](https://www.codewars.com/kata/56fc55cd1f5a93d68a001d4e)
|
algorithms
|
def pack_basket(basket, pile):
charges = {0}
for c in list(map(int, pile . replace('dust', ''). split())):
charges |= {c + d for d in charges if c + d <= basket}
return 'The basket weighs %d kilograms' % max(charges)
|
Help Suzuki pack his coal basket!
|
57f09d0bcedb892791000255
|
[
"Dynamic Programming",
"Algorithms",
"Data Structures",
"Mathematics"
] |
https://www.codewars.com/kata/57f09d0bcedb892791000255
|
5 kyu
|
Assume `"#"` is like a backspace in string. This means that string `"a#bc#d"` actually is `"bd"`
Your task is to process a string with `"#"` symbols.
## Examples
```
"abc#d##c" ==> "ac"
"abc##d######" ==> ""
"#######" ==> ""
"" ==> ""
```
|
algorithms
|
def clean_string(s):
stk = []
for c in s:
if c == '#' and stk:
stk . pop()
elif c != '#':
stk . append(c)
return '' . join(stk)
|
Backspaces in string
|
5727bb0fe81185ae62000ae3
|
[
"Fundamentals",
"Strings",
"Algorithms"
] |
https://www.codewars.com/kata/5727bb0fe81185ae62000ae3
|
6 kyu
|
Construct a function that, when given a string containing an expression in infix notation, will return an identical expression in postfix notation.
The operators used will be `+`, `-`, `*`, `/`, and `^` with left-associativity of all operators but `^`.
The precedence of the operators (most important to least) are : 1) parentheses, 2) exponentiation, 3) times/divide, 4) plus/minus.
The operands will be single-digit integers between 0 and 9, inclusive.
Parentheses may be included in the input, and are guaranteed to be in correct pairs.
```javascript
toPostfix("2+7*5"); // Should return "275*+"
toPostfix("3*3/(7+1)"); // Should return "33*71+/"
toPostfix("5+(6-2)*9+3^(7-1)"); // Should return "562-9*+371-^+"
toPostfix("1^2^3"); // Should return "123^^"
```
```python
to_postfix("2+7*5") # Should return "275*+"
to_postfix("3*3/(7+1)") # Should return "33*71+/"
to_postfix("5+(6-2)*9+3^(7-1)") # Should return "562-9*+371-^+"
to_postfix("1^2^3") # Should return "123^^"
```
```cpp
to_postfix("2+7*5") // Should return "275*+"
to_postfix("3*3/(7+1)") // Should return "33*71+/"
to_postfix("5+(6-2)*9+3^(7-1)") // Should return "562-9*+371-^+"
to_postfix("1^2^3") // Should return "123^^"
```
```ruby
to_postfix("2+7*5") # Should return "275*+"
to_postfix("3*3/(7+1)") # Should return "33*71+/"
to_postfix("5+(6-2)*9+3^(7-1)") # Should return "562-9*+371-^+"
to_postfix("1^2^3") # Should return "123^^"
```
```haskell
toPostfix "2+7*5" -- Should return "275*+"
toPostfix "3*3/(7+1)" -- Should return "33*71+/"
toPostfix "5+(6-2)*9+3^(7-1)" -- Should return "562-9*+371-^+"
toPostfix "1^2^3" -- Should return "123^^"
```
You may read more about postfix notation, also called Reverse Polish notation, here:
http://en.wikipedia.org/wiki/Reverse_Polish_notation
|
algorithms
|
def LEFT(a, b): return a >= b
def RIGHT(a, b): return a > b
PREC = {'+': 2, '-': 2, '*': 3, '/': 3, '^': 4, '(': 1, ')': 1}
OP_ASSOCIATION = {'+': LEFT, '-': LEFT, '*': LEFT, '/': LEFT, '^': RIGHT}
def to_postfix(infix):
stack, output = [], []
for c in infix:
prec = PREC . get(c)
if prec is None:
output . append(c)
elif c == '(':
stack . append(c)
elif c == ')':
while stack and stack[- 1] != '(':
output . append(stack . pop())
stack . pop()
else:
while stack and OP_ASSOCIATION[c](PREC[stack[- 1]], prec):
output . append(stack . pop())
stack . append(c)
return '' . join(output + stack[:: - 1])
|
Infix to Postfix Converter
|
52e864d1ffb6ac25db00017f
|
[
"Mathematics",
"Algorithms"
] |
https://www.codewars.com/kata/52e864d1ffb6ac25db00017f
|
4 kyu
|
If `a = 1, b = 2, c = 3 ... z = 26`
Then `l + o + v + e = 54`
and `f + r + i + e + n + d + s + h + i + p = 108`
So `friendship` is twice as strong as `love` :-)
Your task is to write a function which calculates the value of a word based off the sum of the alphabet positions of its characters.
The input will always be made of only lowercase letters and will never be empty.
|
reference
|
def words_to_marks(s):
return sum(ord(c) - 96 for c in s)
|
Love vs friendship
|
59706036f6e5d1e22d000016
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/59706036f6e5d1e22d000016
|
7 kyu
|
Texas Hold'em is a Poker variant in which each player is given two "hole cards". Players then proceed to make a series of bets while five "community cards" are dealt. If there are more than one player remaining when the betting stops, a showdown takes place in which players reveal their cards. Each player makes the best poker hand possible using five of the seven available cards (community cards + the player's hole cards).
Possible hands are, in descending order of value:
1. Straight-flush (five consecutive ranks of the same suit). Higher rank is better.
2. Four-of-a-kind (four cards with the same rank). Tiebreaker is first the rank, then the rank of the remaining card.
3. Full house (three cards with the same rank, two with another). Tiebreaker is first the rank of the three cards, then rank of the pair.
4. Flush (five cards of the same suit). Higher ranks are better, compared from high to low rank.
5. Straight (five consecutive ranks). Higher rank is better.
6. Three-of-a-kind (three cards of the same rank). Tiebreaker is first the rank of the three cards, then the highest other rank, then the second highest other rank.
7. Two pair (two cards of the same rank, two cards of another rank). Tiebreaker is first the rank of the high pair, then the rank of the low pair and then the rank of the remaining card.
8. Pair (two cards of the same rank). Tiebreaker is first the rank of the two cards, then the three other ranks.
9. Nothing. Tiebreaker is the rank of the cards from high to low.
Given hole cards and community cards, complete the function __hand__ to return the type of hand (as written above, you can ignore case) and a list of ranks in decreasing order of significance, to use for comparison against other hands of the same type, of the best possible hand.
```javascript
hand(["A:♠", "A♦"], ["J♣", "5♥", "10♥", "2♥", "3♦"])
// ...should return {type: "pair", ranks: ["A", "J", "10", "5"]}
hand(["A♠", "K♦"], ["J♥", "5♥", "10♥", "Q♥", "3♥"])
// ...should return {type: "flush", ranks: ["Q", "J", "10", "5", "3"]}
```
```python
hand(["A♠", "A♦"], ["J♣", "5♥", "10♥", "2♥", "3♦"])
# ...should return ("pair", ranks: ["A", "J", "10", "5"]})
hand(["A♠", "K♦"], ["J♥", "5♥", "10♥", "Q♥", "3♥"])
# ...should return ("flush", ["Q", "J", "10", "5", "3"])
```
```csharp
Hand(new[] {"A♠", "A♦"}, new[] {"J♣", "5♥", "10♥", "2♥", "3♦"})
// ...should return ("pair", new[] {"A", "J", "10", "5"})
Hand(new[] {"A♠", "K♦"}, new[] {"J♥", "5♥", "10♥", "Q♥", "3♥"})
// ...should return ("flush", new[] {"Q", "J", "10", "5", "3"})
```
```scala
hand(List("A♠", "A♦"), List("J♣", "5♥", "10♥", "2♥", "3♦"))
// ...should return ("pair", List("A", "J", "10", "5"))
hand(List("A♠", "K♦"), List("J♥", "5♥", "10♥", "Q♥", "3♥"))
// ...should return ("flush", List("Q", "J", "10", "5", "3"))
```
**EDIT**: for Straights with an Ace, only the ace-high straight is accepted. An ace-low straight is invalid (ie. A,2,3,4,5 is invalid). This is consistent with the author's reference solution.
~docgunthrop
|
algorithms
|
class Poker:
value_map = {r: v for r, v in zip(
'2 3 4 5 6 7 8 9 10 J Q K A' . split(), range(2, 15))}
class Card:
def __init__(self, card):
self . rank = card[: - 1]
self . value = Poker . value_map[self . rank]
self . suit = card[- 1]
def __hash__(self):
return hash(self . rank)
def __init__(self, cards):
self . cards = sorted((Poker . Card(c) for c in cards),
key=lambda x: x . value, reverse=True)
self . rank_count = {r: 0 for r in 'A K Q J 10 9 8 7 6 5 4 3 2' . split()}
self . suit_count = {s: 0 for s in '♠♦♣♥'}
for card in self . cards:
self . rank_count[card . rank] += 1
self . suit_count[card . suit] += 1
def best_hand(self):
if hand:
= self . four_of_a_kind():
return ("four-of-a-kind", hand)
elif hand:
= self . full_house():
return ("full house", hand)
elif flush:
= self . flush():
if straight:
= self . straight(flush):
return ("straight-flush", straight)
return ("flush", [c . rank for c in flush[: 5]])
elif straight:
= self . straight(self . cards):
return ("straight", straight)
elif hand:
= self . three_of_a_kind():
return ("three-of-a-kind", hand)
elif r1:
= self . pair():
if r2:
= self . pair(r1[0]):
return ("two pair", [r1[0]] + r2)
return ("pair", r1)
else:
return ("nothing", [c . rank for c in self . cards[: 5]])
def four_of_a_kind(self):
for rank, count in self . rank_count . items():
if count == 4:
tie = [c . rank for c in self . cards if c . rank != rank][0]
return [rank, tie]
return []
def full_house(self):
if three:
= self . three_of_a_kind():
r3 = three[0]
if two:
= self . pair(r3):
r2 = two[0]
return [r3, r2]
return []
def flush(self):
for suit, count in self . suit_count . items():
if count >= 5:
return [card for card in self . cards if card . suit == suit]
return []
def straight(self, cards):
cards = sorted(set(c . rank for c in cards),
key=lambda x: self . value_map[x], reverse=True)
for i in range(len(cards) - 4):
run = cards[i: i + 5]
if all(self . value_map[a] - self . value_map[b] == 1 for a, b in zip(run, run[1:])):
return run
return []
def three_of_a_kind(self):
for rank, count in self . rank_count . items():
if count == 3:
tie = [c . rank for c in self . cards if c . rank != rank][: 2]
return [rank] + tie
return []
def pair(self, exclude=None):
for rank, count in self . rank_count . items():
if count == 2:
if exclude is not None:
if rank != exclude:
tie = [c . rank for c in self . cards if c . rank not in [rank, exclude]][0]
return [rank, tie]
else:
tie = [c . rank for c in self . cards if c . rank != rank][: 3]
return [rank] + tie
return []
def hand(hole_cards, community_cards):
poker = Poker(hole_cards + community_cards)
return poker . best_hand()
|
Texas Hold'em Hands
|
524c74f855025e2495000262
|
[
"Algorithms"
] |
https://www.codewars.com/kata/524c74f855025e2495000262
|
3 kyu
|
A famous casino is suddenly faced with a sharp decline of their revenues. They decide to offer Texas hold'em also online. Can you help them by writing an algorithm that can rank poker hands?
## Task
Create a poker hand that has a method to compare itself to another poker hand:
```csharp
Result PokerHand.CompareWith(PokerHand hand);
```
```fsharp
PokerHand.compareWith: hand: PokerHand -> Result
```
```java
Result PokerHand.compareWith(PokerHand hand);
```
```javascript
PokerHand.prototype.compareWith = function(hand){...};
```
```c
Result compare (Hand* player, Hand* opponent);
```
```cpp
Result compare (const PokerHand &player, const PokerHand &opponent);
```
```python
compare_with(self, other_hand)
```
```ruby
compare_with(other_hand)
```
```elixir
PokerHand.compare(String player, String opponent)
```
A poker hand has a constructor that accepts a string containing 5 cards:
```csharp
PokerHand hand = new PokerHand("KS 2H 5C JD TD");
```
```fsharp
let hand = PokerHand("KS 2H 5C JD TD")
```
```java
PokerHand hand = new PokerHand("KS 2H 5C JD TD");
```
```javascript
var hand = new PokerHand("KS 2H 5C JD TD");
```
```c
Hand *hand = PokerHand ("KS 2H 5C JD TD");
```
```cpp
PokerHand hand ("KS 2H 5C JD TD");
```
```python
PokerHand("KS 2H 5C JD TD")
```
```ruby
PokerHand.new("KS 2H 5C JD TD")
```
```elixir
# no constructor in elixir, pass the string into the compare
"KS 2H 5C JD TD"
```
The characteristics of the string of cards are:
* Each card consists of two characters, where
* The first character is the value of the card: `2, 3, 4, 5, 6, 7, 8, 9, T(en), J(ack), Q(ueen), K(ing), A(ce)`
* The second character represents the suit: `S(pades), H(earts), D(iamonds), C(lubs)`
* A space is used as card separator between cards
The result of your poker hand compare can be one of these 3 options:
```csharp
public enum Result
{
Win,
Loss,
Tie
}
```
```fsharp
type Result =
| Win = 0
| Loss = 1
| Tie = 2
```
```java
public enum Result
{
WIN,
LOSS,
TIE
}
```
```javascript
var Result =
{
"win": 1,
"loss": 2,
"tie": 3
}
```
```c
typedef enum { Win, Loss, Tie } Result;
```
```cpp
enum class Result { Win, Loss, Tie };
```
```python
[ "Win", "Tie", "Loss" ]
```
```ruby
[ "Win", "Tie", "Loss" ]
```
```elixir
@result %{win: 1, loss: 2, tie: 3}
```
## Notes
* Apply the [Texas Hold'em](https://en.wikipedia.org/wiki/Texas_hold_%27em) rules for ranking the cards.
* Low aces are valid in this kata.
* There is no ranking for the suits.
If you finished this kata, you might want to continue with [Sortable Poker Hands](https://www.codewars.com/kata/sortable-poker-hands)
|
algorithms
|
class PokerHand (object):
CARD = "23456789TJQKA"
RESULT = ["Loss", "Tie", "Win"]
def __init__(self, hand):
values = '' . join(sorted(hand[:: 3], key=self . CARD . index))
suits = set(hand[1:: 3])
is_straight = values in self . CARD
is_flush = len(suits) == 1
self . score = (2 * sum(values . count(card) for card in values)
+ 13 * is_straight + 15 * is_flush,
[self . CARD . index(card) for card in values[:: - 1]])
def compare_with(self, other):
return self . RESULT[(self . score > other . score) - (self . score < other . score) + 1]
|
Ranking Poker Hands
|
5739174624fc28e188000465
|
[
"Games",
"Algorithms",
"Object-oriented Programming"
] |
https://www.codewars.com/kata/5739174624fc28e188000465
|
4 kyu
|
# ASC Week 1 Challenge 5 (Medium #2)
Create a function that takes a 2D array as an input, and outputs another array that contains the average values for the numbers in the nested arrays at the corresponding indexes.
Note: the function should also work with negative numbers and floats.
## Examples
```
[ [1, 2, 3, 4], [5, 6, 7, 8] ] ==> [3, 4, 5, 6]
1st array: [1, 2, 3, 4]
2nd array: [5, 6, 7, 8]
| | | |
v v v v
average: [3, 4, 5, 6]
```
And another one:
```
[ [2, 3, 9, 10, 7], [12, 6, 89, 45, 3], [9, 12, 56, 10, 34], [67, 23, 1, 88, 34] ] ==> [22.5, 11, 38.75, 38.25, 19.5]
1st array: [ 2, 3, 9, 10, 7]
2nd array: [ 12, 6, 89, 45, 3]
3rd array: [ 9, 12, 56, 10, 34]
4th array: [ 67, 23, 1, 88, 34]
| | | | |
v v v v v
average: [22.5, 11, 38.75, 38.25, 19.5]
```
|
reference
|
def avg_array(arrs):
return [sum(a) / len(a) for a in zip(* arrs)]
|
Average Array
|
596f6385e7cd727fff0000d6
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/596f6385e7cd727fff0000d6
|
7 kyu
|
A list of integers is sorted in “Wave” order if alternate items are not less than their immediate neighbors (thus the other alternate items are not greater than their immediate neighbors).
Thus, the array `[4, 1, 7, 5, 6, 2, 3]` is in **Wave** order because 4 >= 1, then 1 <= 7, then 7 >= 5, then 5 <= 6, then 6 >= 2, and finally 2 <= 3.
The wave-sorted lists has to begin with an element not less than the next, so `[1, 4, 5, 3]` is not sorted in Wave because 1 < 4
Your task is to implement a function that takes a list of integers and sorts it into wave order in place; your function shouldn't return anything.
Note:
- The resulting array shouldn't necessarily match anyone in the tests, a function just checks if the array is now wave sorted.
|
algorithms
|
def wave_sort(a):
a . sort()
for i in range(1, len(a), 2):
a[i], a[i - 1] = a[i - 1], a[i]
|
Wave Sorting
|
596f28fd9be8ebe6ec0000c1
|
[
"Algorithms",
"Arrays",
"Logic",
"Sorting"
] |
https://www.codewars.com/kata/596f28fd9be8ebe6ec0000c1
|
6 kyu
|
An AI has infected a text with a character!!
This text is now **fully mutated** to this character.
~~~if-not:riscv
If the text or the character are empty, return an empty string.
There will never be a case when both are empty as nothing is going on!!
**Note:** The character is a string of length 1 or an empty string.
~~~
~~~if:riscv
If the text is empty, return an empty string.
~~~
# Example
```
text before = "abc"
character = "z"
text after = "zzz"
```
~~~if:riscv
RISC-V: The function signature is
```c
void contamination(const char *text, char mutation, char *result);
```
The function does not have a return value - you should write the mutated string into `result`. You may safely assume that `result` will be large enough to hold the result.
~~~
|
reference
|
def contamination(text, char):
return char * len(text)
|
Contamination #1 -String-
|
596fba44963025c878000039
|
[
"Strings",
"Fundamentals"
] |
https://www.codewars.com/kata/596fba44963025c878000039
|
8 kyu
|
Gary likes pictures but he also likes words and reading. He has had a desire for a long time to see what words and books would look like if they could be seen as images.
For this task you are required to take a continuous string that can consist of any combination of words or characters and then convert the words that make up this string into hexadecimal values that could then be read as colour values.
A word is defined as a sequence of ASCII characters between two white space characters or the first or last word of a sequence of words.
Each word will represent a hexadecimal value by taking the first three letters of each word and find the ASCII character code for each character. This will then give you one hexadecimal value that represents the colours red, green or blue. You will then combine these values into one readable RGB hexadecimal value, e.g. `#ffffff`.
If your word consists of less than 3 letters, you should use the hexidecimal value `00`, ie `"It"` would return a value `#497400`.
Your answer should be an array of hexadecimal values that correspond to each word that made up your original string.
## Example
The following string would be given:
`"Hello, my name is Gary and I like cheese."`
This string would return the following array:
```
['#48656c', '#6d7900', '#6e616d','#697300','#476172','#616e64','#490000','#6c696b','#636865']
```
|
reference
|
def words_to_hex(words):
return [f"# { w [: 3 ]. hex (): 0 < 6 } " for w in words . encode(). split()]
|
Words to Hex
|
596e91b48c92ceff0c00001f
|
[
"Strings",
"Arrays",
"Recursion",
"Fundamentals"
] |
https://www.codewars.com/kata/596e91b48c92ceff0c00001f
|
6 kyu
|
# Task
Write a function `deNico`/`de_nico()` that accepts two parameters:
- `key`/`$key` - string consists of unique letters and digits
- `message`/`$message` - string with encoded message
and decodes the `message` using the `key`.
First create a numeric key basing on the provided `key` by assigning each letter position in which it is located after setting the letters from `key` in an alphabetical order.
For example, for the key `crazy` we will get `23154` because of `acryz` (sorted letters from the key).
Let's decode `cseerntiofarmit on ` using our `crazy` key.
```
1 2 3 4 5
---------
c s e e r
n t i o f
a r m i t
o n
```
After using the key:
```
2 3 1 5 4
---------
s e c r e
t i n f o
r m a t i
o n
```
# Notes
- The `message` is never shorter than the `key`.
- Don't forget to remove trailing whitespace after decoding the message
# Examples
```javascript
deNico("crazy", "cseerntiofarmit on ") => "secretinformation"
deNico("abc", "abcd") => "abcd"
deNico("ba", "2143658709") => "1234567890"
deNico("key", "eky") => "key"
```
```php
de_nico("crazy", "cseerntiofarmit on "); // => "secretinformation"
de_nico("abc", "abcd"); // => "abcd"
de_nico("ba", "2143658709"); // => "1234567890"
de_nico("key", "eky"); // => "key"
```
Check the test cases for more examples.
# Related Kata
[Basic Nico - encode](https://www.codewars.com/kata/5968bb83c307f0bb86000015)
|
reference
|
def de_nico(key, msg):
ll, order, s = len(key), [sorted(key). index(c) for c in key], ''
while msg:
s, msg = s + '' . join(msg[i] for i in order if i < len(msg)), msg[ll:]
return s . strip()
|
Basic DeNico
|
596f610441372ee0de00006e
|
[
"Fundamentals"
] |
https://www.codewars.com/kata/596f610441372ee0de00006e
|
5 kyu
|
The aspect ratio of an image describes the proportional relationship between its width and its height. Most video shown on the internet uses a 16:9 aspect ratio, which means that for every pixel in the Y, there are roughly 1.77 pixels in the X (where 1.77 ~= 16/9). As an example, 1080p video with an aspect ratio of 16:9 would have an X resolution of 1920, however 1080p video with an aspect ratio of 4:3 would have an X resolution of 1440.
Write a function that accepts arbitrary X and Y resolutions and converts them into resolutions with a 16:9 aspect ratio that maintain equal height. Round your answers up to the nearest integer.
This kata is part of a series with <a href="https://www.codewars.com/kata/aspect-ratio-cropping-part-2">Aspect Ratio Cropping - Part 2</a> .
<h1>Example</h1>
<i>374 × 280 pixel image with a 4:3 aspect ratio.</i>
<a title="By thewikipedian, uploaded by Andreas -horn- Hornig (Photo by thewikipedian.) [GFDL (http://www.gnu.org/copyleft/fdl.html) or CC-BY-SA-3.0 (http://creativecommons.org/licenses/by-sa/3.0/)], via Wikimedia Commons" href="https://commons.wikimedia.org/wiki/File%3AAspect_ratio_4_3_example.jpg"><img width="256" alt="Aspect ratio 4 3 example" src="https://upload.wikimedia.org/wikipedia/commons/4/43/Aspect_ratio_4_3_example.jpg"/></a>
<i>500 × 280 pixel image with a 16:9 aspect ratio.</i>
<a title="By thewikipedian, uploaded by Benedicto16 (Photo by thewikipedian.) [GFDL (http://www.gnu.org/copyleft/fdl.html) or CC-BY-SA-3.0 (http://creativecommons.org/licenses/by-sa/3.0/)], via Wikimedia Commons" href="https://commons.wikimedia.org/wiki/File%3AAspect_ratio_16_9_example3.jpg"><img width="256" alt="Aspect ratio 16 9 example3" src="https://upload.wikimedia.org/wikipedia/commons/2/2c/Aspect_ratio_16_9_example3.jpg"/></a>
|
reference
|
from typing import Tuple
from math import ceil
def aspect_ratio(x: int, y: int) - > Tuple[int, int]:
return (ceil(y * 16 / 9), y)
|
Aspect Ratio Cropping - Part 1
|
596e4ef7b61e25981200009f
|
[
"Mathematics",
"Fundamentals"
] |
https://www.codewars.com/kata/596e4ef7b61e25981200009f
|
8 kyu
|
# The Challenge
You'll need to implement a simple lexer type `Simplexer`, which, when constructed with a given string containing an expression in a simple language, transforms that string into a stream of `Token`s.
## Simplexer
Your `Simplexer` type is created with the expression it should tokenize. It should act like an iterator, yielding `Token` items until there are no more items to yield, at which point it should do whatever the appropriate action is for your chosen language.
~~~if:python
Instances of the `Simplexer` class are initialized with a string and should be iterators as well as iterable, i.e. they must implement both `__iter__` and `__next__`.
Like all iterators, `__next__` should raise a `StopIteration` exception when no more tokens remain to be yielded.
~~~
~~~if:java
Objects of the `Simplexer` class are instantiated with a string and should implement the `Iterator<Token>` interface, meaning the `Simplexer` class must define the `Token next()` and the `boolean hasNext()` methods.
~~~
~~~if:javascript
Objects of the `Simplexer` class are instantiated with a string and must define the `next(): Token` and the `hasNext(): boolean` methods.
~~~
~~~if:csharp
Objects of the `Simplexer` class are instantiated with a string and are `Iterator<T>`, which is an extension of `IEnumerator<T>` with default implementations for `Reset()`, `Dispose()` and `IEnumerator.Current`. You only need to override `MoveNext()` and `Current { get; }`.
~~~
~~~if:rust
The `Simplexer` type must define a `new` function which takes a string and returns an instance of itself. It must also implement `Iterator<Item = Token>`.
~~~
## Tokens
Tokens are represented by `Token` objects, **which are preloaded** for you and take the following shape:
~~~if:java
```java
public class Token {
public final String text;
public final String type;
public Token(String text, String type) {
this.text = text;
this.type = type;
}
}
```
- `Token.text` is the value of the matched portion of the expression
- `Token.type` is the type of the token (see below)
~~~
~~~if:python
```python
class Token:
def __init__(self, text: str, kind: str):
self.text = text
self.kind = kind
```
- `Token.text` is the value of the matched portion of the expression
- `Token.kind` is the type of the token (see below)
~~~
~~~if:javascript
```javascript
function Token(text, type) {
Object.defineProperty(this, 'text', {
enumerable: true,
value: text
});
Object.defineProperty(this, 'type', {
enumerable: true,
value: type
});
};
```
- `text` is a string, the matched portion of the expression
- `type` is a string representing the token type (see below)
~~~
~~~if:csharp
```csharp
class Token
{
private string text { get; }
private string type { get; }
public Token(string text, string type)
{
this.text = text;
this.type = type;
}
}
```
- `Token.text` is the value of the matched portion of the expression
- `Token.type` is the type of the token (see below)
~~~
~~~if:rust
```rust
#[derive(Debug)]
pub struct Token {
pub text: String,
pub kind: TokenKind,
}
impl Token {
pub fn new(text: &str, kind: TokenKind) -> Self
}
pub enum TokenKind {
Integer,
Boolean,
String,
Operator,
Keyword,
Whitespace,
Identifier,
}
```
- `Token.text` is the value of the matched portion of the expression
- `Token.kind` is a `TokenKind` variant that matches the type of the token (see below)
In addition to regular `Debug`, `Token` implements `Display` for succinct and readable output. An example would look like `Integer("42")`.
~~~
## Language Grammar
The language for this task has a simple grammar, consisting of the following constructs and their associated token types:
```
Type Construct
integer: Any sequence of one or more decimal digits (leading zeroes allowed, no negative numbers)
boolean: Any of the following words: [true, false]
string: Any sequence of zero or more characters surrounded by "double quotes"
operator: Any of the following characters: [+, -, *, /, %, (, ), =]
keyword: Any of the following words: if, else, for, while, return, func, break
whitespace: Any sequence of the following characters: [' ', '\t', '\n']
- Consecutive whitespace should be collapsed into a single token
identifier: Any sequence of alphanumeric characters, as well as '_' and '$'
- Must not start with a digit
- Make sure that keywords and booleans aren't matched as identifiers
```
## Notes
- Individual constructs are disambiguated by whitespace if necessary, so
- `true123` is an `identifier`, as opposed to `boolean` followed by `integer`
- `123true` is an `integer` followed by `boolean`
- `"123"true` is a `string` followed by `boolean`
- `x+y` is `identifier` `op` `identifier`
- Any character is permissable between double quotes, including keywords, numbers and arbitrary whitespace, so `"true"` and `"123"` are `string`s. The quotes `""` are to be included in the Token.
- The input strings are guaranteed to be lexically valid according to the grammar above. Specifically:
- Input will consist only of valid constructs that can be mapped unambiguously to one of the above tokens
- No assumptions need be made regarding the structure of tokens in the input, i.e. syntax.
- Input may be the empty string
That means the input will not contain any surprising characters, there is no need for error handling, and quotes will always appear in balanced pairs. This does *not* mean that the input needs to make semantic or syntactic sense. For example, `if 123) return else"five")(` is valid input for this task.
After all, the job of a lexer is not to interpret the given input, merely transform it into tokens that could then be passed on to e.g. a parser, which would then check that the tokens received are syntactically valid and imbue them with semantics.
|
algorithms
|
from itertools import chain
class Simplexer (object):
BOOLS = ["true", "false"]
KEYWORDS = ["if", "else", "for", "while", "return", "func", "break"]
OPERATORS = "+-*/%()="
SPACE = " \n\t\c"
NUMBER = "0123456789"
CHAR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$"
def __init__(self, expression):
self . expression = expression
self . __data = iter(expression)
def __iter__(self):
self . __data = iter(self . expression)
return self
def __next__(self):
token = self . _nextc()
# Operators
if token in self . OPERATORS:
return Token(token, "operator")
# Whitespace
if token in self . SPACE:
while self . _peekc() in self . SPACE:
token += self . _nextc()
return Token(token, "whitespace")
# Strings
if token == '"':
token += self . _nextc()
while token[- 1] != '"':
token += self . _nextc()
return Token(token, "string")
# Integer
if token in self . NUMBER:
while self . _peekc() in self . NUMBER:
token += self . _nextc()
return Token(token, "integer")
if token in self . CHAR:
while self . _peekc() in self . CHAR + self . NUMBER:
token += self . _nextc()
if token in self . BOOLS:
return Token(token, "boolean")
if token in self . KEYWORDS:
return Token(token, "keyword")
return Token(token, "identifier")
def _nextc(self):
return next(self . __data)
def _peekc(self):
# Peeking shouldn't end the iteration
try:
char = next(self . __data)
self . __data = chain([char], self . __data)
except:
char = "END"
return char
|
Simplexer
|
54b8204dcd7f514bf2000348
|
[
"Strings",
"Parsing",
"Algorithms"
] |
https://www.codewars.com/kata/54b8204dcd7f514bf2000348
|
4 kyu
|
Generate a valid randomly generated hexadecimal color string. Assume all of them always have 6 digits.
Valid Output
---
#ffffff
#FfFfFf
#25a403
#000001
Non-Valid Output
---
#fff
#aaa
#zzzzz
cafebabe
#a567567676576756A7
|
games
|
import random
from string import hexdigits
def generate_color_rgb():
return '#' + ''.join([random.choice(hexdigits) for i in range(6)])
|
HTML dynamic color string generation
|
56f1c6034d0c330e4a001059
|
[
"Puzzles"
] |
https://www.codewars.com/kata/56f1c6034d0c330e4a001059
|
6 kyu
|
Given two numbers: 'left' and 'right' (1 <= 'left' <= 'right' <= 200000000000000)
return sum of all '1' occurencies in binary representations of numbers between 'left' and 'right' (including both)
```
Example:
countOnes 4 7 should return 8, because:
4(dec) = 100(bin), which adds 1 to the result.
5(dec) = 101(bin), which adds 2 to the result.
6(dec) = 110(bin), which adds 2 to the result.
7(dec) = 111(bin), which adds 3 to the result.
So finally result equals 8.
```
WARNING: Segment may contain billion elements, to pass this kata, your solution cannot iterate through all numbers in the segment!
|
algorithms
|
import math
def count(n):
if n is 0:
return 0
x = int(math . log(n, 2))
return x * 2 * * (x - 1) + n - 2 * * x + 1 + count(n - 2 * * x)
def countOnes(left, right):
return count(right) - count(left - 1)
|
Count ones in a segment
|
596d34df24a04ee1e3000a25
|
[
"Binary",
"Performance",
"Algorithms"
] |
https://www.codewars.com/kata/596d34df24a04ee1e3000a25
|
4 kyu
|
Not to brag, but I recently became the nexus of the Codewars universe! My honor and my rank were the same number. I cried a little.
Complete the method that takes a hash/object/directory/association list of users, and find the *nexus*: the user whose rank is the closest is equal to his honor. Return the rank of this user. For each user, the key is the rank and the value is the honor.
If nobody has an exact rank/honor match, return the rank of the user who comes closest. If there are several users who come closest, return the one with the lowest rank (numeric value). The hash will not necessarily contain consecutive rank numbers; return the best match from the ranks provided.
## Example
```
rank honor
users = { 1 => 93,
10 => 55,
15 => 30,
20 => 19, <--- nexus
23 => 11,
30 => 2 }
```
|
algorithms
|
def nexus(d):
return min(d, key=lambda x: (abs(x - d[x]), x))
|
Find the Nexus of the Codewars Universe
|
5453dce502949307cf000bff
|
[
"Algorithms"
] |
https://www.codewars.com/kata/5453dce502949307cf000bff
|
6 kyu
|
Motivation
---------
Natural language texts often have a very high frequency of certain letters, in German for example, almost every 5th letter is an E, but only every 500th is a Q. It would then be clever to choose a very small representation for E. This is exactly what the Huffman compression is about, choosing the length of the representation based on the frequencies of the symbol in the text.
Algorithm
--------
Let's assume we want to encode the word `"aaaabcc"`, then we calculate the frequencies of the letters in the text:
Symbol | Frequency
-------|----------
a | 4
b | 1
c | 2
Now we choose a smaller representation the more often it occurs, to minimize the overall space needed. The algorithm uses a tree for encoding and decoding:
```
.
/ \
a .
/ \
b c
```
Usually we choose `0` for the left branch and `1` for the right branch (but it might also be swapped). By traversing from the root to the symbol leaf, we want to encode, we get the matching representation. To decode a sequence of binary digits into a symbol, we start from the root and just follow the path in the same way, until we reach a symbol.
Considering the above tree, we would encode **a** with `0`, **b** with `10` and **c** with `11`. Therefore encoding `"aaaabcc"` will result in `0000101111`.
(**Note:** As you can see the encoding is not optimal, since the code for **b** and **c** have same length, but that is topic of another data compression Kata.)
Tree construction
---------------
To build the tree, we turn each symbol into a *leaf* and sort them by their frequency. In every step, we remove 2 trees with the **smallest** frequency and put them under a node. This node gets reinserted and has the sum of the frequencies of both trees as new frequency. We are finished, when there is only 1 tree left.
(**Hint:** Maybe you can do it without sorting in every step?)
Goal
----
Write functions `frequencies`, `encode` and `decode`.
```if:haskell
Bits are represented as a list of `Z` (zero) and `O` (one).
(**Hint:** You can assume that symbols can be ordered.)
```
```if:javascript,python
Bits are represented as strings of `"0"` (zero) and `"1"` (one).
```
**Note:** Frequency lists with just one or less elements should get rejected. (Because then there is no information we could encode, but the length.).
If you get a frequency list with one or less elements, return `null/None/Nothing`, depending on your language.
|
algorithms
|
from collections import Counter, namedtuple
from heapq import heappush, heappop
def frequencies(strng):
return list(Counter(strng). items())
def freqs2tree(freqs):
heap, Node = [], namedtuple('Node', 'letter left right')
for char, weight in freqs:
heappush(heap, (weight, Node(char, None, None)))
while len(heap) > 1:
(w_left, left), (w_right, right) = heappop(heap), heappop(heap)
heappush(heap, (w_left + w_right, Node("", left, right)))
return heappop(heap)[1]
def encode(freqs, strng):
def tree2bits(tree, parent_bits=1):
if tree:
if tree . letter:
table[ord(tree . letter)] = bin(parent_bits)[3:]
tree2bits(tree . left, parent_bits << 1 | 0)
tree2bits(tree . right, parent_bits << 1 | 1)
if len(freqs) > 1:
table = {}
tree2bits(freqs2tree(freqs))
return strng . translate(table)
def decode(freqs, bits):
def tree2strng(tree, parent_bits=1):
if tree:
if tree . letter:
table[parent_bits] = tree . letter
tree2strng(tree . left, parent_bits << 1 | 0)
tree2strng(tree . right, parent_bits << 1 | 1)
if len(freqs) > 1:
table, code, strng = {}, 1, []
tree2strng(freqs2tree(freqs))
for b in map(int, bits):
code = code << 1 | b
if code in table:
strng . append(table[code])
code = 1
return '' . join(strng)
|
Huffman Encoding
|
54cf7f926b85dcc4e2000d9d
|
[
"Algorithms"
] |
https://www.codewars.com/kata/54cf7f926b85dcc4e2000d9d
|
3 kyu
|
This challenge is to compute a special set of <a href="https://en.wikipedia.org/wiki/Parasitic_number">parasitic numbers</a> for various number bases.
>An n-parasitic number (in base 10) is a positive natural number which can be multiplied by n by moving the rightmost digit of its decimal representation to the front. Here n is itself a single-digit positive natural number. In other words, the decimal representation undergoes a right circular shift by one place. For example, 4 • 128205 = 512820, so 128205 is 4-parasitic
## Special Parasitic Numbers
For some N there may be multiple N-parasitic numbers. This Kata is concerned with finding a special set of n-parasitic numbers where the trailing digit is also the 'N' in the N-parasitic number. In base-10, the above Wikipedia excerpt shows that 128205 is 4-parasitic since 4 • 128205 = 512820; however, the special number this Kata is looking for is the smallest 4-parasitic number that also ends in 4, which is 102564: 4 • 102564 = 410256.
<blockquote>
<h3>A Clarifying Anti-Example</h3>
The "ending in N" portion of the requirements seems easily missed. While 5 • 142857 = 714285, this 142857 number is parasitic but it is <u>not</u> the number sought by this kata because it ends with a 7 in the ones' place rather than 'n' (which is 5 in this case).
```
v--- kata requires this digit to be 5 for n = 5
5 • 142857 = 714285
^--- kata requires this digit to be 5 for n = 5
```
While the product happens to end with a 5 in the one's place, that ends-with-N requirement is on the multiplicand <u>not</u> on the product. The answer sought is much bigger than 142857 for n = 5.
</blockquote>
## Challenge
Provide a method accepting two arguments: the special trailing digit and a number base. Your method should return the string representation of the smallest integer having the special parasitic number property as described above in the requested number-base (octal, decimal and hex.) Each number base will test for all trailing digits other than 0 and 1, giving a total of 28 test cases.
## Why the smallest?
Consider how the special 4-parastic HEX number ending in 4 is 104.
```104 Hex • 4 = 410 Hex.```
Repeating ```104``` twice and multiplying by 4 gives us ```104104 Hex • 4 = 410410 Hex```. This property holds regardless of how many times the set of digits is repeated (e.g., ```104104 Hex • 4 = 410410 Hex, 104104104 Hex • 4 = 410410410 Hex, 104104104104 Hex • 4 = 410410410410 Hex, ...```), leading to an infinite set of these special numbers in each case. Your task is to find only the smallest number that satisfies the special parasitic property. [This fact is a hint on one possible way to solve this problem.]
## Hints:
* Unless you can be clever about it, brute force techniques probably won't work.
* An answer exists satisfying the criteria for each of the trailing-digits tested.
* Leading zero-digits are not allowed.
* Test failures will reveal the inputs rather than the expected value.
### After you have solved it:
Can you find two other algorithmically different approaches to solve this puzzle? The refrence solutions in JavaScript, C# and Python solve the puzzle in fundamentally different ways.
|
games
|
def calc_special(d, b):
rep = {10: 'd', 8: 'o', 16: 'x'}[b]
n = format(d, rep)
while True:
prod = format(d * int(n, b), rep)
if n[- 1:] + n[: - 1] == prod:
return n
n = prod[- len(n):] + n[- 1:]
|
N-Parasitic Numbers Ending in N
|
55df87b23ed27f40b90001e5
|
[
"Algorithms",
"Mathematics",
"Puzzles"
] |
https://www.codewars.com/kata/55df87b23ed27f40b90001e5
|
3 kyu
|
In a grid of 7 by 7 squares you want to place a skyscraper in each square with only some clues:
* The height of the skyscrapers is between 1 and 7
* No two skyscrapers in a row or column may have the same number of floors
* A clue is the number of skyscrapers that you can see in a row or column from the outside
* Higher skyscrapers block the view of lower skyscrapers located behind them
Can you write a program that can solve this puzzle in time?
This kata is based on [4 By 4 Skyscrapers](https://www.codewars.com/kata/4-by-4-skyscrapers/) and [6 By 6 Skyscrapers](https://www.codewars.com/kata/6-by-6-skyscrapers/) by [FrankK](https://www.codewars.com/users/FrankK). By now, examples should be superfluous; you should really solve Frank's kata first, and then probably optimise some more. A naive solution that solved a 4×4 puzzle within 12 seconds might need time somewhere beyond the Heat Death of the Universe for this size. It's quite bad.
# Task
Create
```go
func SolvePuzzle(clues []int) [][]int {}
```
```javascript
function solvePuzzle(clues)
```
```coffeescript
solvePuzzle = (clues) ->
```
```python
def solve_puzzle(clues)
```
```c
int **SolvePuzzle(int *clues);
```
```cpp
std::vector<std::vector<int>> SolvePuzzle(const std::vector<int> &clues);
```
```csharp
public static int[][] SolvePuzzle(int[] clues)
```
```ruby
def solve_puzzle(clues)
```
```java
Skyscrapers.solvePuzzle(int[] clues)
```
```clojure
(defn solve-puzzle [clues] )
```
```fsharp
solvePuzzle (clues :int[]) : int[][]
```
```erlang
solvePuzzle(Clues)
```
```kotlin
Skyscrapers.solvePuzzle(IntArray clues): Array<IntArray>
```
```elixir
PuzzleSolver.solve(clues)
```
```if:go
Clues are passed in as a slice of integers `[]int`.
The return value is a slice of slice of integers `[][]int`.
```
```if:javascript
Clues are passed in as an `Array(28)` of `integers`.
The return value is an `Array(7)` of `Array(7)` of `integers`.
```
```if:coffeescript
Clues are passed in as an `Array(28)` of `integers`.
The return value is an `Array(7)` of `Array(7)` of `integers`.
```
```if:python
Clues are passed in as a `list(28)` of `integers`.
The return value is a `list(7)` of `list(7)` of `integers`.
```
```if:c
Clues are passed in as an `int[28]`.
The return value is an `int[7][7]`.
```
```if:cpp
Clues are passed in as a `const std::vector<int> &`.
The return value is a `std::vector<std::vector<int>>`.
```
```if:csharp
Clues are passed in as an `int[28]`.
The return value is an `int[7][7]`.
```
```if:ruby
Clues are passed in as an `Array(28)` of `integers`.
The return value is an `Array(7)` of `Array(7)` of `integers`.
```
```if:java
Clues are passed in as an `int[28]` array.
The return value is an `int[7][7]` array of arrays.
```
```if:clojure
Clues are passed in as a `vector[28]` of `ints`
The return value is a `vector[7]` of `vector[7]` of `ints`
```
```if:fsharp
Clues are passed in as an int[] array.
The return value is an array of arrays of ints (int[][]).
```
```if:erlang
Clues are passed in as a list of ints.
The return value is a list of lists of ints.
```
```if:kotlin
Clues are passed in as an IntArray.
The return value is an Array of IntArray.
```
```if:elixir
Clues are passed in as a list of ints.
The return value is a list of lists of ints.
```
All puzzles have one possible solution.
All this is the same as with the earlier kata.
Caveat: The tests for this kata have been tailored to run in ~10 seconds with the JavaScript reference solution. You'll need to do _better_ than that! Please note the `performance` tag.
[Conceptis Puzzles](http://www.conceptispuzzles.com/) have [heaps of these puzzles](http://www.conceptispuzzles.com/index.aspx?uri=puzzle/skyscrapers), from 4×4 up to 7×7 and unsolvable within CodeWars time constraints. Old puzzles from there were used for the tests. They also have lots of other logic, numbers and mathematical puzzles, and their puzzle user interface is generally nice, very nice.
|
algorithms
|
N = 7
perms = {i: set() for i in range(0, N + 1)}
for row in __import__('itertools'). permutations(range(1, N + 1), N):
c, s = 0, 0
for h in row:
if h > c:
c, s = h, s + 1
perms[0]. add(row)
perms[s]. add(row)
def solve_puzzle(clues):
rows = [perms[r] & {p[:: - 1] for p in perms[l]}
for (r, l) in zip(clues[N * 4 - 1: N * 3 - 1: - 1], clues[N: N * 2])]
cols = [perms[t] & {p[:: - 1] for p in perms[b]}
for (t, b) in zip(clues[0: N], clues[N * 3 - 1: N * 2 - 1: - 1])]
for _ in range(N * N / / 2):
for r_i in range(N):
for c_i in range(N):
common = {r[c_i] for r in rows[r_i]} & {c[r_i] for c in cols[c_i]}
rows[r_i], cols[c_i] = [r for r in rows[r_i] if r[c_i] in common], [
c for c in cols[c_i] if c[r_i] in common]
for rows1 in __import__('itertools'). product(* rows):
if all(tuple(r[i] for r in rows1) in cols[i] for i in range(N)):
return list(list(r) for r in rows1)
|
7×7 Skyscrapers
|
5917a2205ffc30ec3a0000a8
|
[
"Algorithms",
"Games",
"Performance"
] |
https://www.codewars.com/kata/5917a2205ffc30ec3a0000a8
|
1 kyu
|
<style type="text/css">
table, tr, td {
border: 0px;
}
</style>
In a grid of 6 by 6 squares you want to place a skyscraper in each square with only some clues:
<ul>
<li>The height of the skyscrapers is between 1 and 6</li>
<li>No two skyscrapers in a row or column may have the same number of floors</li>
<li>A clue is the number of skyscrapers that you can see in a row or column from the outside</li>
<li>Higher skyscrapers block the view of lower skyscrapers located behind them</li>
</ul>
<br>
Can you write a program that can solve each 6 by 6 puzzle?
<br>
<br>
<b style="font-size:16px">Example:</b>
<br>
<br>
To understand how the puzzle works, this is an example of a row with 2 clues. Seen from the left there are 6 buildings visible while seen from the right side only 1:
<br>
<br>
<table style="width: 276px">
<tr>
<td style="text-align:center;height:16px;"> 6</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center;height:16px;"> 1</td>
</tr>
</table>
<br>
There is only one way in which the skyscrapers can be placed. From left-to-right all six buildings must be visible and no building may hide behind another building:
<br>
<br>
<table style="width: 276px">
<tr>
<td style="text-align:center;height:16px;"> 6</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 1</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 2</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 3</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 4</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 5</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 6</td>
<td style="text-align:center;height:16px;"> 1</td>
</tr>
</table>
<br>
Example of a 6 by 6 puzzle with the solution:
<br>
<br>
<table style="width: 276px">
<tr>
<td style="text-align:center; border: 0px;height:16px;"> </td>
<td style="text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;"> 2</td>
<td style="text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;"> 2</td>
<td style="text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: 0px;height:16px;"> </td>
</tr>
<tr>
<td style="text-align:center; border: 0px;height:16px;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: 0px;height:16px;"> </td>
</tr>
<tr>
<td style="text-align:center; border: 0px;height:16px;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: 0px;height:16px;"> </td>
</tr>
<tr>
<td style="text-align:center; border: 0px;height:16px;"> 3</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: 0px;height:16px;"> </td>
</tr>
<tr>
<td style="text-align:center; border: 0px;height:16px;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: 0px;height:16px;"> 6</td>
</tr>
<tr>
<td style="text-align:center; border: 0px;height:16px;"> 4</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: 0px;height:16px;"> 3</td>
</tr>
<tr>
<td style="text-align:center; border: 0px;height:16px;"> 4</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: 0px;height:16px;"> </td>
</tr>
<tr>
<td style="text-align:center; border: 0px;height:16px;"> </td>
<td style="height:16px;"> </td>
<td style="height:16px;"> </td>
<td style="height:16px;"> </td>
<td style="height:16px;"> </td>
<td style="text-align:center;height:16px;"> 4</td>
<td style="height:16px;"> </td>
<td style="text-align:center; border: 0px;height:16px;"> </td>
</tr>
</table>
<br>
<table style="width: 276px">
<tr>
<td style="text-align:center; border: 0px;height:16px;"> </td>
<td style="text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;"> 2</td>
<td style="text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;"> 2</td>
<td style="text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: 0px;height:16px;"> </td>
</tr>
<tr>
<td style="text-align:center; border: 0px;height:16px;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 5</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 6</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 1</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 4</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 3</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 2</td>
<td style="text-align:center; border: 0px;height:16px;"> </td>
</tr>
<tr>
<td style="text-align:center; border: 0px;height:16px;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 4</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 1</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 3</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 2</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 6</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 5</td>
<td style="text-align:center; border: 0px;height:16px;"> </td>
</tr>
<tr>
<td style="text-align:center; border: 0px;height:16px;"> 3</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 2</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 3</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 6</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 1</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 5</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 4</td>
<td style="text-align:center; border: 0px;height:16px;"> </td>
</tr>
<tr>
<td style="text-align:center; border: 0px;height:16px;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 6</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 5</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 4</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 3</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 2</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 1</td>
<td style="text-align:center; border: 0px;height:16px;"> 6</td>
</tr>
<tr>
<td style="text-align:center; border: 0px;height:16px;"> 4</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 1</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 2</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 5</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 6</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 4</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 3</td>
<td style="text-align:center; border: 0px;height:16px;"> 3</td>
</tr>
<tr>
<td style="text-align:center; border: 0px;height:16px;"> 4</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 3</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 4</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 2</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 5</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 1</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> 6</td>
<td style="text-align:center; border: 0px;height:16px;"> </td>
</tr>
<tr>
<td style="text-align:center; border: 0px;height:16px;"> </td>
<td style="height:16px;"> </td>
<td style="height:16px;"> </td>
<td style="height:16px;"> </td>
<td style="height:16px;"> </td>
<td style="text-align:center;height:16px;"> 4</td>
<td style="height:16px;"> </td>
<td style="text-align:center; border: 0px;height:16px;"> </td>
</tr>
</table>
<br>
<b style="font-size:16px">Task:</b>
<br>
<br>
<ul>
<li>Finish:</li>
</ul>
```javascript
function solvePuzzle(clues)
```
```csharp
public static int[][] SolvePuzzle(int[] clues)
```
```java
public static int[][] solvePuzzle(int[] clues)
```
```c
int **SolvePuzzle(int *clues);
```
```cpp
std::vector<std::vector<int>> SolvePuzzle(const std::vector<int> &clues);
```
```clojure
(defn solve-puzzle [clues])
```
```fsharp
solvePuzzle (clues : int[]) : int[][]
```
<ul>
<li>
Pass the clues in an array of 24 items. The clues are in the array around the clock. Index:
<br>
<table style="width: 276px">
<tr>
<td style="text-align:center; border: 0px;height:16px;"> </td>
<td style="text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;"> 0</td>
<td style="text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;"> 1</td>
<td style="text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;"> 2</td>
<td style="text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;"> 3</td>
<td style="text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;"> 4</td>
<td style="text-align:center; border-bottom: solid 1px;height:16px;border-color:gray;"> 5</td>
<td style="text-align:center; border: 0px;height:16px;"> </td>
</tr>
<tr>
<td style="text-align:center; border: 0px;height:16px;"> 23</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: 0px;height:16px;"> 6</td>
</tr>
<tr>
<td style="text-align:center; border: 0px;height:16px;"> 22</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: 0px;height:16px;"> 7</td>
</tr>
<tr>
<td style="text-align:center; border: 0px;height:16px;"> 21</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: 0px;height:16px;"> 8</td>
</tr>
<tr>
<td style="text-align:center; border: 0px;height:16px;"> 20</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: 0px;height:16px;"> 9</td>
</tr>
<tr>
<td style="text-align:center; border: 0px;height:16px;"> 19</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: 0px;height:16px;"> 10</td>
</tr>
<tr>
<td style="text-align:center; border: 0px;height:16px;"> 18</td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: solid 1px;height:16px;border-color:gray;"> </td>
<td style="text-align:center; border: 0px;height:16px;"> 11</td>
</tr>
<tr>
<td style="text-align:center; border: 0px;height:16px;"> </td>
<td style="text-align:center;'height:16px;'">17</td>
<td style="text-align:center;height:16px;">16</td>
<td style="text-align:center;height:16px;">15</td>
<td style="text-align:center;height:16px;">14</td>
<td style="text-align:center;height:16px;">13</td>
<td style="text-align:center;height:16px;">12</td>
<td style="text-align:center; border: 0px;height:16px;"> </td>
</tr>
</table>
</li>
<li>If no clue is available, add value `0`</li>
<li>Each puzzle has only one possible solution</li>
<li>`SolvePuzzle()` returns matrix `int[][]`. The first indexer is for the row, the second indexer for the column. Python returns a 6-tuple of 6-tuples, Ruby a 6-Array of 6-Arrays.</li>
</ul>
|
games
|
from itertools import permutations
def solve_puzzle(clues):
size = 6
variants = {i: set() for i in range(size + 1)}
for row in permutations(range(1, size + 1)):
visible = sum(v >= max(row[: i + 1]) for i, v in enumerate(row))
variants[visible]. add(row)
variants[0]. add(row)
possible_cols, possible_rows = [], []
for i in range(size):
clue_left, clue_right = clues[4 * size - 1 - i], clues[size + i]
var_left = variants[clue_left]
var_right = set(map(lambda row: tuple(
reversed(row)), variants[clue_right]))
possible_rows . append(var_left . intersection(var_right))
clue_top, clue_btm = clues[i], clues[3 * size - 1 - i]
var_top = variants[clue_top]
var_btm = set(map(lambda row: tuple(reversed(row)), variants[clue_btm]))
possible_cols . append(var_top . intersection(var_btm))
while any(len(var_row) > 1 for var_row in possible_rows):
for i in range(size):
for j in range(size):
row_set = set(row[j] for row in possible_rows[i])
col_set = set(col[i] for col in possible_cols[j])
union_set = row_set . intersection(col_set)
possible_rows[i] = [row for row in possible_rows[i] if row[j] in union_set]
possible_cols[j] = [col for col in possible_cols[j] if col[i] in union_set]
return tuple(row[0] for row in possible_rows)
|
6 By 6 Skyscrapers
|
5679d5a3f2272011d700000d
|
[
"Mathematics",
"Puzzles",
"Games",
"Arrays",
"Matrix",
"Algorithms"
] |
https://www.codewars.com/kata/5679d5a3f2272011d700000d
|
2 kyu
|
Create a function that finds the largest <a href="https://en.wikipedia.org/wiki/Palindromic_number" target="_blank">palindromic number</a> made from the product of **at least 2** of the given arguments.
### Notes
* Only non-negative numbers will be given in the argument
* You don't need to use all the digits of the products
* Single digit numbers are considered palindromes
* Optimization is needed: dealing with ones and zeros in a smart way will help a lot
<!--
This kata is quite demanding, as you will need to manage all possible combinations to get products, **then** use all or some of the digits of each product to get the largest palindrome: as you can easily guess, the computing time can easily grow exponentially, so you will need to work on optimization to be able to make it in the alloted time.
-->
## Examples
```
[937, 113] --> 81518
```
As `937 * 113 = 105881` and the largest palindromic number that can be arranged from the digits of result is: `81518`
Another one:
```
[57, 62, 23] --> 82128
product palindrome
57 * 62 = 3534 --> 353
57 * 23 = 1311 --> 131
62 * 23 = 1426 --> 6
57 * 62 * 23 = 81282 --> 82128
```
One more:
```
[15, 125, 8] --> 8
product palindrome
15 * 125 = 1875 --> 8
15 * 8 = 120 --> 2
125 * 8 = 1000 --> 1
15 * 125 * 8 = 15000 --> 5
```
|
algorithms
|
from collections import Counter
from itertools import combinations
from functools import reduce
from operator import mul
def best_pal(array):
outside, inside = [], ''
for k, v in Counter(array). items():
if v > 1:
outside . append(k * (v / / 2))
if v % 2:
inside = max(inside, k)
outside = '' . join(sorted(outside))
if outside and outside[- 1] == '0':
outside = ''
return int('' . join(outside[:: - 1] + inside + outside))
def numeric_palindrome(* args):
args = list(filter(None, args))
if len(args) < 2:
return 0
if 1 in args:
args = list(filter(lambda x: x > 1, args)) + [1]
if len(args) == 1:
return best_pal(str(args[0]))
return max(best_pal(str(reduce(mul, test))) for i in range(2, len(args) + 1) for test in combinations(args, i))
|
Largest Numeric Palindrome
|
556f4a5baa4ea7afa1000046
|
[
"Algorithms",
"Performance"
] |
https://www.codewars.com/kata/556f4a5baa4ea7afa1000046
|
4 kyu
|
Your task in this Kata is to emulate text justification in monospace font. You will be given a single-lined text and the expected justification width. The longest word will never be greater than this width.
Here are the rules:
* Use spaces to fill in the gaps between words.
* Each line should contain as many words as possible.
* Use '\n' to separate lines.
* Gap between words can't differ by more than one space.
* Lines should end with a word not a space.
* '\n' is not included in the length of a line.
* Large gaps go first, then smaller ones ('Lorem--ipsum--dolor--sit-amet,' (2, 2, 2, 1 spaces)).
* Last line should not be justified, use only one space between words.
* Last line should not contain '\n'
* Strings with one word do not need gaps ('somelongword\n').
Example with width=30:
```
Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Vestibulum sagittis dolor
mauris, at elementum ligula
tempor eget. In quis rhoncus
nunc, at aliquet orci. Fusce
at dolor sit amet felis
suscipit tristique. Nam a
imperdiet tellus. Nulla eu
vestibulum urna. Vivamus
tincidunt suscipit enim, nec
ultrices nisi volutpat ac.
Maecenas sit amet lacinia
arcu, non dictum justo. Donec
sed quam vel risus faucibus
euismod. Suspendisse rhoncus
rhoncus felis at fermentum.
Donec lorem magna, ultricies a
nunc sit amet, blandit
fringilla nunc. In vestibulum
velit ac felis rhoncus
pellentesque. Mauris at tellus
enim. Aliquam eleifend tempus
dapibus. Pellentesque commodo,
nisi sit amet hendrerit
fringilla, ante odio porta
lacus, ut elementum justo
nulla et dolor.
```
Also you can always take a look at how justification works in your text editor or directly in HTML (css: text-align: justify).
Have fun :)
|
algorithms
|
def justify(text, width):
'''
Iterates through text, calculating 'n' words at a time that would fit in a line.
Caluculates 'extra' remaining characters that would fit and spreads them throughout the line.
'''
text = text . split()
lengths = [len(word) for word in text]
output = '' # end output of text
while text:
line_output = '' # output of text for each line
n = 1 # number of words in line
while sum(lengths[0: n + 1]) + n <= width and n < len(text):
n += 1 # adds more words to line if they would fit and if its not the last word
extra = width - (sum(lengths[0: n])) # remaining space in line
# list of words in line, pop used to remove them from text
line = [text . pop(0) for _ in range(n)]
del lengths[0: n] # deletes lengths of used words
line_output += line[0] # adds the first word in line
if len(line) > 1 and text:
base_space = extra / / (len(line) - 1) # minimum space between words
n_extra_space = extra % (len(line) - 1) # number of words with extra space
# list with spaces between each word in order
spaces = [' ' * base_space if space >= n_extra_space
else ' ' * (base_space + 1) for space in range(len(line) - 1)]
for i, space in enumerate(spaces):
# adds remaining words with space in between them
line_output += space + line[i + 1]
elif len(line) > 1:
line_output = ' ' . join(line) # if last line, spacing is normal
if text:
line_output += '\n' # if not last line, add '\n' to end of line
output += line_output
return output
|
Text align justify
|
537e18b6147aa838f600001b
|
[
"Strings",
"Algorithms"
] |
https://www.codewars.com/kata/537e18b6147aa838f600001b
|
4 kyu
|
# Task
A newspaper is published in Walrusland. Its heading is `s1` , it consists of lowercase Latin letters.
Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string.
After that walrus erase several letters from this string in order to get a new word `s2`.
It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.
For example, the heading is `"abc"`. If we take two such headings and glue them one to the other one, we get `"abcabc"`. If we erase the 1st letter("a") and 5th letter("b"), we get a word `"bcac"`.
Given two string `s1` and `s2`, return the least number of newspaper headings `s1`, which Fangy will need to receive the word `s2`. If it is impossible to get the word `s2` in the above-described manner, return `-1`.
# Example
For `s1="abc", s2="bcac"`, the output should be `2`.
```
"abcabc" --> "bcac"
x x
```
For `s1="abc", s2="xyz"`, the output should be `-1`.
It's impossible to get the word `s2`.
|
algorithms
|
import re
def buy_newspaper(s1, s2):
p = re . sub(r"(.)", r"\1?", s1)
return - 1 if set(s2) - set(s1) else len(re . findall(p, s2)) - 1
|
Simple Fun #342: Buy Newspaper
|
596c26187bd547f3a6000050
|
[
"Algorithms"
] |
https://www.codewars.com/kata/596c26187bd547f3a6000050
|
6 kyu
|
For a given chemical formula represented by a string, count the number of atoms of each element contained in the molecule and return an object (associative array in PHP, `Dictionary<string, int>` in C#, Map<String,Integer> in Java).
For example:
```javascript
var water = 'H2O';
parseMolecule(water); // return {H: 2, O: 1}
var magnesiumHydroxide = 'Mg(OH)2';
parseMolecule(magnesiumHydroxide); // return {Mg: 1, O: 2, H: 2}
var fremySalt = 'K4[ON(SO3)2]2';
parseMolecule(fremySalt); // return {K: 4, O: 14, N: 2, S: 4}
```
```php
parse_molecule('H2O'); // => ['H' => 2, 'O' => 1]
parse_molecule('Mg(OH)2'); // => ['Mg' => 1, 'O' => 2, 'H' => 2]
parse_molecule('K4[ON(SO3)2]2'); // => ['K' => 4, 'O' => 14, 'N' => 2, 'S' => 4]
```
```csharp
Kata.ParseMolecule("H2O"); // => new Dictionary<string, int> {{"H", 2}, {"O", 1}}
Kata.ParseMolecule("Mg(OH)2"); // => new Dictionary<string, int> {{"Mg", 1}, {"O", 2}, {"H", 2}}
Kata.ParseMolecule("K4[ON(SO3)2]2"); // => new Dictionary<string, int> {{"K", 4}, {"O", 14}, {"N", 2}, {"S", 4}}
```
```python
water = 'H2O'
parse_molecule(water) # return {H: 2, O: 1}
magnesium_hydroxide = 'Mg(OH)2'
parse_molecule(magnesium_hydroxide) # return {Mg: 1, O: 2, H: 2}
var fremy_salt = 'K4[ON(SO3)2]2'
parse_molecule(fremySalt) # return {K: 4, O: 14, N: 2, S: 4}
```
```haskell
>>> parseMolecule "H2O" -- water
Right [("H",2),("O",1)]
>>> parseMolecule "Mg(OH)2" -- magnesium hydroxide
Right [("Mg",1),("O",2),("H",2)]
>>> parseMolecule "K4[ON(SO3)2]2" -- Fremy's salt
Right [("K",4),("O",14),("N",2),("S",4)]
>>> parseMolecule "pie"
Left "Not a valid molecule"
```
```rust
parse_molecule("H2O"); // water
// Ok([("H", 2), ("O", 1)])
parse_molecule("Mg(OH)2"); // magnesium hydroxide
// Ok([("Mg", 1), ("O", 2), ("H", 2)]
parse_molecule("K4[ON(SO3)2]2"); // Fremy's salt
// Ok([("K", 4), ("O", 14),("N", 2),("S", 4)])
parse_molecule("pie")
// Err(ParseError)
```
```java
String water = "H2O";
parseMolecule.getAtoms(water); // return [H: 2, O: 1]
String magnesiumHydroxide = "Mg(OH)2";
parseMolecule.getAtoms(magnesiumHydroxide); // return ["Mg": 1, "O": 2, "H": 2]
String fremySalt = "K4[ON(SO3)2]2";
parseMolecule.getAtoms(fremySalt); // return ["K": 4, "O": 14, "N": 2, "S": 4]
parseMolecule.getAtoms("pie"); // throw an IllegalArgumentException
```
As you can see, some formulas have brackets in them. The index outside the brackets tells you that you have to multiply count of each atom inside the bracket on this index. For example, in Fe(NO3)2 you have one iron atom, two nitrogen atoms and six oxygen atoms.
Note that brackets may be **round, square or curly** and can also be **nested**. Index after the braces is **optional**.
|
algorithms
|
from collections import Counter
import re
COMPONENT_RE = (
r'('
r'[A-Z][a-z]?'
r'|'
r'\([^(]+\)'
r'|'
r'\[[^[]+\]'
r'|'
r'\{[^}]+\}'
r')'
r'(\d*)'
)
def parse_molecule(formula):
counts = Counter()
for element, count in re . findall(COMPONENT_RE, formula):
count = int(count) if count else 1
if element[0] in '([{':
for k, v in parse_molecule(element[1: - 1]). items():
counts[k] += count * v
else:
counts[element] += count
return counts
|
Molecule to atoms
|
52f831fa9d332c6591000511
|
[
"Parsing",
"Algorithms",
"Strings"
] |
https://www.codewars.com/kata/52f831fa9d332c6591000511
|
5 kyu
|
Given an array of numbers, calculate the largest sum of all possible blocks of consecutive elements within the array. The numbers will be a mix of positive and negative values. If all numbers of the sequence are nonnegative, the answer will be the sum of the entire array. If all numbers in the array are negative, your algorithm should return zero. Similarly, an empty array should result in a zero return from your algorithm.
```
largestSum([-1,-2,-3]) == 0
largestSum([]) == 0
largestSum([1,2,3]) == 6
```
Easy, right? This becomes a lot more interesting with a mix of positive and negative numbers:
```
largestSum([31,-41,59,26,-53,58,97,-93,-23,84]) == 187
```
The largest sum comes from elements in positions 3 through 7:
```59+26+(-53)+58+97 == 187```
Once your algorithm works with these, the test-cases will try your submission with increasingly larger random problem sizes.
|
algorithms
|
def largest_sum(arr):
sum = max_sum = 0
for n in arr:
sum = max(sum + n, 0)
max_sum = max(sum, max_sum)
return max_sum
|
Compute the Largest Sum of all Contiguous Subsequences
|
56001790ac99763af400008c
|
[
"Mathematics",
"Fundamentals",
"Algorithms"
] |
https://www.codewars.com/kata/56001790ac99763af400008c
|
5 kyu
|
Your company **MRE Tech** has hired a spiritual consultant who advised on a
new *Balance* policy: Don't take sides, don't favour, stay in the middle. This
policy even applies to the software where all strings should now be centered.
You are the poor soul to implement it.
# Task
```if-not:c
Implement a function `center` that takes a string `strng`, an integer `width`,
and an optional character `fill` (default: `' '`) and returns a new string of
length `width` where `strng` is centered and on the right and left padded with
`fill`.
```
```if:c
Implement a function `center` that takes a string `strng`, an integer `width`,
and a character `fill` and returns a new string of length `width` where
`strng` is centered and on the right and left padded with `fill`.
```
```python
center(strng, width, fill=' ')
```
```javascript
center(strng, width, fill=' ')
```
```c
char *center(const char *strng, size_t width, char fill)
```
If the left and right padding cannot be of equal length make the padding on the
left side one character longer.
If `strng` is longer than `width` return `strng` unchanged.
# Examples
```python
center('a', 3) # returns " a "
center('abc', 10, '_') # returns "____abc___"
center('abcdefg', 2) # returns "abcdefg"
```
```javascript
center('a', 3) # returns " a "
center('abc', 10, '_') # returns "____abc___"
center('abcdefg', 2) # returns "abcdefg"
```
```c
center("a", 3, ' ') // returns " a "
center("abc", 10, '_') // returns "____abc___"
center("abcdefg", 2, ' ') // returns "abcdefg"
```
```cobol
Center("a", 3, space) => result = " a "
Center("abc", 10, '_') => result = "____abc___"
Center("abcdefg", 2, space) => result = "abcdefg"
```
|
reference
|
def center(strng, width, fill=' '):
width -= len(strng)
right = width / / 2
left = width - right
return "{}{}{}" . format(left * fill, strng, right * fill)
|
"Center yourself", says the monk.
|
596b8a3fc4cb1de46b000001
|
[
"Strings",
"Fundamentals"
] |
https://www.codewars.com/kata/596b8a3fc4cb1de46b000001
|
7 kyu
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.