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 |
---|---|---|---|---|---|---|---|
A number of single men and women are locked together for a longer while in a villa or on an island, for the sake of a TV show. Because they spend quite some time together, all of them seek a partner to date. They are all shallow people, and they only care about looks, aka physical attractiveness when it comes to dating. Looks levels range from 1 to 10.
The unwritten rules for their choice of partner are the following:
* Women never date men below their own looks level
* Women are content with one partner, and when they have it, they don't look for a second man (yeah, I know, but let's assume this for this kata)
* Because women are hypergamous, they never settle for a man who's not at least 2 levels above their own, unless he's an 8 or above (but even then, the first rule applies)
* Men of level 8 or above (aka Chads) try to get 2 women, men below that are content with one
* When women have a choice between two equally glamorous Chads, they prefer the one without a girlfriend
* Both women and men try to get the best looking date(s) they can get
These rules have nothing to do with reality of course.
You'll be given a list of looks levels representing the men, and another list representing the women. Return a list of the looks levels of the men who stay alone, sorted from hideous to handsome. | algorithms | from typing import Tuple
import pandas as pd
class Person:
@ staticmethod
def sort_key(person: 'Person') - > Tuple[int, int]:
# Sort by descending rating and ascending number of pre-allocated partners
return (- person . rating, len(person . partners))
def __init__(self, sex, rating):
self . rating = rating
self . ideal_partners = 1
self . min_rating = 0
self . partners = []
self . fully_allocated = False
if sex == 'M':
if rating >= 8:
self . ideal_partners = 2
else: # sex == 'F'
self . min_rating = rating
if self . min_rating < 8:
self . min_rating = min(self . rating + 2, 8)
def add_partner(self, partner):
self . partners . append(partner)
if len(self . partners) == self . ideal_partners:
self . fully_allocated = True
def guysAloneFromGroup(men, women):
men = sorted([Person('M', m) for m in men], key=Person . sort_key)
women = sorted([Person('W', w) for w in women], key=Person . sort_key)
for w in women:
for m in men:
if m . fully_allocated:
continue
if m . rating >= w . min_rating:
m . add_partner(w)
w . add_partner(m)
men = sorted(men, key=Person . sort_key)
break
return [m . rating for m in men if not m . partners][:: - 1]
| Dating with hypergamy | 5f304fb8785c540016b9a97b | [
"Algorithms"
] | https://www.codewars.com/kata/5f304fb8785c540016b9a97b | 5 kyu |
> **NOTE:** This a harder version of prsaseta's kata [1 Dimensional cellular automata](https://www.codewars.com/kata/5e52946a698ef0003252b526). If you are unable to solve this, you may catch the gist of the task with that one!
# Basic idea of (1D) cellular automata
Imagine we have a list of ones and zeros:
```
1 0 1 0 1 1 0 1 0
```
If we define some rules, we can apply tranformations to these lists. These rules will also be lists of ones and zeros, but **they must be of odd length**. To transform the list one time, we slide it from start to end and assign the new elements using the following rules:
* If every element of the rule matches the one just below it, then **the central element is assigned a 1**.
* If any element is different from the one below it, then **the central element is assigned a 0**.
* The list **wraps around if the index is out of bounds**.
Let's see an example:
```
rule: 0 1 0
list: 1 0 1 0 1 1 0 1 0
1
0 1 0
0 1 0 1 0 1 1 0 1 0 [The first zero wraps from the end of the list]
^
1 0
0 1 0
1 0 1 0 1 1 0 1 0
^
1 0 1
0 1 0
1 0 1 0 1 1 0 1 0
^
1 0 1 0
0 1 0
1 0 1 0 1 1 0 1 0
^
...
Final result: 1 0 1 0 0 0 0 1 0
```
Now, if we have more than one rule, we apply every rule at every position and we assign a 1 if **any rule gives a one**. In any other case, we put a 0. When the whole list has been applied all rules, we say that we made **a transformation**.
# 2D Automata
To generalize this, we substitute both the rules and the list by 2D matrices of ones and zeros (neither of them have to be square, but they will have odd dimensions):
```
0 0 1
1 1 0
0 1 0
```
The idea to apply the rules is exactly the same, but we use a matrix instead. We slide the rule to every position and use the exact same logic! (For the mathematically oriented people, this is a [non-linear convolutional filter](https://en.wikipedia.org/wiki/Kernel_(image_processing)))
Let's see a simple example:
```
0 0 0 0
1 1 1 0
0 0 1 0
rules: 0 0 0 [1 row x 3 columns for simplicity]
```
We *slide* the rule like this:
```
...
* * * 0
1 1 1 0 => They match, gives 1
0 0 1 0
0 * * *
1 1 1 0 => They match, gives 1
0 0 1 0
...
0 0 0 0
1 1 1 0 => They match, gives 1 [Notice the wrap, the center is on the lower left corner]
* * 1 *
0 0 0 0
1 1 1 0 => They don't match, gives 0
* * * 0
```
Sliding all the positions gives us:
```
1 1 1 1
0 0 0 0
1 0 0 0
```
This gives an idea of how these rules are applied. **note that rules cannot be rotated**.
# Your task
Implement a function ```evolve(matrix: List[List[bool]], rules: List[List[List[bool]]], steps: int)``` that uses ```rules``` to transform ```matrix``` ```steps``` times. Be careful, you only have 240 characters to accomplish this task ;)
```if:python
Note that the use of walrus operator is forbidden (because this kata was created before python 3.8)
```
*Technical notes:*
* Both the matrix and the rules are **row-based**. They represent a list of rows, not a list of columns.
* You **can** mutate the input matrices, but it is not necessary.
*Personal best: 234 characters*
**Good luck :D** | algorithms | import numpy
import scipy . ndimage as i
a = numpy . array
evolve = e = lambda M, R, s: s and e(a([a(r). size == i . correlate(
2 * a(M) - 1, 2 * a(r) - 1, int, 'wrap') for r in R]). any(0). tolist(), R, s - 1) or M
| 2D Cellular Automata [Code Golf] | 5e8886a24475de0032695b9e | [
"Mathematics",
"Restricted",
"Algorithms",
"Cellular Automata"
] | https://www.codewars.com/kata/5e8886a24475de0032695b9e | 5 kyu |
## What is an ASCII Art?
ASCII Art is art made of basic letters and symbols found in the ascii character set.
### Example of ASCII Art (by Joan Stark)
```
_ _ / _
(')-=-(') __|_ {_}
__( " )__ |____| |(|
/ _/'-----'\_ \ | | |=|
___\\ \\ // //___ | | / \
(____)/_\---/_\(____) \____/ |.--|
|| |
|| | . ' .
|'--| ' \~~~/
'-=-' \~~~/ \_/
\_/ Y
Y _|_
_|_
```
## Your Goal
Write a function that takes in:
- The size of the bus
- The speed of the bus
- The number of frames for the animation
- The size for how big a frame will be per line
The output should be a single multi-line string, each frame being seperated by `frame size` number of dashes and a newline character.
### How to Make the Bus
This is the base shape of the bus (when `size = 1`):
```
_____________
| | | | \
|___|____|_|___\
| | | \
`--(o)(o)--(o)--'
```
With each increase in size, an additional middle section is added. Here are the example for `size = 2` and `size = 3` respectively:
```
__________________
| | | | | \
|___|____|____|_|___\
| | | \
`--(o)(o)-------(o)--'
_______________________
| | | | | | \
|___|____|____|____|_|___\
| | | \
`--(o)(o)------------(o)--'
```
### How to Make the Animation
- Each iteration of the frames should make the bus "move forward" by `bus speed` spaces.
- Each line of a frame should always be the size of `frame size`, if the generated frame is more narrow than that, fill the ends of the lines with spaces. If it is wider, cut the characters exceeding the frame's lines.
### Technicalities
- Buses will never have a size less than 1
- Buses will never have a speed less than 0
- New line characters will not count as part of the `frame size`
### Solution Examples
#### Example #1
`bus size = 1, bus speed = 2, frame count = 5, frame size = 20`
```
_____________
| | | | \
|___|____|_|___\
| | | \
`--(o)(o)--(o)--'
--------------------
_____________
| | | | \
|___|____|_|___\
| | | \
`--(o)(o)--(o)--'
--------------------
_____________
| | | | \
|___|____|_|___\
| | |
`--(o)(o)--(o)--
--------------------
_____________
| | | |
|___|____|_|__
| | |
`--(o)(o)--(o)
--------------------
___________
| | | |
|___|____|_|
| | |
`--(o)(o)--(
```
#### Example #2
`bus size = 3, bus speed = 5, frame count = 4, frame size = 35`
```
_______________________
| | | | | | \
|___|____|____|____|_|___\
| | | \
`--(o)(o)------------(o)--'
-----------------------------------
_______________________
| | | | | | \
|___|____|____|____|_|___\
| | | \
`--(o)(o)------------(o)--'
-----------------------------------
_______________________
| | | | | | \
|___|____|____|____|_|___
| | |
`--(o)(o)------------(o)-
-----------------------------------
___________________
| | | | |
|___|____|____|____|
| |
`--(o)(o)-----------
```
#### Example #3
`bus size = 2, bus speed = 0, frame count = 5, frame size = 25`
```
__________________
| | | | | \
|___|____|____|_|___\
| | | \
`--(o)(o)-------(o)--'
-------------------------
__________________
| | | | | \
|___|____|____|_|___\
| | | \
`--(o)(o)-------(o)--'
-------------------------
__________________
| | | | | \
|___|____|____|_|___\
| | | \
`--(o)(o)-------(o)--'
-------------------------
__________________
| | | | | \
|___|____|____|_|___\
| | | \
`--(o)(o)-------(o)--'
-------------------------
__________________
| | | | | \
|___|____|____|_|___\
| | | \
`--(o)(o)-------(o)--'
``` | games | def bus_animation(bn, bs, fc, fs):
b = ['' . join(x[0] + x[1] * (bn - 1) + x[2]) + ' ' * (fs - 17 - 5 * (bn - 1)) for x in [
[' ________', '_____', '_____ '],
['| | ', '| ', '| | \ '],
['|___|____', '|____', '|_|___\ '],
['| ', ' ', '| | \\'],
['`--(o)(o)', '-----', "--(o)--'"]
]]
return f"\n { ' ' * fs } \n { '-' * fs } \n" . join('\n' . join((' ' * i * bs + x)[: fs] for x in b) for i in range(fc))
| Bus ASCII-Art Animation | 61db0b0d5b4a78000ef34d1f | [
"ASCII Art",
"Puzzles"
] | https://www.codewars.com/kata/61db0b0d5b4a78000ef34d1f | 6 kyu |
## Task
Consider an n-th-degree polynomial with integer coefficients:
```math
x^n + a_1*x^{n-1} + ... + a_{n-1}*x + a_n
```
Let's call this polynomial compact if it has only **integer** roots which are **non-repeating** and **non-zero** and `$|a_n|$` is minimal.
Your task is to ο¬nd the maximum and minimum values of `$a_1$` in the compact polynomial.
You're given the degree of the polynomial: `$n$` `$(1β€nβ€10^{18})$`.
```if:python
Return a `tuple` (min, max).
```
```if:cpp
Return a `pair<long long, long long>` {min, max}.
```
```if:c
Assign the correct values to the min and max pointers.
```
#### Note
Test feedback is minimal as part of this puzzle.
## Examples
```if:python
``first_coefficient(1) => (-1, 1)``
```
```if:cpp
``first_coefficient(1) => {-1, 1}``
```
```if:c
``first_coefficient(1, &a, &b) => a := -1; b := 1``
```
| games | def first_coefficient(n): return (k: = n % 2 * ~ n >> 1, - k)
| Compact polynomial | 61daff6b2fdc2a004328ffe4 | [
"Fundamentals",
"Puzzles",
"Mathematics"
] | https://www.codewars.com/kata/61daff6b2fdc2a004328ffe4 | 6 kyu |
# Task
You are given an array `a` of positive integers and an intger `k`. You may choose some integer `X` and update `a` several times, where to update means to perform the following operations:
```
pick a contiguous subarray of length not greater than the given k;
replace all elements in the picked subarray with the chosen X.
```
What is the minimum number of updates required to make all the elements of the array the same?
# Example
For `a = [1, 2, 2, 1, 2, 1, 2, 2, 2, 1, 1, 1] and k = 2`, the output should be `4`.
Here's how a will look like after each update:
```
[1, 2, 2, 1, 2, 1, 2, 2, 2, 1, 1, 1] ->
[1, 1, 1, 1, 2, 1, 2, 2, 2, 1, 1, 1] ->
[1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1] ->
[1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1] ->
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
```
# Input/Output
- `[input]` integer array `a`
An array of positive integers.
Constraints:
`10 β€ a.length β€ 50,`
`1 β€ a[i] β€ 10.`
- `[input]` integer `k`
A positive integer, the maximum length of a subarray.
Constraints: `2 β€ k β€ 9.`
- `[output]` an integer
The minimum number of updates. | games | def array_equalization(a, k):
totals, ends = {}, {}
for i, n in enumerate(a):
if n not in ends:
totals[n], ends[n] = 0, - 1
if i < ends[n]:
continue
count = (i - ends[n] - 1 + k - 1) / / k
totals[n] += count
ends[n] = max(i, ends[n] + count * k)
return min(t + (len(a) - ends[n] - 1 + k - 1) / / k
for n, t in totals . items() if ends[n] < len(a))
| Simple Fun #125: Array Equalization | 58a3c836623e8c72eb000188 | [
"Puzzles"
] | https://www.codewars.com/kata/58a3c836623e8c72eb000188 | 5 kyu |
[The Vigenère cipher](https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher) is a classic cipher that was thought to be "unbreakable" for three centuries. We now know that this is not so and it can actually be broken pretty easily.
**How the Vigenère cipher works**:
The basic concept is that you have a `message` and a `key`, and each character in the `message` is encrypted using a character in the `key`, by applying a Caesar shift. The key is recycled as many times as needed.
You might want to try [this kata](https://www.codewars.com/kata/vigenere-cipher-helper) first, which focuses on the encryption and decryption processes.
## Well how do we break it?
The first thing we have to do is determine the **length of the key** that was used to encrypt the message.
Write a function that takes some cipher text and a maximum possible key length and returns the length of the key that was used in the encryption process.
**Note:** We don't care about what characters are in the key -- only how many of them there are.
---
Any feedback (and suggestions) would be much appreciated
*This kata is based on one of the programming assignments in [Prof. Jonathan Katz's course on cryptography](https://www.coursera.org/course/cryptography) given on Coursera* | algorithms | def get_key_length(cipher_text, max_key_length):
# count the occurences where there is a match when shifting the sequence by a offset
offsets = [len([d for d in zip(cipher_text, cipher_text[offset:]) if d[0] == d[1]])
for offset in range(1, max_key_length)]
# get the offset that generated the most matches
return offsets . index(max(offsets)) + 1
| Cracking the Vigenère cipher, step 1: determining key length | 55d6afe3423873eabe000069 | [
"Strings",
"Cryptography",
"Ciphers",
"Algorithms"
] | https://www.codewars.com/kata/55d6afe3423873eabe000069 | 4 kyu |
You are organizing a soccer tournament, so you need to build a matches table.
The tournament is composed by 20 teams. It is a round-robin tournament (all-play-all), so it has 19 rounds, and each team plays once per round. Each team confront the others once in the tournament (each match does not repeat in the tournament).
~~~if:javascript,csharp
Your mission is to implement a function `buildMatchesTable` that receives the number of teams (always a positive and even number) and returns a matrix.
~~~
~~~if:python,rust
Your mission is to implement a function `build_matches_table` that receives the number of teams (always a positive and even number) and returns a matrix.
~~~
Each line of the matrix represents one round. Each column of the matrix represents one match. The match is represented as an array with two teams. Each team is represented as a number, starting from 1 until the number of teams.
Example:
```javascript
buildMatchesTable(4)
```
```csharp
BuildMatchesTable(4)
```
```python
build_matches_table(4)
```
```rust
build_matches_table(4)
```
```javascript
Should return a matrix like that:
[
[[1,2], [3, 4]], // first round: 1 vs 2, 3 vs 4
[[1,3], [2, 4]], // second round: 1 vs 3, 2 vs 4
[[1,4], [2, 3]] // third round: 1 vs 4, 2 vs 3
]
```
```python
Should return a matrix like this:
[
[(1, 2), (3, 4)], # first round: 1 vs 2, 3 vs 4
[(1, 3), (2, 4)], # second round: 1 vs 3, 2 vs 4
[(1, 4), (2, 3)] # third round: 1 vs 4, 2 vs 3
]
```
```csharp
Should return a matrix of tuples like that:
{
new []{(1,2), (3, 4)}, // first round: 1 vs 2, 3 vs 4
new []{(1,3), (2, 4)}, // second round: 1 vs 3, 2 vs 4
new []{(1,4), (2, 3)} // third round: 1 vs 4, 2 vs 3
}
```
```rust
Should return a matrix like this:
vec![
vec![(1, 2), (3, 4)], // first round: 1 vs 2, 3 vs 4
vec![(1, 3), (2, 4)], // second round: 1 vs 3, 2 vs 4
vec![(1, 4), (2, 3)] // third round: 1 vs 4, 2 vs 3
]
```
You should not care about the order of the teams in the match, nor the order of the matches in the round. You should just care about the rules of the tournament.
Good luck!
```if:javascript
Hint: you may use the preloaded function "printTable" to debug your results.
```
```if:csharp
Hint: you may use the preloaded function "Helper.PrintTable()" to debug your results.
```
```if:python
Hint: you may use the preloaded function `print_table(table)` to debug your results.
```
```if:rust
Hint: you may use the preloaded function `fn print_table(table: &[Vec<(u32, u32)>])` to debug your results.
``` | algorithms | def build_matches_table(t):
teams, ans = [* range(1, t + 1)], []
for _ in range(t - 1):
teams = [teams[0]] + teams[2:] + [teams[1]]
ans += [[(teams[i], teams[t - i - 1]) for i in range(0, t, 2)]]
return ans
| Organize a Round-robin tournament | 561c20edc71c01139000017c | [
"Arrays",
"Logic",
"Algorithms"
] | https://www.codewars.com/kata/561c20edc71c01139000017c | 4 kyu |
I have started studying electronics recently, and I came up with a circuit made up of 2 LEDs and 3 buttons.
Here 's how it works: 2 buttons (`red` and `blue`) are connected to the LEDs (`red` and `blue` respectively). Buttons pressing pattern will be remembered and represented through the LEDs when the third button is pressed.
- Only one LED can blink at a time.
- The LED will only blink once even if the button is held down.
- The button must be released to be pressed again.
- If a button is pressed while the other button is being held down, it will be ignored.
- If two buttons are pressed simultaneously, the red button will be preferred.
- If a button is released while the other is being held down, the other 's LED will blink.
- `0` is up and `1` is down.
- The two inputs will always have the same length.
Here is an example:
```Python
Red: "10011010"
Blue: "10110111"
#=> "RBRB"
Red: "01001000"
Blue: "01011100"
#=> "RB"
Red: "01101000"
Blue: "00111000"
#=> "RB"
```
PS:
This is my first time making a kata, so there may be some errors.
You may report to me if the description is too confusing.
Sorry for my poor grammar.
| games | def button_sequences(seqR, seqB):
pattern, state = '', ''
def toBool(seq): return [i == '1' for i in seq]
for red, blue in zip(toBool(seqR), toBool(seqB)):
if red and state == 'R' or blue and state == 'B':
continue
state = 'R' if red else 'B' if blue else ''
pattern += state
return pattern
| Button sequences | 5bec507e1ab6db71110001fc | [
"Strings",
"Games",
"Puzzles"
] | https://www.codewars.com/kata/5bec507e1ab6db71110001fc | 6 kyu |
#### Task
ISBN stands for International Standard Book Number.
For more than thirty years, ISBNs were 10 digits long. On January 1, 2007 the ISBN system switched to a 13-digit format. Now all ISBNs are 13-digits long. Actually, there is not a huge difference between them. You can convert a 10-digit ISBN to a 13-digit ISBN by adding the prefix number (978) to the beginning and then recalculating the last, check digit using a fairly simple method.
#### Method
1. Take the ISBN *("1-85326-158-0")*.
1. Remove the last character, which can be a number or "X".
1. Add the prefix number (978) and a hyphen (-) to the beginning.
1. Take the 12 digits, then alternately multiply each digit from left to right by 1 or 3.
1. Add up all 12 numbers you got.
1. Take the number and perform a modulo 10 division.
1. If the result is 0, the check digit is 0. If it isn't 0, then subtract the result from 10. In this case, that is the check digit.
1. Add the check digit to the end of the result from step 3.
1. Return the 13-digit ISBN in the appropriate format:
"`prefix number` - `original ISBN except the last character` - `check digit`"
"`978` - `1` - `85326` - `158` - `9`"
#### Example
```
ISBN = "1-85326-158-0"
remove_last_character = "1-85326-158-"
add_prefix = "978-1-85326-158-"
twelve_digits = 978185326158
check_digit = 9*1 + 7*3 + 8*1 + 1*3 + 8*1 + 5*3 + 3*1 + 2*3 + 6*1 + 1*3 + 5*1 + 8*3
= 9 + 21 + 8 + 3 + 8 + 15 + 3 + 6 + 6 + 3 + 5 + 24
= 111
111 % 10 = 1
10 - 1 = 9
thirteen_digit = 9781853261589
return "978-1-85326-158-9"
``` | algorithms | def isbn_converter(isbn):
s = '978' + isbn . replace('-', '')[: - 1]
m = sum(int(d) * (1 + 2 * (i & 1)) for i, d in enumerate(s)) % 10
return f'978- { isbn [: - 1 ] }{ m and 10 - m } '
| Convert ISBN-10 to ISBN-13 | 61ce25e92ca4fb000f689fb0 | [
"Algorithms",
"Regular Expressions",
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/61ce25e92ca4fb000f689fb0 | 6 kyu |
You work at a lock situated on a very busy canal. Boats have queued up at both sides of the lock and your managers are asking for an update on how long it's going to take for all the boats to go through the lock.
Boats are queuing in order and they must go into the lock in that order. Multiple boats can go into the lock at the same time, however they must not exceed the length of the lock. The lock starts empty, and the timer should finish when the lock is down at empty, and all the boats are through. A boat takes its length in minutes to both enter and exit the lock, e.g. a boat of length `4` will take `4` minutes to enter and `4` minutes to leave the lock.
### Notes
* The lock takes `2` minutes to fill and empty each time
* The lock should start and finish at the low end
* No boat will ever be longer than the lock
* The time should be returned in minutes
### Example:
```
low queue = [2, 3, 6, 1]
high queue = [1, 2]
max length = 7
```
* Starting at low end
* Boats `2` and `3` can fit inside the lock - total time is `5` minutes
* The lock fills up - total time is `7` minutes
* Boats `2` and `3` leave the lock - total time is `12` minutes
* Starting at high end
* Boats `1` and `2` enter the lock - total time is `15` minutes
* The lock empties - total time is `17` minutes
* Boats `1` and `2` leave the lock - total time is `20` minutes
* Starting at low end
* Boats `6` and `1` enter the lock - total time is `27` minutes
* The lock fills up - total time is `29` minutes
* Boats `6` and `1` leave the lock - total time is `36` minutes
* Starting at high end
* The lock empties as it must finish empty - total time is `38` minutes | algorithms | def canal_mania(a, b, w):
m = 0
while len(a) + len(b) > 0:
for q in [a, b]:
n = 0
while len(q) and n + q[0] <= w:
n += q . pop(0)
m += 2 * (n + 1)
return m
| Canal Management | 61c1ffd793863e002c1e42b5 | [
"Algorithms"
] | https://www.codewars.com/kata/61c1ffd793863e002c1e42b5 | 6 kyu |
This kata requires you to write a function which merges two strings together. It does so by merging the end of the first string with the start of the second string together when they are an exact match.
```
"abcde" + "cdefgh" => "abcdefgh"
"abaab" + "aabab" => "abaabab"
"abc" + "def" => "abcdef"
"abc" + "abc" => "abc"
```
NOTE: The algorithm should always use the longest possible overlap.
```
"abaabaab" + "aabaabab" would be "abaabaabab" and not "abaabaabaabab"
``` | algorithms | def merge_strings(first, second):
start = 0
stop = len(first)
while True:
if first[start: len(first)] == second[0: stop]:
break
else:
start = start + 1
stop = stop - 1
return first[0: start] + second
| Merge overlapping strings | 61c78b57ee4be50035d28d42 | [
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/61c78b57ee4be50035d28d42 | 7 kyu |
Your task is to implement a ```Miner``` class, which will be used for simulating the mining skill in Runescape. In Runescape, users can click on rocks throughout the game, and if the user has the required mining level, they are able to extract the ore contained in the rock.
In this kata, your ```Miner``` can ```mine``` any of the rocks in the below table, provided they have the required ```level```.
+---------------------------+
| Rock | Level | XP |
+----------------------------
| Clay | 1 | 5 |
| Copper | 1 | 17.5 |
| Tin | 1 | 17.5 |
| Iron | 15 | 35 |
| Silver | 20 | 40 |
| Coal | 30 | 50 |
| Gold | 40 | 65 |
+---------------------------+
Each ```rock``` you mine will grant your ```Miner``` the corresponding amount of experience.
The more experience you gain, the higher your mining level will be. Your mining level is determined by the values in the table below:
+----------------+-----------------+------------------+-----------------+
| Level | XP | Level | XP | Level | XP | Level | XP |
+----------------|-----------------+------------------+-----------------+
| 1 | 0 | 11 | 1358 | 21 | 5018 | 31 | 14833 |
| 2 | 83 | 12 | 1584 | 22 | 5624 | 32 | 16456 |
| 3 | 174 | 13 | 1833 | 23 | 6291 | 33 | 18247 |
| 4 | 276 | 14 | 2107 | 24 | 7028 | 34 | 20224 |
| 5 | 388 | 15 | 2411 | 25 | 7842 | 35 | 22406 |
| 6 | 512 | 16 | 2746 | 26 | 8740 | 36 | 24815 |
| 7 | 650 | 17 | 3115 | 27 | 9730 | 37 | 27473 |
| 8 | 801 | 18 | 3523 | 28 | 10824 | 38 | 30408 |
| 9 | 969 | 19 | 3973 | 29 | 12031 | 39 | 33648 |
| 10 | 1154 | 20 | 4470 | 30 | 13363 | 40 | 37224 |
+----------------+-----------------+------------------+-----------------+
- The rocks table is preloaded in a dictionary called ```ROCKS```. The name of each ```rock``` is a key in the dictionary, and the corresponding value is a tuple of the form (```level```, ```xp```).
- The levels table is preloaded in a dictionary called ```EXPERIENCE```.
To complete this kata, you will need to fill in the ```mine``` method for your ```Miner``` class. ```mine``` takes a single argument as input, ```rock```, which will be the name of a rock in the first table. If you have the required level to mine from the rock, you will gain the corresponding number of experience points.
- If you are too low level to mine the rock, ```mine``` should return ```"You need a mining level of {required_level} to mine {rock_name}."```.
- If you mine the rock, and the experience points gained take you to the next level, ```mine``` should return ```"Congratulations, you just advanced a Mining level! Your mining level is now {new_level}."```
- If you mine the rock, but don't level up, ```mine``` should return ```"You swing your pick at the rock."```
Note:
- All input will be valid.
- Your ```Miner``` may be instantiated with a certain amount of experience, which will always be a positive integer.
- The maximum mining level your ```Miner``` can achieve is 40. Any excess experience points your ```Miner``` gains, or is instantiated with, should not increase your level past 40!
| reference | class Miner:
def __init__(self, exp=0):
self . level = next(i for i in range(40, 0, - 1) if exp >= EXPERIENCE[i])
self . exp = exp
def mine(self, rock):
lvl, exp = ROCKS[rock]
if self . level >= lvl:
self . exp += exp
if self . level < 40 and self . exp >= EXPERIENCE[self . level + 1]:
self . level += 1
return f"Congratulations, you just advanced a Mining level! Your mining level is now { self . level } ."
return "You swing your pick at the rock."
return f"You need a mining level of { lvl } to mine { rock } ."
| Runescape Mining Simulator | 61b09ce998fa63004dd1b0b4 | [
"Fundamentals"
] | https://www.codewars.com/kata/61b09ce998fa63004dd1b0b4 | 6 kyu |
**Context**
You are not sure about what you should name your new kata.
Luckily, your friend TΓ³αΈΏΓ‘Ε has **`$n$`** (`$2β€ n β€20$`) strings (all lowercase latin alphabet characters), **`$s_0, s_1...s_{n-1}$`**, each with a unique, random length between `$1$` and `$10$`, inclusive.
```if:python
IMPORTANT NOTE: For Python, due to time constraints, `$n$` β€ `$15$` will be satisfied for all tests.
```
**Mechanics**
All characters have a "value" being its index in the alphabet ranging from a-z (The value of `a` would be `$1$`, and the value of `z` would be `$26$`). Each string **`$s_i$`** would have a cumulative value that is the sum of its characters' values (`"az"` for example would have value of `$1+26$`, or `$27$`).
You can pick out any number of strings from **`$s$`** and connect them together to form a name.
Example:
If **`$s$`** included the strings `["ab", "cd", "efg"]`,
then `"ab"` and `"efg"` could be selected to form the name: `"abefg"`.
Unfortunately, you have a very specific (and odd) preference of names. Only names with length **`$len$`**, total value **`$tval$`** and **`$tval \leq 10*len$`** would be acceptable. For example, `"abcd"` would be accepted, because `$1+2+3+4 β€ 10*4$`, but `"az"` would not be accepted, since `$1+26 \gt 10*2$`.
**Task**
Return the length of the longest possible acceptable name built from the elements of **`$s$`**. If no acceptable name exists, output `$0$`. | reference | def name(s):
bag = {(0, 0)}
for w in s:
l_, v_ = len(w), sum(bytes(w, 'utf8')) - len(w) * 96
bag |= {(l + l_, v + v_) for l, v in bag}
return max(l for l, v in bag if v <= 10 * l)
| Give your kata a name | 61aa4873f51ce80053a045d3 | [
"Fundamentals"
] | https://www.codewars.com/kata/61aa4873f51ce80053a045d3 | 6 kyu |
Bob has finally found a class that he's interested in -- robotics! He needs help to find out where to put his robot on a table to keep it on the table for the longest.
The size of the table is `n` feet by `m` feet (1 <= n, m <= 10000), and is labeled from 1 to n (top to bottom) and from 1 to m (left to right). Directions are given to the robot as a string consisting of `'U'`, `'D'`, `'L'`, and `'R'`, corresponding to up, down, left, and right respectively, and for each instruction given, the robot moves one foot in the given direction. If the robot moves outside the bounds of the table, it falls off. Your task is to find the coordinates at which the robot must start in order to stay on the table for the longest.
Return your answer as a `tuple`. If there are multiple solutions, return the one with the smallest coordinate values.
Example:
```python3
robot(3, 3, "RRDLUU") => (2, 1)
```
Visual representation:
 | games | def robot(n, m, s):
x, y, xmin, ymin, xmax, ymax = 0, 0, 0, 0, 0, 0
for cur in s:
y += (cur == 'D') - (cur == 'U')
x += (cur == 'R') - (cur == 'L')
xmin = min(xmin, x)
ymin = min(ymin, y)
xmax = max(xmax, x)
ymax = max(ymax, y)
if xmax - xmin + 1 > m or ymax - ymin + 1 > n:
xmin += cur == 'L'
ymin += cur == 'U'
break
return 1 - ymin, 1 - xmin
| Robot on a Table | 61aa487e73debe0008181c46 | [
"Puzzles",
"Performance"
] | https://www.codewars.com/kata/61aa487e73debe0008181c46 | 6 kyu |
Your task is to write a function, called ```format_playlist```, that takes a list of ```songs``` as input.
Each song is a tuple, of the form ```(song_name, duration, artist)```. Your task is to create a string representation of these songs.
Your playlist should be sorted first by the artist, then by the name of the song.
Note:
- All input will be valid.
- The length of the song will be at least 1 minute long, but never 10 minutes or longer. It will be of the form ```m:ss```.
- There will never be empty fields (each song will have a name, duration and artist).
For example, if your function was passed the following ```songs```.
```
songs = [
('In Da Club', '3:13', '50 Cent'),
('Candy Shop', '3:45', '50 Cent'),
('One', '4:36', 'U2'),
('Wicked', '2:53', 'Future'),
('Cellular', '2:58', 'King Krule'),
('The Birthday Party', '4:45', 'The 1975'),
('In The Night Of Wilderness', '5:26', 'Blackmill'),
('Pull Up', '3:35', 'Playboi Carti'),
('Cudi Montage', '3:16', 'KIDS SEE GHOSTS'),
('What Up Gangsta', '2:58', '50 Cent')
]
```
Then your function would return the following:
+----------------------------+------+-----------------+
| Name | Time | Artist |
+----------------------------+------+-----------------+
| Candy Shop | 3:45 | 50 Cent |
| In Da Club | 3:13 | 50 Cent |
| What Up Gangsta | 2:58 | 50 Cent |
| In The Night Of Wilderness | 5:26 | Blackmill |
| Wicked | 2:53 | Future |
| Cudi Montage | 3:16 | KIDS SEE GHOSTS |
| Cellular | 2:58 | King Krule |
| Pull Up | 3:35 | Playboi Carti |
| The Birthday Party | 4:45 | The 1975 |
| One | 4:36 | U2 |
+----------------------------+------+-----------------+
| reference | # Just cleaned it a bit
def format_playlist(songs):
size1 = max((4, * (len(s[0]) for s in songs)))
size2 = max((6, * (len(s[2]) for s in songs)))
border = f"+- { '-' * size1 } -+------+- { '-' * size2 } -+"
def line(
a, b, c): return f"| { a . ljust ( size1 )} | { b . ljust ( 4 )} | { c . ljust ( size2 )} |"
res = []
res . append(border)
res . append(line("Name", "Time", "Artist"))
res . append(border)
for name, duration, artist in sorted(songs, key=lambda k: (k[2], k[0])):
res . append(line(name, duration, artist))
if songs:
res . append(border)
return '\n' . join(res)
| Format the playlist | 61a87854b4ae0b000fe4f36b | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/61a87854b4ae0b000fe4f36b | 6 kyu |
You have an 8-wind compass, like this:

You receive the direction you are `facing` (one of the 8 directions: `N, NE, E, SE, S, SW, W, NW`) and a certain degree to `turn` (a multiple of 45, between -1080 and 1080); positive means clockwise, and negative means counter-clockwise.
Return the direction you will face after the turn.
## Examples
```python
"S", 180 --> "N"
"SE", -45 --> "E"
"W", 495 --> "NE"
```
```haskell
S 180 -> N
SE -45 -> E
W 495 -> NE
```
---
### My other katas
If you enjoyed this kata then please try [my other katas](https://www.codewars.com/users/anter69/authored)! :-)
#### *Translations are welcome!* | algorithms | DIRECTIONS = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']
def direction(facing, turn):
return DIRECTIONS[(turn / / 45 + DIRECTIONS . index(facing)) % 8]
| Turn with a Compass | 61a8c3a9e5a7b9004a48ccc2 | [
"Algorithms"
] | https://www.codewars.com/kata/61a8c3a9e5a7b9004a48ccc2 | 7 kyu |
### Task
Given a number `N`, determine if the sum of `N` ***consecutive numbers*** is odd or even.
- If the sum is definitely an odd number, return `Odd`.
- If the sum is definitely an even number, return `Even`.
- If the sum can be either odd or even ( depending on which first number you choose ), return `Either`.
### Examples
- `Odd_or_Even(1)` should return `Either`, because the sum can be odd or even.
- `Odd_or_Even(6)` should return `Odd`, because `6` consecutive numbers contain `3` odd and `3` even numbers, so their sum is always odd.
- `Odd_or_Even(8)` should return `Even`, because `8` consecutive numbers contain `4` odd and `4` even numbers, so their sum is always even.
~~~if:cpp
### Note
```cpp
enum { Even, Odd, Either };
```
is `Preloaded`.
~~~
~~~if:c
### Note
```c
enum { EVEN, ODD, EITHER };
```
is `Preloaded`.
~~~
~~~if:nasm
### Note
```nasm
%define EVEN 0
%define ODD 1
%define EITHER 2
```
is `Preloaded`.
~~~
~~~if:javascript
### Note
```javascript
const ODD = "Odd";
const EVEN = "Even";
const EITHER = "Either";
```
is `Preloaded`.
~~~
~~~if:haskell
### Note
```haskell
data Parity = EITHER | EVEN | ODD
```
is `Preloaded`.
~~~ | reference | def odd_or_even(n):
return ("Even", "Either", "Odd", "Either")[n % 4]
| Odd or Even? Determine that! | 619f200fd0ff91000eaf4a08 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/619f200fd0ff91000eaf4a08 | 7 kyu |
### Task:
You are given two sorted lists, with distinct elements. Find the maximum path sum while traversing through the lists.
Points to consider for a valid path:
* A path can start from either list, and can finish in either list.
* If there is an element which is present in both lists (regardless of its index in the lists), you can choose to change your path to the other list.
Return only the maximum path sum.
### Example:
```
[0, 2, 3, 7, 10, 12]
[1, 5, 7, 8]
```
Both lists having only 7 as common element, the possible paths would be:
```
0->2->3->7->10->12 => 34
0->2->3->7->8 => 20
1->5->7->8 => 21
1->5->7->10->12 => 35 (maximum path)
```
Hence, the output will be 35 in the example above.
### Notes:
* The arrays may contain no common terms.
* The common element should only be counted once.
* Aim for a linear time complexity.
```if:python
* Range of possible inputs: ` 0 <=len(l1), len(l2) <= 70000`
```
```if:javascript
* Range of possible inputs: ` 0 <=len(l1), len(l2) <= 125000`
``` | reference | def max_sum_path(a, b):
i, j, A, B = 0, 0, 0, 0
while i < len(a) and j < len(b):
x, y = a[i], b[j]
if x == y:
A = B = max(A, B)
if x <= y:
i, A = i + 1, A + x
if x >= y:
j, B = j + 1, B + y
return max(A + sum(a[i:]), B + sum(b[j:]))
| Max sum path | 61a2fcac3411ca0027e71108 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/61a2fcac3411ca0027e71108 | 5 kyu |
Given an integer n, we can construct a new integer with the following procedure:
- For each digit d in n, find the dth prime number. (If d=0, use 1)
- Take the product of these prime numbers. This is our new integer.
For example, take 25:
The 2nd prime is 3, and the 5th is 11. So 25 would evaluate to 3*11 = 33.
If we iterate this procedure, we generate a sequence of integers.
Write a function that, given a positive integer n, returns the maximum value in the sequence starting at n.
```
Example: 8 -> 19 -> 46 -> 91 -> 46 -> 91 -> ...
So the maximum here would be 91.
```
0 <= n <= 10^12 | games | from functools import reduce
PRIMES = [1, 2, 3, 5, 7, 11, 13, 17, 19, 23]
def find_max(n):
s = set()
while n not in s:
s . add(n)
n = reduce(lambda x, d: x * PRIMES[int(d)], str(n), 1)
return max(s)
| Prime Cycles | 5ef1fe9981e07b00015718a8 | [
"Puzzles"
] | https://www.codewars.com/kata/5ef1fe9981e07b00015718a8 | 6 kyu |
# Background
Often times when working with raw tabular data, a common goal is to split the data into groups and perform an aggregation as a way to simplify and draw meaningful conclusions from it. The aggregation function can be anything that reduces the data (sum,mean,standard deviation,etc.). For the purpose of this kata, it will always be the sum function.
# Task
Define a function that accepts two arguments, the first being a list of list that represents the raw data, and the second being a list of column indices. The return value should be a dictionary with the key being the groups as a tuple and the values should be a list containing the aggregated sums.
# Example
```
arr = [
[1, 6, 2, 10],
[8, 9, 4, 11],
[9, 8, 7, 12],
[1, 6, 3, 20],
]
idx = [0, 1]
group(arr, idx) == {
(1, 6): [5, 30], # [2 + 3, 10 + 20]
(8, 9): [4, 11],
(9, 8): [7, 12]
}
```
## Explanation
* Columns `0` and `1` are used for grouping, so columns `2` and `3` will be aggregated
* Rows `0` and `3` are grouped together because they have the same values in columns `idx`, so the columns which are not a part of `idx` are aggregated
* Row `1` and `2` have different values in columns `idx`, so they are not grouped, and the aggregated results will simply be their own values in the columns which are not a part of `idx`
### Notes
- all inputs are valid
- arguments will never be empty | reference | # Not sure why the set the right order without sorting it but eh, it works
def group(arr, idx):
result, idx2 = {}, set(range(len(arr[0]))) - set(idx)
for row in arr:
key = tuple(map(row . __getitem__, idx))
value = map(row . __getitem__, idx2)
result[key] = list(map(int . __add__, result[key], value)
) if key in result else list(value)
return result
| Group-by and Sum | 5ed056c9263d2f001738b791 | [
"Fundamentals"
] | https://www.codewars.com/kata/5ed056c9263d2f001738b791 | 6 kyu |
# Centered pentagonal number
Complete the function that takes an integer and calculates how many dots exist in a pentagonal shape around the center dot on the Nth iteration.
In the image below you can see the first iteration is only a single dot. On the second, there are 6 dots. On the third, there are 16 dots, and on the fourth there are 31 dots.
The sequence is: `1, 6, 16, 31...`

If the input is equal to or less than 0, return `-1`
## Examples
```
1 --> 1
2 --> 6
8 --> 141
0 --> -1
```
```if:python,ruby
#### Note:
Input can reach `10**20`
```
```if:cpp
#### Note:
In the tests cases n can reach `1358187913`
```
```if:c
#### Note:
Input numbers can reach `1920767766`; watch out for integer overflow (it is guaranteeed that the result will fit in a `long long`).
``` | reference | def pentagonal(n):
return 1 + 5 * (n - 1) * n / / 2 if n > 0 else - 1
| Centered pentagonal number: | 5fb856190d5230001d48d721 | [
"Performance",
"Logic",
"Fundamentals"
] | https://www.codewars.com/kata/5fb856190d5230001d48d721 | 7 kyu |
You are given an array of 6-faced dice. Each die is represented by its face up.
Calculate the minimum number of rotations needed to make all faces the same.
`1` will require one rotation to have `2`, `3`, `4` and `5` face up, but would require two rotations to make it the face `6`, as `6` is the opposite side of `1`.
The opposite side of `2` is `5` and `3` is `4`.
## Examples
```
dice = {1, 1, 1, 1, 1, 6} --> 2:
rotate 6 twice to get 1
dice = {1, 2, 3} --> 2:
2 rotations are needed to make all faces either 1, 2, or 3
dice = {3, 3, 3} --> 0:
all faces are already identical
dice = {1, 6, 2, 3} --> 3:
rotate 1, 6 and 3 once to make them all 2
``` | reference | def count_min_rotations(d): return min(
sum((v != i) + (v + i == 7) for v in d) for i in range(1, 7))
| Dice Rotation | 5ff2093d375dca00170057bc | [
"Fundamentals"
] | https://www.codewars.com/kata/5ff2093d375dca00170057bc | 7 kyu |
### Task
You are given a matrix of numbers. In a mountain matrix the absolute difference between two adjecent (orthogonally or diagonally) numbers is not greater than 1. One change consists of increasing a number of the matrix by 1. Your task is to return the mountain matrix that is obtained from the original with the least amount of changes.
### Examples
```
to_mountain([[2, 2, 1, 2],
[1, 0, 2, 1],
[1, 0, 1, 2],
[1, 2, 2, 1]])
# returns: [[2, 2, 1, 2],
# [1, 1, 2, 1],
# [1, 1, 1, 2],
# [1, 2, 2, 1]]
to_mountain([[2, 2, 1, 2],
[1, 0, 2, 1],
[1, 0, 1, 2],
[1, 2, 2, 4]])
# returns: [[2, 2, 1, 2],
# [1, 2, 2, 2],
# [1, 2, 3, 3],
# [1, 2, 3, 4]]
```
### Constraints
* 0 < len(matrix) <= 100
* 0 < len(matrix[0]) <= 100
* 0 <= n <= 1e9 and n is a integer for each number n in the matrix
### Tests
8 fixed tests and 126 random tests | algorithms | def to_mountain(mat):
h, w = len(mat), len(mat[0])
for j in range(h):
for i in range(w):
if j:
mat[j][i] = max(mat[j][i], mat[j - 1][i] - 1)
if i:
mat[j][i] = max(mat[j][i], mat[j][i - 1] - 1)
if j and i:
mat[j][i] = max(mat[j][i], mat[j - 1][i - 1] - 1)
if j and i + 1 < w:
mat[j][i] = max(mat[j][i], mat[j - 1][i + 1] - 1)
if j + 1 < h and i:
mat[j][i] = max(mat[j][i], mat[j + 1][i - 1] - 1)
for j in reversed(range(h)):
for i in reversed(range(w)):
if j + 1 < h:
mat[j][i] = max(mat[j][i], mat[j + 1][i] - 1)
if i + 1 < w:
mat[j][i] = max(mat[j][i], mat[j][i + 1] - 1)
if j + 1 < h and i + 1 < w:
mat[j][i] = max(mat[j][i], mat[j + 1][i + 1] - 1)
if j and i + 1 < w:
mat[j][i] = max(mat[j][i], mat[j - 1][i + 1] - 1)
if j + 1 < h and i:
mat[j][i] = max(mat[j][i], mat[j + 1][i - 1] - 1)
return mat
| Mountain map | 617ae98d26537f000e04a863 | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/617ae98d26537f000e04a863 | 4 kyu |
Due to the popularity of a [similar game](https://www.codewars.com/kata/58c21c4ff130b7cab400009e), a hot new game show has been created and your team has been invited to play!
## The Rules
The game rules are quite simple. The team playing (`n` players) are lined up at decreasing heights, facing forward such that each player can clearly see all the players in front of them, but none behind.
`Red` and `Blue` hats are then placed randomly on the heads of all players, carefully so that a player can not see their own hat. (There may be more `Red` hats than blue, or vice versa. There might also be no `Red`, or no `Blue` hats).
Starting at the back of the line, all players take turns to guess out loud their hat colour. Each team is allowed only one mistake. If two or more players guess the wrong colour, then the game is over and the team loses! But if there is (at most) only one mistake, then they win a huge prize! (All players are on the same team, working together)
There is no communication allowed. If any player tries to say anything (besides their own guess), or tries to turn around, etc. Then that team is immediately disqualified. Play fair!
<svg xmlns="http://www.w3.org/2000/svg" width="235" height="344" viewBox="0 0 124.4621 182.1672"><path fill="#fff" d="M0 0h124.462v182.1672H0z"/><path fill="none" stroke="#a40" stroke-width="3" d="M4.156 79.0297h28.08v27.54h28.62v27h30.24v27h26.2298l-.239 16.5588"/><g transform="translate(-20.684 -22.6203)"><circle cx="40.4502" cy="45.3425" r="8.0137" fill="none" stroke="#000" stroke-width="1.5"/><ellipse cx="45.6279" cy="44.4919" fill="#520" rx="1.1448" ry="1.3356"/><path fill="none" stroke="#000" stroke-width="1.5" d="m40.542 53.9544-.9145 35.9695 8.0261 10.57M39.6275 89.924l-7.6207 10.364"/><path fill="none" stroke="#000" stroke-width="1.5" d="m32.0068 72.5488 7.9255-5.4869 8.5352 7.6207"/><path fill="#df0000" stroke="#000" d="M31.6215 38.7764h18.5944v-2.4386h-5.4868V28.717h-8.84v7.6207h-4.2676z"/><path fill="none" stroke="#000" stroke-width=".8" d="m47.6846 49.4858-4.9302-.233h.6646m33.5647 27.7213-4.9302-.233h.6646m33.15 27.616-4.9301-.2329h.6645m31.0702 26.6806-4.9302-.233h.6646"/></g><g transform="translate(8.3886 5.2476)"><circle cx="40.4502" cy="45.3425" r="8.0137" fill="none" stroke="#000" stroke-width="1.5"/><ellipse cx="45.6279" cy="44.4919" fill="#520" rx="1.1448" ry="1.3356"/><path fill="none" stroke="#000" stroke-width="1.5" d="m40.542 53.9544-.9145 35.9695 8.0261 10.57M39.6275 89.924l-7.6207 10.364"/><path fill="none" stroke="#000" stroke-width="1.5" d="m32.0068 72.5488 7.9255-5.4869 8.5352 7.6207"/><path fill="#0000df" stroke="#000" d="M31.6215 38.7764h18.5944v-2.4386h-5.4868V28.717h-8.84v7.6207h-4.2676z"/></g><g transform="translate(37.578 32.3497)"><circle cx="40.4502" cy="45.3425" r="8.0137" fill="none" stroke="#000" stroke-width="1.5"/><ellipse cx="45.6279" cy="44.4919" fill="#520" rx="1.1448" ry="1.3356"/><path fill="none" stroke="#000" stroke-width="1.5" d="m40.542 53.9544-.9145 35.9695 8.0261 10.57M39.6275 89.924l-7.6207 10.364"/><path fill="none" stroke="#000" stroke-width="1.5" d="m32.0068 72.5488 7.9255-5.4869 8.5352 7.6207"/><path fill="#0000df" stroke="#000" d="M31.6215 38.7764h18.5944v-2.4386h-5.4868V28.717h-8.84v7.6207h-4.2676z"/><text xml:space="preserve" x="-23.6162" y="60.4449" stroke-width=".2646" font-family="sans-serif" font-size="10.5833" font-weight="400" style="line-height:1.25"><tspan x="-23.6162" y="60.4449">1</tspan></text><text xml:space="preserve" x="6.9846" y="87.609" stroke-width=".2646" font-family="sans-serif" font-size="10.5833" font-weight="400" style="line-height:1.25"><tspan x="6.9846" y="87.609">2</tspan></text><text xml:space="preserve" x="36.3824" y="113.1856" stroke-width=".2646" font-family="sans-serif" font-size="10.5833" font-weight="400" style="line-height:1.25"><tspan x="36.3824" y="113.1856">3</tspan></text><text xml:space="preserve" x="63.822" y="139.103" stroke-width=".2646" font-family="sans-serif" font-size="10.5833" font-weight="400" style="line-height:1.25"><tspan x="63.822" y="139.103">4</tspan></text></g><g transform="translate(64.6556 59.146)"><circle cx="40.4502" cy="45.3425" r="8.0137" fill="none" stroke="#000" stroke-width="1.5"/><ellipse cx="45.6279" cy="44.4919" fill="#520" rx="1.1448" ry="1.3356"/><path fill="none" stroke="#000" stroke-width="1.5" d="m40.542 53.9544-.9145 35.9695 8.0261 10.57M39.6275 89.924l-7.6207 10.364"/><path fill="none" stroke="#000" stroke-width="1.5" d="m32.0068 72.5488 7.9255-5.4869 8.5352 7.6207"/><path fill="#df0000" stroke="#000" d="M31.6215 38.7764h18.5944v-2.4386h-5.4868V28.717h-8.84v7.6207h-4.2676z"/></g></svg>
_In the image above, player `1` sees `Blue, Blue, Red`, and guesses `Blue` (wrong!). Then player `2` guesses `Blue` (correct!). Then player `3` guesses `Red` (wrong!). Since that was the second mistake, the team loses._
## Task
Your team really wants to win, so you decide to plan a strategy beforehand.
Write a function `guess_colour` which will be your players strategy to win the game. Each player, when it is their turn, will use this strategy (your function, with the relevant inputs) to determine what their guess will be.
To pass the kata, your function must consistently allow your team to win the game (by the rules explained above). If it causes more than one wrong guess per game, you lose!
**Inputs:**
- `guesses`: a `list` of all previous guesses (`"Red"` or `"Blue"`) which the player has heard so far (in order).
- `hats`: a `list` of all the hats (`"Red"` or `"Blue"`) which the player can see in front of them (in order).
**Output:** the player's guess (`"Red"` or `"Blue"`).
_All inputs will be valid, and length of each list will be between `0` and `999` inclusive. Total size of teams will be between `2` and `1000` inclusive._
**Note:** the players strategy should not require global variables or state. Tests will check that the strategy is consistent even when called at unexpected times.
Good luck!
#### Try some other riddle kata:
- [Extreme Hat Game](https://www.codewars.com/kata/62bf879e8e54a4004b8c3a92)
- [Hat Game 2](https://www.codewars.com/kata/634f18946a80b8003d80e728)
- [Identify Ball Bearings](https://www.codewars.com/kata/61711668cfcc35003253180d)
| games | def guess_colour(guesses, hats):
return "Red" if ((hats + guesses). count("Blue")) % 2 else "Blue"
| Hat Game | 618647c4d01859002768bc15 | [
"Riddles"
] | https://www.codewars.com/kata/618647c4d01859002768bc15 | 6 kyu |
You are given a list of four points (x, y). Each point is a tuple
Your task is to write a function which takes an array of points and returns whether they form a square.
If the array doesn't contain 4 points, return False.
All points coordinates are integers.
Squares can be rotated using a random degree.
<h1>Examples</h1>
```
((1,1), (3,3), (1,3), (3,1)) -> True
((0, 0), (0,2), (2,0), (2,1)) -> False
([]) -> False
```
<h1>
Constraints:
</h1>
```
1 <= x, y <= 1000
```
Note:
Performance does not enforced in this kata. | reference | from itertools import combinations
from math import dist
def is_square(points: list) - > bool:
# (Number of points = Number of unique points = 4) and (Two kind of distances)
return (len(points) == len(set(points)) == 4) and (len(set(dist(* pair) for pair in combinations(points, 2))) == 2)
| Do the points form a square? | 618688793385370019f494ae | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/618688793385370019f494ae | 6 kyu |
You are given a positive natural number `n` (which is `n > 0`) and you should create a regular expression pattern which only matches the decimal representation of all positive natural numbers strictly less than `n` without leading zeros. The empty string, numbers with leading zeros, negative numbers and non-numbers should not match the regular expression compiled from your returned pattern.
# Input
* `n > 0` natural number, `n` can be from the full possible positive range
# Output
* regular expression pattern as string which will be used to compile a regular expression to do the matches
# Tests
The compiled regular expression will be tested against decimal representations of random numbers with and without leading zeros, strings including letters and the empty string and should only match for decimal representations of numbers `k` with `0 < k < n`.
~~~if:java
Tests use `java.util.regex.Matcher.matches()` to do the matches.
~~~
~~~if:javascript
Tests use `chai.assert.match()` which itself uses `RegExp.prototype.exec()` to do the matches.
~~~
~~~if:python
Tests use `re.match()` to do the matches.
~~~ | reference | def regex_below(n): return (s: = str(n)) and "^(?=[^0])(" + '|' . join(f'( { s [: i ]} [^\D { int ( d )} -9])?\d{{ { len ( s ) - i - 1 } }} ' for i, d in enumerate(s)) + ")$"
| Regex matching all positive numbers below n | 615da209cf564e0032b3ecc6 | [
"Regular Expressions"
] | https://www.codewars.com/kata/615da209cf564e0032b3ecc6 | 5 kyu |
A stranger has lost himself in a forest which looks like a _2D square grid_. Night is coming, so he has to protect himself from wild animals. That is why he decided to put up a campfire.
Suppose this stranger has __four sticks__ with the same length which is equal to __k__. He can arrange them in square grid so that they form _k_ x _k_ square (each stick endpoint lies on a grid node). Using this strategy he can build campfire with areas 1, 4, 9, ... Also, if he rotates the sticks as it is shown in the image, he will get another campfire areas 2, 5, 10, ...
(If the image does not show up, check the [link](https://raw.githubusercontent.com/RevelcoS/Codewars/master/campfire_housing/impossible_squares.jpg))

# Problem
Given campfire area __A__ (__A__ is a natural number) is it possible to construct a campfire with four sticks so that their endpoints lie on grid nodes?
# Input
```math
1\le A\le10^9
```
#
# Output
Return boolean (```true``` if it is possible to construct a campfire, otherwise ```false```):
* ```True``` or ```False``` in Python
* ```true``` or ```false``` in C/C++ or JavaScript
# Cases
* If A = 3, then it is impossible to construct a campfire because it is impossible to get the square root of 3 on the grid
* If A = 8, then it is possible to construct a campfire, for example, by doubling the side length of a square with area 2 in the image
# Inspiration
This kata is inspired by the Numberphile [video](https://www.youtube.com/watch?v=xyVl-tcB8pI&ab_channel=Numberphile) | algorithms | from math import sqrt
def is_constructable(area):
'''
Is "area" the sum of two perfect squares?
'''
return any(
sqrt(area - num * * 2). is_integer()
for num in range(int(sqrt(area)) + 1)
)
| Campfire building | 617ae2c4e321cd00300a2ec6 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/617ae2c4e321cd00300a2ec6 | 6 kyu |
- In the planet named Hoiyama, scientists are trying to find the weights of the mountains.
- They managed to find the weights of some mountains.
- But calculating them manually takes a really long time.
- That's why they hired you to develop an algorithm and easily calculate the weights of the mountains.
- Your function has only one parameter which is the width of the mountain and you need to return the weight of that mountain.
- _The widths of the mountains are only odd numbers._
- They gave you some information about calculating the weight of a mountain.
- Examine the information given below and develop a solution accordingly.
```
width = 3
3 -> 3
1,2,1 -> 4
+___
weight: 7
```
```
width = 5
5 -> 5
3,4,3 -> 10
1,2,3,2,1 -> 9
+___
weight: 24
```
```
width = 7
7 -> 7
5,6,5 -> 16
3,4,5,4,3 -> 19
1,2,3,4,3,2,1 -> 16
+___
weight: 58
```
```
width = 9
9 -> 9
7,8,7 -> 22
5,6,7,6,5 -> 29
3,4,5,6,5,4,3 -> 30
1,2,3,4,5,4,3,2,1 -> 25
+___
weight: 115
```
```
width = 17
17 -> 17
15,16,15 -> 46
13,14,15,14,13 -> 69
11,12,13,14,13,12,11 -> 86
9,10,11,12,13,12,11,10,9 -> 97
7,8,9,10,11,12,11,10,9,8,7 -> 102
5,6,7,8,9,10,11,10,9,8,7,6,5 -> 101
3,4,5,6,7,8,9,10,9,8,7,6,5,4,3 -> 94
1,2,3,4,5,6,7,8,9,8,7,6,5,4,3,2,1 -> 81
+____
weight: 693
``` | algorithms | def mountains_of_hoiyama(w):
return ((w + 1) * * 3 - w * * 2) / / 8 + 1
| Mountains of Hoiyama | 617bfa617cdd1f001a5cadc9 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/617bfa617cdd1f001a5cadc9 | 7 kyu |
Imagine that you went to a zoo and some zoologists asked you for help.
They want you to find the strongest ape of its own kind and there are 4 types of apes in the zoo. (Gorilla, Gibbon, Orangutan, Chimpanzee)
* There will be only one parameter which is a list containing lots of dictionaries.
* Each dictionary will be like this: `{"name": name, "weight": weight, "height": height, "type": type}`
* To find the strongest ape, you need to compare the sum of weight and height of each apes of that kind.
* The ape with the highest weight and height will be the strongest ape.
* You need to return a dictionary which contains the names of the strongest apes of all kinds.`{"Gorilla": strongest_gorilla, "Gibbon": strongest_gibbon, "Orangutan": strongest_orangutan, "Chimpanzee": strongest_chimpanzee}`
* There can be 2 or more apes which has the same highest weight and height. In that case, you need to sort their names by alphabet and then choose the first one as the strongest ape.
* If there are no apes for a kind (e.g. Gorilla), you need to return a dictionary like this: `{"Gorilla": None, "Gibbon": strongest_gibbon, "Orangutan": strongest_orangutan, "Chimpanzee": strongest_chimpanzee}`
__Example 1:__
```
find_the_strongest_apes(
[{"name": "aba", "weight": 101, "height": 99, "type": "Gorilla"},
{"name": "abb", "weight": 99, "height": 101, "type": "Gorilla"},
{"name": "abc", "weight": 101, "height": 99, "type": "Orangutan"},
{"name": "abd", "weight": 99, "height": 101, "type": "Orangutan"}])
```
Should return `{'Gorilla': 'aba', 'Gibbon': None, 'Orangutan': 'abc', 'Chimpanzee': None}`
__Example 2:__
```
find_the_strongest_apes(
[{"name": "aba", "weight": 140, "height": 120, "type": "Gorilla"},
{"name": "abb", "weight": 20, "height": 50, "type": "Gibbon"},
{"name": "abc", "weight": 75, "height": 110, "type": "Orangutan"},
{"name": "abd", "weight": 50, "height": 100, "type": "Chimpanzee"}])
```
Should return `{'Gorilla': 'aba', 'Gibbon': 'abb', 'Orangutan': 'abc', 'Chimpanzee': 'abd'}`
__Example 3:__
```
find_the_strongest_apes(
[{"name": "aba", "weight": 140, "height": 120, "type": "Gorilla"},
{"name": "abb", "weight": 150, "height": 120, "type": "Gorilla"},
{"name": "abc", "weight": 75, "height": 110, "type": "Orangutan"},
{"name": "abd", "weight": 50, "height": 100, "type": "Chimpanzee"}])
```
Should return `{'Gorilla': 'abb', 'Gibbon': None, 'Orangutan': 'abc', 'Chimpanzee': 'abd'}`
_*English is not my native language, so some sentences may not be descriptive enough or even give incorrect information. If you find a wrong sentence, please feel free to comment._ | algorithms | def find_the_strongest_apes(apes):
apes . sort(key=lambda a: a['name'])
imt = {'Gorilla': 0, 'Gibbon': 0, 'Orangutan': 0, 'Chimpanzee': 0}
res = {'Gorilla': None, 'Gibbon': None,
'Orangutan': None, 'Chimpanzee': None}
for ape in apes:
k = ape['height'] + ape['weight']
if imt[ape['type']] < k:
imt[ape['type']] = k
res[ape['type']] = ape['name']
return res
| Find the Strongest Apes | 617af2ff76b7f70027b89db3 | [
"Lists",
"Sorting",
"Algorithms"
] | https://www.codewars.com/kata/617af2ff76b7f70027b89db3 | 6 kyu |
<h1 align="center">Hit the target</h1>
<em>This is the second part of the kata :3 πππππ</em><br>
given a matrix <code>n x n</code> (2-7), determine if the arrow is directed to the target (x). <br>
Now there are one of 4 types of arrows (<code> '^', '>', 'v', '<' </code>) and only one target (<code>x</code>)<br>
An empty spot will be denoted by a space " ", the target with a cross "x", and the scope ">"
<h2>Examples:</h2>
given matrix 4x4: <br>
<code>[<br>
[' ', 'x', ' ', ' '],<br>
[' ', ' ', ' ', ' '], --> return true<br>
[' ', '^', ' ', ' '],<br>
[' ', ' ', ' ', ' ']<br>
] </code><br>
given matrix 4x4: <br>
<code>[<br>
[' ', ' ', ' ', ' '],<br>
[' ', 'v', ' ', ' '], --> return false<br>
[' ', ' ', ' ', 'x'],<br>
[' ', ' ', ' ', ' ']<br>
] </code><br>
given matrix 4x4: <br>
<code>[<br>
[' ', ' ', ' ', ' '],<br>
['>', ' ', ' ', 'x'], --> return true<br>
[' ', '', ' ', ' '],<br>
[' ', ' ', ' ', ' ']<br>
] </code>
In this example, only a 4x4 matrix was used, the problem will have matrices of dimensions from 2 to 7<br>
And here is the first part of this kata - <a href='https://www.codewars.com/kata/5ffc226ce1666a002bf023d2'>click me βvβ</a><br>
Happy hacking as they say! π»
| reference | def solution(mtrx):
return any(i . index('>') < i . index('x') for i in mtrx if '>' in i and 'x' in i) or \
any(i . index('<') > i . index('x') for i in mtrx if '<' in i and 'x' in i) or \
any(i . index('^') > i . index('x') for i in zip(* mtrx) if '^' in i and 'x' in i) or \
any(i . index('v') < i . index('x')
for i in zip(* mtrx) if 'v' in i and 'x' in i)
| Game Hit the target - 2nd part | 6177b4119b69a40034305f14 | [
"Matrix",
"Arrays",
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/6177b4119b69a40034305f14 | 6 kyu |
# introduction
## In this kata you can learn
- How to deal with bytes files in python
- Caesar code
- Convert bytes to int
- Few things about PNG format
## Caesar code
In cryptography, a Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code or Caesar shift, is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on. The method is named after Julius Caesar, who used it in his private correspondence.
In our kata we deal with bytes not letters.
Each byte is shift by a number between 0 and 255.
## Few words about PNG Format
A PNG file starts with an 8-byte signature (in hexadecimal: 89 50 4E 47 0D 0A 1A 0A).
After the header, comes a series of chunks, each of which conveys certain information about the image.
A chunk consists of four parts:
- LENGTH : length of data (4 bytes, big-endian)
- TYPE : The name of the chunk (4 bytes). In the image we are going to use Name can be (IHDR PLTE IDAT IEND)
- DATA : (length bytes)
- CRC : (cyclic redundancy code/checksum; 4 bytes)
### For this 1 orange pixel png
```
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\rIDAT\x08\x99c\xf8\xbf\x94\xe1?\x00\x06\xef\x02\xa4+\x9by\xe0\x00\x00\x00\x00IEND\xaeB`\x82'
```
We have :
- The signature `\x89PNG\r\n\x1a\n` in hexa :`89 50 4E 47 0D 0A 1A 0A`
- First Chunk
- `b'\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89'`
- In hexa :`00 00 00 0d` `49 48 44 52` `00 00 00 01 00 00 00 01 08 06 00 00 00` `1f 15 c4 89`
- With:
- Size : `00 00 00 0d` = 13
- Type : `49 48 44 52` = b'IHDR'
- Data : '00 00 00 01 00 00 00 01 08 06 00 00 00'
- CRC : `1f 15 c4 89'
- Second Chunk
- `b'\x00\x00\x00\rIDAT\x08\x99c\xf8\xbf\x94\xe1?\x00\x06\xef\x02\xa4+\x9by\xe0'`
- size `00 00 00 0d`
- Type `49 44 41 54` = `IDAT`
- Data `08 99 63 f8 bf 94 e1 3f 00 06 ef 02 a4`
- CRC `2b 9b 79 e0`
- Last Chunk
- b'\x00\x00\x00\x00IEND\xaeB`\x82'
- with size 0, Type `IEND`, no data and CRC `ae 42 60 82`
# The challenge
You will have de decode a serie of PNG images.
PNG image will be encrypted like this :
- The signature is let untouched
- Each chunk is encrypted with cesar code with its own key (amount of shift)
Have fun ... | reference | from itertools import islice
def decipher(bs):
bs = iter(bs)
def eat(n): return islice(bs, n)
def decode(size, key): return [(c - key) % 256 for c in eat(size)]
out = [* eat(8)]
for key in bs:
sizeB = decode(3, key)
size = int . from_bytes(sizeB, byteorder='big') + 8
out . extend((0, * sizeB, * decode(size, key)))
return b'' . join(i . to_bytes(1, byteorder='big') for i in out)
| Break Caesar cipher variation : PNG image | 6174318832e56300079b7d4b | [
"Cryptography",
"Fundamentals"
] | https://www.codewars.com/kata/6174318832e56300079b7d4b | 5 kyu |
## Task
Write a function that can deduce which key was used during a Vigenere cipher encryption, given the resulting ciphertext, and the length of that key.
### Notes
* The input string, as well as the encryption key, will consist of uppercase letters only
* All texts will be in English
___
### Vigenere cipher
(For a full description, check the [wikipedia article](https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher#Description).)
> In a Caesar cipher, each letter of the alphabet is shifted along some number of places. For example, with a shift of `3`, `A` would become `D`, `B` would become `E`, `Y` would become `B`, and so on. The Vigenère cipher has several Caesar ciphers in sequence with different shift values.
The secret key is selected, and then repeated until it becomes as long as the text you want to encrypt/decrypt (if the key ends up being longer than the text, the superfluous key-characters can be removed):
```
text = "HELLOWORLD"
original key = "ABCXYZ"
repeated key = "ABCXYZABCX" (superfluous "YZ" at the end was removed)
```
Each character of the key tells how many times a character of the original text standing at the same position has to be shifted:
```
text: H E L L O W O R L D
------------------------------------------------
key: A B C X Y Z A B C X
------------------------------------------------
shift: 0 1 2 23 24 25 0 1 2 23
------------------------------------------------
result: H F N I M V O S N A
```
A ciphertext can then be decrypted by applying the same shifts but with a negative sign:
```
text: H F N I M V O S N A
------------------------------------------------
key: A B C X Y Z A B C X
------------------------------------------------
shift: 0 -1 -2 -23 -24 -25 0 -1 -2 -23
------------------------------------------------
result: H E L L O W O R L D
``` | algorithms | from collections import Counter
from string import ascii_uppercase
ALPHABET = ascii_uppercase * 2
FREQUENCY_LETTERS = {
'A': 0.0815, 'B': 0.0144, 'C': 0.0276, 'D': 0.0379, 'E': 0.1311, 'F': 0.0292, 'G': 0.0199,
'H': 0.0526, 'I': 0.0635, 'J': 0.0013, 'K': 0.0042, 'L': 0.0339, 'M': 0.0254, 'N': 0.0710,
'O': 0.0800, 'P': 0.0198, 'Q': 0.0012, 'R': 0.0638, 'S': 0.0610, 'T': 0.1047, 'U': 0.0246,
'V': 0.0092, 'W': 0.0154, 'X': 0.0017, 'Y': 0.0198, 'Z': 0.0008
}
def get_keyword(text, key_len):
keyword = [find_key_for_group([text[letter] for letter in range(i, len(text), key_len)])
for i in range(key_len)]
return '' . join(keyword)
def find_key_for_group(group):
blocks = [Counter(ALPHABET[ALPHABET . find(letter) - i]
for letter in group) for i in range(26)]
chi_squared = [(index, sum(get_chi_squared(block, len(group))))
for index, block in enumerate(blocks)]
return ALPHABET[min(chi_squared, key=lambda x: x[1])[0]]
def get_chi_squared(block, length):
return [(block . get(letter, 0) - (length * FREQUENCY_LETTERS[letter])) * * 2 / (length * FREQUENCY_LETTERS[letter])
for letter in ascii_uppercase]
| Breaking the Vigenère Cipher | 544e5d75908f2d5eb700052b | [
"Ciphers",
"Cryptography",
"Algorithms"
] | https://www.codewars.com/kata/544e5d75908f2d5eb700052b | 3 kyu |
Failure on the factory floor!! One box of 'deluxe' ball-bearings has been mixed in with all the boxes of 'normal' ball-bearings! We need your help to identify the right box!
## Information
What you know about the bearings:
- 'deluxe' ball-bearings weigh exactly `11 grams`
- 'normal' ball-bearings weigh exactly `10 grams`
- Besides weight, both kinds of ball-bearings are identical
- There are (effectively) infinite bearings in each box
To help you identify the right box, you also have access to a *Super Scaleβ’* which will tell you the exact weight of anything you give it. Unfortunately, getting it ready for each measurement takes a long time, so you only have time to use it once!
## Task
Write a function which accepts two arguments:
- `bearings`: A list of the bearing types contained in each 'box'. (length between `1` and `200` inclusive)
```if:python
- `weigh`: a function which accepts any number of arguments, returning the total weight of all. Can only be used once!
```
```if:csharp
- `weigh`: a function which accepts a collection of bearings, returning the total weight of all. Can only be used once!
```
Your function should identify and return the single 'deluxe' bearing sample from `bearings`.
## Example
```python
def identify_bb(bearings, weigh):
a, b, c = bearings
if weigh(a, b) == 20:
# bearings 'a' and 'b' must both be 10, so 'c' must be deluxe
return c
if weigh(a) == 10: # Error: weigh has already been used!
return b
return a
```
```csharp
public static Bearing IdentifyBb(Bearing[] bearings, Func<IEnumerable<Bearing>, long> weigh)
{
Bearing a = bearings[0],
b = bearings[1],
c = bearings[2];
if (weigh(a, b) == 20)
// bearings 'a' and 'b' must both be 10, so 'c' must be deluxe
return c;
if (weigh(a) == 10) // Error: weigh has already been used!
return b;
return a;
}
```
```if:python
Note: modules `sys` and `inspect` have been disabled.
```
#### Try some other riddle kata:
- [Hat Game](https://www.codewars.com/kata/618647c4d01859002768bc15)
- [Extreme Hat Game](https://www.codewars.com/kata/62bf879e8e54a4004b8c3a92)
- [Hat Game 2](https://www.codewars.com/kata/634f18946a80b8003d80e728) | games | # what "best practice" should be about
def identify_bb(boxes, weigh):
boxes_amount = len(boxes)
sample = (box for count, box in enumerate(boxes, 1) for _ in range(count))
sample_weight = weigh(* sample)
sample_amount = triangular(boxes_amount)
deluxe_number = sample_weight % sample_amount - 1
return boxes[deluxe_number]
def triangular(number):
return number * (number + 1) / / 2
| Identify Ball Bearings | 61711668cfcc35003253180d | [
"Riddles"
] | https://www.codewars.com/kata/61711668cfcc35003253180d | 6 kyu |
<h2>Task:</h2>
Your job is to write a function, which takes three integers `a`, `b`, and `c` as arguments, and returns `True` if exactly two of the three integers are positive numbers (greater than zero), and `False` - otherwise.
<h2>Examples:</h2>
```python
two_are_positive(2, 4, -3) == True
two_are_positive(-4, 6, 8) == True
two_are_positive(4, -6, 9) == True
two_are_positive(-4, 6, 0) == False
two_are_positive(4, 6, 10) == False
two_are_positive(-14, -3, -4) == False
```
```javascript
twoArePositive(2, 4, -3) == true
twoArePositive(-4, 6, 8) == true
twoArePositive(4, -6, 9) == true
twoArePositive(-4, 6, 0) == false
twoArePositive(4, 6, 10) == false
twoArePositive(-14, -3, -4) == false
```
```csharp
TwoArePositive(2, 4, -3) == true
TwoArePositive(-4, 6, 8) == true
TwoArePositive(4, -6, 9) == true
TwoArePositive(-4, 6, 0) == false
TwoArePositive(4, 6, 10) == false
TwoArePositive(-14, -3, -4) == false
```
```rust
two_are_positive(2, 4, -3) == true
two_are_positive(-4, 6, 8) == true
two_are_positive(4, -6, 9) == true
two_are_positive(-4, 6, 0) == false
two_are_positive(4, 6, 10) == false
two_are_positive(-14, -3, -4) == false
``` | reference | def two_are_positive(a, b, c):
return sum([a > 0, b > 0, c > 0]) == 2
| Two numbers are positive | 602db3215c22df000e8544f0 | [
"Fundamentals"
] | https://www.codewars.com/kata/602db3215c22df000e8544f0 | 7 kyu |
The workers of CodeLand intend to build a brand new building in the town centre after the end of the 3rd Code Wars.
They intend to build a triangle-based pyramid (tetrahedron) out of cubes.
They require a program that will find the tallest potential height of the pyramid, given a certain number of cubes.
Your function needs to return the pyramid with largest number of full layers possible with the input.
The input will be an integer of how many cubes are available, and your output should return the height of the tallest pyramid buildable with that number of cubes.
The schematic below shows a **cross-section** of each layer of the pyramid, top down:
Layer 1 -
x
Layer 2 -
x
x x
Layer 3 -
x
x x
x x x | games | def find_height(n):
r = int((n * 6) * * (1 / 3))
return r if r * (r + 1) * (r + 2) / / 6 <= n else r - 1
| The Pyramid of Cubes | 61707b71059070003793bc0f | [
"Mathematics",
"Puzzles"
] | https://www.codewars.com/kata/61707b71059070003793bc0f | 6 kyu |
# Introduction
In this kata, you'll have to write an algorithm that, given a set of input-output examples, synthesizes a Boolean function that takes on the behaviour of those examples. For instance, for the set of input-output examples:
```
(false, false) β¦ false
(false, true) β¦ false
(true, true) β¦ true
```
We could synthesize the function:
```
f(v1, v2) = v1 AND v2
```
However, sometimes it's impossible to synthesize a function. For instance, in this set of input-output examples, two of the examples are contradictory:
```
(true) β¦ false
(false) β¦ true
(false) β¦ false
```
In these cases, your solution should indicate that no correct function exists.
# The Problem
You'll need to implement the function:
```
synthesize(var_count: Int, examples: List[Example]) -> BoolFunction?
```
The `var_count` parameter gives you the number of input variables to the target function and the `examples` parameter gives you the list of input-output examples. The returned value will be the synthesized function, or nothing if no function can be synthesized from the examples. You'll have access to a small Boolean logic DSL from which you can construct the function:
```
BoolFunction := Variable (indexed by an integer)
| True
| False
| BoolFunction AND BoolFunction
| BoolFunction OR BoolFunction
| NOT BoolFunction
```
Boolean functions should be represented as ASTs over this DSL. Language-specific details about the AST representation are given in the initial solution and example tests.
Remember that your solution **does not** have to synthesize a smallest or most optimal functionβany working function will do. Your solution, however, should be reasonably efficient; if it has complexity exponential in `var_count`, you might have trouble with tests where `var_count > 100`.
Good luck!
| algorithms | # the DSL is preloaded, and is constructed as follows:
# variables: Variable(index: int)
# constants: CTrue() ; CFalse()
# binary operators: And(a: BoolFn, b: BoolFn) ; Or(a: BoolFn, b: BoolFn)
# unary operators: Not(a: BoolFn)
# the function beval(fn: BoolFn, vars: list[bool]) -> bool can be used to eval a DSL term
# var_count: the number of input variables to the target function
# examples: a list of examples, each of which is a pair (inputs, output)
# inputs is a tuple of bools and output is a single bool
# return: the synthesized target function, expressed in the DSL as above
# return None if it's impossible to synthesize a correct function
from functools import reduce
import operator
def synthesize(var_count, examples):
dic = {}
for inp, out in examples:
if inp in dic and dic[inp] != out:
return None
dic[inp] = out
if var_count == 0:
if examples and examples[0][1] == True:
return CTrue()
else:
return CFalse()
if all(not out for inp, out in examples):
return CFalse()
return reduce(Or, (reduce(And, (Variable(i) if e else Not(Variable(i)) for i, e in enumerate(k))) for k, v in examples if v))
| Synthesize Boolean Functions From Examples | 616fcf0580f1da001b925606 | [
"Algorithms"
] | https://www.codewars.com/kata/616fcf0580f1da001b925606 | 5 kyu |
# Flatten Rows From DataFrame
## Input parameters
1. dataframe: `pandas.DataFrame` object
2. col: target column
## Task
Your function must return a new ``pandas.DataFrame`` object with the same columns as the original input. However, targeted column has in some of its cells a list instead of one single element.You must transform each element of a list-like cell to a row.
Input DataFrame will never be empty. You must not modify the original input. The target column will always be one of the dataframe columns.
## Examples
### Input
```python
A B
0 [1, 2] 5
1 [a, b, c] 6
2 77 3
col = "A"
```
### Output
```python
A B
0 1 5
1 2 5
2 a 6
3 b 6
4 c 6
5 77 3
``` | reference | import pandas as pd
def flatten(dataframe, col):
return dataframe . explode(col). reset_index(drop=True)
| Pandas Series 104: Flatten Rows From DataFrame | 615bf5f446a1190007bfb9d9 | [
"Lists",
"Data Frames",
"Fundamentals",
"Data Science"
] | https://www.codewars.com/kata/615bf5f446a1190007bfb9d9 | 6 kyu |
Polygons are planar (2-D) shapes with all straight sides.
Web polygons also called Tree polygons are polygons which can be formed by a peculiar sequencing pattern. It results in the formation of rhombus like polygons on a web.
Each 'n' in the sequence causes 'n' branches, these branches can be closed by the number '1' in the sequence, thus forming polygons!. The branch which is opened recently, will be the first one to close if and only if it gets closed by a '1'.
**Task**
Count **all possible number** polygons.
~~~if:javascript
A Sequence of Positive integers (Array) will be provided and the program must return the possible number of polygons (BigInt).
~~~
~~~if:python
A Sequence of Positive Integers (list) will be provided and the program must return the possible number of polygons (int).
~~~
~~~if:rust
A Sequence of Positive Integers (Boxed Slice Reference) will be provided and the program must return the possible number of polygons (u128).
~~~
~~~if:cpp
A Vector of Positive Integers (vector < int >) will be provided and the program must return the possible number of polygons (unsigned long long).
~~~
**Rules**
1) The number 1 in a sequence has an important function which is to converge any number of branches to 1.
2) The Web can be completely closed or opened however if '1' is not present after a certain branching value (v>1) then its not possible to form a polygon (example 3)
3) Assume that the Polygons formed in 2 or more seperate branches do not touch or interfere with one another.
4) Do **NOT** consider Polygons to be hollow .i.e Counting a polygon with a hole and without hole is prohibited instead count it as without a hole once. (example 6)
**Examples**
```
1) Sequence [1,2,2,1,2,1,1,1,1,1,3,1,1]
(smaller 2 branches closed by 1)
2 1 2 1
/\ /\
/ \/ \
/\ /\ /\
/ \/ \/ \
2 / \ 1 3 /\ 1
1__/ \___1___1__1_/__\_1_
\ / \ /
\ / \/
\ /\ /\ / (3 branch closed by 1)
\/ \/ \/
\ /\ /
\/ \/
2 1 2 1
(Large 2 branch closed by 1)
2 causes 2 branches to be formed and each 2 is paired by a particular 1 and therefore closed!.
Answer: Number of polygons = 23
2) Sequence [1,1,1,3,2,1]
(2 branch closed)
2 /\1
/\/
3 /
1__1__1__/_2_/\1
\ \/
\
2 \/\1
\/
(3 branch NOT CLOSED.)
3 causes 3 branches and each of one them has 2 branches which is closed by 1.
But 3 is not closed!.
Answer: Number of polygons = 3
3) Sequence [2,3]
3 /_
/\
2 /
\
3 \/_
\
None of the branches are closed!
(No branch closed)
Answer: Number of polygons = 0
4) Sequence [1,2,1,1,3,3]
3 /_
/\
2/\ 1 /
_1_/ \__1_3/___3/_
\ / \ \
2\/ 1 \
\/_
3 \
only 2 is closed none of the other branches are closed
Answer: Number of polygons = 1
5) Sequence [1,2,2,1,1,1,1]
2 /\ 1
/\/\
/ \
1_2/ \1__1_1
\ /
\ /
2 \/\/ 1
\/
2 causes more 2 branches which are closed by respective '1's. and the previous 2 is closed by the next one
Answer: Number of polygons = 6
6) Sequence [1,3,2,1,1]
/\
2 / \1
/\ /\
/ \/ \
/ \
/ /\ \
_1_3/___2/ \1 __\__1_
\ \ / /
\ \/ /
\ /
\ /\ /
\/ \/1
2 \ /
\/
3 causes 3 branches, each branch has 2 branch openings which are closed by 1's
Answer: Number of polygons = 15
```
**Note**
Try Drawing the web on your own and figure out the relations!
```if:python
* Input size <10000
* 1<=Input element<100
```
```if:javascript
* Input size <= 11000
* 1 <= Input element <= 100
```
```if:rust
* Input size <50
* 1<=Input element<10
```
```if:cpp
* Input size <1000
* 1<=Input element<100
``` | algorithms | def webpolygons(a):
stack = [[1, 1, 0]]
for n in a:
if n > 1:
stack . append([n, 1, 0])
elif len(stack) > 1:
branch, prod_, sum_ = stack . pop()
stack[- 1][1] *= branch * prod_
stack[- 1][2] += branch * sum_ + \
branch * ~ - branch / / 2 * prod_ * * 2
while len(stack) > 1:
branch, prod_, sum_ = stack . pop()
stack[- 1][2] += branch * sum_
return stack[- 1][2]
| Web Polygons | 609243c36e796b003e79e6b5 | [
"Algorithms",
"Data Structures",
"Mathematics",
"Geometry"
] | https://www.codewars.com/kata/609243c36e796b003e79e6b5 | 4 kyu |
# Cargo-Bot

Cargo-Bot is a programming videogame consisting of vertical stacks of crates and a claw to move the crates from one stack to another. The aim of the game is to move the crates from an initial position to a desired final position.
The player controls the claw by placing commands into one of four programs. The player presses a "play" button when they are ready and the commands are executed. If, after executing the commands, the crates are in the desired final position, the player wins.
Your task in this kata will be to run the player's commands with a given initial state for the crates and return the ending state of the crates.
---
## Crates
Crates are objects having a `color` field which contains one of 4 possible strings: `"RED"`, `"YELLOW"`, `"GREEN"`, or `"BLUE"`.
The initial state of the board is given as a 2D list of crates, where each inner list represents a stack of crates. For example, the following would represent three stacks with a red crate on top of a yellow crate in the left-most stack and one blue crate in the middle stack:
```
initial_state = [
[Crate("YELLOW"), Crate("RED")],
[Crate("BLUE")],
[]
]
```
or
```
|
| ^ |
| |
| R |
| Y B _ |
```
---
## Programs & Commands
The player controls the claw by placing commands into one of four programs. The programs are provided as a 2D list of commands where each list represents one of the four programs.
Commands are objects with 2 fields: `command` which represents an action to be performed and `flag` which represents an optional condition (described in detail below).
The interpreter always starts with the first command in the first program and executes each command in sequence until the end of the program. Programs 2, 3, and 4 are only run if called from the first program.
There are seven different commands: 3 commands for moving the claw and 4 commands for calling programs
#### Claw Commands
* `"LEFT"` - Moves the claw one position to the left (if the claw is already on the left-most stack, nothing happens)
* `"RIGHT"` - Moves the claw one position to the right (if the claw is already on the right-most stack, nothing happens)
* `"DOWN"` - Does one of three things depending on its state:
* If the claw is empty and there are no crates in the stack below, nothing happens.
* If the claw is empty and there are crates in the stack below, the claw picks up the top crate.
* If the claw is holding a crate, the claw drops the crate on top of the stack below.
For example, the following program would pick up a crate, move the claw to the right, and set down the crate:
```
program = [Command("DOWN"), Command("RIGHT"), Command("DOWN")]
```
After 3 steps, this program would produce the following:
```
| |
| ^ | | ^ |
| | --> | |
| R | | R |
| Y B _ | | Y B _ |
```
**Note**: the claw always starts above the left-most stack.
#### Program Commands
In addition to the claw commands, there are four program commands: `"PROG1"`, `"PROG2"`, `"PROG3"`, and `"PROG4"`. Each of these commands directs the interpreter to begin reading commands from the beginning of the corresponding program. Once all the commands from the called program are run, the interpreter returns to the calling program and completes any remaining commands.
For example, the following set of programs would pick up two crates and move them one position to the right:
```
programs = [
[Command("PROG2"), Command("LEFT"), Command("PROG2")],
[Command("DOWN"), Command("RIGHT"), Command("DOWN")],
[],
[]
]
```
After 9 steps, these programs would produce the following:
```
| |
| ^ | | ^ |
| | | |
| | --> | Y |
| R | | R |
| Y B _ | | _ B _ |
```
#### Conditional Flags
Each command can also have a conditional flag which instructs the interpreter to only execute the command if the condition is met. The possible flag values together with the conditions they represent are listed below:
* `"NONE"` - the claw is not holding anything.
* `"ANY"` - the claw is holding a crate.
* `"RED"` - the claw is holding a red crate.
* `"YELLOW"` - the claw is holding a yellow crate.
* `"GREEN"` - the claw is holding a green crate.
* `"BLUE"` - the claw is holding a blue crate.
For example, the programs below would move each red crate on the top of each stack one step to the left:
```python
programs = [
[Command("RIGHT"), Command("PROG2"), Command("PROG1")],
[Command("DOWN"), Command("PROG3", "RED"), Command("DOWN", "ANY")],
[Command("LEFT"), Command("DOWN"), Command("RIGHT")],
[]
]
```
After 42 steps, these programs would produce the following:
```
| |
| ^ | | ^ |
| | | |
| R | --> | R |
| B R G R| | B R G |
| Y B B G B _ Y| | Y B B G B R Y|
```
---
## Counting Steps
Since many programs will run indefinitely, you will be provided with a maximum number of steps. Your interpreter should return the final state of the board after either
* No more commands are left to be run
* You have performed the maximum number of steps
Every command counts as a step, even if the command does nothing (`"DOWN"` with no crate present or `"LEFT"`/`"RIGHT"` against a wall) or was not executed due to its conditional flag. | algorithms | def cargobot(states, programs, max_steps):
def isValid(cmd):
return cmd . flag is None \
or hold and (cmd . flag == 'ANY' or cmd . flag == hold . color) \
or hold is None and cmd . flag == 'NONE'
def pushCmds(i): stk . extend(reversed(programs[i]))
pos, hold, stk, states = 0, None, [], [x[:] for x in states]
pushCmds(0)
for _ in range(max_steps):
if not stk:
break
cmd = stk . pop()
if not isValid(cmd):
continue
cmd = cmd . command
if cmd in 'LEFT RIGHT':
pos += (- 1) * * (cmd == 'LEFT')
pos = max(0, min(pos, len(states) - 1))
elif cmd == 'DOWN':
if hold:
states[pos]. append(hold)
hold = None
elif states[pos]:
hold = states[pos]. pop()
else:
pushCmds(int(cmd[- 1]) - 1)
return states
| Cargo-Bot Interpreter | 616a585e6814de0007f037a7 | [
"Interpreters",
"Games",
"Algorithms"
] | https://www.codewars.com/kata/616a585e6814de0007f037a7 | 5 kyu |
You are a barista at a big cafeteria. Normally there are a lot of baristas, but your boss runs a contest and he told you that, if you could handle all the orders with only one coffee machine in such a way that the sum of all the waiting times of the customers is the smallest possible, he will give you a substantial raise.
So you are the only barista today, and you only have one coffee machine that can brew one coffee at a time.
People start giving you their orders.
Let's not think about the time you need to write down their orders, but you need `2` additional minutes to clean the coffee machine after each coffee you make.
Now you have a list `coffees` of the orders and you write down next to each of the orders the time you need to brew each one of those cups of coffee.
___Task:___
Given a list of the times you need to brew each coffee, return the minimum total waiting time.
If you get it right, you will get that raise your boss promised you!
___Note that:___
* It is possible to receive no orders. (It's a free day :), maybe the next day your boss will start giving you some orders himself, you probably don't want that :) )
* You can only brew one coffee at a time.
* Since you have one coffee machine, you have to wait for it to brew the current coffee before you can move on to the next one.
* Ignore the time you need to serve the coffee and the time you need to take the orders and write down the time you need to make each one of them.
* If you have three customers with times `[4,3,2]`, the first customer is going to wait `4` minutes for his coffee, the second customer is going to wait `4` minutes (the time needed for the first customer to get his coffee), another `2` minutes (the time needed to clean the machine) and `3` more minutes (the time you need to brew his coffee), so in total `9` minutes. The third customer, by the same logic, is about to wait `9` minutes (for the first two customers) + `2` more minutes(cleaning) + `2` minutes (his coffee brewing time). This order of brewing the coffee will end up in a total waiting time of `26` minutes, but note that this may not be the minimum time needed. This time depends on the order you choose to brew the cups of coffee.
* The order in which you brew the coffee is totally up to you.
___Examples:___
```
coffees = [3,2,5,10,9] -> 85
coffees = [20,5] -> 32
coffees = [4,3,2] -> 22
```
~~~if:lambdacalc
___Encodings:___
`purity: LetRec`
`numEncoding: BinaryScott`
export constructors `nil, cons` for your `List` encoding
~~~
___Next Task___
[Barista Manager](https://www.codewars.com/kata/624f3171c0da4c000f4b801d)
__Special Thanks to the great Discord community for helping with the creation of this kata and also to the programmers that helped a lot in the " discuss " section.__
| reference | from itertools import accumulate
def barista(coffees):
return sum(accumulate(sorted(coffees), lambda a, c: a + 2 + c))
| Barista problem | 6167e70fc9bd9b00565ffa4e | [
"Fundamentals",
"Sorting"
] | https://www.codewars.com/kata/6167e70fc9bd9b00565ffa4e | 7 kyu |
There are numbers for which the `$n^{th}$` root equals the sum of their digits. For example:
`$\sqrt[3]{512} = 5+1+2 = 8$`
Complete the function that returns **all** natural numbers (in ascending order) for which the above statement is true for the given `n`, where `2 β€ n β€ 50`
#### Note
*To avoid hardcoding the answers, your code is limited to 1000 characters*
## Examples
```python
2 --> [1, 81]
3 --> [1, 512, 4913, 5832, 17576, 19683]
```
---
### My other katas
If you enjoyed this kata then please try [my other katas](https://www.codewars.com/users/anter69/authored)! :-)
#### *Translations are welcome!* | algorithms | def nth_root_equals_digit_sum(n):
answer = []
for x in range(1, 1000):
if sum([int(i) for i in (str(x * * n))]) == x:
answer . append(x * * n)
return answer
| Nth Root Equals Digit Sum | 60416d5ee50db70010e0fbd4 | [
"Algorithms"
] | https://www.codewars.com/kata/60416d5ee50db70010e0fbd4 | 6 kyu |
Little boy Vasya was coding and was playing with arrays. He thought: "Is there any way to generate N-dimensional array"? </br>
Let us help little boy Vasya. Target of this Kata is to create a function, which will generate N-dimensional array. For simplicity all arrays will have the same length.</br>
<h3>Input:</h3>
N: number -> depth of outter array, N > 0 </br>
size: number -> length of all arrays, size > 0 </br>
All inputs will be valid.
On the last (deepest) level we should put a string wich will describe the depth of our array. Example: 'level 2'
<h3>Example:</h3>
for <code>createNDimensionalArray(2,3)</code> output should be: </br>
<pre>
[
['level 2', 'level 2', 'level 2'],
['level 2', 'level 2', 'level 2'],
['level 2', 'level 2', 'level 2'],
]
</pre></br>
for <code>createNDimensionalArray(3,2)</code> output should be: </br>
<pre>
[
[
['level 3', 'level 3'],
['level 3', 'level 3'],
],
[
['level 3', 'level 3'],
['level 3', 'level 3'],
],
]
</pre>
Good luck! | reference | def create_n_dimensional_array(n, size):
res = f'level { n } '
for _ in range(n):
res = [res] * size
return res
| Create N-dimensional array | 6161847f52747c0025d0349a | [
"Arrays",
"Recursion",
"Fundamentals"
] | https://www.codewars.com/kata/6161847f52747c0025d0349a | 6 kyu |
# Introduction:
If you liked the _previous_ Kata [_(Sequence Duality and "Magical" Extrapolation)_](https://www.codewars.com/kata/6146a6f1b117f50007d44460), you may also be interested by this one, as -despite being somewhat "more advanced"- it is also based on the following principle:
- Start from an abstract-looking Mathematical Structure...
- "Magically" turn that into a surprisingly powerful and "concrete" algorithm by just adding __one* short line__ of code!
<font size=2>(* don't worry: you're obviously free to put as much code as you wish, but be aware that, once the class `R_e` defined, the function `deriv()` you'll be asked to implement can easily be coded in just one short [but possibly somewhat "subtle"...maybe ;) ] line, so no need to try "too complicated things")</font>
Here, the "Abstract-looking Mathematical tool" will be:
- "Nilpotent Ring Extensions" (or, if you prefer, ["Dual Numbers"](https://en.wikipedia.org/wiki/Dual_number))
While our algorithm will be about:
- nth derivatives of Algebraic Functions! (in fact, this kind of method is officially known as ["Automatic Differentiation"](https://en.wikipedia.org/wiki/Automatic_differentiation))
<font size=1>_((Sidenote: just like with the "Binomial Transform & Extrapolation", when I "discovered" those little "tricks" and -later- came up with the idea to make a Kata out of it, I wasn't aware [though it would be predictable] they are quite "well-known" algorithms with such "official names" and so much documentation on Wikipedia... Just found out now... :'( ))_</font>
Note that our algorithm will be much _"cleaner"_ than what is usually seen elsewhere, in the sense that it will __NOT__ involve any kind of "approximation" nor "string manipulation" nor any other "dirty thing" commonly used when "dealing with derivatives"!.. ;)
<br/>
# Your Task:
- Build a class: `R_e` <br/>
(which will represent "Dual Numbers")
- ...as well as a function: `deriv()` <br/>
(which will calculate nth derivatives of Algebraic Functions)
such that:
- elements of __the `R_e` class__ should behave just like `Dual Numbers` <font size=2>[see information [below](#theory) (or [on Wikipedia](https://en.wikipedia.org/wiki/Dual_number))]</font> where `R_e(a,b)` will represent an element of the form
```math
a+b\epsilon, \quad \epsilon^2 = 0 \quad (\epsilon \neq 0)
```
You'll have to define all the standard methods such as `__add__`, `__sub__`, `__mul__`, `__truediv__`, `__pow__` etc; but don't worry: things have been included in the `solution setup` so that you "don't forget"! ;)
But keep in mind that, just as those arithmetic operations can usually mix floats with integers etc (...) the ones you'll define should also be able to mix "Dual Numbers" with "Real Numbers" (=floats, integers etc), so keep in mind that operations such as `R_e(0,1)+1` should be _well-defined!_ (in this case, it would return `R_e(1,1)`)
- __the `deriv(f,n=1)` function__ should take as input an `algebraic function` as well as a positive integer (the latter being "optional": if no integer is given as an input, the `deriv()` function will consider "1" by default), and return another algebraic function, corresponding to the input's nth derivative.
Here, `algebraic function` just means any function (of one variable) that applies algebraic operations on its input (including non-integer exponentiation, so although this class of functions does include "polynomial functions" and "rational functions", it is much wider, as it can also combine those with -for example- "square/cubic roots" etc etc).
For instance,
```python
deriv(lambda x : 1/x**0.5 + x - 5)
```
should return "the equivalent of":
```python
lambda x : -0.5/x**1.5 + 1
```
and note that in order to apply the obtained `n`th derivative of a function `f` to an element `x`, it then suffices to call:
```python
deriv(f,n)(x)
```
or simply
```python
deriv(f)(x)
```
in the case where n=1
<font size=2>(If this happens to sound "complicated" at very first glance: don't worry! Once the `R_e` class is defined, this becomes totally trivial [as I said: `deriv()` gets implemented in just _one short line of code_!])</font>
__Note__ that `n` is always assumed to be a positive integer, and in the case where `n=0`, then `deriv(f,0)` should simply return `f`
<br id="theory"/>
# Some Theory: "What (the h...) is a _Dual Number_?"
Just as the field of Real Numbers can be extended into the field of Complex Numbers, by inserting a new element "i" such that:
```math
i^2 = -1
```
One can aslo extend the Field of Real Numbers <font size=1>(in fact, this is not -at all- limited to "Real Numbers", it can be done with basically any "Semi-Ring"...)</font> into a new Ring called "Dual Numbers", by just inserting a new element "epsilon" which behaves as a <font size=1>(nontrivial)</font> "_nilpotent_" <font size=1>(of _index 2_)</font>, meaning that:
```math
\epsilon^2 = 0, \quad \epsilon \neq 0
```
Elements of this "new ring" are then of the form:
```math
a + b\epsilon
```
and, just like with Complex numbers, it is easy to deduce how they behave under arithmetic operations:
```math
(a + b\epsilon) + (x + y\epsilon) = (a+x) + (b+y)\epsilon \\
(a + b\epsilon)*(x + y\epsilon) = (a*x) + (a*y + b*x)\epsilon
```
also, if "a" is nonzero, then "a+b* epsilon" turns out to be _invertible_ :
```math
(a + b\epsilon)^{-1} = (a^{-1}) + (-a^{-1}*b*a^{-1})\epsilon = ({{1}\over{a}}) + (-{{b}\over{a^{2}}})\epsilon
```
<font size=1>(Sidenote: the second equality holds thanks to <b>commutativity</b>, while the first equality remains true even over non-commutative structures)</font>
More generally, using recursion and commutativity <font size=2>(or the binomial coefficients with the nilpotent property)</font>, it is easy to deduce the formula for exponentiation:
```math
(a + b\epsilon)^{k} = (a^{k}) + (k*a^{k-1}*b)\epsilon
```
...Which actually continues to hold for non-integer values of `k`...
More generally, a Real function is said to be `Analytic` when equal to its Taylor Series Expansion; so that we get:
```math
f(x+h) = f(x) + h*f'(x) + {{h^2}\over{2}}f''(x) + {{h^3}\over{6}}f'''(x) + ...
```
Such functions can then be naturally extended to Dual Numbers, by taking
```math
h = b\epsilon
```
and using the fact that
```math
\epsilon^{2} = 0
```
so that
```math
f(a+b\epsilon) = f(a) + f'(a)*b\epsilon
```
In particular, note that:
```math
f(x+\epsilon) = f(x) + f'(x)\epsilon
```
<br/>
# Hints for computing deriv():
- Computing the `(first) derivative` of Algebraic functions by using Dual Numbers should be obvious enough; either by looking at how Dual Numbers behave under multiplication and comparing it to the Leibniz Rule for derivatives; or simply using the [above] "last remark" about `Analytic Functions`...
- As for the `nth derivatives`, you can either _explore what happens_ when applying (for instance) `R_e(R_e(a,b),R_e(c,d))`... or choose "not to even bother with it" and just go for a _recursive function_...
<br/>
# Some Examples:
- `R_e` :
```python
R_e(5) #returns R_e(5, 0)
R_e(5,6) == R_e(5,6) #returns True
R_e(5,6) == R_e(5,7) #returns False
R_e(5,6) == R_e(6,6) #returns False
R_e(5,6) == 5 #returns False
R_e(5) == 5 #returns True
5 == R_e(5) #returns True
5 + R_e(10,20) #returns R_e(15, 20)
R_e(10,20)+6 #returns R_e(16, 20)
R_e(1,5)+R_e(6,-7) #returns R_e(7, -2)
-R_e(1,2) #returns R_e(-1, -2)
1-R_e(2,3) #returns R_e(-1, -3)
R_e(2,3) - 1 #returns R_e(1, 3)
R_e(3,4) - R_e(5,10) #returns R_e(-2, -6)
10*R_e(3,4) #returns R_e(30, 40)
R_e(2,3)*5 #returns R_e(10, 15)
R_e(3,4)*R_e(5,6) #returns R_e(15, 38)
R_e(0,5)*R_e(0,12) #returns R_e(0, 0)
R_e(1,5)*R_e(1,-5) #returns R_e(1, 0)
1/R_e(1,10) #returns R_e(1.0, -10.0)
1/R_e(5,10) #returns R_e(0.2, -0.4)
R_e(5,10)/5 #returns R_e(1.0, 2.0)
R_e(5,10)/R_e(5,-10) #returns R_e(1.0, 4.0)
R_e(1,10)**(-1) #returns R_e(1.0, -10.0)
R_e(5,-10)**2 #returns R_e(25, -100)
R_e(25, -100)**0.5 #returns R_e(5.0, -10.0)
R_e(1,3)**3 #returns R_e(1, 9)
R_e(1, 9)**(1/3) #returns R_e(1.0, 3.0)
```
- deriv()
```python
deriv(lambda x : 3*x**2 + 2*x + 1) #returns "the equivalent of": lambda x : 6*x + 2
deriv(lambda x : 3*x**2 + 2*x + 1,2) #returns "the equivalent of": lambda x : 6
deriv(lambda x : x/(x**2+1)**0.5) #returns "the equivalent of"... lambda x: 1/(x**2+1)**0.5 - x**2/(x**2+1)**1.5
deriv(lambda x : x**7,4) #returns "the equivalent of": lambda x: 840*x**3
deriv(lambda x : x**7,4)(0) #returns 0
deriv(lambda x : x**7,4)(1) #returns 840
deriv(lambda x : x**7,4)(2) #returns 6720
```
<br/>
# "Beyond the Kata": Extra Information "for Curious people" ;)
(...who'd like to explore further/understand more in-depth...)
### Note that:
- Despite always talking about "Real Numbers" in this Kata, everything should already "automatically work on Complex Numbers too"
- Despite focusing on "Algebraic functions" in this Kata, the algorithm can (VERY) easily be extended to include more [analytic] functions such as trigonometric/hyperbolic/elliptic functions (for instance); it suffices for this to define their behaviour on the class R_e (which basically amounts to coding their derivative); then any nth derivative of any combinations of such functions will automatically be calculable...
- It's not only about "Real/Complex Numbers": this algorithm can go way beyond and (VERY) easily be extended to more general structures: e.g. "Quaternions", "Matrices", "Algebraic Expressions (With possibly many variables)", or any kind of (possibly non-commutative) _semi-Ring_!..
- ((Here, in the examples, I chose "R_e(a,b)" as a representation of Dual Numbers (as it's probably the "cleaner option"); but I usually find it feels "more natural" (though "not good practice") to define a global variable epsilon = R_e(0,1) and represent the Dual Numbers as (a+b*epsilon) ))
- Giving "Dual Numbers as an input to Dual Numbers", i.e. "R_e(R_e(a,b),R_e(c,d))" will basically produce the equivalent of "a nilpotent extension of the nilpotent extension", which -mathematically- amounts to taking some kind of "Tensor Product" (of Dual Numbers over R) : this allows -amongst others- to generate nilpotent elements of index higher than 2...
- (As in the process of calculating the nth derivative, the "previous ones" are calculated too, it might be an interesting approach to "keep them" [which can then be reused for other tasks, such as "integrating", for instance] rather than "only returning the nth one")
- For nth derivative, the complexity (and memory allocated) quickly gets awful as n grows, at least using a "naive implementation" (as I did and as you are expected to do!..)
...but there exist ways to consistently increase the algorithm's efficiency!.. ;) (But you're NOT asked to implement such optimizations in this Kata)
| reference | class R_e:
def __init__(self, real, epsilon=0):
self . real = real
self . epsilon = epsilon
def __str__(self): # (Not necessary to complete the Kata; but always useful)
return "R_e(" + str(self . real) + ", " + str(self . epsilon) + ")"
def __repr__(self): # (Not necessary to complete the Kata; but always useful)
return str(self)
def inclusion_map(self, other): # Will be used later to implicitly convert reals into R_e
return other if type(other) == type(self) else R_e(other)
def __eq__(self, other):
other = self . inclusion_map(other)
return self . real == other . real and self . epsilon == other . epsilon
def __add__(self, other):
other = self . inclusion_map(other)
return R_e(self . real + other . real, self . epsilon + other . epsilon)
def __radd__(self, other): # Obviously assumes commutativity for addition
return self + other
def __neg__(self):
return R_e(- self . real, - self . epsilon)
def __sub__(self, other):
return self + (- other)
def __rsub__(self, other):
return other + (- self)
def __mul__(self, other): # Does not necessarily have to be commutative
other = self . inclusion_map(other)
return R_e(self . real * other . real, self . real * other . epsilon + self . epsilon * other . real)
def __rmul__(self, other): # Does not necessarily assume the multiplication to be commutative; hence can easily be generalized to non-commutative structures (...Such as "Quaternions" :) )
other = self . inclusion_map(other)
return R_e(other . real * self . real, other . real * self . epsilon + other . epsilon * self . real)
def inverse(self): # Does not necessarily assume multiplication to be commutative, hence can be generalized to... (gosh I really do like "Quaternions")
# Otherwise, one could just compute __pow__ first, and then return self**(-1)
rx = 1 / self . real
# General non-commutative formula
return R_e(rx, - rx * (self . epsilon) * rx)
def __truediv__(self, other):
return self * (self . inclusion_map(other). inverse())
def __rtruediv__(self, other):
return other * (self . inverse())
def __pow__(self, n): # n must be "real"; NB: here, for this Kata, this function assumes that the "real" and "epsilon" parts commute together (which will always trivially be the case with Real or Complex Numbers),
# thus allowing to use this "simpler version", which also allows "non-integer" values for n
# however, if this were to be implemented for more general, non-commutative structures, the "power" should then be
# defined recursively (for integers), using, for example the well-known "Exponentiation by squaring" algorithm...
return R_e(self . real * * n, n * self . real * * (n - 1) * self . epsilon)
def deriv(f, n=1): # the "+R_e(0)" is there only to handle the particular case where f is a constant such as lambda x : 1; as epsilon is not defined for integers
return f if n == 0 else deriv(lambda x: (f(R_e(x, 1)) + R_e(0)). epsilon, n - 1)
| "Dual Numbers" and "Automatic" (nth) Derivatives | 615e3cec46a119000efd3b1f | [
"Mathematics",
"Algebra",
"Fundamentals",
"Tutorials"
] | https://www.codewars.com/kata/615e3cec46a119000efd3b1f | 5 kyu |
More difficult version: [Kingdoms Ep2: The curse (normal)](https://www.codewars.com/kata/615b636c3f8bcf0038ae8e8b)
Our King was cursed - He can not pronounce an entire word anymore. Looking for the witch, the inquisition punishes every beautiful and intelligent woman in the Kingdom. Trying to save your wife and to stop the violence, you beg the audience of the Highest Priest, explaining that you can understand the King's speech. The future of your family is in your hands!
Given the string `speech` and the array `vocabulary`. You should return a string of replaced "encoded" _words_ in `speech` with appropriate word from `vocabulary`.
#### Notes:
- Encoded words consist of lowercase letters and at least one asterisk;
- There will always be only one appropriate word from `vocabulary` for every word in `speech`;
- `speech` consists of lowercase letters, spaces and marks `?!,.` ;
- There might be more words in `vocabulary` than `words` in speech;
- The length of an encoded word must be the same as an appropriate word of vocabulary;
- The minimum length of a word is 3;
#### Example:
```javascript
given: speech = "***lo w***d!" and vocabulary = ["hello", "world"]
return "hello world!"
```
```javascript
given: speech = "c**l, w*ak!" and vocabulary = ["hell", "cell", "week", "weak"]
return "cell, weak!"
```
If you like this kata, check out the another one: [Kingdoms Ep.3: Archery Tournament](https://www.codewars.com/kata/616eedc41d5644001ff97462/javascript)

_The King suspecting you don't understand him_
(to break the curse read the words in the final test) | reference | import re
def translate(s, voc):
return re . sub(r'[\w*]+', lambda m: next(filter(re . compile(m . group(). replace('*', '.')). fullmatch, voc)), s)
| Kingdoms Ep2: The curse (simplified) | 6159dda246a119001a7de465 | [
"Fundamentals",
"Arrays",
"Regular Expressions"
] | https://www.codewars.com/kata/6159dda246a119001a7de465 | 6 kyu |
# Info
Lists are general purpose data structures. In Lambda Calculus, lists can be represented with pairs: the first element of a pair indicates whether the list is empty or not ( as a Church Boolean ), and the second element is another pair of the head and the tail of the list.
Pairs can be represented as a function that will run its ( embedded ) values on its argument, also a function.
Booleans can be represented as a function that chooses between its two arguments.
This kata uses the above encodings.
***Note**: If not already, you may want to familiarize yourself with the concepts of [function currying](https://www.codewars.com/kata/53cf7e37e9876c35a60002c9) and [Church encoding](https://www.codewars.com/kata/5ac739ed3fdf73d3f0000048) before you start this kata.*
~~~if:haskell,
For technical reasons, `type`s `Boolean`, `Pair` and `List` are `newtype`s ( see `Preloaded` ). There will be wrapping and unwrapping, possibly a lot. We apologise for the inconvenience.
~~~
~~~if:lambdacalc,
## Definitions
A `Boolean` is either `True` or `False` (Church booleans).
`Pair` is built from two elements. When a `Boolean` is applied to a `Pair`, either the first element (for `True`) or second element (for `False`) is returned.
`List` is `Pair Empty (Pair Head Tail)` where `Empty` is a `Boolean` indicating if this is the end of the `List`, `Head` is a single element, and `Tail` is the remaining `List`.
Purity is `LetRec`.
~~~
~~~if-not:haskell,lambdacalc
## Definitions
`BOOL` is either `TRUE` or `FALSE` (Church booleans)
`PAIR` is built from two elements. When a `BOOL` is applied to a `PAIR`, either the first element (for `TRUE`) or second element (for `FALSE`) is returned.
`LIST` is `PAIR(EMPTY)(PAIR(HEAD)(TAIL))` where `EMPTY` is a `BOOL` indicating if this is the end of the `LIST`, `HEAD` is a single element, and `TAIL` is the remaining `LIST`.
~~~
## Task
~~~if:python,javascript,
You will be required to write two functions: `APPEND` and `PREPEND`.
~~~
~~~if:haskell,lambdacalc,
You will be required to write two functions: `append` and `prepend`.
~~~
Both take a list and an element as arguments and add the element to the list, in last and first position respectively.
## Given Functions
The following functions are given to you `Preloaded` :
```python
TRUE = lambda a: lambda b: a
FALSE = lambda a: lambda b: b
PAIR = lambda a: lambda b: lambda c: c(a)(b)
FIRST = lambda p: p(TRUE)
SECOND = lambda p: p(FALSE)
NIL = PAIR(TRUE)(TRUE)
IS_EMPTY = lambda xs: FIRST(xs)
HEAD = lambda xs: FIRST(SECOND(xs))
TAIL = lambda xs: SECOND(SECOND(xs))
```
```javascript
TRUE = t => f => t // Boolean
FALSE = t => f => f // Boolean
PAIR = fst => snd => fn => fn(fst)(snd) // creates a pair
FIRST = fn => fn(TRUE) // extracts first value from a pair
SECOND = fn => fn(FALSE) // extracts second value from a pair
NIL = PAIR(TRUE)() // constant: the empty list
IS_EMPTY = xs => FIRST(xs) // returns a Church Boolean indicating if a list is empty
HEAD = xs => FIRST(SECOND(xs)) // returns the first element of a list // list must not be empty
TAIL = xs => SECOND(SECOND(xs)) // returns a list without its first element // list must not be empty
```
```haskell
newtype Boolean = Boolean { runBoolean :: forall a. a -> a -> a }
false,true :: Boolean
false = Boolean $ \ t f -> f
true = Boolean $ \ t f -> t
newtype Pair x y = Pair { runPair :: forall z. (x -> y -> z) -> z }
pair :: x -> y -> Pair x y
pair x y = Pair $ \ z -> z x y
first :: Pair x y -> x
first (Pair xy) = xy $ \ x y -> x
second :: Pair x y -> y
second (Pair xy) = xy $ \ x y -> y
newtype List x = List { runList :: Pair Boolean (Pair x (List x)) }
nil :: List x
nil = List $ pair true undefined
isEmpty :: List x -> Boolean
isEmpty (List xs) = first xs
head :: List x -> x
head (List xs) = first $ second xs
tail :: List x -> List x
tail (List xs) = second $ second xs
```
```lambdacalc
True = \ t _ . t
False = \ _ f . f
Pair = \ a b . \ f . f a b
first = \ p . p True
second = \ p . p False
Nil = Pair True ()
is-empty = \ xs . first xs
head = \ xs . first (second xs)
tail = \ xs . second (second xs)
```
## Syntax
```python
# showing a list as < value .. > to emphasise it's not a native Python list
APPEND (NIL) ( 1 ) == < 1 >
PREPEND (NIL) ( 1 ) == < 1 >
APPEND (< 1 >) ( 2 ) == < 1 2 >
PREPEND (< 1 >) ( 2 ) == < 2 1 >
```
```javascript
// showing a list as < value .. > to emphasise it's not a JavaScript array
APPEND (NIL) ( 1 ) => < 1 >
PREPEND (NIL) ( 1 ) => < 1 >
APPEND (< 1 >) ( 2 ) => < 1 2 >
PREPEND (< 1 >) ( 2 ) => < 2 1 >
```
```haskell
-- showing a list as < value .. > to emphasise it's not a native Haskell list
append nil 1 -> < 1 >
prepend nil 1 -> < 1 >
append < 1 > 2 -> < 1 2 >
prepend < 1 > 2 -> < 2 1 >
```
```lambdacalc
# Showing a list as < value .. >
append Nil 1 # < 1 >
prepend Nil 1 # < 1 >
append < 1 > 2 # < 1 2 >
prepend < 1 > 2 # < 2 1 >
```
~~~if:javascript
This is Lambda Calculus, and so there are restrictions on the syntax allowed.
In Javascript, this means only definitions (without `const`, `let` or `var`). Functions can be defined using fat arrow notation only. Functions may take either zero or one argument.
Some examples of *valid* syntax:
```javascript
pair = a => b => c => c(a)(b)
zero = _ => x => x
cons = pair
thunk = (() => x) ()
```
Some examples of *invalid* syntax:
```javascript
const one = f => x => f(x); // const, and semicolon (;) are not allowed
function head(l) { return l(true) } // functions must use fat arrow notation
fold = f => x => l => l.reduce(f, x) // Only variables, functions and applications are allowed. Attribute accessing (.), and functions taking multiple arguments, are not allowed.
```
~~~
~~~if:python
This is Lambda Calculus, and so there are restrictions on the syntax allowed.
In Python, this means only definitions. Functions can be defined using lambda notation only. Functions must always take a single argument.
Some examples of *valid* syntax:
```python
pair = lambda a: lambda b: lambda c: c(a)(b)
zero = lambda f: lambda x: x
cons = pair
```
Some examples of *invalid* syntax:
```python
one = lambda: lambda f,x: f(x) # Functions must take one argument
def head(l):
return l(true) # functions must use lambda notation
choose = lambda a: lambda b: lambda c: a if c else b # Only variables, lambda functions and applications are allowed. Anything else (eg. ... if ... else ... ) is not.
```
~~~
## Help:
[Wikipedia: Lambda Calculus](https://en.wikipedia.org/wiki/Lambda_calculus)
[The Y Combinator](https://en.wikipedia.org/wiki/Fixed-point_combinator#Y_combinator)
[YouTube: Computerphile](https://www.youtube.com/watch?v=eis11j_iGMs&feature=youtu.be)
### Notes
Feel free to contribute to the kata in anyway.
Feedback would be greatly appreciated. | reference | def PREPEND(vs): return lambda v: PAIR(FALSE)(PAIR(v)(vs))
def BUILD_TAIL(vs): return lambda v: PREPEND(APPEND(TAIL(vs))(v))(HEAD(vs))
def APPEND(vs): return (IS_EMPTY(vs)(PREPEND)(BUILD_TAIL))(vs)
| Lambda Calculus: Lists | 5eecd4a5e5d13e000150e249 | [
"Functional Programming",
"Fundamentals",
"Lists",
"Data Structures"
] | https://www.codewars.com/kata/5eecd4a5e5d13e000150e249 | 5 kyu |
You are given an array of strings that need to be spread among N columns. Each column's width should be the same as the length of the longest string inside it.
Separate columns with `" | "`, and lines with `"\n"`; content should be left-justified.
`{"1", "12", "123", "1234", "12345", "123456"}` should become:
```
1
12
123
1234
12345
123456
```
for 1 column,
```
1 | 12
123 | 1234
12345 | 123456
```
for 2 columns,
```
1 | 12 | 123 | 1234
12345 | 123456
```
for 4 columns. | algorithms | from itertools import zip_longest
def columnize(a, n):
a = [a[i: i + n] for i in range(0, len(a), n)]
b = [max(map(len, x)) for x in zip_longest(* a, fillvalue="")]
return "\n" . join(" | " . join(y . ljust(z) for y, z in zip(x, b)) for x in a)
| Columnize | 6087bb6050a6230049a068f1 | [
"Fundamentals",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/6087bb6050a6230049a068f1 | 6 kyu |
## Task
Implement a function which takes an array of nonnegative integers and returns **the number of subarrays** with an **odd number of odd numbers**. Note, a subarray is a ***contiguous subsequence***.
## Example
Consider an input:
```python
[1, 2, 3, 4, 5]
```
The subarrays containing an odd number of odd numbers are the following:
```python
[1, 2, 3, 4, 5], [2, 3, 4], [1, 2], [2, 3], [3, 4], [4, 5], [1], [3], [5]
```
The expected output is therefore `9`.
## Test suite
**100 random tests**, with small arrays, `5 <= size <= 200`, testing the correctness of the solution.
```if:python
**10 performance tests**, with arrays of size `200 000`.
```
```if:cpp
**50 performance tests**, with arrays of size `500 000`.
```
The expected output for an **empty array** is `0`, otherwise the content of the arrays are always integers `k` such that `0 <= k <= 10000`.
**Expected time complexity is O(n)** | algorithms | def solve(arr):
e, o, s = 0, 0, 0
for n in arr:
if n & 1:
e, o = o, e + 1
else:
e += 1
s += o
return s
| Subarrays with an odd number of odd numbers | 6155e74ab9e9960026efc0e4 | [
"Algorithms",
"Performance"
] | https://www.codewars.com/kata/6155e74ab9e9960026efc0e4 | 5 kyu |
Your task is to return the amount of white rectangles in a `NxN` spiral. Your font may differ, if we talk of white rectangles, we talk about the symbols in the top row.
#### Notes:
* As a general rule, the white snake cannot touch itself.
* The size will be at least 5.
* The test cases get very large, it is not feasible to calculate the solution with a loop.
## Examples
For example, a spiral with size 5 should look like this:
β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬
And return the value 17 because the total amount of white rectangles is 17.
---
A spiral with the size 7 would look like this:
β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬
And return the value 31 because the total amount of white rectangles is 31.
---
A spiral with the size 8 would look like this:
β¬β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬β¬
And return the value 39 because the total amount of white rectangles is 39.
---
A spiral with the size 9 would look like this:
β¬β¬β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬β¬β¬
And return the value 49 because the total amount of white rectangles is 49.
---
A spiral with the size 10 would look like this:
β¬β¬β¬β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬β¬β¬β¬\
β¬β¬β¬β¬β¬β¬β¬β¬β¬β¬
And return the value 59 because the total amount of white rectangles is 59.
| games | def spiral_sum(n): return (n + 1) * * 2 / / 2 - 1
| Count a Spiral | 61559bc4ead5b1004f1aba83 | [
"Puzzles"
] | https://www.codewars.com/kata/61559bc4ead5b1004f1aba83 | 6 kyu |
This kata is based on the [Socialist distribution](https://www.codewars.com/kata/socialist-distribution) by GiacomoSorbi. It is advisable to complete it first to grasp the idea, and then move on to this one.
___
## Task
You will be given a list of numbers representing the people's resources, and an integer - the minimum wealth each person must possess. You have to redistribute the resources among the people in such way that everybody would fulfil the minimum-wealth requirement.
The redistribution step consists of 2 operations:
* taking 1 unit of the resource from the first richest person in the list
* giving 1 unit of the resource to the first poorest person in the list
This process is repeated until everybody hits the minimum required wealth level.
**Note**: there's always enough resources for everybody.
## Example (step by step)
```
distribution([4, 7, 2, 8, 8], 5) == [5, 6, 5, 6, 7]
0. [4, 7, 2, 8, 8]
+ -
1. [4, 7, 3, 7, 8]
+ -
2. [4, 7, 4, 7, 7]
+ -
3. [5, 6, 4, 7, 7]
+ -
4. [5, 6, 5, 6, 7]
``` | algorithms | def distribution(population, minimum):
if (diff := sum(minimum - p for p in population if p < minimum)) == 0:
return population
popul, total = sorted(population, reverse=True), 0
rich = next(k for k, (v, p) in enumerate(
zip(popul, popul[1:]), 1) if (total := total + v) - p * k >= diff)
money, rem = divmod(total - diff, rich)
return [minimum if p < minimum else money + int((rich := rich - 1) < rem) if p > money else p for p in population]
| Socialist distribution (performance edition) | 5dd08d43dcc2e90029b291af | [
"Algorithms",
"Performance"
] | https://www.codewars.com/kata/5dd08d43dcc2e90029b291af | 5 kyu |
# Narrative
Your task is to create brain for amoeba. You're lucky because this creature doesn't think a lot - all what it wants is food.
```
~* ::
```
Your fellow amoeba floats in 2D primordial soup that looks like a maze. It has no eyes, so it can't see the whole maze, but it have sense of smell that helps it to know how far from food it is.
```
|| ||
|| ||
|||||| ||||||
~* "sniff"
|||||| ||||||
|| ||
|| ||
```
Amoeba needs to hurry, because it could starve to death if it will take too long to get to food.
# Task
Your task is to implement navigation logic from random point in maze to point with food. Navigation logic must be implemented in get_move_direction() method of AmoebaBrain class.
Notes on maze:
* Size and structure of maze will be random.
* Method get_move_direction() will be called (size_of_maze**1.7 + size_of_maze) times, and if amoeba won't get to food at last call - it will die. I ran thousands of simulations - this value of iterations will cover worst case scenario for optimal algorithm.
get_move_direction() has two parameters: surrounding and food_smell.
* surrounding -- list of lists with bool values, that shows possible move directions without obstacles.
This is how it could look:
```python
surrounding = [
[False, False, False],
[True, False, True],
[False, True, False]]
```
From this surrounding amoeba could understand that directions left (-1, 0), down (0, -1) and right (1, 0) are possible. Central "direction" (direction[1][1]) is always False.
* food_smell -- float value in range [0, 1] that shows how far amoeba is from food: 0 - farthest point from food, 1 - food.
Food smell doesn't work through walls, and shows shortest path to the food - if amoeba will go in directions with increasing values, it will find food.
* get_move_direction() returns tuple of two integer values in range of [-1, 1], that represents x and y direction where amoeba will try to move. Y axis directed up, X axis directed right - (-1, 1) is left-up (west-north) direction.
If amoeba will try to go through wall - it will just remain on the same place (you will see print in logs if this situation occurs).
# Help in debugging
In test cases you could use additional parameters "size_of_maze" and "show_maze_iterations" for functions:
```python
def test_amoeba_brain(amoeba_brain, maze=None, size_of_maze_to_generate=None,
show_debug=False, iterations_limit=None):
...
```
* amoeba_brain - AmoebaBrain class to test.
* maze - custom maze. It's list of lists with values in range [0, 3]: 0 - empty, 1, wall, 2 - amoeba, 3 - food. There is example in sample test.
* size_of_maze_to_generate - size of maze, must be in range [3, 50]. You could use this parameter if you want to test your amoeba in some random maze with given size.
* show_debug - toggles debug print of all maze traversal iterations.
* iterations_limit - you could set this parameter if you want to check only several iterations of simulation (to reduce log size when show_debug is on).
* return value - is this amoeba found it's food?
Only one of parameters "maze" or "size_of_maze_to_generate" could be specified at one time.
Legend for debug print:
* ~* - amoeba
* :: - food
* || - wall
* number - smell value of empty space
Example of one iteration debug:
```
::::::::::::::ITERATION 0/20::::::::::::::
~~~~~~~~BEFORE MOVE~~~~~~~~
:: || 16 22 28
94 || || || 34
88 82 76 || 40
|| || 70 || 46
52 58 64 58 ~*
~~~~get_move_direction()~~~~
~~~~~~~~AFTER MOVE~~~~~~~~~
:: || 16 22 28
94 || || || 34
88 82 76 || 40
|| || 70 || ~*
52 58 64 58 52
:::::::::::::::::::::::::::::::::::::::
```
If your amoeba will die, you will receive postmortem log like this, to figure out what's wrong:
```
Amoeba died from starvation :c
~~~~~~HELP IN DEBUGGING~~~~~~
You've reached maximum amount of iterations: 20
Here is how maze looked like at start:
52 58 64 || ::
46 || 70 || 94
40 || 76 82 88
34 || || || ||
~* 22 16 10 04
Here is how it looks at the end:
52 58 64 || ::
46 || 70 || 94
40 || 76 82 88
34 || || || ||
~* 22 16 10 04
You could debug this maze by putting following list in "maze" parameter in test_amoeba_brain():
[[0, 0, 0, 1, 3], [0, 1, 0, 1, 0], [0, 1, 0, 0, 0], [0, 1, 1, 1, 1], [2, 0, 0, 0, 0]]
```
P.S.: I'm new in Kata's creation, so please leave feedback - I want to get better at it. Thank you! c: | games | class AmoebaBrain:
def __init__(self):
self . smell = - 1
self . checked = set()
self . back = None
self . X = self . Y = 0
def get_move_direction(self, surrounding, food_smell):
# Current pos is now tested, no need to try it again later
self . checked . add((self . X, self . Y))
# We went in the wrong direction, let's go back
if food_smell < self . smell:
self . X += self . back[0]
self . Y += self . back[1]
return self . back
# Best smell is new smell
self . smell = food_smell
for x in range(- 1, 2):
for y in range(- 1, 2):
# That's not a wall and we didn't check this path before
if surrounding[- y + 1][x + 1] and (self . X + x, self . Y + y) not in self . checked:
# Onward to food!
self . X += x
self . Y += y
self . back = (- x, - y)
return (x, y)
# Guess we're starving
raise Exception("No path found!")
| Amoeba: Blind Maze | 614f1732df4cfb0028700d03 | [
"Puzzles"
] | https://www.codewars.com/kata/614f1732df4cfb0028700d03 | 5 kyu |
<h3>Electronics #1. Ohm's Law</h3>
This is based on Ohm's Law: V = IR
<br>being:
<br>V: Voltage in volts (V)
<br>I: Current in amps (A)
<br>R: Resistance in ohms (R)
<h3>Task</h3>
Create a function ohms_law(s) that has an input string.
<br>Your get a string in the form:
<br>'2R 10V' or '1V 1A' for example.
<br>Each value of magnitude in the string will be expressed in 'V', 'A' or 'R'
<br>Each value is separated by a space bar in the string.
<br>You must return a string with the value of missing magnitude followed by the unit ('V', 'A', 'R').
<br>That value will be rounded to six (6) decimals.
<h3>Examples</h3>
'25V 1e-2A' --> '2500.0R'
<br>'2200R 5V' --> '0.002273A'
<br>'3.3e-3A 1e3R' --> '3.3V'
<h3>Inputs</h3>
All inputs will be valid, no need to check them.
| reference | f = {
'V': lambda d: d['A'] * d['R'],
'A': lambda d: d['V'] / d['R'],
'R': lambda d: d['V'] / d['A']
}
def ohms_law(s):
data = {v[- 1]: float(v[: - 1]) for v in s . split()}
res_key = next(iter(set(f) - set(data)))
value = str(round(f[res_key](data), 6))
return f' { value }{ res_key } '
| Electronics #1. Ohm's Law | 614dfc4ce78d31004a9c1276 | [
"Fundamentals"
] | https://www.codewars.com/kata/614dfc4ce78d31004a9c1276 | 7 kyu |
Expansion is performed for a given 2x2 matrix.
```
[
[1,2],
[5,3]
]
```
After expansion:
```
[
[1,2,a],
[5,3,b],
[c,d,e]
]
```
- a = 1 + 2 = 3
- b = 5 + 3 = 8
- c = 5 + 1 = 6
- d = 3 + 2 = 5
- e = 1 + 3 = 4
Final result:
```
[
[1,2,3],
[5,3,8],
[6,5,4]
]
```
## TASK
Let expansion be a function which takes two arguments:
- A: given NxN matrix
- n: number of expansions
| games | import numpy as np
def expansion(matrix, n):
arr = np . array(matrix)
for i in range(n):
new_col = arr . sum(axis=1)
new_row = arr . sum(axis=0)
new_e = np . trace(arr)
new_row = np . append(new_row, new_e). reshape((1, len(arr) + 1))
arr = np . c_[arr, new_col]
arr = np . r_[arr, new_row]
arr[- 1, - 1] = new_e
return arr . tolist()
| Matrix Expansion | 614adaedbfd3cf00076d47de | [
"Algebra",
"Puzzles",
"Matrix"
] | https://www.codewars.com/kata/614adaedbfd3cf00076d47de | 6 kyu |
Jack's teacher gave him a ton of equations for homework. The thing is they are all kind of same so they are boring.
So help him by making a equation solving function that will return the value of x.
Test Cases will be like this:
```
# INPUT # RETURN
'x + 1 = 9 - 2' # 6
'- 10 = x' # -10
'x - 2 + 3 = 2' # 1
'- x = - 1' # 1
```
- All test cases are valid.
- Every `+`, `-` and numbers will be separated by space.
- There will be only one `x` either on the left or right.
- `x` can have a `-` mark before it.
- returned object will be a integer. | algorithms | def solve(eq):
a, b = eq . replace('x', '0'). split('=')
x = eval(a) - eval(b)
if '- x' in eq:
x *= - 1
return x if eq . index('x') > eq . index('=') else - x
| Value of x | 614ac445f13ead000f91b4d0 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/614ac445f13ead000f91b4d0 | 5 kyu |
[Fischer random chess](https://en.wikipedia.org/wiki/Fischer_random_chess), also known as Chess960, is a variant of chess, invented by Bobby Fischer on June 19, 1996.
The rules are the same as regular chess, but the starting position is randomized according to the **randomization rules** (see below). Note that prior knowledge of chess is not required to solve this kata, however some basic knowledge like piece distribution, initial setup, ranks vs files etc. is assumed. [Here](https://en.wikipedia.org/wiki/Chess#Setup) is a quick refresher.
**Randomization Rules**
1) The 2nd and 7th rank stay the same as in a normal game, filled with pawns.
2) All the remaining white pieces must be on the 1st rank, and black pieces on the 8th rank.
3) The two bishops must start on differently colored squares.
4) The rooks must be located on either side of the king; in other words, the king must be placed on a square between the two rooks.
5) The queen and knights can be located on any remaining square in the rank.
Both White and Black share the same starting position, drawn at random, in accordance to these rules.
Side note: in accordance with these rules, there are a total of 960 possible starting positions, hence the name of the variant.
**Representation of position**
For the purpose of this kata:
- Rooks are abbreviated as `R`
- Knights are abbreviated as `N`
- Bishops are abbreviated as `B`
- Queen is abbreviated as `Q`
- King is abbreviated as `K`
Since black mirrors white's setup, it is enough to list White's position to fully describe the position. Furthermore, only the first rank needs to be defined, as the second rank is filled with pawns regardless of situation.
A starting position is represented by an 8 character long `String`. Each character in the `String` denotes a specific piece, in order from left-to-right.
An example starting position would be:
`RNBQKBNR`
## Your task
Given a string representation, determine whether it represents a valid Chess960 starting position. Note that the input is guaranteed to represent one king, one queen, two rooks, two bishops and two knights, in some order. You do not have to validate for missing pieces or extra pieces.
| reference | def is_valid(positions):
# get relevant positions
bishop_left = positions . find("B")
bishop_right = positions . rfind("B")
rook_left = positions . find("R")
rook_right = positions . rfind("R")
king = positions . find("K")
# valid if king between rooks and bishops on different colors
return rook_left < king < rook_right and bishop_left % 2 != bishop_right % 2
| Is this a valid Chess960 position? | 61488fde47472d000827a51d | [
"Fundamentals",
"Algorithms",
"Games",
"Strings"
] | https://www.codewars.com/kata/61488fde47472d000827a51d | 7 kyu |
## Task
Given a positive integer, `n`, return the number of possible ways such that `k` positive integers multiply to `n`. Order matters.
**Examples**
```
n = 24
k = 2
(1, 24), (2, 12), (3, 8), (4, 6), (6, 4), (8, 3), (12, 2), (24, 1) -> 8
n = 100
k = 1
100 -> 1
n = 20
k = 3
(1, 1, 20), (1, 2, 10), (1, 4, 5), (1, 5, 4), (1, 10, 2), (1, 20, 1),
(2, 1, 10), (2, 2, 5), (2, 5, 2), (2, 10, 1), (4, 1, 5), (4, 5, 1),
(5, 1, 4), (5, 2, 2), (5, 4, 1), (10, 1, 2), (10, 2, 1), (20, 1, 1) -> 18
```
**Constraints**
`1 <= n <= 1_000_000_000_000`
and `1 <= k <= 1_000` | algorithms | from scipy . special import comb
def multiply(n, k):
r, d = 1, 2
while d * d <= n:
i = 0
while n % d == 0:
i += 1
n / /= d
r *= comb(i + k - 1, k - 1, exact=True)
d += 1
if n > 1:
r *= k
return r
| Multiply to `n` | 5f1891d30970800010626843 | [
"Mathematics",
"Algebra",
"Performance",
"Algorithms"
] | https://www.codewars.com/kata/5f1891d30970800010626843 | 4 kyu |
## Description:
The Padovan sequence is the sequence of integers P(n) defined by the initial values
P(0)=P(1)=P(2)=1
and the recurrence relation
P(n)=P(n-2)+P(n-3)
The first few values of P(n) are
1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37, 49, 65, 86, 114, 151, 200, 265, ...
## Task
```if:java
The task is to write a method that returns i-th Padovan number for i around 1,000,000
```
```if:python
n can go upto 2000000. The import of all aiding libraries like `numpy, scipy, sys...` is forbidden.
```
## Examples
```if:java
> Padovan.Get(0) == 1
> Padovan.Get(1) == 1
> Padovan.Get(2) == 1
> Padovan.Get(n) == Padovan.Get(n-2) + Padovan.Get(n-3)
```
```if:python
padovan(0) == 1
padovan(1) == 1
padovan(2) == 1
padovan(n) == padovan(n-2) + padovan(n-3)
```
Hint: use matrices | reference | def padovan(n):
x, y, z = 1, 0, 0
for c in map(int, bin(n)[2:]):
x, y, z = x * x + 2 * y * z, 2 * x * y + y * \
y + z * z, x * z + 2 * y * z + x * z + y * y
if c:
x, y, z = y, z, x + y
return x + y + z
| Big Big Big Padovan Number | 5819f1c3c6ab1b2b28000624 | [
"Performance",
"Algorithms",
"Big Integers"
] | https://www.codewars.com/kata/5819f1c3c6ab1b2b28000624 | 4 kyu |
The goal of this Kata is to build a very simple, yet surprisingly powerful algorithm to extrapolate sequences of _numbers_*
(* in fact, it would work with literally any "[sequence of] _objects that can be added and subtracted_"!)
This will be achieved by using a little Mathematical "trick" (Binomial Transform), which will be explained below; and by splitting the problem into 3 (simpler) tasks:
* __Task1:__ Build a function `delta()`, which will take a number sequence (list) as an input and return the differences of its successive terms (see below for further explanation)
* __Task2:__ Build a function `dual_seq()`, which will take a number sequence (list) and return its "Dual" (_Binomial Transform_; see information below)
* __Task3:__ Finally, build a function `extra_pol()`, which will take a number sequence (list), as well as a positive integer "n" and return the sequence completed by the "n" following terms, according to the "best possible polynomial extrapolation" (don't worry: the code for this part should actually be (much) shorter than this sentence! ;) )
___Some Theory:___
__Differences__
* Let `(x_0, x_1, x_1, ..., x_{n-1}, x_n)` be a finite sequence of length `n+1`, one can compute its successive differences in the following way: `(x_0 - x_1, x_1 - x_2, ..., x_{n-1}-x_{n})`, which will -obviously- be of length `n` . (This is what your function `delta()` will be expected to do!)
__Dual Sequence (Binomial Transform)__
* By iterating the process, one can compute its _Binomial Transform_, which will be given by: (y_0, y_1, ..., y_n), where:
```math
y_0 = x_0 \\
y_1 = x_0 - x_1 \\
y_2 = (x_0 - x_1) - (x_1 - x_2) = x_0 - 2x_1 + x_2 \\
y_3 = (x_0 - 2x_1 + x_2) - (x_1 - 2x_2 + x_3) = x_0 - 3x_1 + 3x_2 -x_3 \\
y_4 = (x_0 - 3x_1 + 3x_2 -x_3) - (x_1 - 3x_2 + 3x_3 -x_4) \\
\quad = x_0 - 4x_1 + 6x_2 - 4x_3 +x_4 \\
etc \quad etc...
```
(notice the binomial coefficients)
The Binomial transform possesses several useful properties; including:
* `linearity` : if a _pointwise_ sum were defined on the sequences (NB: you are obviously NOT asked to implement this), we could easily see that `dual_seq(A+B) = dual_seq(A)+dual_seq(B)`
* `involution`: as the name `dual` suggests, it is always true that `dual_seq(dual_seq(A)) = A` (this is not only "elegant" but also very useful!)
* finally, it might be useful to notice that this tranform behaves in a particular way on `polynomials`: indeed, if a sequence `(x_n)` is obtained from a polynomial `p` of degree `d` i.e. such that
```math
\forall n, \quad x_n = p(n)
```
then it follows that its Dual (Binomial Transform) will be of the form:
```math
y_0, y_1, y_2, ... y_d, 0, 0, 0, 0, ...
```
(i.e. only zeros after the term `y_d`)
__Polynomial values__
* Given a sequence `(x_0, x_1, ..., x_d)` of `d+1` points, there exists a unique polynomial `p_d` of degree (not higher than) `d`, which passes successively through those points; i.e. such that
```math
p_{d}(0) = x_0, \quad p_{d}(1) = x_1, \quad ..., \quad p_{d}(d) = x_d
```
It is with respect to this polynomial that your function `extra_pol` is supposed to extrapolate: in other words, it will take:
```math
(x_0, x_1, ..., x_d)
```
as well as a parameter `n` and return:
```math
(x_0, x_1, ..., x_d, p_{d}(d+1), p_{d}(d+2), ..., p_{d}(d+n))
```
(Again, _don't worry: the description is quite long but the code should be quite short!_ ;) )
___Some Examples___
`delta()`
```python
delta([17,12]) #returns [5]
delta([1,4,9,16,25]) #returns [-3, -5, -7, -9]
delta([1,-2,4,-8,16,-32]) #returns [3, -6, 12, -24, 48]
```
```nim
delta(@[17,12]) #returns @[5]
delta(@[1,4,9,16,25]) #returns @[-3, -5, -7, -9]
delta(@[1,-2,4,-8,16,-32]) #returns @[3, -6, 12, -24, 48]
```
```ruby
delta([17,12]) #returns [5]
delta([1,4,9,16,25]) #returns [-3, -5, -7, -9]
delta([1,-2,4,-8,16,-32]) #returns [3, -6, 12, -24, 48]
```
```javascript
delta([17,12]) //returns [5]
delta([1,4,9,16,25]) //returns [-3, -5, -7, -9]
delta([1,-2,4,-8,16,-32]) //returns [3, -6, 12, -24, 48]
```
```haskell
delta [17, 12] -- [5]
delta [1, 4, 9, 16, 25] -- [-3, -5, -7, -9]
delta [1, -2, 4, -8, 16, -32] -- [3, -6, 12, -24, 48]
```
```r
delta(c(17,12)) #returns c(5)
delta(c(1,4,9,16,25)) #returns c(-3, -5, -7, -9)
delta(c(1,-2,4,-8,16,-32)) #returns c(3, -6, 12, -24, 48)
```
```csharp
Delta(new int[] {17, 12}) // new int[] {5}
Delta(new int[] {1, 4, 9, 16, 25}) // new int[] {-3, -5, -7, -9}
Delta([new int[] {1, -2, 4, -8, 16, -32}) // new int[] {3, -6, 12, -24, 48}
```
`dual_seq()`
```python
dual_seq([1]) #returns [1]
dual_seq([1,2,3,4,5]) #returns [1, -1, 0, 0, 0]
dual_seq([1, -1, 0, 0, 0]) #returns [1, 2, 3, 4, 5]
dual_seq([2,4,6,8,10]) #returns [2, -2, 0, 0, 0]
dual_seq([1,3,5,7,9]) #returns [1, -2, 0, 0, 0]
dual_seq([1,1,1,1,1]) #returns [1, 0, 0, 0, 0]
dual_seq([1, 0, 0, 0, 0]) #returns [1, 1, 1, 1, 1]
dual_seq([1, 4, 9, 16, 25, 36, 49]) #returns [1, -3, 2, 0, 0, 0, 0]
dual_seq([1, -3, 2, 0, 0, 0, 0]) #return [1, 4, 9, 16, 25, 36, 49]
dual_seq([1, -3, 2]) #returns [1, 4, 9]
dual_seq([8, 27, 64, 125, 216]) #returns [8, -19, 18, -6, 0]
dual_seq([1,2,4,8,16,32,64,128,256]) #returns [1, -1, 1, -1, 1, -1, 1, -1, 1]
dual_seq([1, -1, 1, -1, 1, -1, 1, -1, 1]) #returns [1, 2, 4, 8, 16, 32, 64, 128, 256]
dual_seq([1, 1, 2, 3, 5, 8, 13, 21]) #returns [1, 0, 1, 1, 2, 3, 5, 8]
dual_seq([0, 1, 1, 2, 3, 5, 8, 13, 21]) #returns [0, -1, -1, -2, -3, -5, -8, -13, -21]
```
```nim
dual_seq(@[1]) #returns @[1]
dual_seq(@[1,2,3,4,5]) #returns @[1, -1, 0, 0, 0]
dual_seq(@[1, -1, 0, 0, 0]) #returns @[1, 2, 3, 4, 5]
dual_seq(@[2,4,6,8,10]) #returns @[2, -2, 0, 0, 0]
dual_seq(@[1,3,5,7,9]) #returns @[1, -2, 0, 0, 0]
dual_seq(@[1,1,1,1,1]) #returns @[1, 0, 0, 0, 0]
dual_seq(@[1, 0, 0, 0, 0]) #returns @[1, 1, 1, 1, 1]
dual_seq(@[1, 4, 9, 16, 25, 36, 49]) #returns @[1, -3, 2, 0, 0, 0, 0]
dual_seq(@[1, -3, 2, 0, 0, 0, 0]) #return @[1, 4, 9, 16, 25, 36, 49]
dual_seq(@[1, -3, 2]) #returns @[1, 4, 9]
dual_seq(@[8, 27, 64, 125, 216]) #returns @[8, -19, 18, -6, 0]
dual_seq(@[1,2,4,8,16,32,64,128,256]) #returns @[1, -1, 1, -1, 1, -1, 1, -1, 1]
dual_seq(@[1, -1, 1, -1, 1, -1, 1, -1, 1]) #returns @[1, 2, 4, 8, 16, 32, 64, 128, 256]
dual_seq(@[1, 1, 2, 3, 5, 8, 13, 21]) #returns @[1, 0, 1, 1, 2, 3, 5, 8]
dual_seq(@[0, 1, 1, 2, 3, 5, 8, 13, 21]) #returns @[0, -1, -1, -2, -3, -5, -8, -13, -21]
```
```ruby
dual_seq([1]) #returns [1]
dual_seq([1,2,3,4,5]) #returns [1, -1, 0, 0, 0]
dual_seq([1, -1, 0, 0, 0]) #returns [1, 2, 3, 4, 5]
dual_seq([2,4,6,8,10]) #returns [2, -2, 0, 0, 0]
dual_seq([1,3,5,7,9]) #returns [1, -2, 0, 0, 0]
dual_seq([1,1,1,1,1]) #returns [1, 0, 0, 0, 0]
dual_seq([1, 0, 0, 0, 0]) #returns [1, 1, 1, 1, 1]
dual_seq([1, 4, 9, 16, 25, 36, 49]) #returns [1, -3, 2, 0, 0, 0, 0]
dual_seq([1, -3, 2, 0, 0, 0, 0]) #return [1, 4, 9, 16, 25, 36, 49]
dual_seq([1, -3, 2]) #returns [1, 4, 9]
dual_seq([8, 27, 64, 125, 216]) #returns [8, -19, 18, -6, 0]
dual_seq([1,2,4,8,16,32,64,128,256]) #returns [1, -1, 1, -1, 1, -1, 1, -1, 1]
dual_seq([1, -1, 1, -1, 1, -1, 1, -1, 1]) #returns [1, 2, 4, 8, 16, 32, 64, 128, 256]
dual_seq([1, 1, 2, 3, 5, 8, 13, 21]) #returns [1, 0, 1, 1, 2, 3, 5, 8]
dual_seq([0, 1, 1, 2, 3, 5, 8, 13, 21]) #returns [0, -1, -1, -2, -3, -5, -8, -13, -21]
```
```javascript
dualSeq([1]) //returns [1]
dualSeq([1,2,3,4,5]) //returns [1, -1, 0, 0, 0]
dualSeq([1, -1, 0, 0, 0]) //returns [1, 2, 3, 4, 5]
dualSeq([2,4,6,8,10]) //returns [2, -2, 0, 0, 0]
dualSeq([1,3,5,7,9]) //returns [1, -2, 0, 0, 0]
dualSeq([1,1,1,1,1]) //returns [1, 0, 0, 0, 0]
dualSeq([1, 0, 0, 0, 0]) //returns [1, 1, 1, 1, 1]
dualSeq([1, 4, 9, 16, 25, 36, 49]) //returns [1, -3, 2, 0, 0, 0, 0]
dualSeq([1, -3, 2, 0, 0, 0, 0]) //return [1, 4, 9, 16, 25, 36, 49]
dualSeq([1, -3, 2]) //returns [1, 4, 9]
dualSeq([8, 27, 64, 125, 216]) //returns [8, -19, 18, -6, 0]
dualSeq([1,2,4,8,16,32,64,128,256]) //returns [1, -1, 1, -1, 1, -1, 1, -1, 1]
dualSeq([1, -1, 1, -1, 1, -1, 1, -1, 1]) //returns [1, 2, 4, 8, 16, 32, 64, 128, 256]
dualSeq([1, 1, 2, 3, 5, 8, 13, 21]) //returns [1, 0, 1, 1, 2, 3, 5, 8]
dualSeq([0, 1, 1, 2, 3, 5, 8, 13, 21]) //returns [0, -1, -1, -2, -3, -5, -8, -13, -21]
```
```haskell
dualSeq [1] -- [1]
dualSeq [1, 2, 3, 4, 5] -- [1, -1, 0, 0, 0]
dualSeq [1, -1, 0, 0, 0] -- [1, 2, 3, 4, 5]
dualSeq [2, 4, 6, 8, 10] -- [2, -2, 0, 0, 0]
dualSeq [1, 3, 5, 7, 9] -- [1, -2, 0, 0, 0]
dualSeq [1, 1, 1, 1, 1] -- [1, 0, 0, 0, 0]
dualSeq [1, 0, 0, 0, 0] -- [1, 1, 1, 1, 1]
dualSeq [1, 4, 9, 16, 25, 36, 49] -- [1, -3, 2, 0, 0, 0, 0]
dualSeq [1, -3, 2, 0, 0, 0, 0 -- [1, 4, 9, 16, 25, 36, 49]
dualSeq [1, -3, 2] -- [1, 4, 9]
dualSeq [8, 27, 64, 125, 216] -- [8, -19, 18, -6, 0]
dualSeq [1, 2, 4, 8, 16, 32, 64, 128, 256] -- [1, -1, 1, -1, 1, -1, 1, -1, 1]
dualSeq [1, -1, 1, -1, 1, -1, 1, -1, 1] -- [1, 2, 4, 8, 16, 32, 64, 128, 256]
dualSeq [1, 1, 2, 3, 5, 8, 13, 21] -- [1, 0, 1, 1, 2, 3, 5, 8]
dualSeq [0, 1, 1, 2, 3, 5, 8, 13, 21] -- [0, -1, -1, -2, -3, -5, -8, -13, -21]
```
```r
dual_seq(c(1)) #returns c(1)
dual_seq(c(1,2,3,4,5)) #returns c(1, -1, 0, 0, 0)
dual_seq(c(1, -1, 0, 0, 0)) #returns c(1, 2, 3, 4, 5)
dual_seq(c(2,4,6,8,10)) #returns c(2, -2, 0, 0, 0)
dual_seq(c(1,3,5,7,9)) #returns c(1, -2, 0, 0, 0)
dual_seq(c(1,1,1,1,1)) #returns c(1, 0, 0, 0, 0)
dual_seq(c(1, 0, 0, 0, 0)) #returns c(1, 1, 1, 1, 1)
dual_seq(c(1, 4, 9, 16, 25, 36, 49)) #returns c(1, -3, 2, 0, 0, 0, 0)
dual_seq(c(1, -3, 2, 0, 0, 0, 0)) #return c(1, 4, 9, 16, 25, 36, 49)
dual_seq(c(1, -3, 2)) #returns c(1, 4, 9)
dual_seq(c(8, 27, 64, 125, 216)) #returns c(8, -19, 18, -6, 0)
dual_seq(c(1,2,4,8,16,32,64,128,256)) #returns c(1, -1, 1, -1, 1, -1, 1, -1, 1)
dual_seq(c(1, -1, 1, -1, 1, -1, 1, -1, 1)) #returns c(1, 2, 4, 8, 16, 32, 64, 128, 256)
dual_seq(c(1, 1, 2, 3, 5, 8, 13, 21)) #returns c(1, 0, 1, 1, 2, 3, 5, 8)
dual_seq(c(0, 1, 1, 2, 3, 5, 8, 13, 21)) #returns c(0, -1, -1, -2, -3, -5, -8, -13, -21)
```
```csharp
DualSeq(new int[] {1}) //returns new int[] {1}
DualSeq(new int[] {1,2,3,4,5}) //returns new int[] {1, -1, 0, 0, 0}
DualSeq(new int[] {1, -1, 0, 0, 0}) //returns new int[] {1, 2, 3, 4, 5}
DualSeq(new int[] {2,4,6,8,10}) //returns new int[] {2, -2, 0, 0, 0}
DualSeq(new int[] {1,3,5,7,9}) //returns new int[] {1, -2, 0, 0, 0}
DualSeq(new int[] {1,1,1,1,1}) //returns new int[] {1, 0, 0, 0, 0}
DualSeq(new int[] {1, 0, 0, 0, 0}) //returns new int[] {1, 1, 1, 1, 1}
DualSeq(new int[] {1, 4, 9, 16, 25, 36, 49}) //returns new int[] {1, -3, 2, 0, 0, 0, 0}
DualSeq(new int[] {1, -3, 2, 0, 0, 0, 0}) //return new int[] {1, 4, 9, 16, 25, 36, 49}
DualSeq(new int[] {1, -3, 2}) //returns new int[] {1, 4, 9}
DualSeq(new int[] {8, 27, 64, 125, 216}) //returns new int[] {8, -19, 18, -6, 0}
DualSeq(new int[] {1,2,4,8,16,32,64,128,256}) //returns new int[] {1, -1, 1, -1, 1, -1, 1, -1, 1}
DualSeq(new int[] {1, -1, 1, -1, 1, -1, 1, -1, 1}) //returns new int[] {1, 2, 4, 8, 16, 32, 64, 128, 256}
DualSeq(new int[] {1, 1, 2, 3, 5, 8, 13, 21}) //returns new int[] {1, 0, 1, 1, 2, 3, 5, 8}
DualSeq(new int[] {0, 1, 1, 2, 3, 5, 8, 13, 21}) //returns new int[] {0, -1, -1, -2, -3, -5, -8, -13, -21}
```
`extra_pol()`
```python
extra_pol([1],0) #returns [1]
extra_pol([1],5) #returns [1, 1, 1, 1, 1, 1]
extra_pol([1,4],5) #returns [1, 4, 7, 10, 13, 16, 19]
extra_pol([1,4,9],5) #returns [1, 4, 9, 16, 25, 36, 49, 64]
extra_pol([4,16,36],5) #returns [4, 16, 36, 64, 100, 144, 196, 256]
extra_pol([216, 125 ,64 ,27],7) #returns [216, 125, 64, 27, 8, 1, 0, -1, -8, -27, -64]
```
```nim
extra_pol(@[1],0) #returns @[1]
extra_pol(@[1],5) #returns @[1, 1, 1, 1, 1, 1]
extra_pol(@[1,4],5) #returns @[1, 4, 7, 10, 13, 16, 19]
extra_pol(@[1,4,9],5) #returns @[1, 4, 9, 16, 25, 36, 49, 64]
extra_pol(@[4,16,36],5) #returns @[4, 16, 36, 64, 100, 144, 196, 256]
extra_pol(@[216, 125 ,64 ,27],7) #returns @[216, 125, 64, 27, 8, 1, 0, -1, -8, -27, -64]
```
```ruby
extra_pol([1],0) #returns [1]
extra_pol([1],5) #returns [1, 1, 1, 1, 1, 1]
extra_pol([1,4],5) #returns [1, 4, 7, 10, 13, 16, 19]
extra_pol([1,4,9],5) #returns [1, 4, 9, 16, 25, 36, 49, 64]
extra_pol([4,16,36],5) #returns [4, 16, 36, 64, 100, 144, 196, 256]
extra_pol([216, 125 ,64 ,27],7) #returns [216, 125, 64, 27, 8, 1, 0, -1, -8, -27, -64]
```
```javascript
extraPol([1],0) //returns [1]
extraPol([1],5) //returns [1, 1, 1, 1, 1, 1]
extraPol([1,4],5) //returns [1, 4, 7, 10, 13, 16, 19]
extraPol([1,4,9],5) //returns [1, 4, 9, 16, 25, 36, 49, 64]
extraPol([4,16,36],5) //returns [4, 16, 36, 64, 100, 144, 196, 256]
extraPol([216, 125 ,64 ,27],7) //returns [216, 125, 64, 27, 8, 1, 0, -1, -8, -27, -64]
```
```haskell
extraPol [1] 0 -- [1]
extraPol [1] 5 -- [1, 1, 1, 1, 1, 1]
extraPol [1, 4] 5 -- [1, 4, 7, 10, 13, 16, 19]
extraPol [1, 4, 9] 5 -- [1, 4, 9, 16, 25, 36, 49, 64]
extraPol [4, 16, 36] 5 -- [4, 16, 36, 64, 100, 144, 196, 256]
extraPol [216, 125, 64, 27] 7 -- [216, 125, 64, 27, 8, 1, 0, -1, -8, -27, -64]
```
```r
extra_pol(c(1),0) #returns c(1)
extra_pol(c(1),5) #returns c(1, 1, 1, 1, 1, 1)
extra_pol(c(1,4),5) #returns c(1, 4, 7, 10, 13, 16, 19)
extra_pol(c(1,4,9),5) #returns c(1, 4, 9, 16, 25, 36, 49, 64)
extra_pol(c(4,16,36),5) #returns c(4, 16, 36, 64, 100, 144, 196, 256)
extra_pol(c(216, 125 ,64 ,27),7) #returns c(216, 125, 64, 27, 8, 1, 0, -1, -8, -27, -64)
```
```csharp
ExtraPol(new int[] {1},0) //returns new int[] {1}
ExtraPol(new int[] {1},5) //returns new int[] {1, 1, 1, 1, 1, 1}
ExtraPol(new int[] {1,4},5) //returns new int[] {1, 4, 7, 10, 13, 16, 19}
ExtraPol(new int[] {1,4,9},5) //returns new int[] {1, 4, 9, 16, 25, 36, 49, 64}
ExtraPol(new int[] {4,16,36},5) //returns new int[] {4, 16, 36, 64, 100, 144, 196, 256}
ExtraPol(new int[] {216, 125 ,64 ,27},7) //returns new int[] {216, 125, 64, 27, 8, 1, 0, -1, -8, -27, -64}
```
__Note:__ The _number sequences_ will be given by non-empty* `lists`; (* but possibly of size 1)
((`lists` in the case of Python; other languages may use (dynamic) `Arrays` (JavaScript,Ruby), `sequences` (Nim), `vectors` (R) etc, but the context (Description and Solution Setup) should make it clear enough... )) | algorithms | def delta(lst):
return [a - b for a, b in zip(lst, lst[1:])]
def dual_seq(lst):
return lst[: 1] + [(lst := delta(lst))[0] for _ in lst[1:]]
def extra_pol(lst, n):
return dual_seq(dual_seq(lst) + [0] * n)
| Sequence Duality and "Magical" Extrapolation (Binomial Transform) | 6146a6f1b117f50007d44460 | [
"Mathematics",
"Algebra",
"Algorithms",
"Tutorials"
] | https://www.codewars.com/kata/6146a6f1b117f50007d44460 | 6 kyu |
You get a list of non-zero integers `A`, its length is always greater than one. Your task is to find such non-zero integers `W` that the weighted sum
```math
A_0 \cdot W_0 + A_1 \cdot W_1 + .. + A_n \cdot W_n
```
is equal to `0`.
Unlike the [first kata](https://www.codewars.com/kata/5fad2310ff1ef6003291a951) in the series, here the length of the list `A` can be odd.
# Examples
```python
# One of the possible solutions: W = [-10, -1, -1, 1, 1, 1]
# 1*(-10) + 2*(-1) + 3*(-1) + 4*1 + 5*1 + 6*1 = 0
weigh_the_list([1, 2, 3, 4, 5, 6])
# One of the possible solutions: W = [-5, -12, 4, 3, 1]
# 1*(-5) + 2*(-12) + 3*4 + 4*3 + 5*1 = 0
weigh_the_list([1, 2, 3, 4, 5])
# One of the possible solutions: W = [4, 1]
# -13*4 + 52*1 = 0
weigh_the_list([-13, 52])
# One of the possible solutions: W = [1, 1]
# -1*1 + 1*1 = 0
weigh_the_list([-1, 1])
```
```haskell
weights [ 1, 2, 3, 4, 5 ] -> [ -2, -2, -1, 1, 1 ] -- other solution are possible
-- 1 * (-2) + 2 * (-2) + 3 * (-1) + 4 * 1 + 5 * 1 == 0
weights [ -13, 52 ] -> [ 4, 1 ] -- other solutions are possible
-- (-13) * 4 + 52 * 1 == 0
weights [ 1, 1 ] -> [ -1, 1 ] -- other solutions are possible
-- 1 * (-1) + 1 * 1 == 0
```
```javascript
weights([ 1, 2, 3, 4, 5 ]) => [ -2, -2, -1, 1, 1 ] // other solution are possible
// 1 * (-2) + 2 * (-2) + 3 * (-1) + 4 * 1 + 5 * 1 == 0
weights([ -13, 52 ]) => [ 4, 1 ] // other solutions are possible
// (-13) * 4 + 52 * 1 == 0
weights([ 1, 1 ]) => [ -1, 1 ] // other solutions are possible
// 1 * (-1) + 1 * 1 == 0
```
[Previous kata](https://www.codewars.com/kata/5fad2310ff1ef6003291a951)
Have fun! :) | reference | from math import prod
def weigh_the_list(xs):
p = prod(xs)
return [p / / x for x in xs[: - 1]] + [- p * (len(xs) - 1) / / xs[- 1]]
| Weigh The List #2 | 5fafdcb2ace077001cc5f8d0 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/5fafdcb2ace077001cc5f8d0 | 6 kyu |
***
Nicky has had Myopia (Nearsightedness) since he was born. Because he always wears glasses, he really hates digits `00` and he loves digits 1 and 2. He calls numbers, that don't contain `00` (two consecutive zeros), the Blind Numbers. He will give you `n`, the digit-length of number in 10-adic system, and you need to help him to count how many numbers are there of length `n`, that only consist of digits 0, 1 and 2 and are not Blind Numbers.
***
### Noteπ
We include 0 in the begin of number also.
The numbers will be very huge, so return the answer modulo 1000000007
### Example
`n = 3`
The answer is 22. The below list is all 27 possible numbers of length 3, with digits 0-2, and there 5 numbers that contain `00` so we not include those.
```
[000, 001, 002, 010, 011, 012, 020, 021, 022, 100, 101, 102, 110, 111, 112, 120 121, 122, 200, 201, 202, 210 , 211, 212, 220, 221, 222]
```
### Constraints
`1 β€ n β€ 500000`
| reference | def blind_number(n):
a, b = 1, 3
for _ in range(n):
a, b = b, (a + b) * 2 % 1000000007
return a
| Blind Numbers | 5ee044344a543e001c1765b4 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/5ee044344a543e001c1765b4 | 6 kyu |
# Cubes in the box
Your job is to write a function `f(x,y,z)` to count how many cubes <b>of any size</b> can fit inside a `x*y*z` box. For example, a `2*2*3` box has 12 `1*1*1` cubes, 2 `2*2*2` cubes, so a total of 14 cubes in the end. See the animation below for a visual description of the task!
### Notes:
- `x`,`y`,`z` are strictly positive and will not be too big.

*Animation made by [AwesomeAD](https://www.codewars.com/users/awesomead)* | reference | def f(x, y, z):
return sum((x - i) * (y - i) * (z - i) for i in range(min(x, y, z)))
| Cubes in the box | 61432694beeca7000f37bb57 | [
"Mathematics",
"Fundamentals",
"Geometry"
] | https://www.codewars.com/kata/61432694beeca7000f37bb57 | 7 kyu |
# Description
Your task in this kata is to solve numerically an ordinary differential equation. This is an equation of the form `$\dfrac{dy}{dx} = f(x, y)$` with initial condition `$y(0) = x_0$`.
## Motivation and Euler's method
The method you will have to use is Runge-Kutta method of order 4. The Runge-Kutta methods are generalization of Euler's method, which solves a differential equation numerically by extending the trajectory from point `$(x_0, y_0)$` by small steps with intervals `h` with the below-mentioned formula:
```math
y(x_0) = y_0 \\
y(x+h) = y(x) + h \cdot f(x, y(x))
```
This directly follows from the fact, that
<center>
```math
\displaystyle f(x, y(x)) = \lim_{h \to 0}\dfrac{y(x+h) - y(x)} {(x + h) - x}
```
</center>
which is equivalent to the geometrical meaning of derivative (a tangent of `$y(x)$` at point `$x$`).
By making a step arbitrary small, one may theoretically make the computation arbitrary precise. However, in practice the step is bounded by smallest floating point number, and this yields quite imprecise results, because residue in Euler's method is accumulated over a number of steps (which is usually counted in thousands/millions).
In order to reduce the residue as much as possible, one may use a generalization methods, i.e. a family of Runge-Kutta methods. An RK method performs more computations on each step, but also approximates more terms in [Taylor decomposition](https://en.wikipedia.org/wiki/Taylor_series) of function `$f(x, y)$` and thus produces overall smaller residue. The order of RK method corresponds to precision and to a number of calculations on each step.
Further reading: [Wikipedia](https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods)
## The actual Runge-Kutta 4
We will be using the most common RK method of order 4.
It is given by formula
<center>
```math
y(x+h) = y(x) + \dfrac{k_1 + 2k_2 + 2k_3 + k_4}{6}
```
</center>
where
```math
k_1 = h f(x,y) \\
k_2 = h f(x+\frac{h}{2}, y+\frac{k_1}{2}) \\
k_3 = h f(x+\frac{h}{2}, y+\frac{k_2}{2}) \\
k_4 = h f(x+h, y+k_3)
```
## The task
You will be given the following inputs:
- `x0, y0` : the initial point
- `h`: step, will be >0
- `f(x,y)`: the value of derivative dy/dx at point (x,y)
- `x1`: the x value for the final point. (x1 > x0)
Execute numerical integration with Runge-Kutta 4 and return the following:
- An array of `y` values for xs from `x0` to `x1` inclusive separated by step `h`. You should calculate the value of `y` for each integer `k >= 0` such that `x0 + k * h <= x1`.
Float outputs are compared to reference with tolerance `1e-9`.
| algorithms | def RK4(x0, y0, h, f, x1):
ys, cur = [y0], x0
while cur < x1:
k1 = h * f(cur, ys[- 1])
k2 = h * f(cur + h / 2, ys[- 1] + k1 / 2)
k3 = h * f(cur + h / 2, ys[- 1] + k2 / 2)
k4 = h * f(cur + h, ys[- 1] + k3)
ys . append(ys[- 1] + (k1 + 2 * k2 + 2 * k3 + k4) / 6)
cur += h
return ys
| Approximate solution of differential equation with Runge-Kutta 4 | 60633afe35b4960032fd97f9 | [
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/60633afe35b4960032fd97f9 | 6 kyu |
Similar but fairly harder version : [Linked](https://www.codewars.com/kata/540d0fdd3b6532e5c3000b5b)
Create a function that takes a integer number `n` and returns the formula for `$(a+b)^n$` as a string. (**Input --> Output**)
```
0 --> "1"
1 --> "a+b"
2 --> "a^2+2ab+b^2"
-2 --> "1/(a^2+2ab+b^2)"
3 --> "a^3+3a^2b+3ab^2+b^3"
5 --> "a^5+5a^4b+10a^3b^2+10a^2b^3+5ab^4+b^5"
```
The formula for `n=5` is like so :
```math
a^5 + 5a^4b+10a^3b^2+10a^2b^3+5ab^4+b^5
```
So the answer would look like so : `a^5+5a^4b+10a^3b^2+10a^2b^3+5ab^4+b^5`
# Important notes :
- Your string may not have spaces so you can't do this : `a^5 + 5a^4 b + 10a^3 b^2...`
- You will show raised to power of by `^` and not using `**`.
- You need not put `*` between each multiplication
- There is no need to show `a^1` or `b^1` since that is basically `a` and `b`
- `a^0` and/or `b^0` also don't need be shown instead be a normal person and use `1` since that is what they equate to.
- You will need to handle both `positive and negative numbers + 0`
- Note :
- ```math
a^{-n} = \frac 1{a^n}
```
- You will not be tested for float (only negative integers and whole numbers)
- input `n` goes from -200 to 200.
```if:java,javascript
You will need to use BigInt since otherewise it will not work for both JS and Java
```
```if:c
In C you will not have to deal with numbers that cannot fit in an unsigned 64 bits integer.
``` | games | from math import comb
def formula(n):
return (f'1/( { formula ( - n ) } )' if n < 0 else '1' if not n else
'+' . join(binom(n - i, i) for i in range(n + 1)))
def binom(a, b):
c = comb(a + b, a)
return f" { c if c > 1 else '' }{ term ( 'a' , a ) }{ term ( 'b' , b ) } "
def term(c, n):
return f' { c } ^ { n } ' if n > 1 else c if n else ''
| (a+b)^n | 61419e8f0d12db000792d21a | [
"Mathematics",
"Algebra",
"Strings"
] | https://www.codewars.com/kata/61419e8f0d12db000792d21a | 6 kyu |
You must organize contest, that contains two part, knockout and round-robin.
# **Part 1**
Knockout part goes until we get an odd number of players.
In each round players are paired up; each pair plays a game with the winning player advancing to the next round (no ties). This part continues as long as number of players is even. When we come to round with are an odd number of players we go to part 2.
- Part 1 will be skipped, if starting quantity of players is odd
- If Part 1 ends with 1 player then contest is considered over, we have a winner
# **Part 2**
Round-robin.
Each participant plays every other participant once. The player with the most points is the winner.
How many players you must invite to participate in the contest for got N games to be played?
-----
# Input/Output
`[input]` integer `n`
A positive number
`1 β€ n β€ 10^9`
`[output]` array of Int
Return array of all possible amounts of players. Array can be empty if requested number of games cannot be achieved by any one amount of players. Array must be sorted by ASC.
If this kata is too easy, you can try much [harder version](https://www.codewars.com/kata/61407509f979cd000e2e7cf0).
-----
# Examples
**3 games**
- We can invite 3 players. In this case part 1 will be skipped and contest start with part 2, where 3 games will played.
- Or we can invite 4 players, then part 1 will be made with 3 games. 2 semi-finals, final and we got a winner. Part 2 need no to be played, because we got 1 player only (winner of part 1).
**12 games**
- We must invite 12 players. Contest start with Part 1, where will be played 6 + 3 games, than 3 more games will be played in Part 2. So the got 6 + 3 + 3 = 12 games.
| algorithms | from itertools import count, takewhile
from math import isqrt
def find_player_counts(number_of_games):
"""
let games(p) = number of games for p players
let i, k be nonnegative integers
games(2^i * (2k + 1)) = (2^i - 1) * (2k + 1) + (2k + 1) * (2k + 1 - 1) / 2
let n = 2^i - 1
games((n + 1) * (2k + 1)) = 2k^2 + (2n+1)k + n
let g be the given number of games.
solve 2k^2 + (2n+1)k + (n - g) = 0 for k
(only need the greater solution, must be an integer)
"""
ns = takewhile(lambda n: n <= number_of_games,
((1 << i) - 1 for i in count()))
guesses = ((n, quadratic(2, 2 * n + 1, n - number_of_games)) for n in ns)
return [(n + 1) * (2 * k + 1) for n, k in guesses if k is not None]
def quadratic(a, b, c):
sq = b * b - 4 * a * c
sqrt = isqrt(sq)
if sqrt * sqrt != sq:
return None
top = - b + sqrt
if top % (2 * a):
return None
return top / / (2 * a)
| Number of players for knockout/round-robin hybrid contest (easy mode) | 613f13a48dfb5f0019bb3b0f | [
"Combinatorics",
"Permutations",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/613f13a48dfb5f0019bb3b0f | 5 kyu |
You are doing an excercise for chess class.
Your job given a bishop's start position (`pos1 / startPos`) find if the end position (`pos2 / endPos`) given is possible within `n` moves.
### INPUT :
```
startPos (1st param) ==> The position at which bishop is at
endPos (2nd param) ==> The position at which he is supposed to end at
number (3rd param) ==> The number of moves allowed to bishop to move to said position
```
### BOARD :
```
8 |_|#|_|#|_|#|_|#|
7 |#|_|#|_|#|_|#|_|
6 |_|#|_|#|_|#|_|#|
5 |#|_|#|_|#|_|#|_|
4 |_|#|_|#|_|#|_|#|
3 |#|_|#|_|#|_|#|_|
2 |_|#|_|#|_|#|_|#|
1 |#|_|#|_|#|_|#|_|
a b c d e f g h
```
The board is a `8 x 8` board goes from `a1` to `h8`
### BISHOP MOVEMENT :
> The bishop chess piece moves in any direction diagonally. Chess rules state that there is no limit to the number of squares a bishop can travel on the chessboard, as long as there is not another piece obstructing its path. Bishops capture opposing pieces by landing on the square occupied by an enemy piece.
### OUTPUT :
Find out whether within `n` moves he can move from start pos to end pos. If he can return `true`, if not return `false`
### NOTES :
- Return true if start and end position are same; even if number of moves is 0
- Both start and end positions will always be valid (so within a1 ---> h8)
- Input positions will always follow this pattern : `f1` (i.e : Char(representing one of a-h)Number(represnting one of 1-8) on chess board)
- The alphabet will always be lowercase followed immediately by number no space.
- For our purpose, chess board is always empty, i.e: the bishop is the only one that can be played.
- The number of moves `n` will always be whole number i.e : 0 or greater.
- Your bishop may only move using its predefined moment method (it may not act like a queen or knight).
This is part 1 of challenge (part 2 will be listed when its done)
| algorithms | def bishop(start, end, moves):
sx, sy = map(ord, start)
ex, ey = map(ord, end)
dx, dy = abs(ex - sx), abs(ey - sy)
return moves > 1 and dx % 2 == dy % 2 or dx == dy and (moves > 0 or dx == 0)
| Bishop Movement checker | 6135e4f40cffda0007ce356b | [
"Games",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/6135e4f40cffda0007ce356b | 6 kyu |
# Task
An employee wishes to resign.
*Do not let him go.*
Locate the entrance to his office so we can send its coordinates to the
orbital obstacle placement service (OOPS).
The floor plan of the office is given as a list (python) or an array (java) of strings.
Walls are marked with a `#` and interior with `.`. Strings can vary in length, and if they do, align them to the left.
Return the coordinates of the office entrance as a tuple `(x, y)` in python or Point in java.
Top left is `(0, 0)`, `x` is oriented to the right ("columns") and
`y` downwards ("rows"):
+----> x
|
|
V
y
## Examples
###.###
#.....#
#.....# -> (3, 0)
#....##
######
#####
#...#
....#
#...# -> (1, 2)
##...#
#....#
######
| algorithms | def locate_entrance(office: list) - > tuple:
def is_on_edge(r, c):
try:
return r == 0 or r == len(office) - 1 or \
c == 0 or c == len(office[r]) - 1 or \
office[r][c - 1] == ' ' or office[r][c + 1] == ' ' or \
office[r + 1][c] == ' ' or office[r - 1][c] == ' '
except IndexError:
return True
for row_num, row in enumerate(office):
for col_num, tile in enumerate(row):
if tile == '.' and is_on_edge(row_num, col_num):
return col_num, row_num
| Do not let him go | 61390c407d15c3003fabbd35 | [
"Strings",
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/61390c407d15c3003fabbd35 | 6 kyu |
The King organizes the jousting. You are a young human lady and your fiancΓ© is an ogre. Today is his anniversary and he would love to visit the tournament, but it's forbidden for ogres to visit the Kingdom. So you decided to go there, to paint the exact moments of clash of cavalry and to present these paintings to your beloved.
You are given the array / tuple (`listField`) of two strings of equal length.
Each the string contains `"$->"` and `"<-P"`(knight with lance) respectively.
The knights move towards each other and they can only take simultaneous steps of length `vKnightLeft` and `vKnightRight`.
When the index of `">"` is equal or more than the index of `"<"`, return the array / tuple representing the knights' positions.
Some examples of the collision:
```
["$-> ",
" <-P"]
```
```
[" $-> ",
" <-P"]
```
```
[" $-> ",
" <-P "]
```
## Notes:
- "The knight `"$->"` always starts in the position 0 of the first string;
- "The knight `"<-P"` always starts in the last position of the second string;
- Velocity of knights can be different from 0 to 3 inclusive;
- Sometimes the collision can happen immediately;
- Sometimes there is no an immediate collision and velocitity of both knights is 0. At this case return an original array / tuple.
Example 1:
```
given
listField = ["$-> ",
" <-P"]
vKnightLeft = 1
vKnightRight = 1
return
[" $-> ",
" <-P "]
```
Example 2:
```
given
listField = ["$->",
"<-P"]
vKnightLeft = 1
vKnightRight = 1
return
["$->",
"<-P"]
```
If you like this kata, check out the another one: [Kingdoms Ep2: The curse (simplified)](https://www.codewars.com/kata/6159dda246a119001a7de465)

_One of your beautiful paintings for your Ogre_
| reference | def joust(list_field: tuple, v_knight_left: int, v_knight_right: int) - > tuple:
if v_knight_left == 0 and v_knight_right == 0:
return list_field
len1, len2 = len(list_field[0]), len(list_field[1])
left_point, right_point = 2, len1 - 3
while left_point < right_point:
left_point += v_knight_left
right_point -= v_knight_right
return (" " * (left_point - 2) + "$->" + " " * (len1 - left_point - 1),
" " * right_point + "<-P" + " " * (len2 - right_point - 3))
| Kingdoms Ep1: Jousting | 6138ee916cb50f00227648d9 | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/6138ee916cb50f00227648d9 | 6 kyu |
Hopefully you are familiar with the game of ten-pin bowling! In this kata you will need to calculate the winner of a match between two players.
<h1>Scoring a frame</h1>
Each player will play three frames, consisting of ten attempts to knock down ten pins. At each attempt a player can take either one or two rolls, one if they score ten on their first roll, and a second roll if they score less than ten.
</br></br>
At each attempt the total number of pins knocked down is added to the player's score for that frame. Foul balls (denoted by 'F') contribute nothing.
</br></br>
If a player knocks down all ten pins on their first roll - a strike - then the total number of pins knocked down <i>on the next two rolls</i> is added to their score.
</br></br>
If a player knocks down all ten pins after both rolls - a spare - then the total number of pins knocked down <i>on the next roll</i> is added to their score.
</br></br>
If a player scores a strike or a spare on their final attempt then they get to roll either 1 or 2 'fill' balls so that they get the full bonus points!
<h1>Scoring a match</h1>
For each frame player, a player will receive 2 points if they win that frame, and 0 if they lose. Tied frames award 1 point to each player.
</br></br>
Then, after points for all three frames have been totalled for both players, a single bonus point is awarded to the player who knocks down the most pins across all three frames - bonus points for strikes / spares do <b>NOT</b> count, but fill balls (extra rolls awarded for getting a strike / spare on the last attempt) will be included.
</br></br>
The winner will be the player with the most points in total.
<h1>Input</h1>
The (Python translation) input will be a 2-tuple of 3-tuples, representing each of the two player's three frames. Each 3-tuple (i.e. frame) is itself a 10-tuple, repesenting the attempts in that frame. Each 'attempt' will show the score on the first and second rolls, or will show (10, None) for a strike. Remember that 'F' denotes a foul throw here, which scores nothing.
The final tuple will show the score obtained on the fill ball(s) where applicable.
<h1>Output</h1>
Return a dictionary showing the full tree structure of the scoring for the match.
</br></br>
This needs to show a sub-dictionary for each player with a list for the scores on each frame, and a list for their points scored (including the bonus point, which may be 0 for both players).
</br></br>
The dictionary also needs to show a string with the overall winner as per the following rules:
If player 1's total points exceed player 2's, `'Player 1 won!'`
<br>
If player 2's total points exceed player 1's, `'Player 2 won!'`
<br>
If both players are tied on points, `'The match is a draw!'`
</br>
Please see the examples for exactly how the return value should look.
<h1>Example</h1>
Player 1's frames:
``` python
frame1 = (((10, None), (7, 3), (9, 0), (10, None), (0, 8), (8, 2), (0, 6), (10, None), (10, None), (9, 1, 1)))
frame2 = (((8, 2), (8, 0), (10, None), (6, 1), (7, 3), (0, 10), (0, 6), (9, 1), (10, None), (5, 2)))
frame3 = (((10, None), (7, 3), (9, 0), (10, None), (0, 8), (8, 2), (0, 6), (10, None), (10, None), (10, 8, 1)))
```
Player 2's frames:
``` python
frameA = (((8, 1), (8, 0), (1, 0), (6, 1), (6, 3), (0, 0), (0, 6), (4, 1), (4, 1), (5, 2)))
frameB = (((10, None), (10, None), (7, 'F'), (8, 1), (6, 'F'), (3, 7), (9, 'F'), ('F', 9), (10, None), (6, 'F')))
frameC = (((10, None), (7, 3), (9, 0), (10, None), (0, 8), (8, 2), (0, 6), (10, None), (10, None), (10, 8, 1)))
```
Player 1's scores for each frame are `[150, 120, 167]`
Player 2's scores for each frame are `[57, 125, 167]`
In addition, total pins knocked down by player 1 and player 2 are 284 and 245 respectively, so player 1 wins the bonus point. If both players knock down the same number of pins then nobody gets an additonal bonus point.
Therefore player 1's points are `[2, 0, 1, 1]`, and those of player 2 are `[0, 2, 1, 0]`.
So the function should return the following dictioary:
```python
{'player 1': {'frames': [150, 120, 167],
'points': [2, 0, 1, 1]},
'player 2': {'frames': [57, 125, 167],
'points': [0, 2, 1, 0]},
'result': 'Player 1 won!'}
``` | games | def score_match(frames):
pts, pins = [[], []], [0, 0]
for f in zip(* frames):
for i, (s, p) in enumerate(map(scoreFrame, f)):
pts[i]. append(s)
pins[i] += p
score1 = [1 + (a > b) - (a < b) for a, b in zip(* pts)]
a, b = pins
scores = [score1 + [a > b], [2 - s for s in score1] + [b > a]]
overall = int . __sub__(* map(sum, scores))
res = {'result': "The match is a draw!" if not overall else f"Player { 1 if overall > 0 else 2 } won!"}
res . update(
{f'player { i + 1 } ': {'frames': pts[i], 'points': scores[i]} for i in range(2)})
return res
def scoreFrame(frame):
score, pins = 0, 0
frame = [tuple(v != 'F' and v or 0 for v in f) for f in frame]
for i, (a, b, c) in enumerate(zip(frame, frame[1:] + [(0, 0)], frame[2:] + [(0, 0)] * 2)):
s = sum(a)
score += s + b[0] * (s == 10) + (a[0] == 10) * (b[1] + c[0] * (b[0] == 10))
pins += s
return score, pins
| Ten-pin bowling - score the frame | 5b4f309dbdd074f9070000a3 | [
"Puzzles"
] | https://www.codewars.com/kata/5b4f309dbdd074f9070000a3 | 6 kyu |
A "True Rectangle" is a rectangle with two different dimensions and four equal angles.
---
## Task:
In this kata, we want to **decompose a given true rectangle** into the minimum number of squares,
Then aggregate these generated squares together to form **all** the possible true rectangles.
---
## Examples:
>
<img src="http://i.imgur.com/cjegc25.png"/>
> As shown in this figure,
we want to decompose the `(13*5)` true rectangle into the minimum number of squares which are `[5, 5, 3, 2, 1, 1]` to **return** all the possible true rectangles from aggregating these squares together :
```Java
rectIntoRects(13, 5) should return the ractangles: ["(10*5)", "(8*5)", "(2*1)", "(3*2)", "(5*3)", "(13*5)"] //or any other order
```
Another example :
>
<img src="http://i.imgur.com/QWwhfxi.png"/>
> Here is the `(22*6)` true rectangle, it will be decomposed into the `[6, 6, 6, 4, 2, 2]` squares. so we should aggregate these squares together to form all the possible true rectangles :
```Java
rectIntoRects(22, 6) should return the ractangles: ["(12*6)", "(18*6)", "(22*6)", "(12*6)", "(16*6)", "(10*6)", "(6*4)", "(4*2)"] //or any other order
```
More Examples :
> The **(8*5)** true rectangle will be decomposed into `[5, 3, 2, 1, 1]` squares, so :
```Java
rectIntoRects(8, 5) should return: ["(8*5)", "(5*3)", "(3*2)", "(2*1)"] //or any other order
```
> The **(20*8)** rectangle will be decomposed into `[8, 8, 4, 4]` squares, so :
```Java
rectIntoRects(20, 8) should return: ["(16*8)", "(20*8)", "(12*8)", "(8*4)"] //or any other order
```
**See the example test cases for more examples.**
---
## Notes:
- You should take each square with its all adjacent squares or rectangles to form the resulting true rectangles list.
- Do not take care of the resulting rectangles' orientation. just `"(long_side*short_side)"`.
---
## Edge cases:
- `rectIntoRects(17, 5)` should equal `rectIntoRects(5, 17)`.
```if:java
- If `length == width` it should return `null`
- If `length == 0` or `width == 0` it should return `null`
```
```if-not:java
- If `length == width` it should return an empty list/array
- If `length == 0` or `width == 0` it should return an empty list/array
```
---
## References:
https://www.codewars.com/kata/55466989aeecab5aac00003e
| games | class Rectangle:
@ staticmethod
def rect_into_rects(length, width):
if width < length:
width, length = length, width
rects = []
while 0 < length < width:
sqs, width = divmod(width, length)
rects += sum(([(d * length, length)] * (sqs - d + 1)
for d in range(2, sqs + 1)), [])
if width:
rects += [(d * length + width, length) for d in range(1, sqs + 1)]
width, length = length, width
return list(map('({0[0]}*{0[1]})' . format, rects)) or None
| Rectangle into Rectangles | 58b22dc7a5d5def60300002a | [
"Puzzles",
"Fundamentals",
"Algorithms",
"Geometry"
] | https://www.codewars.com/kata/58b22dc7a5d5def60300002a | 5 kyu |
Specification pattern is one of the OOP design patterns. Its main use is combining simple rules into more complex ones for data filtering. For example, given a bar menu you could check whether a drink is a non-alcoholic cocktail using the following code:
```
drink = # ...
is_cocktail = IsCocktail()
is_alcoholic = IncludesAlcohol()
is_non_alcoholic = Not(is_alcoholic)
is_non_alcoholic_cocktail = And(is_cocktail, is_non_alcoholic)
is_non_alcoholic_cocktail.is_satisfied_by(drink)
```
But, this code is terrible! We have to create lots of unnecessary variables, and if we were to write this specification in one line, the result would be getting more and more unreadable as its complexity grows:
```
drink = # ...
And(IsCocktail(), Not(IncludesAlcohol())).is_satisfied_by(drink)
```
Obviously, you don't want to write such code. Instead, you should implement a much more beautiful specification pattern by:
* using the `&`, `|`, `~` operators instead of creating superfluous `And`, `Or`, `Not` classes
* getting rid of those annoying class instantiations
* calling the specification directly without any `is_satisfied_by` methods
And have this instead:
```
drink = # ...
(IsCocktail & ~IncludesAlcohol)(drink)
```
To do so you have to create a class `Specification` which will be inherited by other classes (like aforementioned `IsCocktail` or `IncludesAlcohol`), and will allow us to do this magic.
**Note**: whenever a class inheriting from `Specification` (e.g. `IsCocktail`) or a complex specification (e.g. `IsCocktail & ~IncludesAlcohol`) is called, instead of constructing and initializing a truthy/falsey instance, `True`/`False` must be returned. | reference | class Meta (type):
def __invert__(self): return Meta(
"", (), {"__new__": lambda _, x: not self(x)})
def __and__(self, other): return Meta(
"", (), {"__new__": lambda _, x: self(x) and other(x)})
def __or__(self, other): return Meta(
"", (), {"__new__": lambda _, x: self(x) or other(x)})
class Specification (metaclass=Meta):
pass
| Readable Specification Pattern | 5dc424122c135e001499d0e5 | [
"Fundamentals",
"Object-oriented Programming",
"Design Patterns"
] | https://www.codewars.com/kata/5dc424122c135e001499d0e5 | 5 kyu |
# Longest Palindromic Substring (Linear)
A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g.,
'madam' or 'racecar'. Even the letter 'x' is considered a palindrome.
For this Kata, you are given a string ```s```. Write a function that returns the longest _contiguous_ palindromic substring in ```s``` (it could be the entire string). In the event that there are multiple longest palindromic substrings, return the first to occur.
I'm not trying to trick you here:
- You can assume that all inputs are valid strings.
- Only the letters a-z will be used, all lowercase (your solution should, in theory, extend to more than just the letters a-z though).
**NOTE:** Quadratic asymptotic complexity _(O(N^2))_ or above will __NOT__ work here.
-----
## Examples
### Basic Tests
```
Input: "babad"
Output: "bab"
(Note: "bab" occurs before "aba")
```
```
Input: "abababa"
Output: "abababa"
```
```
Input: "cbbd"
Output: "bb"
```
### Edge Cases
```
Input: "ab"
Output: "a"
```
```
Input: ""
Output: ""
```
-----
## Testing
Along with the example tests given:
- There are **500** tests using strings of length in range [1 - 1,000]
- There are **50** tests using strings of length in range [1,000 - 10,000]
- There are **5** tests using strings of length in range [10,000 - 100,000]
All test cases can be passed within 10 seconds, but non-linear solutions will time out every time. _Linear performance is essential_.
## Good Luck!
-----
This problem was inspired by [this](https://leetcode.com/problems/longest-palindromic-substring/) challenge on LeetCode. Except this is the performance version :^)
| algorithms | '''
Write a function that returns the longest contiguous palindromic substring in s.
In the event that there are multiple longest palindromic substrings, return the
first to occur.
'''
def longest_palindrome(s, sep=" "):
# Interpolate some inert character between input characters
# so we only have to find odd-length palindromes
t = sep + sep . join(s) + sep
r = 0 # Rightmost index in any palindrome found so far ...
c = 0 # ... and the index of the centre of that palindrome.
spans = [] # Length of the longest substring in T[i:] mirrored in T[i::-1]
# Manacher's algorithm
for i, _ in enumerate(t):
span = min(spans[2 * c - i], r - i - 1) if i < r else 0
while span <= i < len(t) - span and t[i - span] == t[i + span]:
span += 1
r, c = max((r, c), (i + span, i))
spans . append(span)
span = max(spans)
middle = spans . index(span)
return t[middle - span + 1: middle + span]. replace(sep, "")
| Longest Palindromic Substring (Linear) | 5dcde0b9fcb0d100349cb5c0 | [
"Performance",
"Algorithms",
"Puzzles"
] | https://www.codewars.com/kata/5dcde0b9fcb0d100349cb5c0 | 4 kyu |
<!-- Stable Weight Arrangement -->
Here is a simple task. Take an array/tuple of unique positive integers, and two additional positive integers. Here's an example below:
```javascript
const arr = [3,5,7,1,6,8,2,4];
const n = 3; // span length
const q = 13; // weight threshold
```
```python
arr = (3,5,7,1,6,8,2,4)
n = 3 # span length
q = 13 # weight threshold
```
```go
var arr = []int{3,5,7,1,6,8,2,4}
var n int = 3 // span length
var q int = 13 // weight threshold
```
Try to re-arrange `arr` so that the sum of any `n` consecutive values does not exceed `q`.
```javascript
solver(arr,n,q); // one possible solution: [4,7,1,5,6,2,3,8]
```
```python
solver(arr,n,q) ## one possible solution: (4,7,1,5,6,2,3,8)
```
```go
Solver(arr,n,q) // one possible solution: {4,7,1,5,6,2,3,8}
```
Did you succeed? Great! Now teach a computer to do it.
<h2 style='color:#f88'>Technical Details</h2>
- All test inputs will be valid
- All test cases will have `0` or more possible solutions
- If a test case has no solution, return an empty array/tuple. Otherwise, return a valid solution
- Test constraints:
- `2 <= n <= 6`
- `4 <= arr length < 12`
- `n < arr length`
- Every value in `arr` will be less than `q`
- `11` fixed tests, `25` random tests
- In JavaScript, `module` and `require` are disabled
- For JavaScript, use Node 10+
- For Python, use Python 3.6+
<p>If you enjoyed this kata, be sure to check out <a href='https://www.codewars.com/users/docgunthrop/authored' style='color:#9f9;text-decoration:none'>my other katas</a></p> | algorithms | def gen(l, p, arr, n, q):
if not p:
yield []
return
for i in p:
if len(l) + 1 < n or sum(l[len(l) - n + 1:]) + arr[i] <= q:
for s in gen(l + [arr[i]], p - set([i]), arr, n, q):
yield [arr[i]] + s
def solver(arr, n, q):
return next(gen([], set(range(len(arr))), arr, n, q), ())
| Stable Weight Arrangement | 5d6eef37f257f8001c886d97 | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/5d6eef37f257f8001c886d97 | 5 kyu |
Find the lowest-cost Hamiltonian cycle of an undirected graph.
Input is an adjacency matrix consisting of a dictionary of dictionaries of costs, such that `d[A][B]` is the cost going from A to B or from B to A. Output is a sequence of nodes representing the minimum cost Hamiltonian cycle through all nodes. If no such path is available, return `None`.
Randomized tests use up to 10 nodes.
Relevant readings:
https://en.wikipedia.org/wiki/Hamiltonian_path
## Kata in this Series
1. [Coping with NP-Hardness #1: 2-SAT](https://www.codewars.com/kata/5edeaf45029c1f0018f26fa0)
2. [Coping with NP-Hardness #2: Max Weight Independent Set of a Tree](https://www.codewars.com/kata/5edfad4b32ebb000355347d2)
3. **Coping with NP-Hardness #3: Finding the Minimum Hamiltonian Cycle**
4. [Coping with NP-Hardness #4: 3-Recoloring](https://www.codewars.com/kata/5ee17ff3c28ec6001f371b61) | games | def get_minimum_hamiltonian_cycle(adj):
candidates = [((a,), 0) for a in adj]
best_cycle = None
best_cost = float('inf')
len_adj = len(adj)
while candidates:
path, cost = candidates . pop()
for node, c in adj[path[- 1]]. items():
new_cost = cost + c
if node not in path:
if new_cost < best_cost:
candidates . append(((* path, node), new_cost))
elif node == path[0] and len(path) == len_adj and new_cost < best_cost:
best_cycle = path
best_cost = new_cost
return best_cycle
| Coping with NP-Hardness #3: Finding the Minimum Hamiltonian Cycle | 5ee12f0a5c357700329a6f8d | [
"Puzzles"
] | https://www.codewars.com/kata/5ee12f0a5c357700329a6f8d | 5 kyu |
*This is the advanced version of the [Total Primes](https://www.codewars.com/kata/total-primes/) kata.*
The number `23` is the smallest prime that can be "cut" into **multiple** primes: `2, 3`. Another such prime is `6173`, which can be cut into `61, 73` or `617, 3` or `61, 7, 3` (all primes). A third one is `557` which can be sliced into `5, 5, 7`. Let's call these numbers **total primes**.
Notes:
* one-digit primes are excluded by definition;
* leading zeros are also excluded: e.g. splitting `307` into `3, 07` is **not** valid
### Task
Complete the function that takes a range `[a..b]` (both limits included) and returns the total primes within that range (`a β€ total primes β€ b`).
The tests go up to 10<sup>6</sup>.
~~~if:python
For your convenience, a list of primes up to 10<sup>6</sup> is preloaded, called `PRIMES`.
~~~
### Examples
```
(0, 100) --> [23, 37, 53, 73]
(500, 600) --> [523, 541, 547, 557, 571, 577, 593]
```
Happy coding!
---
### My other katas
If you enjoyed this kata then please try [my other katas](https://www.codewars.com/users/anter69/authored)! :-)
#### *Translations are welcome!* | algorithms | from bisect import bisect_left, bisect
sp = set(map(str, PRIMES))
def tp(s):
for x in range(1, len(s)):
if s[: x] in sp and (s[x:] in sp or tp(s[x:])):
return True
return False
TOTAL_PRIMES = [i for i in PRIMES if tp(str(i))]
def total_primes(a, b):
return TOTAL_PRIMES[bisect_left(TOTAL_PRIMES, a): bisect(TOTAL_PRIMES, b)]
| Total Primes - Advanced Version | 5d2351b313dba8000eecd5ee | [
"Performance",
"Algorithms"
] | https://www.codewars.com/kata/5d2351b313dba8000eecd5ee | 5 kyu |
# Task
John bought a bag of candy from the shop. Fortunately, he became the 10000000000000000000000th customer of the XXX confectionery company. Now he can choose as many candies as possible from the company's `prizes`. With only one condition: the sum of all the candies he chooses must be multiples of `k`.
Your task is to help John choose the `prizes`, returns the maximum possible amount of candies that John can got.
# Input/Output
`[input]` integer array `prizes`
The prizes of candies. Each element is a bag of candies. John can only choose the whole bag. Open bag and take some candies is not allowed ;-)
`1 β€ prizes.length β€ 100`
`1 β€ prizes[i] β€ 5000000`
`[input]` integer `k`
A positive integer.
`2 β€ k β€ 20`
`[output]` an integer
The maximum amount of candies that John can got. The number should be a multiples of `k`. If can not find such a number, return `0` instead.
# Example
For `prizes = [1,2,3,4,5] and k = 5`, the output should be `15`
`1 + 2 + 3 + 4 + 5 = 15, 15 is a multiple of 5`
For `prizes = [1,2,3,4,5] and k = 7`, the output should be `14`
`2 + 3 + 4 + 5 = 14, 14 is a multiple of 7`
| algorithms | def lucky_candies(a, k):
l = [0] + (k - 1) * [float('-inf')]
for x in a:
l = [max(l[(i - x) % k] + x, y) for i, y in enumerate(l)]
return l[0]
| Simple Fun #314: Lucky Candies | 592e5d8cb7b59e547c00002f | [
"Algorithms",
"Dynamic Programming",
"Performance"
] | https://www.codewars.com/kata/592e5d8cb7b59e547c00002f | 5 kyu |
***note: linear algebra experience is recommended for solving this problem***
## Problem
Spike is studying spreading spores graphs. A spreading spores graph represents an undirected graph where each node has a float amount (possibly negative or fractional) of spores in it. At each step in time, all the initial spores in a node disappear, but not before spreading an equal amount of spores to each adjacent node. For example, in the following graph:
```
(1) a (0) b (2) c (2)
/ \ -> / \ -> / \ -> / \
(0)-(0) (1)-(1) (1)-(1) (3)-(3)
```
- `Step a`: the top node spreads `1` spore to its adjacent nodes, and then the initial `1` spore in the top node disappears (or equivalently is subtracted from its total)
- `Step b`: the bottom two nodes spread `1+1=2` spores the top node, and `1` spore to eachother
- `Step c`: the top node spreads `2` spores to the bottom nodes, and the bottom nodes spread `1` spore to eachother, for a total of `2+1=3` spores in the bottom nodes. The bottom nodes spread `1+1=2` spores to the top node
Some more examples:
```
(1.5)-(0) -> (0)-(1.5) -> (1.5)-(0)
```
```
(-1)-(2)-(0) -> (2)-(-1)-(2) -> (-1)-(4)-(-1)
```
For a given spreading spores graph, usually the ratio of spores between each node changes after every step. However, Spike notices if he places spores carefully in a graph, he can get it so the amount of spores in every node is multiplied by the same amount. For a triangular graph, he finds 2 examples:
```
(1) x2 (2) x2 (4)
/ \ -> / \ -> / \
(1)-(1) (2)-(2) (4)-(4)
```
```
(0) x-1 (0) x-1 (0)
/ \ -> / \ -> / \
(-1)-(1) (1)-(-1) (-1)-(1)
```
Spike is interested in these graphs, which he calls scaling graphs; particularly, he is interested in a scaling graph that is multiplied by the greatest amount each step, and would like to find how much it's multiplied by. In the examples he discovered for the triangle graph, he concludes this amount is `2`, corresponding to the first example and beating out `-1`. (Note that in the first example, the first, second, and third iteration of the graph are distinct but share the same greatest spore multiplier.)
### Problem Definition
Your task is to, given an undirected graph, create a function `get_greatest_spore_multiplier` to find the multiplier of a scaling graph (created by putting spores in the undirected graph's nodes) that grows fastest. The graph with all nodes being empty shouldn't be considered.
- The graph is given in [adjacency list](https://en.wikipedia.org/wiki/Adjacency_list) format, being represented by a dict mapping a node to its adjacent nodes. Each node in the graph is represented by a number in `range(0, num nodes)`. For example, the graph (with numbers being labels rather than number of spores)
```
# 0 - 1
# | |
# 2 - 3
```
is represented by
```python
square_graph = {
0: [1, 2],
1: [0, 3],
2: [0, 3],
3: [1, 2]
}
```
- You can assume the graphs are undirected
- The multiplier returned should be non-negative
- If there are no scaling graphs with a positive multiplier, return `0`
- In the case of the empty graph `{}`, return `0`
- Because the answer you give is a float, you only need to give an [approximately correct](https://docs.codewars.com/languages/python/codewars-test#approximate-equality-tests) answer within a relative/absolute margin of `0.01`.
## Examples
```python
# 0
# / \
# 1 - 2
triangle_graph = {
0: [1, 2],
1: [0, 2],
2: [0, 1]
}
# Multiplier corresponds to putting 1 spore on each node
test.assert_approx_equals(
get_greatest_spore_multiplier(triangle_graph),
2
)
```
```python
# 0 - 1
# | |
# 2 - 3
square_graph = {
0: [1, 2],
1: [0, 3],
2: [0, 3],
3: [1, 2]
}
# Multiplier corresponds to putting 1 spore on each node
test.assert_approx_equals(
get_greatest_spore_multiplier(square_graph),
2
)
```
```python
# 0 - 1
line = {
0: [1],
1: [0],
}
# Multiplier corresponds to putting 1 spore on each node
test.assert_approx_equals(
get_greatest_spore_multiplier(line),
1
)
```
```python
# 0 - 1
# | X |
# 2 - 3
complete_graph_with_4_nodes = {
0: [1, 2, 3],
1: [0, 2, 3],
2: [0, 1, 3],
3: [0, 1, 2]
}
# Multiplier corresponds to putting 1 spore on each node
test.assert_approx_equals(
get_greatest_spore_multiplier(complete_graph_with_4_nodes),
3
)
```
```python
# 3
# |
# 0
# / \
# 1 - 2
# / \
# 4 5
triangle_graph_with_tails = {
0: [1, 2, 3],
1: [0, 2, 4],
2: [0, 1, 5],
3: [0],
4: [1],
5: [2],
}
# Multiplier corresponds to putting 1 spore on the 'tails' (3, 4, 5),
# and 1 + β2 spores on the triangle nodes (0, 1, 2)
test.assert_approx_equals(
get_greatest_spore_multiplier(triangle_graph_with_tails),
1 + 2 ** .5
)
``` | algorithms | from typing import Dict, List
from numpy import array
from numpy . linalg import eigvalsh
def get_greatest_spore_multiplier(graph: Dict[int, List[int]]) - > float:
if not graph:
return 0
matrix = array([[x in adj for x in graph] for adj in graph . values()])
return max(eigvalsh(matrix))
| Spreading Spores Graph | 60f3639b539c06001a076267 | [
"Linear Algebra",
"Mathematics",
"Combinatorics",
"NumPy",
"Algorithms",
"Graph Theory"
] | https://www.codewars.com/kata/60f3639b539c06001a076267 | 5 kyu |
You have to write a function that takes for input a 8x8 chessboard in the form of a bi-dimensional array of chars (or strings of length 1, depending on the language) and returns a boolean indicating whether the king is in check.
The array will include 64 squares which can contain the following characters :
```if:c,haskell,cobol,java
<ul>
<li>'K' for the black King;</li>
<li>'Q' for a white Queen;</li>
<li>'B' for a white Bishop;</li>
<li>'N' for a white kNight;</li>
<li>'R' for a white Rook;</li>
<li>'P' for a white Pawn;</li>
<li>' ' (a space) if there is no piece on that square.</li>
</ul>
```
```if:javascript,python,rust,go
<ul>
<li>'β' for the black King;</li>
<li>'β' for a white Queen;</li>
<li>'β' for a white Bishop;</li>
<li>'β' for a white Knight;</li>
<li>'β' for a white Rook;</li>
<li>'β' for a white Pawn;</li>
<li>' ' (a space) if there is no piece on that square.</li>
</ul>
Note : these are actually inverted-color [chess Unicode characters](https://en.wikipedia.org/wiki/Chess_symbols_in_Unicode) because the codewars dark theme makes the white appear black and vice versa. Use the characters shown above.
```
There will always be exactly one king, which is the **black** king, whereas all the other pieces are **white**.<br>
**The board is oriented from Black's perspective.**<br>
Remember that pawns can only move and take **forward**.<br>
Also be careful with the pieces' lines of sight ;-) .
The input will always be valid, no need to validate it.
To help you visualize the position, tests will print a chessboard to show you the problematic cases.
Looking like this :
<pre>
|---|---|---|---|---|---|---|---|
| | | | | | | | |
|---|---|---|---|---|---|---|---|
| | | | β | | | | |
|---|---|---|---|---|---|---|---|
| | | | | | | | |
|---|---|---|---|---|---|---|---|
| | | | β | | | | |
|---|---|---|---|---|---|---|---|
| | | | | | | | |
|---|---|---|---|---|---|---|---|
| | | | | | | | |
|---|---|---|---|---|---|---|---|
| | | | | | | | |
|---|---|---|---|---|---|---|---|
| | | | | | | | |
|---|---|---|---|---|---|---|---|
</pre>
| algorithms | UNITS = {'β': {"moves": [(1, 1), (1, - 1), (- 1, 1), (- 1, - 1)], "limit": False},
'β': {"moves": [(1, 0), (0, 1), (- 1, 0), (0, - 1)], "limit": False},
'β': {"moves": [(1, 1), (1, - 1)], "limit": True},
'β': {"moves": [(2, 1), (2, - 1), (- 2, 1), (- 2, - 1), (- 1, 2), (1, 2), (- 1, - 2), (1, - 2)], "limit": True},
'β': {"moves": [(1, 1), (1, - 1), (- 1, 1), (- 1, - 1), (1, 0), (0, 1), (- 1, 0), (0, - 1)], "limit": False}}
def king_is_in_check(chessboard):
hostile = [(square, x, y) for x, row in enumerate(chessboard)
for y, square in enumerate(row) if square not in (' ', 'β')]
return any([move(square, x, y, chessboard) for square, x, y in hostile])
def move(unit, x, y, board):
if UNITS[unit]["limit"]:
for a, b in UNITS[unit]["moves"]:
try:
if not is_in_board(x + a, y + b):
continue
square = board[x + a][y + b]
if square == 'β':
return True
except:
pass
return False
else:
for a, b in UNITS[unit]["moves"]:
base_a, base_b = a, b
while True:
try:
if not is_in_board(x + base_a, y + base_b):
break
square = board[x + base_a][y + base_b]
if square != ' ':
print(square)
if square == 'β':
return True
else:
break
base_a += a
base_b += b
except:
break
return False
def is_in_board(x, y):
return x >= 0 and y >= 0
| Is the King in check ? | 5e28ae347036fa001a504bbe | [
"Games",
"Arrays",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5e28ae347036fa001a504bbe | 5 kyu |
Removed due to copyright infringement.
<!---
Little Petya often visits his grandmother in the countryside. The grandmother has a large vertical garden, which can be represented as a set of `n` rectangles of varying height. Due to the newest irrigation system we can create artificial rain above them.
Creating artificial rain is an expensive operation. That's why we limit ourselves to creating the artificial rain only above one section. The water will then flow to the neighbouring sections but only if each of their heights does not exceed the height of the previous watered section.
___
## Example:
Let's say there's a garden consisting of 5 rectangular sections of heights `4, 2, 3, 3, 2`.
Creating the artificial rain over the left-most section is inefficient as the water **WILL FLOW DOWN** to the section with the height of `2`, but it **WILL NOT FLOW UP** to the section with the height of `3` from there. Only 2 sections will be covered: `4, 2`.
The most optimal choice will be either of the sections with the height of `3` because the water will flow to its neighbours covering 4 sections altogether: `2, 3, 3, 2`. You can see this process in the following illustration:
<img src="https://i.ibb.co/KjvKDrD/Screenshot-1.png" alt="Screenshot-1" border="0"></a>
___
As Petya is keen on programming, he decided to find such section that if we create artificial rain above it, the number of watered sections will be maximal.
## Output:
The maximal number of watered sections if we create artificial rain above exactly one section.
**Note: performance will be tested.**
---> | algorithms | def artificial_rain(garden):
left, area, record = 0, 0, 1
for i in range(1, len(garden)):
if garden[i] < garden[i - 1]:
left = i
elif garden[i] > garden[i - 1]:
area = max(area, record)
record = i - left
record += 1
return max(area, record)
| Artificial Rain | 5c1bb3d8e514df60b1000242 | [
"Algorithms",
"Logic",
"Performance"
] | https://www.codewars.com/kata/5c1bb3d8e514df60b1000242 | 5 kyu |
### You work at a taxi central.
People contact you to order a taxi. They inform you of the time they want to be picked up and dropped off.
A taxi is available to handle a new customer 1 time unit after it has dropped off a previous customer.
**What is the minimum number of taxis you need to service all requests?**
### Constraints:
* Let **N** be the number of customer requests:
- **N** is an integer in the range **[1, 100k]**
* All times will be integers in range **[1, 10k]**
* Let **PU** be the time of pickup and **DO** be the time of dropoff
- Then for each request: **PU < DO**
* The input list is **NOT sorted**.
### Examples:
```python
# Two customers, overlapping schedule. Two taxis needed.
# First customer wants to be picked up 1 and dropped off 4.
# Second customer wants to be picked up 2 and dropped off 6.
requests = [(1, 4), (2, 6)]
min_num_taxis(requests) # => 2
# Two customers, no overlap in schedule. Only one taxi needed.
# First customer wants to be picked up 1 and dropped off 4.
# Second customer wants to be picked up 5 and dropped off 9.
requests = [(1, 4), (5, 9)]
min_num_taxis(requests) # => 1
``` | algorithms | from heapq import heappush, heappop
def min_num_taxis(requests):
taxis = [- 1]
for start, end in sorted(requests):
if taxis[0] < start:
heappop(taxis)
heappush(taxis, end)
return len(taxis)
| Minimum number of taxis | 5e1b37bcc5772a0028c50c5d | [
"Data Structures",
"Algorithms",
"Priority Queues",
"Scheduling"
] | https://www.codewars.com/kata/5e1b37bcc5772a0028c50c5d | 5 kyu |
## Typed Function overloading
Python is a very flexible language, however one thing it does not allow innately, is the overloading of functions. _(With a few exceptions)_. For those interested, [this existing kata](https://www.codewars.com/kata/5f24315eff32c4002efcfc6a) explores the possibility of overloading object methods for different amounts of arguments. In this kata we are going to implement a form of overloading for any function/method, based on the _classes_ of arguments, using decorators.
### Overview
You will be writing a decorator `@overload(*types)` that will allow a function or method to be defined multiple times for different combinations of types of input arguments. The combination and order of classes of the arguments should call a specific defined function.
To keep this kata relatively simple, various aspects of functions (Going out of scope, etc) will not be tested, more details on what will and won't be tested are listed below.
### Basic Example
```python
@overload(int)
def analyse(x):
print('X is an int!')
@overload(list)
def analyse(x):
print('X is a list!')
analyse([]) # X is a list!
analyse(3) # X is an int!
```
## Additional Information:
### The decorator
- It should accept any type or class, even user made classes. Note that an inherited class does **NOT** count as its parent class. Each custom class should be considered unique.
- It should be able to handle any number of arguments, including zero.
- If an overloaded function/method is called without a matching set of types/classes, an Exception should be raised.
- The decorator can be used on regular functions and on instance methods of a class as well (see below about overloading vs overwritting behaviours). 'Magic methods' (eg. `__init__`, `__call__`) will **NOT** be tested.
### The decorated function or method
- The function/method should return correct values.
- All other usual function behaviours should work (Recursion, passing function as argument, etc).
- Static and class methods will ***NOT*** be tested.
- Note that when decorating an instance method, the type of `self` isn't provided to the decorator. The decorated function should yet be able to use the reference to `self`.
- Varargs (`*args`) may be used in functions definitions. In that case, trust the types given to the decorator to decide what call must be mapped to that function.
- You do not need to consider scope problems, like having 2 different functions with the same name but in 2 different scope. All functions will be defined as top level functions, or top level object methods.
### Overloading vs overwritting behaviours
- Multiple different overloaded functions/methods must be able to exist at a time: `func(int,list)` overloads a previous `func(list)` and doesn't overwrite it.
- Functions and methods should be considered *distinct*, ie. `analyse(int)` and `my_obj.analyse(int)` are not the same and one shouldn't overwrite the other.
- If a function/method with a "known" name is decorated again with an already existing types combination, the previous definition should be overwritten (See examples below).
## More specific Examples
Should accept any class or type. Variable length args should work:
```python
class My_Class: pass
class My_Inherited_Class(My_Class): pass
@overload(int, My_Class, str)
def some_function(*args):
return 'Option 1'
@overload()
def some_function():
return 'Option 2'
A = My_Class()
B = My_Inherited_Class()
some_function() # Option 2
some_function(3, A, 'Words') # Option 1 <= trust the types given to the decorator
some_function('oops!') # Exception raised <= no matching types combination
some_function(3, B, 'Words') # Exception raised <= doesn't consider inheritence
```
Should be able to manage functions **AND** methods:
```python
@overload(int)
def spin(x):
return x*3-1
@overload(str)
def spin(x):
return x[1:] + x[0]
print(spin(6)) # 17
print(spin('Hello')) # elloH <= overload correctly, just like before...
print(spin('')) # raise IndexError
class T:
def __init__(self, x):
self.val = x
@overload(int)
def spin(self, x):
return self.val * x
@overload(str)
def spin(self, x):
return x + str(self.val)
obj = T(7)
print(spin(6)) # 17 <= the instance method doesn't overwrite the function
print(obj.spin(2)) # 14 <= `self` is still usable
print(spin('Hello')) # elloH
print(obj.spin('Hello')) # Hello7
```
Previous definitions should be overwritten:
```python
@overload(str)
def upgrade(x):
print('First')
@overload(str)
def upgrade(x):
print('Second')
upgrade('Y') # Second
```
Good luck, and I hope you enjoy the Kata! | reference | from collections import defaultdict
from functools import wraps
CACHE = defaultdict(lambda: defaultdict(lambda: None))
def overload(* types):
def dec(func):
overloads = CACHE[func . __qualname__]
overloads[types] = func
@ wraps(func)
def wrapper(* a, * * kw):
typs = tuple(type(v) for v in a + tuple(kw . values()))
f = overloads[typs] or overloads[typs[1:]]
return f(* a, * * kw)
return wrapper
return dec
| Function Overloading for Types | 6025224447c8ed001c6d8a43 | [
"Decorator",
"Language Features",
"Metaprogramming"
] | https://www.codewars.com/kata/6025224447c8ed001c6d8a43 | 5 kyu |
I often find that I end up needing to write a function to return multiple values, in this case I would often split it up into two different functions but then I have to spend time thinking of a new function name! Wouldn't it be great if I could use same name for a function again and again...
In this kata your task is to make a decorator, `FuncAdd` which will allow function names to be reused and when called all functions with that name will be called (in order) and the results returned as a tuple.
```python
@FuncAdd
def foo():
return 'Hello'
@FuncAdd
def foo():
return 'World'
foo() --> ('Hello', 'World')
```
As well as this you will have to implement two more things, a way of deleting a particular function, and a way of deleting all stored functions. The `delete` method must work as follows:
```python
@FuncAdd
def foo():
return 'Hello'
FuncAdd.delete(foo) # Delete all foo() functions only
foo() # Should raise NameError
```
And the `clear` method must work like this:
```python
@FuncAdd
def foo():
return 'Hello'
FuncAdd.clear() # Delete all decorated functions
foo() # Should raise NameError
```
The functions must also accept args and kwargs which would all be passed to every function. | reference | from collections import defaultdict
class FuncAdd:
# Good Luck!
funcs = defaultdict(list)
def __init__(self, func):
name = func . __name__
FuncAdd . funcs[name]. append(func)
self . name = name
def __call__(self, * args, * * kwargs):
vals = []
if self . name not in FuncAdd . funcs:
raise NameError()
for f in FuncAdd . funcs[self . name]:
vals . append(f(* args, * * kwargs))
return tuple(vals)
@ classmethod
def delete(cls, self):
del cls . funcs[self . name]
@ classmethod
def clear(cls):
cls . funcs = defaultdict(list)
| Function Addition | 5ebcfe1b8904f400208e3f0d | [
"Fundamentals"
] | https://www.codewars.com/kata/5ebcfe1b8904f400208e3f0d | 5 kyu |
# Basic pseudo-lisp syntax
Let's create a language that has the following syntax (_BackusβNaur form_):
```prolog
<expression> ::= <int> | <func_call>
<digit> ::= '0' | '1' | '2' | ... | '9'
<int> ::= <digit> [<int>]
<name_char> ::= (any character except parentheses and spaces)
<func_name> ::= <name_char> [<func_name>]
<func_args> ::= <expression> [' ' <func_args>]
<func_call> ::= '(' <func_name> <func_args> ')'
```
A quick interpretation of this syntax tells us that expressions in this pseudo-lisp language look like this:
```lisp
53
(neg 3)
(+ (* 2 4) 2)
(+ (* (+ 1 1) 4) (^2 2))
(pow (mul 2 4) 3)
```
These are all valid expressions that can be evaluated into a number if you know how to apply the functions. Let's see some examples with well-known operators:
```lisp
3 ; Evaluates to 3
(- 3) ; Evaluates to -3
(+ 1 3) ; Evaluates to 4
(* (- 3) (+ 1 3)) ; Evaluates to -12
```
Simple enough, right? Now let's play around with this idea :)
# Your task
Write a funtion `parse(code: str, function_table: Dict[str, Callable])` that takes the code to parse in pseudo-lisp and a dictionary of functions and returns the result that a correct interpreter for this language would give.
Now, the thing is that you only have **160 characters** to do this, so be careful :D
*__Personal best:__ 154 characters.*
# Preloaded code
all the contents of the `regex` (not `re`) module have been preloaded with `from regex import *`, so you can use any of this freely.
# Examples
```python
f = {
'sum': lambda a, b: a + b,
'mul': lambda a, b: a * b,
'div': lambda a, b: a / b,
'pow': lambda a, b: a ** b,
'neg': lambda a: -a,
'sqr': lambda a: a*a
}
parse('(sum 2 (mul 5 6))', f) == 32
parse('(sqr (neg 5))', f) == 25
parse('(pow 2 (sum 2 6))', f) == 256
```
## As always, have fun :) | algorithms | def parse(c, f): return eval(sub(* ' ,', sub('\((\S*) ', r"f['\1'](", c)))
| Lisp-esque parsing [Code Golf] | 5ea1de08a140dc0025b10d82 | [
"Parsing",
"Restricted",
"Algorithms"
] | https://www.codewars.com/kata/5ea1de08a140dc0025b10d82 | 5 kyu |
Your task in this kata is to implement simple version of <a href="https://docs.python.org/2/library/contextlib.html">contextlib.contextmanager</a>.
The decorator will be used on a generator functions and use the part of function before yield as context manager's "enter section" and the part after the yield as "exit section".
If exception occurs inside the context of the with statement, the exception should be passed to the generator via its throw method.
Examples:
```python
@contextmanager
def file_opened(file):
fp = open(file)
try:
yield fp
finally:
fp.close()
with file_opened('a.txt') as fp:
print fp.readline()
@contextmanager
def transaction(connection):
connection.begin()
try:
yield
except:
connection.rollback()
raise
else:
connection.commit()
with transaction():
# ...
raise Exception()
```
_Note: contextlib as been forbidden, write your own..._ | reference | # I think this kate could use more tests
class MyClass:
def __init__(self, f): self . gen = f()
def __enter__(self): return next(self . gen)
def __exit__(self, * args): pass
def contextmanager(f):
def wrapper(): return MyClass(f)
return wrapper
| Context manager decorator | 54e0816286522e95990007de | [
"Fundamentals"
] | https://www.codewars.com/kata/54e0816286522e95990007de | 5 kyu |
You are a chess esthete. And you try to find beautiful piece combinations. Given a chess board you want to see how this board will look like by removing each piece, one at a time.
*Note:* after removing a piece, you should put it back to its position, before removing another piece.
Also, you are a computer nerd. No need to look at the board in real life, you will play around with the first part of [FEN](https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation) strings like this:
`rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR`.
# Input
A FEN string
# Expected Output
A list of FENs
# Example
```javascript,python
fen = '2p5/8/k2Q4/8/8/8/8/4K3'
=> [
'8/8/k2Q4/8/8/8/8/4K3',
'2p5/8/3Q4/8/8/8/8/4K3',
'2p5/8/k7/8/8/8/8/4K3',
'2p5/8/k2Q4/8/8/8/8/8'
]
```
___
Translations are appreciated.^^
If you like matrices take a look at [2D Cellular Neighbourhood](https://www.codewars.com/kata/2d-cellular-neighbourhood)
If you like puzzles and python take a look at [Rubik's cube](https://www.codewars.com/kata/5b3bec086be5d8893000002e) | algorithms | def get_without_every_piece(s):
Z = []
for i, x in enumerate(s):
if not x . isalpha():
continue
a, b, c, p, q = s[: i], 1, s[i + 1:], 0, 0
if a and a[- 1]. isdigit():
p, a = int(a[- 1]), a[: - 1]
if c and c[0]. isdigit():
q, c = int(c[0]), c[1:]
Z += [a + str(p + q + b) + c]
return Z
| Chess Aesthetics | 5b574980578c6a6bac0000dc | [
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/5b574980578c6a6bac0000dc | 6 kyu |
# Task
You are given an sequence of zeros and ones. With each operation you are allowed to remove consecutive equal elements, however you may only remove single elements if no more groups of consective elements remain. How many operations will it take to remove all of the elements from the given sequence?
# Example
For `arr = [0, 1, 1, 1, 0]`, the result should be `2`.
It can be cleared in two steps:
`[0, 1, 1, 1, 0] -> [0, 0] -> [].`
For `arr = [0, 1, 0, 0, 0]`, the result should be `3`.
It can be cleared in three steps:
`[0, 1, 0, 0, 0] -> [0, 1] -> [0] -> []`
Note that you can not remove `1` at the first step, because you cannot remove just one element while there are still groups of consective elements (see the rule above ^_^)
~~~if:javascript
### Input
An array `arr` of 0s and 1s.<br>
`1 <= arr.length <= 100`
### Output
The minimum number (integer) of operations.
~~~
~~~if:python
### Input
A list `lst` of 0s and 1s.<br>
`1 <= len(lst) <= 100`
### Output
The minimum number (integer) of operations.
~~~
# Special thanks:
Thanks for docgunthrop's solution ;-) | algorithms | from math import ceil
def array_erasing(lst):
# coding and coding...
dic = []
last = lst[0]
count = 0
for i, j in enumerate(lst):
if j == last:
count += 1
else:
dic . append(count)
last = j
count = 1
dic . append(count)
step = 0
length = len(dic)
p1 = (length - 1) / / 2
p2 = length / / 2
while True:
if len(dic) > 4:
if dic[p1] > 1 or dic[p2] > 1:
return step + ceil((length + 1) / 2)
if dic[p1 - 1] > 1:
step += 1
dic[p1 - 2] += dic[p1]
dic . pop(p1 - 1)
dic . pop(p1 - 1)
length = len(dic)
p1 = (length - 1) / / 2
p2 = length / / 2
continue
if dic[p2 + 1] > 1:
step += 1
dic[p2] += dic[p2 + 2]
dic . pop(p2 + 1)
dic . pop(p2 + 1)
length = len(dic)
p1 = (length - 1) / / 2
p2 = length / / 2
continue
if p1 >= 2 and p2 <= len(dic) - 4:
p1 -= 1
p2 += 1
elif len(dic) <= 4:
continue
else:
if dic[0] + dic[- 1] > 2:
return step + ceil(len(dic) / 2) + 1
else:
return step + ceil((len(dic) + 1) / 2)
else:
length = len(dic)
if length == 4:
if dic[1] + dic[2] == 2 and dic[0] + dic[3] >= 4:
return step + 4
else:
return step + 3
elif length == 3:
if dic[1] == 1 and dic[0] + dic[2] >= 3:
return step + 3
else:
return step + 2
else:
return len(dic)
| Simple Fun #112: Array Erasing | 589d1c08cc2e997caf0000e5 | [
"Algorithms"
] | https://www.codewars.com/kata/589d1c08cc2e997caf0000e5 | 5 kyu |
# Boxlines
Given a `X*Y*Z` box built by arranging `1*1*1` unit boxes, write a function `f(X,Y,Z)` that returns the number of edges (hence, **boxlines**) of length 1 (both inside and outside of the box)
### Notes
* Adjacent unit boxes share the same edges, so a `2*1*1` box will have 20 edges, not 24 edges
* `X`,`Y` and `Z` are strictly positive, and can go as large as `2^16 - 1`
### Interactive Example
The following is a diagram of a `2*1*1` box. Mouse over the line segments to see what should be counted!
<svg width="600" xmlns="http://www.w3.org/2000/svg" viewBox="-10 -10 780 582">
<style>
line {fill: none;stroke-linecap: round;stroke-miterlimit: 10;stroke-width: 10px;}
line:hover {stroke: #ff0550;}
#frontfacing {stroke: #337;}
#backfacing {stroke: #66b;}
.blue {fill: #8dd43b;}
polygon {opacity: 0.5;}
.green {fill: #aa27e1;}
</style>
<polygon class="blue" points="286 27 2 61.5 25.5 411 250.5 536.5 527.5 418.5 541.5 59 286 27"></polygon>
<polygon class="green" points="286 27 493 2 748.5 23.5 722.5 334 527.5 418.5 541.5 59 286 27"></polygon>
<g id="backfacing">
<line x1="288.5" y1="329.5" x2="25.5" y2="411"></line>
<line x1="485" y1="268.5" x2="288.5" y2="329.5"></line>
<line x1="722.5" y1="334" x2="485" y2="268.5"></line>
<line x1="288.5" y1="329.5" x2="527.5" y2="418.5"></line>
<line x1="493" y1="2" x2="485" y2="268.5"></line>
<line x1="286" y1="27" x2="288.5" y2="329.5"></line>
</g>
<g id="frontfacing">
<line x1="2" y1="61.5" x2="243" y2="109"></line>
<line x1="250.5" y1="536.5" x2="243" y2="109"></line>
<line x1="25.5" y1="411" x2="250.5" y2="536.5"></line>
<line x1="2" y1="61.5" x2="25.5" y2="411"></line>
<line x1="527.5" y1="418.5" x2="722.5" y2="334"></line>
<line x1="250.5" y1="536.5" x2="527.5" y2="418.5"></line>
<line x1="541.5" y1="59" x2="286" y2="27"></line>
<line x1="243" y1="109" x2="541.5" y2="59"></line>
<line x1="722.5" y1="334" x2="748.5" y2="23.5"></line>
<line x1="493" y1="2" x2="748.5" y2="23.5"></line>
<line x1="541.5" y1="59" x2="748.5" y2="23.5"></line>
<line x1="527.5" y1="418.5" x2="541.5" y2="59"></line>
<line x1="2" y1="61.5" x2="286" y2="27"></line>
<line x1="493" y1="2" x2="286" y2="27"></line>
</g>
</svg>
*Interactive diagram made by [@awesomead](https://www.codewars.com/users/awesomead)*
This is my first kata, so I hope every one will enjoy it <3 | reference | def f(a, b, c):
return 3 * (a * b * c) + 2 * (a * b + b * c + a * c) + a + b + c
| Boxlines | 6129095b201d6b000e5a33f0 | [
"Fundamentals",
"Geometry",
"Mathematics"
] | https://www.codewars.com/kata/6129095b201d6b000e5a33f0 | 7 kyu |
# Task
You have a long strip of paper with integers written on it in a single line from left to right. You wish to cut the paper into exactly three pieces such that each piece contains at least one integer and the sum of the integers in each piece is the same. You cannot cut through a number, i.e. each initial number will unambiguously belong to one of the pieces after cutting. How many ways can you do it?
# Example
For a = [0, -1, 0, -1, 0, -1], the output should be 4.
Here are all possible ways:
```
[0, -1] [0, -1] [0, -1]
[0, -1] [0, -1, 0] [-1]
[0, -1, 0] [-1, 0] [-1]
[0, -1, 0] [-1] [0, -1]
```
# Input/Output
- `[input]` integer array `a`
Constraints: `5 β€ a.length β€ 1000, -10000 β€ a[i] β€ 10000`
- `[output]` an integer
It's guaranteed that for the given test cases the answer always fits signed 32-bit integer type. | games | def three_split(arr):
need = sum(arr) / 3
result, chunks, current = 0, 0, 0
for i in range(0, len(arr) - 1):
current += arr[i]
if current == 2 * need:
result += chunks
if current == need:
chunks += 1
return result
| Simple Fun #44: Three Split | 588833be1418face580000d8 | [
"Puzzles",
"Performance"
] | https://www.codewars.com/kata/588833be1418face580000d8 | 5 kyu |
## Background Information
### When do we use an URL shortener?
In your PC life you have probably seen URLs like this before:
- https://bit.ly/3kiMhkU
If we want to share a URL we sometimes have the problem that it is way too long, for example this URL:
- https://www.google.com/search?q=codewars&tbm=isch&ved=2ahUKEwjGuLOJjvjsAhXNkKQKHdYdDhUQ2-cCegQIABAA&oq=codewars&gs_lcp=CgNpbWcQAzICCAAyBAgAEB4yBAgAEB4yBAgAEB4yBAgAEB4yBAgAEB4yBAgAEB4yBAgAEB4yBAgAEB4yBggAEAUQHlDADlibD2CjEGgAcAB4AIABXIgBuAGSAQEymAEAoAEBqgELZ3dzLXdpei1pbWfAAQE&sclient=img&ei=RJmqX8aGHM2hkgXWu7ioAQ&bih=1099&biw=1920#imgrc=Cq0ZYnAGP79ddM
In such cases a URL shortener is very useful.
### How does it work?
The URL shortener is given a long URL, which is then converted into a shorter one. Both URLs are stored in a database. It is important that each long URL is assigned a unique short URL.
If a user then calls up the short URL, the database is checked to see which long URL belongs to this short URL and you are redirected to the original/long URL.
**Important Note:** Some URLs such as `www.google.com` are used very often. It can happen that two users want to shorten the same URL, so you have to check if this URL has been shortened before to save memory in your database.
## Task
```if:javascript
Write a class with two methods, ```shorten``` and ```redirect```
```
### URL Shortener
```if:javascript,python
Write a method ```shorten```, which receives a long URL and returns a short URL starting with `short.ly/`, consisting only of `lowercase letters` (and one dot and one slash) and max length of `13`.
```
```if:java
Write a function ```urlShortener(longUrl)```, which receives a long URL and returns a short URL starting with `short.ly/`, consisting only of `lowercase letters` (and one dot and one slash) and max length of `13`.
```
```if:rust
Complete the function `shorten()`, which receives a long URL and returns a short URL starting with `short.ly/`, consisting only of `lowercase letters` (and one dot and one slash) and max length of `13`.
```
**Note:** `short.ly/` is not a valid short URL.
### Redirect URL
```if:javascript,python
Write a method ```redirect```, which receives the shortened URL and returns the corresponding long URL.
```
```if:java
Write a function ```urlRedirector(shortUrl)```, which receives the shortened URL and returns the corresponding long URL.
```
```if:rust
Complete the function `redirect()`, which receives the shortened URL and returns the corresponding long URL.
```
## Performance
There are `475_000` random tests.
You don't need a complicated algorithm to solve this kata, but iterating each time through the whole database to check if a URL was used before or generating short URLs based on randomness, won't pass.
**GOOD LUCK AND HAVE FUN!** | algorithms | from itertools import product
from string import ascii_lowercase
def short_url_generator():
for l in range(1, 5):
yield from ('short.ly/' + '' . join(p) for p in product(ascii_lowercase, repeat=l))
class UrlShortener:
short_urls = short_url_generator()
long_to_short = {}
short_to_long = {}
@ classmethod
def shorten(cls, long_url):
if long_url in cls . long_to_short:
return cls . long_to_short[long_url]
short_url = next(cls . short_urls)
cls . long_to_short[long_url] = short_url
cls . short_to_long[short_url] = long_url
return short_url
@ classmethod
def redirect(cls, short_url):
if short_url in cls . short_to_long:
return cls . short_to_long[short_url]
raise Exception('Redirection failed!')
Url_shortener = UrlShortener
| URL shortener | 5fee4559135609002c1a1841 | [
"Databases",
"Algorithms",
"Data Structures"
] | https://www.codewars.com/kata/5fee4559135609002c1a1841 | 5 kyu |
Let us go through an example.
You have a string (here a short one):
`s = "GCAGCaGCTGCgatggcggcgctgaggggtcttgggggctctaggccggccacctactgg"`,
with only upper or lower cases letters A, C, G, T.
You want to find substrings in this string. Each substring to find has a label.
The different substrings to find are given in a string of the following form:
```
Base = "Version xxxx
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Partial Database
http://...
Copyright (c) All rights reserved.
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
<>
AaaI (XmaIII) CGGCCG
AacI (BamHI) GGATCC
AaeI GGATCC
AagI (ClaI) ATCGAT
AarI CACCTGCNNNN
Acc38I (EcoRII) CCWGG
AceI (TseI) GCWGC"
```
Only the first lines of a Base are given here.
In first place you get a few lines of comments.
Then in three columns: the labels of the substrings, in the second one - that can be empty -
kind of comments, in the 3rd one the substring corresponding to the label.
Notice that other letters than A, C, G, T appear.
The conventions for these other letters follow:
```
R stands for G or A
Y stands for C or T
M stands for A or C
K stands for G or T
S stands for G or C
W stands for A or T
B stands for not A ie (C or G or T)
D stands for not C ie (A or G or T)
H stands for not G ie (A or C or T)
V stands for not T ie (A or C or G)
N stands for A or C or G or T
```
In the tests there are two different Bases called `Base` and `Base1` and two long strings: `data` and `data1`.
Given a base `base` (Base or Base1), a string `strng` (which will be data or data1 or s of the example) and a query name `query` - e.g label "AceI" - the function `get_pos` will return:
- the *non-overlapping* positions in `strng` where the `query` substring has been found.
In the previous example we will return `"1 7"` since the positions are numbered from 1 and not from 0.
### Explanation:
label `"AceI"` is the name of the substring `"GCWGC"` that can be written (see conventions above) `"GCAGC"` found at position `1` in `s` or `"GCTGC"` found at position `7`.
### Particular cases
If `query` name doesn't exist in Base return:
`"This query name does not exist in given Base"`.
If `query` name exists but `query` is not found in `strng` return:
`"... is not in given string"` (`...` being the query argument).
### Examples:
```
get_pos(Base, str, "AceI") => "1 7"
get_pos(Base, str, "AaeI") => "AaeI is not in given string"
get_pos(Base, str, "XaeI") => "This query name does not exist in given Base"
```
### Notes
- You can see other examples in the "Sample tests".
- Translators are welcome for all languages, except for Ruby since the Bash random tests needing Ruby a Ruby reference solution is already there though not yet published. | reference | import re
REPL = {'R': '[GA]', 'Y': '[CT]', 'M': '[AC]', 'K': '[GT]', 'S': '[GC]',
'W': '[AT]', 'B': '[CGT]', 'D': '[AGT]', 'H': '[ACT]', 'V': '[ACG]', 'N': '[ACGT]'}
REGIFY = re . compile(f'[ { "" . join ( REPL ) } ]')
def get_pos(base, seq, query):
q = next(re . finditer(
rf' { query } \s+(?:\([^)]*\)\s+)?([A-Z]+)', base), ['', ''])[1]
if not q:
return "This query name does not exist in given Base"
regS = REGIFY . sub(lambda m: REPL . get(m[0], m[0]), q)
found = " " . join(str(m . start() + 1)
for m in re . finditer(regS, seq, flags=re . I))
return found or f" { query } is not in given string"
| Positions of a substring in a string | 59f3956825d575e3330000a3 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/59f3956825d575e3330000a3 | 5 kyu |
A (blank) domino has 2 squares. Tetris pieces, also called tetriminos/tetrominoes, are made up of 4 squares each. A __polyomino__ generalizes this concept to _n_ connected squares on a flat grid.
Such shapes will be provided as a dictionary of `x` coordinates to sets of `y` coordinates. For example, the domino could be written as `{0: {1, 2}}` in a vertical orientation, or `{1: {0}, 2: {0}}` in a horizonal orientation. (Translation of all squares by some fixed `x` and `y` is not considered to change the shape.)
Some polyominoes have __symmetry__, while others do not. For instance, the 2-by-2 block in Tetris is highly symmetrical, not changing at all on each quarter rotation. In contrast, the L and J shaped Tetris pieces, which are mirror images of each other, have no symmetry. Some Tetris pieces can be rotated 180 degrees, or 2-fold. The domino not only has this rotational symmetry, but is its own mirror image.
Given a polyomino, your task is to determine its symmetry, and return one of the following classifications. Examples are given for each.
```
"C1" for no symmetry
L shape in Tetris: {0: {0, 1, 2}, 1: {0}}
Conway's R pentomino: {0: {1}, 1: {0, 1, 2}, 2: {2}}
```
```
"D1" for mirror symmetry only
T shape in Tetris: {0: {0, 1, 2}, 1: {1}}
Right angle ruler: {0: {0}, 1: {0, 1}}
```
```
"C2" for 2-fold rotational symmetry
S shape in Tetris: {0: {0}, 1: {0, 1}, 2: {1}}
Tallest net of the cube: {0: {0, 1, 2}, 1: {2, 3, 4}}
```
```
"D2" for both mirror and 2-fold rotational symmetry
I shape in Tetris: {0: {0, 1, 2, 3}}
Joined blocks: {0: {0, 1}, 1: {0, 1, 2}, 2: {1, 2}}
```
```
"C4" for 4-fold rotational symmetry
Smallest example has 8 squares:
{0: {2}, 1: {0, 1, 2}, 2: {1, 2, 3}, 3: {1}}
```
```
"D4" for both mirror and 4-fold rotational symmetry
Block shape in Tetris: {0: {0, 1}, 1: {0, 1}}
X like a plus sign: {0: {1}, 1: {0, 1, 2}, 2: {1}}
```
Mirror symmetry can result from horizontal, vertical, or 45-degree diagonal reflection. _C2_ and _C4_ are chiral like _C1_, meaning those polyominoes do not have mirror symmetry. Conventionally, `C` stands for cyclic group, and `D` for dihedral group.
Best of luck! `:~)`
| algorithms | TRANSFORMS = {
'M': [lambda x, y:(x, - y), lambda x, y:(- x, y), lambda x, y:(y, x), lambda x, y:(- y, - x)],
'C4': [lambda x, y:(y, - x)],
'C2': [lambda x, y:(- x, - y)],
}
GROUPS = (
('D4', {'C4', 'M'}),
('D2', {'C2', 'M'}),
('C4', {'C4'}),
('C2', {'C2'}),
('M', {'M'}),
)
def norm(lst):
mX, mY = map(min, zip(* lst))
return {(x - mX, y - mY) for x, y in lst}
def matchGrp(coords, f):
return coords == norm([f(x, y) for x, y in coords])
def symmetry(polyomino):
coords = norm([(x, y) for x, d in polyomino . items() for y in d])
ops = {grp for grp, syms in TRANSFORMS . items() if any(matchGrp(coords, f)
for f in syms)}
return next((grpName for grpName, grpOps in GROUPS if grpOps <= ops), 'N')
| Polyomino symmetry | 603e0bb4e7ce47000b378d10 | [
"Algorithms"
] | https://www.codewars.com/kata/603e0bb4e7ce47000b378d10 | 5 kyu |
# Directory tree
Given a string that denotes a directory, and a list (or array or ArrayList, etc, depending on language) of strings that denote the paths of files relative to the given directory, your task is to write a function that produces an _iterable_ (list, array, ArrayList, generator) of strings that, when printed successively, draws a tree of the directory structure of the files.
This is best explained with an example:
Given:
```
root = 'Desktop'
```
and
```
files = [
'meetings/2021-01-12/notes.txt',
'meetings/2020_calendar.ods',
'meetings/2021-01-12/report.pdf',
'misc/photos/forest_20130430.jpg',
'misc/photos/sunset_20130412.jpg',
'scripts/tree.py',
'meetings/2021-01-24/report.pdf',
]
```
the goal is to write a function (or method) `tree` that, when called with `root` and `files`, returns an iterable (list, generator, iterator, or other) that produces the following lines when iterated over:
```
Desktop
βββ meetings
β βββ 2021-01-12
β β βββ notes.txt
β β βββ report.pdf
β βββ 2021-01-24
β β βββ report.pdf
β βββ 2020_calendar.ods
βββ misc
β βββ photos
β βββ forest_20130430.jpg
β βββ sunset_20130412.jpg
βββ scripts
βββ tree.py
```
## Details
### Input
The `files` argument is not sorted in any particular way.
The given list `files` contains paths to files only (not directories), which implies that all leaves in the tree are files. This can be used to determine which nodes are directories and which are files. No naming conventions are used to distinguish directories from files. For example, `'a'` can be the name of a directory or a file.
In the tests, directory and file names contain ASCII characters only, but this does not prevent solutions from allowing non-ASCII characters.
The given paths in `files` contain no references to parent directory, current directory, home directory, or variables (e.g., `..`, `.`, `~`, `$HOME`).
The separator used in paths is a forward slash:`'/'`. (Sorry, Microsoft users.) The given paths contain no initial or trailing slashes.
### Output
Directories and files shall appear in alphabetical order, directories first, files thereafter. For example, in the `meetings` directory, the sub-directories `2021-01-12` and `2021-01-24` are listed before `2020_calendar.ods` although the latter comes before in alphabetical order, because directories are listed before files.
Lines shall contain no trailing whitespace characters.
Special characters required to draw the tree can be copied from this example or the given example tests.
Further details can be derived from given example tests. | reference | from typing import List
def tree(root: str, files: List[str]):
padders = (('βββ ', 'β '),
('βββ ', ' '))
def dfs(root, tree, pad='', link='', follow=''):
yield pad + link + root
pad += follow
lst = sorted(tree . items(), key=lambda it: (not it[1], it[0]))
for n, (k, v) in enumerate(lst, 1):
yield from dfs(k, v, pad, * padders[n == len(lst)])
tree = {}
for path in files:
d = tree
for v in path . split('/'):
d[v] = d . get(v, {})
d = d[v]
yield from dfs(root, tree)
| Directory tree | 5ff296fc38965a000963dbbd | [
"Fundamentals"
] | https://www.codewars.com/kata/5ff296fc38965a000963dbbd | 5 kyu |
An array consisting of `0`s and `1`s, also called a binary array, is given as an input.
### Task
Find the length of the longest contiguous subarray which consists of **equal** number of `0`s and `1`s.
### Example
```
s = [1,1,0,1,1,0,1,1]
|_____|
|
[0,1,1,0]
length = 4
```
### Note
<!-- this should show the first block for every language except LC -->
```c
0 <= length(array) < 120 000
```
```lambdacalc
0 <= length list <= 25
```
~~~if:lambdacalc
### Encodings
purity: `LetRec`
numEncoding: `BinaryScott`
export constructors `nil, cons` for your `List` encoding
~~~ | reference | from itertools import accumulate
def binarray(lst):
d, m = {}, 0
acc = accumulate(lst, lambda a, v: a + (v or - 1), initial=0)
for i, a in enumerate(acc):
if a not in d:
d[a] = i
else:
m = max(m, i - d[a])
return m
| Binary Contiguous Array | 60aa29e3639df90049ddf73d | [
"Algorithms",
"Dynamic Programming",
"Arrays"
] | https://www.codewars.com/kata/60aa29e3639df90049ddf73d | 5 kyu |
__Definition:__ According to Wikipedia, a [complete binary tree](https://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees) is a binary tree _"where every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible."_
The Wikipedia page referenced above also mentions that _"Binary trees can also be stored in breadth-first order as an implicit data structure in arrays, and if the tree is a complete binary tree, this method wastes no space."_
Your task is to write a method (or function) that takes an array (or list, depending on language) of integers and, assuming that the array is ordered according to an _in-order_ traversal of a complete binary tree, returns an array that contains the values of the tree in breadth-first order.
__Example 1:__
Let the input array be `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]`. This array contains the values of the following complete binary tree.
```
_ 7_
/ \
4 9
/ \ / \
2 6 8 10
/ \ /
1 3 5
```
In this example, the input array happens to be sorted, but that is _not_ a requirement.
__Output 1:__ The output of the function shall be an array containing the values of the nodes of the binary tree read top-to-bottom, left-to-right. In this example, the returned array should be:
```[7, 4, 9, 2, 6, 8, 10, 1, 3, 5]```
__Example 2:__
Let the input array be `[1, 2, 2, 6, 7, 5]`. This array contains the values of the following complete binary tree.
```
6
/ \
2 5
/ \ /
1 2 7
```
Note that an in-order traversal of this tree produces the input array.
__Output 2:__ The output of the function shall be an array containing the values of the nodes of the binary tree read top-to-bottom, left-to-right. In this example, the returned array should be:
```[6, 2, 5, 1, 2, 7]```
| reference | def complete_binary_tree(a):
def in_order(n=0):
if n < len(a):
yield from in_order(2 * n + 1)
yield n
yield from in_order(2 * n + 2)
result = [None] * len(a)
for i, x in zip(in_order(), a):
result[i] = x
return result
| Complete Binary Tree | 5c80b55e95eba7650dc671ea | [
"Binary Trees",
"Heaps",
"Data Structures",
"Fundamentals"
] | https://www.codewars.com/kata/5c80b55e95eba7650dc671ea | 5 kyu |
You are provided with the following functions:
```python
t = type
k = lambda x: lambda _: x
```
Write a function `f` that returns the string `Hello, world!`.
The rules are:
* The solution should not exceed 33 lines
* Every line should have at most 2 characters
Note: There is the same [kata](https://www.codewars.com/kata/5935558a32fb828aad001213) for this task on JS, but way harder than Python one, so it is the best option to create a separated kata with fair rank. | games | f \
= \
t(
'', (
),
{'\
f\
':
k('\
H\
e\
l\
l\
o\
,
\
w
o
r
l
d !'
)}
)(
)\
. f
| Multi Line Task: Hello World (Easy one) | 5e41c408b72541002eda0982 | [
"Puzzles"
] | https://www.codewars.com/kata/5e41c408b72541002eda0982 | 5 kyu |
<!--Dots and Boxes Validator-->
<p><span style='color:#8df'><a href='https://en.wikipedia.org/wiki/Dots_and_Boxes' style='color:#9f9;text-decoration:none'>Dots and Boxes</a></span> is a game typically played by two players. It starts with an empty square grid of equally-spaced dots. Two players take turns adding a single horizontal or vertical line between two unjoined adjacent dots. A player who completes the fourth side of a <code>1 x 1</code> box earns one point and takes another turn. The game ends when no more lines can be placed.</p>
<p>Your task is to return the scores of the two players of a finished game.</p>
<h2 style='color:#f88'>Input</h2>
Your function will receive an array/tuple of integer pairs, each representing a link between two dots. Dots are denoted by a sequence of integers that increases left to right and top to bottom, like shown below.
```
for a 3 x 3 square
0 1 2
3 4 5
6 7 8
```
<h2 style='color:#f88'>Output</h2>
Your function should return an array/tuple consisting of two non-negative integers representing the scores of both players.
<h2 style='color:#f88'>Test Example</h2>
<img src='https://i.imgur.com/kwS3rDy.png'/><br/>
<!-- <sup style='color:#ccc'>Sequence for the test example</sup> -->
```python
moves = ((0,1),(7,8),(1,2),(6,7),(0,3),(8,5),(3,4),(4,1),(4,5),(2,5),(7,4),(3,6))
dots_and_boxes(moves) # should return (3,1)
```
```javascript
let moves = [[0,1],[7,8],[1,2],[6,7],[0,3],[8,5],[3,4],[4,1],[4,5],[2,5],[7,4],[3,6]];
dotsAndBoxes(moves) // should return [3,1]
```
```go
var moves = [][2]int{{0,1},{7,8},{1,2},{6,7},{0,3},{8,5},{3,4},{4,1},{4,5},{2,5},{7,4},{3,6}}
DotsAndBoxes(moves) // should return [3 1]
```
```haskell
moves = [(0,1),(7,8),(1,2),(6,7),(0,3),(8,5),(3,4),(4,1),(4,5),(2,5),(7,4),(3,6)]
dotsAndBoxes moves -- should return (3,1)
```
```elixir
moves = [{0,1},{7,8},{1,2},{6,7},{0,3},{8,5},{3,4},{4,1},{4,5},{2,5},{7,4},{3,6}]
DnB.dots_and_boxes(moves) # should return {3,1}
```
```csharp
var moves = new int[][]{new[]{0,1}, new[]{7,8}, new[]{1,2}, new[]{6,7}, new[]{0,3} ,new[]{8,5}, new[]{3,4}, new[]{4,1}, new[]{4,5}, new[]{2,5}, new[]{7,4}, new[]{3,6}};
DnB.DotsAndBoxes(moves) // should return int[2]{3,1}
```
```kotlin
val moves = arrayOf(Pair(0,1),Pair(7,8),Pair(1,2),Pair(6,7),Pair(0,3),Pair(8,5),Pair(3,4),Pair(4,1),Pair(4,5),Pair(2,5),Pair(7,4),Pair(3,6))
DnB.dotsAndBoxes(moves) // should return Pair(3,1)
```
```rust
let moves = vec![(0,1),(7,8),(1,2),(6,7),(0,3),(8,5),(3,4),(4,1),(4,5),(2,5),(7,4),(3,6)];
dnb::dots_and_boxes(moves) // should return (3,1)
```
<h2 style='color:#f88'>Additional Details</h2>
- All inputs will be valid
- `n x n` board size range: `3 <= n <= 12`
- Full Test Suite: `10` fixed tests and `100` random tests
- Use Python 3+ for the Python translation
- For JavaScript, `module` and `require` are disabled
<p>If you enjoyed this kata, be sure to check out <a href='https://www.codewars.com/users/docgunthrop/authored' style='color:#9f9;text-decoration:none'>my other katas</a></p> | algorithms | from itertools import chain
def dots_and_boxes(moves):
nodes = 1 + max(chain . from_iterable(moves))
player, Y = 0, int(nodes * * .5)
pts, grid = [0, 0], [4] * nodes
for a, b in moves:
swap = 1
if a > b:
a, b = b, a
for i in (a, a - Y if b - a == 1 else a - 1):
if i < 0:
continue
grid[i] -= 1
if not grid[i]:
pts[player] += 1
swap = 0
player ^= swap
return tuple(pts)
| Dots and Boxes Validator | 5d81d8571c6411001a40ba66 | [
"Games",
"Algorithms"
] | https://www.codewars.com/kata/5d81d8571c6411001a40ba66 | 5 kyu |
# Preface
Billy is tired of his job. He thinks that his boss is rude and his pay is pathetic. Yesterday he found out about forex trading. Now he looks at the charts and fantasizes about becoming a trader and how much money he would make.
# Task
Write a function that accepts a list of price points on the chart and returns the maximum possible profit from trading.
# Example
```
ideal_trader([1.0, 1.0, 1.2, 0.8, 0.9, 1.0]) -> 1.5
```
Let's say that our ideal trader has `x` dollars on his deposit before he starts trading.
Here's what he does with it:
1. He uses all his money to buy at 1.0.
2. He sells everything at 1.2, taking a 20% profit. His deposit is now worth `1.2x`
3. He uses all his money to buy again at 0.8.
4. He sells everything at 1.0, taking a 25% profit. His deposit is now worth `1.5x`
So, during this session, an ideal trader would turn `x` dollars into `1.5x` dollars.
# Input
The input list of prices:
* Always contains at least two price points.
* Contains only positive prices.
* Can contain repeating prices (like `1.0, 1.0` in the example).
# Additional notes for traders
You should assume that in Billy's fantasies:
* There are no broker commissions.
* No leverage is used, including shorting (Billy doesn't know about this stuff yet, good for him).
* He can always buy or sell exactly at the current price (there is no [price slippage](https://www.investopedia.com/terms/s/slippage.asp)).
* [Orders](https://www.investopedia.com/terms/m/marketorder.asp) are executed instantly (before the price changes).
- - -
An early version of this kata allowed shorting, but shorts got removed because of issues (see [discussion](https://www.codewars.com/kata/610ab162bd1be70025d72261/discuss)). Some old C/C++/Python solutions are invalid now. | reference | def ideal_trader(prices):
res = 1
for i in range(1, len(prices)):
if prices[i] > prices[i - 1]:
res *= prices[i] / prices[i - 1]
return res
| Ideal Trader | 610ab162bd1be70025d72261 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/610ab162bd1be70025d72261 | 6 kyu |
## Task
Let `S` be a finite set of points on a plane where no three points are collinear. A windmill is the process where an infinite line (`l`), passing through an inital pivot point (`P`), rotates clockwise. Whenever `l` meets another element of `S` (call it `Q`), `Q` takes over as the pivot for `l`. This process continues until `l` has rotated 360 degrees. It is guaranteed that `l` will return to `P`.
In this kata, `P` will always = `(0, 0)` and you should always choose an initial orientation of `l` in the positive y-direction.
Below is a visualisation by XRFXLP.
<center>
<video loop="loop" autoplay>
<source src="https://thumbs.gfycat.com/WatchfulFearlessHippopotamus-mobile.mp4">
</video>
</center>
If you count how many times the line has hit a point in `S` __during the 360 degree rotation__, we can call this the cycle length. You must return the cycle length for a given `S`. You are not looking for the smallest repeating sequence - the line must have turned 360 degrees for it to be considered a cycle (see tests).
## Input/Output
The input is a list of points where the x and y coordinates are all integers. No three points in `S` are collinear. No point in `S` (other than `P`) will have an x-coordinate of `0`.
Return the length of the windmill cycle (integer). The tests will display the correct order that the points get hit in for debugging; you are looking for the length of that list.
If you want to visualise `S` then you can see all the static tests in Desmos <a href="https://www.desmos.com/calculator/4gqtcfrkn2">here</a>.
## Examples
```
Input: [(0, 0), (1, 0)]
Output: 2
```
Two points in a line. Let's define the angle to be the angle between the direction vector of `l` and the positive y axis counting clockwise as positive. Thus, after 90 degrees, `l` hits `(1, 0)` and it takes over as the pivot. The count of pivots used increases to 1. After 270 degrees, we hit `(0, 0)` and the count increases to 2. When we finish the windmill, at 360 degrees, we have hit two points so the answer is 2.
```
Input: [(0, 0), (2, 1), (-1, 2), (-1, -2)]
Output: 9
```
The table below should explain this cycle. (Note that `l` starts pointing up at 0 degrees but doesn't hit another point until angle = 26.6 degrees).
Angle (deg) | Pivot that is hit | Cumulative Hits
------------|-------------------|----------------
26.6 | (-1, -2) | 1
45 | (2, 1) | 2
63.4 | (0, 0) | 3
153.4 | (-1, 2) | 4
180 | (-1, -2) | 5
206.6 | (0, 0) | 6
243.4 | (2, 1) | 7
288.4 | (-1, 2) | 8
333.4 | (0, 0) | 9
### Links
* The start of this question is based on <a href="https://artofproblemsolving.com/wiki/index.php/2011_IMO_Problems#Problem_2.">Problem 2 </a>from the 2011 IMO
* <a href="https://www.youtube.com/watch?v=M64HUIJFTZM">This video</a> explains why the line always returns to `P` after 360 degrees.
| algorithms | from math import atan2, pi
def angle(p, q, direction):
return min((a for a in (atan2(p[0]-q[0],p[1]-q[1]), atan2(q[0]-p[0],q[1]-p[1])) if a > direction), default=None)
def windmill(points):
direction = -pi
p = 0, 0
n = 0
while c := min(((a, q) for q in points if q != p and (a := angle(p, q, direction)) is not None), default = None):
direction, p = c
n += 1
return n | Windmill Cycle | 5fe919c062464e001856d70e | [
"Mathematics",
"Geometry",
"Algorithms"
] | https://www.codewars.com/kata/5fe919c062464e001856d70e | 5 kyu |
# Description
You get a list that contains points. A "point" is a tuple like `(x, y)`, where `x` and `y` are integer coordinates. By connecting three points, you get a triangle. There will be `n > 2` points in the list, so you can draw one or more triangles through them.
Your task is to write a program that returns a tuple containing the areas of the largest and smallest triangles, which could be formed by these points.
### Example:
Points `(-4, 5), (-4, 0), (2, 3), (6, 0)` can formate 4 different triangles with following areas:

The largest area is __25__ and the smallest is __5__. So the correct return value is `(25, 5)`
### Additional information:
- In the returned tuple, the first position should be the largest area, and the second is the smallest.
- Areas should be rounded to tenths.
- You will always get at least __3__ points.
- If the points create only one triangle or several with the same areas, the returned tuple shoud look like this: `(10, 10)`
- Make your program efficient. With 5 points, you can make 60 triangles, but only 10 of them will be different.
- Three points can form a straight line. This doesn't count as a triangle!
- Use Google! | reference | from itertools import combinations
def area(a, b, c):
return abs(a[0] * (b[1] - c[1]) + b[0] * (c[1] - a[1]) + c[0] * (a[1] - b[1])) / 2
def maxmin_areas(points):
r = list(filter(lambda x: x > 0, map(
lambda p: area(* p), combinations(points, 3))))
return max(r), min(r)
| Triangles made of random points | 5ec1692a2b16bb00287a6d8c | [
"Mathematics",
"Geometry",
"Algorithms",
"Arrays",
"Performance",
"Fundamentals"
] | https://www.codewars.com/kata/5ec1692a2b16bb00287a6d8c | 6 kyu |
[Perfect powers](https://en.wikipedia.org/wiki/Perfect_power) are numbers that can be written `$m^k$`, where `$m$` and `$k$` are both integers greater than 1.
Your task is to write a function that returns the perfect power nearest any number.
#### Notes
* When the input itself is a perfect power, return this number
* Since 4 is the smallest perfect power, for inputs < 4 (including 0, 1, and negatives) return 4
* The input can be either a floating-point number or an integer
* If there are two perfect powers equidistant from the input, return the smaller one
## Examples
For instance,
```python
0 --> 4
11 --> 9 # 9 = 3^2
34 --> 32 # 32 = 2^5 and 36 = 6^2 --> same distance, pick the smaller
```
| algorithms | from math import ceil, floor, log2
def closest_power(n):
return (4 if n <= 4 else min(
(f(n * * (1 / i)) * * i
for i in range(2, ceil(log2(n)) + 1)
for f in (floor, ceil)),
key=lambda x: (abs(x - n), x)))
| Closest Perfect Power | 57c7930dfa9fc5f0e30009eb | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/57c7930dfa9fc5f0e30009eb | 6 kyu |
Binary trees can be encoded as strings of balanced parentheses (in fact, the two things are *isomorphic*).
Your task is to figure out such an encoding, and write the two functions which convert back and forth between the binary trees and strings of parentheses.
Here's the definition of binary trees:
```haskell
data Tree = Leaf | Tree :*: Tree deriving (Eq, Show)
```
```javascript
class Tree {}
class Leaf extends Tree {}
class Branch extends Tree { constructor(left,right) {} }
```
```ocaml
type tree =
| Leaf
| Node of tree * tree
```
```python
class Tree:pass
class Leaf(Tree): pass
class Branch(Tree):
left: Tree
right: Tree
```
```rust
#[derive(PartialEq, Eq, Debug)]
pub enum Tree {
Leaf,
Branch {left: Box<Tree>, right: Box<Tree>}
}
```
```if:python
All classes are frozen dataclasses: the left and right children cannot be modified once the instance has been created.
```
And here are the functions you need to define:
```haskell
treeToParens :: Tree -> String
parensToTree :: String -> Tree
```
```javascript
function treeToParens(Tree) => String
function parensToTree(String) => Tree
```
```ocaml
tree_to_parens : tree -> string
parens_to_tree : string -> tree
```
```python
treeToParens(Tree) -> str
parensToTree(str) -> Tree
```
```rust
fn tree_to_parens(tree: &Tree) -> String;
fn parens_to_tree(parens: &str) -> Tree;
```
The first function needs to accept any binary tree, and return only strings of valid balanced parentheses (like `"()(())"`).
The second needs to accept any string of balanced parentheses (including the empty string!), and return a binary tree.
Also, the functions need to be inverses of each other.
In other words, they need to satisfy the following equations:
```haskell
forall s. treeToParens (parensToTree s) = s
forall t. parensToTree (treeToParens t) = t
```
```javascript
treeToParens(parensToTree(parens)) === parens
parensToTree(treeToParens(tree)) === tree
```
```ocaml
tree_to_parens (parens_to_tree s) = s
parens_to_tree (tree_to_parens t) = t
```
```python
tree_to_parens(parens_to_tree(s)) == s
parens_to_tree(tree_to_parens(t)) == t
```
```rust
tree_to_parens(&parens_to_tree(s)) == s
parens_to_tree(&tree_to_parens(t)) == t
```
---
Note:
There is more than one possible answer to this puzzle! There are number of different ways to "encode" a binary tree as a string of parentheses. Any solution that follows the laws above will be accepted.
~~~if:javascript,
Your functions will run in sandboxes; only `Tree`, `Leaf`, `Branch` and `console` ( for `.log` ) will be in scope, and they will be frozen. If you need helper functions, define them _inside_ your functions. If you experience any problems with this setup, please leave a comment in the `Discourse`.
~~~
~~~if:python,
Your functions must not share any global state, to attempt to bypass the encoding logic. If they do, you will pass all tests except the `state check` batch at the end of the full test suite. So just don't use shared states...
If you experience any problems with this setup, please leave a comment in the `Discourse`.
~~~
| reference | from preloaded import Tree, Leaf, Branch
def tree_to_parens(tree: Tree) - > str:
def infix(tree):
node = tree
while getattr(node, 'right', None) is not None:
yield '('
yield from infix(node . left)
yield ')'
node = node . right
return '' . join(infix(tree))
def parens_to_tree(parens: str) - > Tree:
def chain():
node = Leaf()
while stack[- 1] is not None:
node = Branch(stack . pop(), node)
return node
stack = [None]
for par in parens:
if par == '(':
stack . append(None)
else:
stack[- 1] = chain()
return chain()
| Trees to Parentheses, and Back | 5fdb81b71e47c6000d26dc4b | [
"Trees",
"Fundamentals"
] | https://www.codewars.com/kata/5fdb81b71e47c6000d26dc4b | 5 kyu |
# The Situation
In my bathroom, there is a pile of `n` towels. A towel either has the color `red` or `blue`. We will represent the pile as sequence of `red` and `blue`.The leftmost towel is at the bottom of the pile, the rightmost towel is at the top of the pile.
As the week goes by, I use `t` towels. Whenever I grab a new one it's always the towel at the top of the pile.
All used towels are placed in a basket.
At the end of the week, I wash all used towels in the basket and put them on top of the existing pile again.
But my favorite color is `blue`, so I want to use `blue` towels as often as possible. Therefore, when the washed towels are placed on the pile again, the `blue` towels are always on top of the `red` towels.
# An Example
If there are `n=5` towels, a pile may be:`blue, red, blue, red, blue`
If I grab `t=3` towels during the week, this will be the remaining pile at the end of the week: `blue, red`
The basket will contain the following towels: `blue, red, blue`
After I sorted the washed towels and put them on the pile according to the rule described above, the resulting pile is:`blue, red, red, blue, blue`
# Your Task: Sort the Pile
You are given an initial pile of towels as a sequence of the strings `"red"` and `"blue"`.
On top of that, you receive a sequence of non-negative integers.
The first integer describes the number of used towels `t` in the first week, the second integer describes the number of used towels `t` in the second week and so forth.
My question is: How will my pile of towels look like in the end, if I use `t` towels every week and place them on top of the the pile according to the rule defined above?
# Notes
It is ensured that `0 <= t <= n`
| algorithms | def sort_the_pile(p, t):
for i in t:
if i > 0:
p = p[: - i] + sorted(p[- i:], reverse=True)
return p
| Pile of towels | 61044b64704a9e0036162a1f | [
"Sorting",
"Algorithms"
] | https://www.codewars.com/kata/61044b64704a9e0036162a1f | 6 kyu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.