description
stringlengths 38
154k
| category
stringclasses 5
values | solutions
stringlengths 13
289k
| name
stringlengths 3
179
| id
stringlengths 24
24
| tags
sequencelengths 0
13
| url
stringlengths 54
54
| rank_name
stringclasses 8
values |
---|---|---|---|---|---|---|---|
# Task
Given a point in a [Euclidean plane](//en.wikipedia.org/wiki/Euclidean_plane) (`x` and `y`), return the quadrant the point exists in: `1`, `2`, `3` or `4` (integer). `x` and `y` are non-zero integers, therefore the given point never lies on the axes.
# Examples
```
(1, 2) => 1
(3, 5) => 1
(-10, 100) => 2
(-1, -9) => 3
(19, -56) => 4
```
# Reference
<center>
<img style="background:white" src="https://upload.wikimedia.org/wikipedia/commons/thumb/1/1a/Cartesian_coordinates_2D.svg/300px-Cartesian_coordinates_2D.svg.png" title="Quadrants">
<i>Quadrants</i>
</center>
There are four quadrants:
1. First quadrant, the quadrant in the top-right, contains all points with positive X and Y
2. Second quadrant, the quadrant in the top-left, contains all points with negative X, but positive Y
3. Third quadrant, the quadrant in the bottom-left, contains all points with negative X and Y
4. Fourth quadrant, the quadrant in the bottom-right, contains all points with positive X, but negative Y
More on quadrants: [Quadrant (plane geometry) - Wikipedia](https://en.wikipedia.org/wiki/Quadrant_(plane_geometry))
# Task Series
1. Quadrants _(this kata)_
2. [Quadrants 2: Segments](https://www.codewars.com/kata/643ea1adef815316e5389d17) | reference | def quadrant(x, y): return ((1, 2), (4, 3))[y < 0][x < 0]
| Quadrants | 643af0fa9fa6c406b47c5399 | [
"Fundamentals",
"Mathematics",
"Geometry"
] | https://www.codewars.com/kata/643af0fa9fa6c406b47c5399 | 8 kyu |
### Background:
[Wikidata](https://www.wikidata.org/wiki/Wikidata:Main_Page) is a public database with over a hundred million entries in it. You can find almost anything documented, from scientific articles to new species scientists have found.
To help developers use the site better, the website provides accessible JSON data for every submitted item. Today, you are going to program something that can read that data.
The link below leads to the page explaining how to access the corresponding JSON address of a specific Wikidata item. Although the direct URL to the data will be provided ([example)](https://www.wikidata.org/wiki/Special:EntityData/Q42.json), you might find it helpful to see the stuff your collecting from.
https://www.wikidata.org/wiki/Wikidata:Data_access
Now let's move on to the actual scraping.
### What to do:
Take a look at this labeled section of a Wikidata page:

All of this information can be found on the given JSON pages (link in the previous section). Your function should return a dictionary with the English (`en`) values of the **Identifier**, **Label**, and **Description**. The dictionary should have the keys `"ID"`, `"LABEL"`, and `"DESCRIPTION"`, respectively.
Given the URL to our example, you should return:
```json
{
"ID": "Q42",
"LABEL": "Douglas Adams",
"DESCRIPTION": "English science fiction writer and humourist"
}
```
Be careful. Some information won't always be available in English, and some might not have a value associated with any language. That's because Wikidata only requires you to give one label or description. If the en label or description aren't included, put "No Label" or "No Description". <u>Please be careful you are getting values from the "en" value, and not localized english versions such as "en-uk" or en-ca</u>.
If you were given the URL to [this unhelpful entry](https://www.wikidata.org/wiki/Special:EntityData/Q97226458.json), you would return the following:
```json
{
"ID": "Q97226458",
"LABEL": "No Label",
"DESCRIPTION": "No Description"
}
```
That should be it for instructions. If you have any more questions, check out the section below, or ask them in the Discourse (after you read the section below please.)
Good Luck!
### Formal Input/Output Requirements
You are given a single argument named `url`, a string with a link to a wikidata page in JSON format.
Your function should return a dictonary with keys "ID", "LABEL", and "DESCRIPTION" containing the matching "en" values.
### Technical Notes
- All inputs are valid (they will all link to a scrapable JSON page)
- Since performance might be an issue, there will be 5-10 random tests (depending on language) instead of the usual 100. I don't want performance to be the focus of this kata, but if you think I should raise the number, raise a suggestion.
- This is supposed to train research skills, so not all of the information should be here. If you think there's a link I should provide, or a piece of information is missing that makes it unsolvable, head on over to the discourse.
| algorithms | import requests
def wikidata_scraper(url):
res = requests . get(url). json()
entry = list(res['entities']. values())[0]
return {
"ID": entry['id'],
"LABEL": entry['labels']. get('en', {'value': 'No Label'})['value'],
"DESCRIPTION": entry['descriptions']. get('en', {'value': 'No Description'})['value'],
}
| Wikidata Json Scraper | 643869cb0e7a563b722d50ad | [
"Algorithms",
"Web Scraping",
"Searching",
"JSON",
"Filtering"
] | https://www.codewars.com/kata/643869cb0e7a563b722d50ad | 6 kyu |
# Binary with unknown bits:
You received a string of a __binary number__, but there are some `x` in it. It cannot be used, so the solution is to get the average of all possible numbers.
___
# Rule:
* The string consists of `0`, `1` and `x`, if it has 2 or more bits, it would have at least one `x`.
* Unless the number is a single zero(`0`), otherwise no leading zeros would occur, you don't need to worry about invalid input.
* `x` can be 0 or 1, but it has to follow the 2nd rule above.
* You need to return the `average number` of all possible numbers following the above rule. As it may be a float, the difference should be less than `0.01`.
___
# Performance:
The length of input `binary` string would be less or equal to _50_.
It may consist up to _30_ `x`, so the approach of listing out all possible numbers would time out.
___
# Examples:
Here are some examples:
```
binary = 'x'
possible: '0', '1' => 0, 1
average = 0.5
binary = 'x0'
possible: '10' => 2 ('00' violated the rule)
average = 2
binary = '1x0x'
possible: '1000', '1001', '1100', '1101' => 8, 9, 12, 13
average = 10.5
other sample tests:
'0' => 0
'1' => 1
'1x' => 2.5
'xx' => 2.5
'1x0' => 5
'1xxx1xxx0xxx0xxx1xxx1xxx0xxx0xxx1xxx0' => 105084647303
``` | algorithms | def binary_average(binary):
if len(binary) > 1 and binary[0] == 'x':
binary = '1' + binary[1:]
a = int(binary . replace('x', '1'), 2)
b = int(binary . replace('x', '0'), 2)
return (a + b) / 2
| Binary with unknown bits: the average | 64348795d4d3ea00196f5e76 | [
"Mathematics",
"Binary",
"Performance"
] | https://www.codewars.com/kata/64348795d4d3ea00196f5e76 | 6 kyu |
You know you can convert a floating-point value to an integer, and you can round up, down, etc? How about going the other way around, converting an integer to floating-point, rounding up/down?
# Task description
Define two functions, each one taking an integer `n` and returning a double-precision (officially, 'binary64') floating point number `f`:
- `ifloor(n)`: largest `f` such that `$\mathtt{f} \le \mathtt{n}$`
- `iceil(n)`: smallest `f` such that `$\mathtt{f} \ge \mathtt{n}$`
The return value `f` can't be not-a-number (NaN), but it can be positive or negative infinity. When comparing values or determining 'largest' or 'smallest', the floating-point and integer values are ordered in terms of their values in `$[-\infty, +\infty]$`, i.e. as finite real numbers or infinity. The rules for special values are:
- `$+\infty$` is equal to itself and larger than everything else
- `$-\infty$` is equal to itself and smaller than everything else
- Floating-point `+0` and `-0` are considered equal (and equally acceptable as the result `f`)
In particular, don't round before comparing!
# Note: Hex floats (or: what is `0x1.fff...p+59`)
To aid in debugging the exact values, floating point values are also printed in hexadecimal in this format: `{dec} = {hex}`. The hex float has this syntax:
```
[sign]0x{mantissa}p[sign]{exponent}
```
The part before the `p` is the sign and mantissa written in hexadecimal, with (hexadecimal) fractional digits. The part after is the exponent written in *decimal* and is the power of two to multiply.
For example, `-0x1.ffp-3` means:
```
- 0x1 .f f p-3
-1 * (1 + 15/16 + 15/256) * (2 ** -3)
= -0.24951171875 (exactly)
```
Since the floating point type we're using is represented in binary, this notation exactly and faithfully represents a floating point number. Hope you find it helpful when debugging.
See this for a more detailed explanation on the syntax: <https://docs.python.org/3/library/stdtypes.html#float.fromhex>. You can also play around with the values at <https://float.exposed/>.
# Language-specific notes
- For Python 3:
- `n` is `int` and `f` is `float`
- Use [`float.fromhex`][float-fromhex] to read hex floats
- For Haskell:
- `n` is `Integer` and `f` is `Double`
- Hex float literals are supported in the language
- For Rust:
- `n` is [`num::BigInt`][num-bigint] and `f` is `f64`
- Hex float literals are unsupported, but you can just use the decimal value — it's exactly the same
[float-fromhex]: https://docs.python.org/3/library/stdtypes.html#float.fromhex
[num-bigint]: https://docs.rs/num/latest/num/struct.BigInt.html
# Exact floating-point numbers, a primer
What the hell is going on, I thought floating-point numbers were approximate?
Despite what some simplified explanations may tell you, floating-point numbers are exact; they're just rounded in calculations.
This isn't some sort of wordplay or philosophical distinction. Each floating-point has an exact value. It's a bit like how integer division rounds the results to an integer, but it doesn't affect the fact that the integers themselves are exact.
On `$[-\infty, +\infty]$`, the number line including infinities, there are a large but finite number of points representable with the double. Integers with small absolute values are representable, but for ones with larger absolute value, there's no double value that's exactly this number, because it only has 53 bits of precision. So all but the highest 53 bits of its absolute value must be zero.
For example for `$2^{60} + 1$`, it falls between these two integers that representable with a double: (`**` means power)
```
<= 53 bits ===>
2**60 = binary 1 0000 ... 0000 0000 0000
2**60 + 2**8 = binary 1 0000 ... 0001 0000 0000
```
Ordinarily when converting an integer to floating-point, the nearer one would be picked, in this case `2**60`. For this kata, `ifloor` should return the lower `2**60`, and `iceil` should return the higher `2**60 + 2**8`.
The sign of a floating-point number is represented separately from its absolute values and does not use two's-complement. That's how you get separate `+0` and `-0`.
That's the most important things you need to know for this kata. You can find more details on more topics with your favorite web search engine. Some possibly interesting ones include: Not-a-Number, nearest ties-to-even rounding, denormal numbers.
There are some functions that can help you deal with floating-point representations without delving into bitwise details. Read the docs carefully β these functions don't work the same across languages!
- For Python 3: [`math.frexp`][math-frexp]
- For Haskell: [`decodeFloat`][decodeFloat] and [`encodeFloat`][encodeFloat]
- For Rust: [`num::Float::integer_decode`][num-integer_decode]
[math-frexp]: https://docs.python.org/3/library/math.html#math.frexp
[decodeFloat]: https://hackage.haskell.org/package/base-4.18.0.0/docs/Prelude.html#v:decodeFloat
[encodeFloat]: https://hackage.haskell.org/package/base-4.18.0.0/docs/Prelude.html#v:encodeFloat
[num-integer_decode]: https://docs.rs/num/latest/num/trait.Float.html#tymethod.integer_decode
| reference | from gmpy2 import RoundDown, RoundUp, context
from sys import float_info
def ifloor(n: int) - > float:
return float(context(round=RoundDown, emax=float_info . max_exp). rint(n))
def iceil(n: int) - > float:
return float(context(round=RoundUp, emax=float_info . max_exp). rint(n))
| Convert integer to float while rounding up and down | 642eba25b8c5c20031058225 | [
"Language Features",
"Big Integers"
] | https://www.codewars.com/kata/642eba25b8c5c20031058225 | 6 kyu |
For a long time little Annika had wanted to contribute to the ARM64 port of the Factor language. One day she finally could grasp where to start and fell into a rabbit hole learning ARM assembly and started finishing the non-optimizing compiler.
In the process of debugging an unrelated segfault, she realized that the 13-bit bitfields of <abbr title="AND, ANDS, EOR and ORR perform bit-wise and, or and xor to clear, set or flip bits. There's also a variant of MOV that puts a bitmask into a register.">logical instructions</abbr> operating on 64-bit values are not the lower 13 bits of the <abbr title="operand that is not stored in a register or in memory but in the instruction itself">immediate</abbr> but encode 64-bit bitmasks.
The 13 bits consist of three contiguous bitfields `N` (1 bit wide), `immr` and `imms` (6 bits wide each), which is commonly expressed as `N:immr:imms`. `N:imms` encodes the size and composition of a pattern of bits that is repeated to fill the 64-bit immediate. The size of the pattern is a power of 2, the exponent can range from 1 to 6 (therefore the pattern can be 2, 4, 8, 16, 32 or 64 bits long). The pattern is restricted to a sequence of zeroes followed by a sequence of ones, the whole pattern is then rotated by `immr` bits to the right.
`N:imms` consists of three parts: `6-n` ones to indicate the pattern length, a zero and the rest is the length of the sequence of ones minus 1. The `N` bit is stored inverted. It is not possible to encode patterns of only zeroes or ones.
Annika realizes that support for the encoding is not present in the Factor ARM assembler. βOh, not again,β she groans as she does not want to have to extend it any further. Please help her implement support for logical immediates. Write a word/function/β¦ that takes a 64-bit immediate and returns an integer representing `N:immr:imms`. Return `f`/`None`/β¦ if the immediate cannot be encoded this way.
# Examples
* 32 zeroes, 32 ones: `0000 0000 0000 0000 0000 0000 0000 0000 1111 1111 1111 1111 1111 1111 1111 1111`. The pattern size is 64 bits, there are 32 ones, the pattern is not rotated. `N:imms` is constructed of 0 ones, followed by a 0, followed by the binary representation of the number 31 (32 ones minus 1): `0 011111`. The left-most bit gets inverted: `N:imms` = `1 011111`. There are zero rotations to the pattern, so `immr` is the binary representation of 0: `immr` = `000000`. Putting everything together `N:immr:imms` is `1 000000 011111`, which is `4127` in decimal.
* `1000 0001 1000 0001 1000 0001 1000 0001 1000 0001 1000 0001 1000 0001 1000 0001`, pattern size 8 bits (3 ones), 2 ones (encoded as 1), rotated by 1 bit: `N:imms` = `011 0 001`, `immr` = `000001`, `N:immr:imms` = `0 000001 110001` = `113` | algorithms | def logical_immediate(imm64):
b = f' { imm64 :0 64 b } '
for i in range(1, 7):
l = 2 * * i
for w in range(1, l):
for immr in range(l):
z = '0' * (l - w) + '1' * w
y = (z[- immr:] + z[: - immr]) * (64 / / l)
if y == b:
r = f' { 2 * * ( 7 - i ) - 2 : 0 b }{ w - 1 : 0 { i } b } '
i, imms = '01' ['10' . index(r[0])], r[1:]
return int(f' { i }{ immr :0 6 b }{ imms } ', 2)
| Logical immediates | 6426b201e00c7166d61f2028 | [
"Binary",
"Algorithms"
] | https://www.codewars.com/kata/6426b201e00c7166d61f2028 | 5 kyu |
# Task:
In this Golfing Kata, you are going to receive 2 non-negative numbers `a` and `b`, `b` is equal to or greater than `a`.
Then do the following procedure:
* Add `a` to `b`, then divide it by `2` with __integer division__.
* Repeat the procedure until `b` is equal to `a`.
* Return how many times it took to make `b` equal to `a`.
* Now golf your code, the length limit is `35`, in one line.
(The length of reference solution is `31`)
___
# Examples:
```
a = 3 and b = 9
b = (3 + 9) // 2 = 6 --- 1 time
b = (3 + 6) // 2 = 4 --- 2 times
b = (3 + 4) // 2 = 3 --- 3 times
So the result for a=3 and b=9 is `3`.
```
__More examples:__
```
input --> output
f(0, 0) --> 0
f(1, 2) --> 1
f(3, 9) --> 3
f(4, 20) --> 5
f(5, 36) --> 5
``` | games | def f(a, b): return (b - a). bit_length()
| [Code Golf] How many times of getting closer until it is the same? | 642b375dca15841d3aaf1ede | [
"Mathematics",
"Restricted"
] | https://www.codewars.com/kata/642b375dca15841d3aaf1ede | 7 kyu |
This is a challenge version of [Sudoku board validator](https://www.codewars.com/kata/sudoku-board-validator); if you haven't already, you should do that first.
The rules stay mostly the same: Your task is to write a function that takes a 9x9 sudoku board as input and returns a boolean indicating if the board is valid or not. For a sudoku board to be considered valid, every row, column, and 3x3 block must contain the numbers 1 to 9 exactly once.
However, there is now an additonal requirement:
~~~if:python,
your solution length must be under `150` characters.
~~~
~~~if:haskell,
your solution length must be under `100` characters.
( `module` and `import` lines do _not_ count against the limit )
~~~ | games | def validate_sudoku(b, R=range): return all({* r} == {* R(1, 10)} for r in [* zip(* b)] + b + [[b[i / / 3 * 3 + j / / 3][i % 3 * 3 + j % 3] for j in R(9)] for i in R(9)])
| Sudoku board validator - Code Golf | 63e5119516648934be4c98bd | [
"Algorithms",
"Games",
"Restricted"
] | https://www.codewars.com/kata/63e5119516648934be4c98bd | 5 kyu |
You've found yourself a magic box, which seems to break the laws of physics.
You notice that if you put some money in it, it seems to spit out more money than was put in. Free money right?
In time you notice the following facts:
- If you start with N dollars, using the box twice yields exactly 3*N dollars
- You never seem to get any fractional dollar amounts
- The box consistently gives the same amount out, if the amount put in is the same
- The more money you put in, the more money you get out
Note: "using the box twice" means using it once, and then using it again with all of the money the box gave you.
The four above mentioned facts can be succinctly stated as follows:
`f` is a function mapping between non-negative integers such that `f(f(n)) = 3*n` and `f(n+1) > f(n)` for all `n`
Your task is to define the function f, such that it predicts the number of dollars produced by the box when n dollars are put in it.(i.e. `f(n)` gives how many dollars the box gives when used on `n` *once*, not *twice*.
A Note of tests:
- Input 0 <= N < 10000000
- The actual output for any given input is NOT validated directly. As long as your function satisfies the above specifications, you should pass the tests
Credits:
The source from where this kata was heavily inspired from is mentioned in [this comment](https://www.codewars.com/kata/64294e2be00c71422d1f59c2/discuss/scala#6429b5d92dcd5c00589aac51) which will be hidden till you solve this Kata. Please do remember to check out the source once you have solve the Kata!
| games | from math import log
# 6kyu????????????????
def f(n):
if not n:
return 0
k = 3 * * int(log(n) / log(3))
z = 2 * max(0, n - 2 * k)
return n + z + k
| Triple your Money! | 64294e2be00c71422d1f59c2 | [
"Mathematics",
"Number Theory",
"Performance"
] | https://www.codewars.com/kata/64294e2be00c71422d1f59c2 | 6 kyu |
Same task as [Total area covered by rectangles][kata-easier] but now there are more rectangles.
[kata-easier]: https://www.codewars.com/kata/55dcdd2c5a73bdddcb000044
# Task
Write a function `calculate` that, given a list of rectangles, finds the area of their union.
Each rectangle is represented by four integers <code>[x<sub>0</sub>, y<sub>0</sub>, x<sub>1</sub>, y<sub>1</sub>]</code>, where <code>(x<sub>0</sub>, y<sub>0</sub>)</code> is the lower-left corner and <code>(x<sub>1</sub>, y<sub>1</sub>)</code> is the upper-right corner. The origin `(0, 0)` is bottom left. For the representation used for your language, see the example tests.
See linked kata for a more detailed example.
# Constraints
- Performance requirement: Number of rectangles <code>n ≥ 0</code>:
- For JavaScript: `10` tests with <code>n ≤ 5000</code>, and `10` tests with <code>n ≤ 20,000</code>
- For Python: `10` tests with <code>n ≤ 1500</code>, and `7` tests with <code>n ≤ 8000</code>
- Coordinates: <code>0 ≤ x<sub>i</sub>, y<sub>i</sub> ≤ 1,000,000</code>
| algorithms | from math import log2, ceil
def calculate(rectangles):
if not rectangles:
return 0
events = []
ys = set()
for x0, y0, x1, y1 in rectangles:
events . append((x0, y0, y1, 1))
events . append((x1, y0, y1, - 1))
ys . add(y0)
ys . add(y1)
events . sort()
ys = sorted(ys)
indices = {y: i for i, y in enumerate(ys)}
length = 2 * * ceil(log2(len(ys)))
counts = [0] * (2 * length)
covers = [0] * (2 * length)
def update(i, tl, tr, l, r, t):
if r <= tl or tr <= l:
return
c = counts[i]
if l <= tl and tr <= r:
c += t
counts[i] = c
covers[i] = ys[tr] - ys[tl]
else:
tm = (tl + tr) / / 2
update(2 * i, tl, tm, l, r, t)
update(2 * i + 1, tm, tr, l, r, t)
if c == 0:
covers[i] = i < length and covers[2 * i] + covers[2 * i + 1]
prev_x = 0
result = 0
for x, y0, y1, t in events:
result += covers[1] * (x - prev_x)
update(1, 0, length, indices[y0], indices[y1], t)
prev_x = x
return result
| Total area covered by more rectangles | 6425a1463b7dd0001c95fad4 | [
"Algorithms",
"Data Structures",
"Geometry",
"Performance"
] | https://www.codewars.com/kata/6425a1463b7dd0001c95fad4 | 2 kyu |
## Task
Your task is to write a function that accept a single parameter - a whole number `N` and generates an array with following properties.
1. There are exactly 2 * N + 1 elements in this array
2. There is only one 0 (zero) in array
3. Other elements are pairs of natural numbers from 1 to N
4. Number of elements between a pair of numbers is equal to the number itself
For example, the number of elements between pair of 2s should be exactly 2, for 3s - three and so on.
## Examples of arrays
```python
[1, 0, 1] # Exactly one element between 1s
[1, 2, 1, 0 2] # Exactly one element between 1s and exactly two elements between 2s
```
## Example usage
```python
generate(4)
[1, 3, 1, 4, 2, 3, 0, 2, 4]
```
Notice that there may be multiple solutions for each number. For example, for number 3 both arrays are valid:
```python
[2, 3, 1, 2, 1, 3, 0]
[1, 3, 1, 2, 0, 3, 2]
```
Notice that a reverse of a correct solution is a correct solution as well.
## Tests
The solution will be tested for N < 1024 | algorithms | def generate(n):
return [0] if n <= 0 else [
* reversed(range(2, n, 2)),
n, 0,
* range(2, n, 2),
* reversed(range(1, n, 2)),
n,
* range(1, n, 2),
]
| Array with distance of N | 6421c6b71e5beb000fc58a3e | [
"Algorithms",
"Arrays",
"Performance"
] | https://www.codewars.com/kata/6421c6b71e5beb000fc58a3e | 5 kyu |
You are in the process of creating a new framework. In order to enhance flexibility, when your user assigns value to an instance attribute, you want to give them the option to supply a callable without arguments instead. When the attribute is accessed, either the assigned value (as usual), or the result of the call (if defined as a callable) should be returned.
Create a class called `Setting` that supports the 'Optionally callable attribute' pattern.
## Details
- Only public and private __instance__ attributes should follow the 'Optionally callable attribute' pattern.
- Subclassing `Setting` should work normally, and subclasses will also have to support the "Optionally callable attribute" pattern.
- Private properties, class level properties or any kind of methods defined on the class or subclass body won't support the 'Optionally callable attribute' pattern, and these won't be modified at runtime. Note that methods should work normally.
- It must be possible to assign 'optionally callable attributes' on different instances of the same class with different values/callables.
- 'Optionally callable attributes' can be reassigned at any time, callable attributes may be reassigned with non-callable values and vice versa.
- The callables may use variables of the scope in which they were defined. They will never make use of the `self` argument, since they are called with no arguments.
## Example
In the code below, we have an instance attribute `_pressure` storing the current pressure in Pa, and two class attributes `unit` and `unit_multiplier` shared by all instances. The `pressure` is defined as a callable that automatically returns `_pressure` converted into the correct `unit` on each access:
``` python
class Setting:
# Your code here
pass
setting = Setting()
setting._pressure = 101_325
Setting.unit = 'Pa'
Setting.unit_multiplier = {'Pa': 1, 'kPa': 10**3, 'bar': 10**5, 'MPa': 10**6}
setting.pressure = lambda: setting._pressure / Setting.unit_multiplier[Setting.unit]
Setting.unit = 'Pa'
setting.pressure # -> 101325.0
Setting.unit = 'kPa'
setting.pressure # -> 101.325
Setting.unit = 'bar'
setting.pressure # -> 1.01325
Setting.unit = 'MPa'
setting.pressure # -> 0.101325
```
Note that in the example above, the `lambda` function is accessing `setting` as a variable of the scope at the time of declaration, and not as the actual instance of itself. This is less than ideal, and while it would be possible to make use of the `self` argument, this is not part of the objectives of your tiny framework. | reference | from inspect import ismethod
class Setting:
def __getattribute__(self, name):
attr = super(). __getattribute__(name)
return attr() if callable(attr) and not ismethod(attr) else attr
| Optionally callable attributes | 641c4d0e88ce6d0065531b88 | [
"Object-oriented Programming",
"Language Features"
] | https://www.codewars.com/kata/641c4d0e88ce6d0065531b88 | 6 kyu |
<h1> Situation </h1>
After giving out the final Calculus II exam, you come to a frightening realization. Only 4 of your 100 students passed.
How could this be?!? Maybe you're not a such great teacher? No, that can't be; your iΜΆnΜΆfΜΆeΜΆrΜΆiΜΆoΜΆrΜΆsΜΆ students are definitely the problem here. How **dare** they not know how to solve a problem as simple and trivial as **β« βπ‘ππ(π) π
π** in under 5 minutes!
Anyway, regardless of why your students failed so badly, this result is unacceptable, and if you show it to your supervisor, you will almost certainly be fired.
To counteract this, you devise a completely original and amazing idea that has certainly never been done before */s*. You will give your students a curve on their grade.
It's very simple: for every sΜΆhΜΆiΜΆtΜΆtΜΆyΜΆ unsatisfactory grade your students get, you will give them a better grade in order to increase the number of people who pass.
<br>
<h1> Task </h1>
Write a function ```curve``` that take an integer from ```0``` to ```100``` (inclusive), the student's grade and returns a value greater or equal to the input, the "curved grade".
Sounds vague? That's because *it is*.
There are **no specific right values to be returned**, only a **set of rules** the output must follow, according to the input.
<br>
<h1> Rules </h1>
- If you're given ```0``` or ```100``` return the given value. <br>
You can't have a student get over the maximum score or have a student who did nothing get points; that would be **too suspicious**.
- All outputs should be **integers**. <br>
Imagine getting a test score of ```2.718```; how outrageous!
- All outputs should be **between** ```0``` and ```100```, inclusive. <br>
Consider receiving a ```-31.4``` or even a ```628``` on a test; simply unacceptable!
- All outputs should be **greater than or equal** to their respective inputs. <br>
The curve should help the students, not make their lives harder.
- The **average** of all inputs across the whole domain should be greater or equal to 60. <br>
No one likes a mediocre curve, so the curve should be useful.
- The output should be **non-decreasing** as a function of the inputs. In other words, a higher initial grade should return a value that is **equal to or greater** than a lower one. <br>
A student who got a ```10``` can't do better than the guy who aced the test.
- The output should be **mostly injective** as a function of the inputs. Don't worry if you're unaware of this term; I just made it up. It means that your function should return a **different value** for each interval of ```10``` which means that the inputs ```(0, 10, 20,..., 100)```, as well as any other possible sequence of inputs with that interval, such as ```(5, 15, 25,..., 95)```, must be **increasing**. <br>
Constant functions are simply *too boring*!
<br>
<h1> Code Length </h1>
The length of your code must **not surpass** ```32``` characters.
I don't have a good excuse that fits the story for this one. It would just be too easy to hardcode otherwise.
<br>
<h1> Example </h1>
Here's an example of a solution written in mathematical notation that **follows all rules**, failling only the **length test**.
π : [0, 100] β [0, 100] | π(π) = β(-π^2 + 200π) / 100β <br>
ββ represents the ceilling function.
- Rule 1:
π(0) = 0, π(100) = 100
- Rule 2:
π(π) β β€ β π β [0, 100] <br>
- Rule 3:
π(π) β [0, 100] β π β [0, 100] <br>
- Rule 4:
π(π) >= π β π β [0, 100]
- Rule 5:
(β π(π), π = 0 π‘π 100) / 101 = 67.57 >= 60
- Rule 6:
π(0) <= π(1) <= π(2) <= ... <= π(99) <= π(100)
- Rule 7:<br>
π(0) < π(10) < π(20) < ... < π(90) < π(100)<br>
π(1) < π(11) < π(21) < ... < π(81) < π(91)
<br> ...
<br>π(9) < π(19) < π(29) < ... < π(89) < π(99) | algorithms | def curve(g): return g * * .5 / / .0999
| [Code Golf] Save Your Students | 641d08d7a544092654a8b29c | [
"Mathematics",
"Restricted",
"Statistics"
] | https://www.codewars.com/kata/641d08d7a544092654a8b29c | 7 kyu |
# Async Request Manager | Don't let server down!
**Note**: this kata is slightly extended version of this kata:
https://www.codewars.com/kata/62c702489012c30017ded374
Feel free to check it out first if you wish or if you
have problems with solving this little bit harder one.
Original requirements:
---
Your task is it to implement a coroutine which
sends `n` requests and concats the returned
strings of each response to one string.
A request can be made by invoking the prebuild
coro `send_request`. When invoked, the coro
sleeps for 1 sec and then returns a single
character.
Your overall task is to implement an async
`request_manager` which completes all `n` requests
in under **2.1** sec
Aditional requirement:
---
Async gives you great power. But it turns out that
with great power comes great responsibility.
Resource you're requesting for is a pretty weak
little... smart toaster? Anyway, **DON'T LET SERVER DOWN!**
under the almighty onslaught of hundreds of simultaneous requests.
**TIP:** The "server" can handle up to ``150``
requests at the same time (concurrently).
**Note:** The kata has a really thin gap between "too fast"
and "too slow". But with the right setup, you're guaranteed
to hit the right time without letting the "server" down.
---
## Summary:
- Implement a coro `request_manager` which sends and processes fake requests
- It accepts the parameter `n` which represents the amount of requests that should be made
- Requests have to be made with `send_request`
- `send_request` is a preloaded coroutine : `(coro) send_request() -> str`
- It takes 1 sec until a character is returned to the caller
- The waiting time is implemented via `asyncio.sleep`
- Characters returned by `send_request` have to be concat to one string
- That string is then returned by your `request_manager`
- The characters in the string need to be ordered, so that the character returned
by the first request is at index 0, the character returned by the second request
is at index 1 etc.
- Your `request_manager` has 2.1 sec to start & process all `n` requests and to
return the desired string
- `150` simultaneous requests is the threshold. If in the process of handling
them the "server" receives one hundred and fifty-first request in the queue -
the game is over.
---
Solve the kata, and use your asynchronous power wisely, my friend.
P.S. (Not a bug, but a feature): if the toaster receives too many
requests, it will actually overheat and thus fail not only the
test in which it received an overheat, but also all subsequent
ones automaticaly. Be gentle with him, in short ;) | reference | import asyncio
async def send_request_politely(s: asyncio . Semaphore) - > str:
async with s:
return await send_request()
async def request_manager(n: int) - > str:
s = asyncio . Semaphore(150)
return "" . join(await asyncio . gather(* (send_request_politely(s) for _ in range(n))))
| Async Requests | Don't let server down! | 6417797d022e4c003ebbd575 | [
"Asynchronous"
] | https://www.codewars.com/kata/6417797d022e4c003ebbd575 | 6 kyu |
Write a function that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return `true` if the string is valid, and `false` if it's invalid.
## Examples
```
"()" => true
")(()))" => false
"(" => false
"(())((()())())" => true
```
## Constraints
`0 <= length of input <= 100`
- All inputs will be strings, consisting only of characters `(` and `)`.
- Empty strings are considered balanced (and therefore valid), and will be tested.
- For languages with mutable strings, the inputs should not be mutated.
<br>
***Protip:** If you are trying to figure out why a string of parentheses is invalid, paste the parentheses into the code editor, and let the code highlighting show you!* | algorithms | def valid_parentheses(x):
while "()" in x:
x = x . replace("()", "")
return x == ""
| Valid Parentheses | 6411b91a5e71b915d237332d | [
"Strings",
"Parsing",
"Algorithms"
] | https://www.codewars.com/kata/6411b91a5e71b915d237332d | 7 kyu |
Task
----
Write a function that reflects a point over a given line and returns the reflected point as a tuple.
Arguments:
- point: a tuple of the form `$(x, y)$` representing the coordinates of the point to be reflected.
- line: a tuple of the form `$(m, b)$` representing the slope-intercept equation of the line `$y = mx + b$`.
Returns:
- A tuple of the form `$(x^\prime, y^\prime)$` representing the coordinates of the reflected point.
- `$x^\prime$` and `$y^\prime$` should be accurate within a margin of `$0.00001$`.

Examples
--------
```python
reflect((2, 3), (1, 0)) == (3, 2)
reflect((1, 2), (3, 4)) == (-2, 3)
reflect((-2, -3), (-1, 0)) == (3, 2)
```
Tests
-----
- Fixed and Randomized Tests.
- For randomized tests `$x$`, `$y$`, `$m$`, `$b$` are sampled in batches from `$\pm 10^8$`.
- 100 assertions per batch (800 in total). | games | def reflect(point, line):
x, y = point
a, c = line
return x - 2 * a * (a * x - y + c) / (a * * 2 + 1), y + 2 * (a * x - y + c) / (a * * 2 + 1)
| Reflect Point Over Line | 64127b25114de109258fb6fe | [
"Mathematics",
"Geometry"
] | https://www.codewars.com/kata/64127b25114de109258fb6fe | 7 kyu |
You have a square shape of 4x4, you need to find out by what criterion there are cute and not cute patterns in these cases:
[](https://www.linkpicture.com/view.php?img=LPic640875a1a4c02163944404)
According to the given arrangement of tiles, it is required to determine whether the executed pattern is cute. You need to write a function.
**Input data**:
_A string value is entered into the function by type_ "BWBW\nBBWB\nWWBB\nBWWW".
B - black tile
W - white tile
\n - included just for line wrapping
**Output data**:
_Return True if the pattern is cute and False otherwise._
Examples:
```python
cute_pattern("BWBW\nBBWB\nWWBB\nBWWW") # should return True
cute_pattern("BBWB\nBBWB\nWWBW\nBBWB") # should return False
```
If you want to solve our problems, they are here:
[From Singularity Hub Community](https://www.codewars.com/collections/from-singularity-hub-community)
*I will gladly accept help for other languages in telegram* @fimermaker | games | import re
def cute_pattern(tiles):
return not re . search(r"BB...BB|WW...WW", tiles, re . DOTALL)
| [Mystery #1] - Cute Pattern | 64087fd72daf09000f60dc26 | [
"Puzzles"
] | https://www.codewars.com/kata/64087fd72daf09000f60dc26 | 7 kyu |
## Pythagorean Triples
A Pythagorean triple consists of three positive integers _a, b, c_, which satisfy the Pythagorean formula for the sides of a right-angle triangle: _aΒ² + bΒ² = cΒ²_. For simplicity we assume _a < b < c_.
A easy way of generating Pythagorean triples is to rewrite the equation as _aΒ² = cΒ² - bΒ² = (c-b)(c+b)_.
So if we know the difference _c-b_ between the other two sides of the triangle, then, given any positive integer _a_, we just have to find _b_ and _c_ such that _c+b = aΒ²/(c-b)_.
## Task
Create a function that takes positive integers _diff, low, high_, and returns a list of all Pythagorean triples whose smallest side _a_ lies between _low_ and _high_ inclusive (assume _low <= high_) and whose other sides satisfy _c-b = diff_. The list should be in ascending order by _a_.
## Examples
```
(1, 2, 10) -> [(3,4,5), (5,12,13), (7,24,25), (9,40,41)]
(3, 10, 25) -> [(15,36,39), (21,72,75)]
(4, 100, 100) -> [(100,1248,1252)]
(10, 91, 99) -> []
```
The random tests have diff <= 9,999 and low <= high <= 9,999,999.
Other kata involving Pythagorean triples are [Pythagorean triples](https://www.codewars.com/kata/59c32c609f0cbce0ea000073)
and [Primitive Pythagorean triples](https://www.codewars.com/kata/5622c008f0d21eb5ca000032) .
| reference | def create_pythagorean_triples(diff, low, high):
return [(a, a * a / / diff - diff >> 1, a * a / / diff + diff >> 1) for a in range(low, high + 1)
if not a * a % diff and a * a / / diff % 2 == diff % 2 and 2 * a + diff < a * a / / diff]
| A Fun Way of Finding Pythagorean Triples | 640aa37b431f2da51c7f27ae | [
"Geometry",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/640aa37b431f2da51c7f27ae | 6 kyu |
<strong>Task</strong>
Find the volume of the largest cube that will fit inside a cylinder of given height <code>h</code> and radius <code>r</code>.
Don't round your result. The result needs to be within <code>0.01</code> error margin of the expected result.
HINT: There are two cases to consider. Will it be the cylinder's height or the cylinder's radius that determines the maximum size of your cube? An if/else statement might be useful here.
<strong>Examples</strong>
`````
cubeVolume(3,7); //27
cubeVolume(11,5); //353.55
````` | games | def cube_volume(h, r):
return min(h, r * 2 * * .5) * * 3
| Volume of the Largest Cube that Fits Inside a Given Cylinder | 581e09652228a337c20001ac | [
"Geometry",
"Mathematics"
] | https://www.codewars.com/kata/581e09652228a337c20001ac | 7 kyu |
**Description**:
To get to the health camp, the organizers decided to order buses. It is known that some children `kids` and adults `adults` are going to go to the camp. Each bus has a certain number of seats `places`. There must be at least two adults on each bus in which children will travel.
Determine whether it will be possible to send all children and adults to the camp, and if so, what is the minimum number of buses required to order for this.
**Input data**:
_arguments `kids`, `adults`, `places` each of them does not exceed 10,000._
**Output data**:
_We need to return the number of buses that need to be ordered. If it is impossible to send everyone to the camp, return 0_
kids=10, adults=4, places=7 --> 2 (2 buses, both seating 2 adults & 5 kids)
kids=10, adults=4, places=5 --> 0 (impossible to send everyone to the camp)
Happy coding :)
| reference | from math import ceil
import math
def buses(kids, adults, places):
if places == 0:
return 0
buses_by_people = math . ceil((kids + adults) / places)
if adults < (buses_by_people * 2) and kids > 0:
return 0
else:
return buses_by_people
| Buses! | 640dee7cbad3aa002e7c7de4 | [
"Mathematics"
] | https://www.codewars.com/kata/640dee7cbad3aa002e7c7de4 | 7 kyu |
This is a rather simple but interesting kata. Try to solve it using logic. The shortest solution can be fit into one line.
## Task
The point is that a natural number N (1 <= N <= 10^9) is given. You need to write a function which finds the number of natural numbers not exceeding N and not divided by any of the numbers [2, 3, 5].
___
### Example
Let's take the number 5 as an example:
1. 1 - doesn't divide integer by 2, 3, and 5
2. 2 - divides integer by 2
3. 3 - divides integer by 3
4. 4 - divides integer by 2
5. 5 - divides integer by 5
Answer: 1
because only one number doesn't divide integer by any of 2, 3, 5
___
### Note
_Again, try to think of a formula that will shorten your solution and help you pass big tests._
Good luck :)
If you want to solve our problems, they are here:
[From Singularity Hub Community](https://www.codewars.com/collections/from-singularity-hub-community)
| algorithms | def real_numbers(n):
return n - n / / 2 - n / / 3 - n / / 5 + n / / 6 + n / / 10 + n / / 15 - n / / 30
| Mysterious Singularity Numbers | 6409aa6df4a0b773ce29cc3d | [
"Fundamentals",
"Logic",
"Mathematics",
"Arrays",
"Algorithms",
"Performance"
] | https://www.codewars.com/kata/6409aa6df4a0b773ce29cc3d | 7 kyu |
Imagine a honeycomb - a field of hexagonal cells with side `N`. There is a bee in the top left cell `A`. In one move it can crawl one cell down, one cell down-right or one cell up-right (the bee does not crawl up or left).
<!-- Embed Image as SVG -->
<svg width="106.97mm" height="53.56mm" version="1.1" viewBox="0 0 106.97 53.56" xmlns="http://www.w3.org/2000/svg"><defs><marker id="o" overflow="visible" markerHeight="0.80000001" markerWidth="1.09" orient="auto-start-reverse" preserveAspectRatio="none" viewBox="0 0 1 1"><path transform="scale(.5)" d="m5.77 0-8.65 5v-10z" fill="context-stroke" fill-rule="evenodd" stroke="context-stroke" stroke-width="1pt"/></marker><marker id="m" overflow="visible" markerHeight="0.80000001" markerWidth="1.09" orient="auto-start-reverse" preserveAspectRatio="none" viewBox="0 0 1 1"><path transform="scale(.5)" d="m5.77 0-8.65 5v-10z" fill="context-stroke" fill-rule="evenodd" stroke="context-stroke" stroke-width="1pt"/></marker><marker id="f" overflow="visible" markerHeight="0.80000001" markerWidth="1.09" orient="auto-start-reverse" preserveAspectRatio="none" viewBox="0 0 1 1"><path transform="scale(.5)" d="m5.77 0-8.65 5v-10z" fill="context-stroke" fill-rule="evenodd" stroke="context-stroke" stroke-width="1pt"/></marker><marker id="h" overflow="visible" markerHeight="0.80000001" markerWidth="1.09" orient="auto-start-reverse" preserveAspectRatio="none" viewBox="0 0 1 1"><path transform="scale(.5)" d="m5.77 0-8.65 5v-10z" fill="context-stroke" fill-rule="evenodd" stroke="context-stroke" stroke-width="1pt"/></marker><marker id="a" overflow="visible" markerHeight="0.80000001" markerWidth="1.09" orient="auto-start-reverse" preserveAspectRatio="none" viewBox="0 0 1 1"><path transform="scale(.5)" d="m5.77 0-8.65 5v-10z" fill="context-stroke" fill-rule="evenodd" stroke="context-stroke" stroke-width="1pt"/></marker><marker id="n" overflow="visible" markerHeight="0.80000001" markerWidth="1.09" orient="auto-start-reverse" preserveAspectRatio="none" viewBox="0 0 1 1"><path transform="scale(.5)" d="m5.77 0-8.65 5v-10z" fill="context-stroke" fill-rule="evenodd" stroke="context-stroke" stroke-width="1pt"/></marker><marker id="i" overflow="visible" markerHeight="0.80000001" markerWidth="1.09" orient="auto-start-reverse" preserveAspectRatio="none" viewBox="0 0 1 1"><path transform="scale(.5)" d="m5.77 0-8.65 5v-10z" fill="context-stroke" fill-rule="evenodd" stroke="context-stroke" stroke-width="1pt"/></marker><marker id="l" overflow="visible" markerHeight="0.80000001" markerWidth="1.09" orient="auto-start-reverse" preserveAspectRatio="none" viewBox="0 0 1 1"><path transform="scale(.5)" d="m5.77 0-8.65 5v-10z" fill="context-stroke" fill-rule="evenodd" stroke="context-stroke" stroke-width="1pt"/></marker><marker id="k" overflow="visible" markerHeight="0.80000001" markerWidth="1.09" orient="auto-start-reverse" preserveAspectRatio="none" viewBox="0 0 1 1"><path transform="scale(.5)" d="m5.77 0-8.65 5v-10z" fill="context-stroke" fill-rule="evenodd" stroke="context-stroke" stroke-width="1pt"/></marker><marker id="b" overflow="visible" markerHeight="0.80000001" markerWidth="1.09" orient="auto-start-reverse" preserveAspectRatio="none" viewBox="0 0 1 1"><path transform="scale(.5)" d="m5.77 0-8.65 5v-10z" fill="context-stroke" fill-rule="evenodd" stroke="context-stroke" stroke-width="1pt"/></marker><marker id="d" overflow="visible" markerHeight="0.80000001" markerWidth="1.09" orient="auto-start-reverse" preserveAspectRatio="none" viewBox="0 0 1 1"><path transform="scale(.5)" d="m5.77 0-8.65 5v-10z" fill="context-stroke" fill-rule="evenodd" stroke="context-stroke" stroke-width="1pt"/></marker><marker id="c" overflow="visible" markerHeight="0.80000001" markerWidth="1.09" orient="auto-start-reverse" preserveAspectRatio="none" viewBox="0 0 1 1"><path transform="scale(.5)" d="m5.77 0-8.65 5v-10z" fill="context-stroke" fill-rule="evenodd" stroke="context-stroke" stroke-width="1pt"/></marker><marker id="e" overflow="visible" markerHeight="0.80000001" markerWidth="1.09" orient="auto-start-reverse" preserveAspectRatio="none" viewBox="0 0 1 1"><path transform="scale(.5)" d="m5.77 0-8.65 5v-10z" fill="context-stroke" fill-rule="evenodd" stroke="context-stroke" stroke-width="1pt"/></marker><marker id="j" overflow="visible" markerHeight="0.80000001" markerWidth="1.09" orient="auto-start-reverse" preserveAspectRatio="none" viewBox="0 0 1 1"><path transform="scale(.5)" d="m5.77 0-8.65 5v-10z" fill="context-stroke" fill-rule="evenodd" stroke="context-stroke" stroke-width="1pt"/></marker><marker id="g" overflow="visible" markerHeight="0.80000001" markerWidth="1.09" orient="auto-start-reverse" preserveAspectRatio="none" viewBox="0 0 1 1"><path transform="scale(.5)" d="m5.77 0-8.65 5v-10z" fill="context-stroke" fill-rule="evenodd" stroke="context-stroke" stroke-width="1pt"/></marker></defs><g transform="translate(-17.915 -53.095)"><rect x="17.915" y="53.095" width="106.97" height="53.56" fill="#fff"/><g transform="matrix(.61512 0 0 .61521 28.286 30.756)"><g fill="none" stroke="#000" stroke-width=".32512"><path transform="translate(82.696 27.133)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/><path transform="translate(96.645 19.08)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/><path transform="translate(96.645 35.187)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/><path transform="translate(110.59 27.133)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/><path transform="translate(110.59 43.24)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/><path transform="translate(96.645 51.294)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/><path transform="translate(82.696 43.24)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/><path transform="translate(68.747 35.187)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/><path transform="translate(68.747 51.194)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/><path transform="translate(82.696 59.347)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/><path transform="translate(96.645 67.434)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/><path transform="translate(110.59 59.381)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/><path transform="translate(124.54 51.327)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/><path transform="translate(124.54 35.287)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/><path transform="translate(124.54 18.98)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/><path transform="translate(110.59 10.926)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/><path transform="translate(96.645 2.8727)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/><path transform="translate(82.696 11.026)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/><path transform="translate(68.747 19.08)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/></g><path d="m89.565 66.47-0.29766-1.0666h-1.8852l-0.30592 1.0666h-1.0087l1.5999-5.4033h1.4221l1.5999 5.4033zm-1.2278-4.4111-0.71107 2.5135h1.4139z" fill="#1a1a1a" stroke-width=".052917" aria-label="A"/><path d="m142.27 98.717v-5.4033h1.7446q0.92191 0 1.3808 0.32246 0.46302 0.32246 0.46302 0.97565 0 0.20257-0.0496 0.39688-0.0455 0.19017-0.14469 0.3514-0.0992 0.16123-0.24805 0.28525-0.14883 0.12402-0.3514 0.1943 0.20257 0.03307 0.38447 0.13229 0.18604 0.09508 0.32246 0.25218 0.14056 0.15296 0.21911 0.3638 0.0827 0.21084 0.0827 0.47129 0 0.82682-0.55397 1.2444-0.55397 0.41341-1.5999 0.41341zm2.5301-3.9274q0-0.15296-0.0496-0.27699-0.0496-0.12402-0.16123-0.21084-0.10749-0.08682-0.28112-0.13229-0.1695-0.04961-0.41341-0.04961h-0.61599v1.4304h0.61599q0.24804 0 0.41754-0.05788 0.17363-0.06201 0.28112-0.16536 0.11162-0.10749 0.1571-0.24391 0.0496-0.13643 0.0496-0.29352zm-0.81029 3.0965q0.24391 0 0.42581-0.06201 0.18604-0.06201 0.31006-0.1695 0.12403-0.11162 0.18604-0.26045 0.0661-0.14883 0.0661-0.31833 0-0.3514-0.26458-0.54984-0.26045-0.19844-0.80202-0.19844h-0.63252v1.5586z" fill="#1a1a1a" stroke-width=".052917" aria-label="B"/><g stroke="#000" stroke-width=".2"><path d="m93.008 66.68 5.1962 3" marker-end="url(#j)"/><path d="m92.804 61.273 5.1962-3" marker-end="url(#e)"/><path d="m88.629 69.342v6" marker-end="url(#g)"/></g></g><path d="m80.712 59.899q-0.0093 0.06201-0.03721 0.10542t-0.06511 0.07131q-0.03411 0.0279-0.07441 0.04031-0.04031 0.0124-0.08061 0.0124h-0.20155q-0.08061 0-0.13643-0.0186-0.05581-0.0186-0.09922-0.06201-0.04031-0.04651-0.07441-0.11782-0.03101-0.07441-0.06821-0.18294l-0.75344-2.1394q-0.07751-0.22944-0.15503-0.45579-0.07441-0.22944-0.14573-0.45889h-0.0062q-0.04031 0.25425-0.08682 0.5054-0.04651 0.25115-0.09612 0.50229l-0.46509 2.3378q-0.0062 0.02481-0.02481 0.04341-0.0155 0.0186-0.04961 0.03101-0.03101 0.0093-0.08371 0.0155-0.04961 0.0093-0.12092 0.0093-0.07131 0-0.12092-0.0093-0.04651-0.0062-0.07131-0.0155-0.0248-0.0124-0.03411-0.03101-0.0062-0.0186 0-0.04341l0.73794-3.7021q0.02481-0.12402 0.10232-0.17673 0.08061-0.05271 0.16123-0.05271h0.24495q0.07441 0 0.13022 0.0155 0.05581 0.0155 0.09612 0.05581t0.07131 0.10542q0.03101 0.06201 0.06821 0.16123l0.75964 2.1673q0.07131 0.20154 0.13953 0.40308 0.07131 0.20154 0.13953 0.40618h0.0062q0.04341-0.25425 0.09302-0.5271 0.05271-0.27285 0.10232-0.5271l0.43718-2.1735q0.0062-0.02481 0.0217-0.04031 0.0155-0.0186 0.04651-0.03101 0.03101-0.0124 0.07751-0.0186 0.04961-0.0062 0.12402-0.0062 0.07131 0 0.11782 0.0062 0.04961 0.0062 0.07441 0.0186 0.0279 0.0124 0.03721 0.03101 0.0093 0.0155 0.0062 0.04031zm3.606-1.0697q0 0.0186-0.0031 0.04961t-0.0124 0.06821q-0.0062 0.03721-0.0186 0.07441-0.0124 0.03411-0.03411 0.06511-0.0186 0.02791-0.04651 0.04651-0.0248 0.0186-0.05581 0.0186h-2.3378q-0.04031 0-0.06511-0.02791-0.02481-0.0279-0.02481-0.08992 0-0.03411 0.0093-0.08682 0.0093-0.05581 0.0279-0.10542 0.0217-0.05271 0.05271-0.08992 0.03411-0.03721 0.08372-0.03721h2.3409q0.04341 0 0.06201 0.03101 0.0217 0.03101 0.0217 0.08372zm0.24185-1.2061q0 0.0217-0.0031 0.05271t-0.0124 0.06511q-0.0062 0.03411-0.0186 0.07131-0.0124 0.03721-0.03411 0.06821-0.0186 0.02791-0.04651 0.04961-0.02481 0.0186-0.05891 0.0186h-2.3378q-0.03721 0-0.06201-0.02791-0.0248-0.0279-0.0248-0.09302 0-0.03411 0.0093-0.08682t0.02791-0.10232q0.0217-0.05271 0.05271-0.08992 0.03411-0.03721 0.08372-0.03721h2.3409q0.04341 0 0.06201 0.03101 0.0217 0.0279 0.0217 0.08062zm2.8742 1.2154q0 0.15193-0.04031 0.31006-0.03721 0.15813-0.12092 0.30696-0.08372 0.14883-0.21394 0.28215-0.12712 0.13022-0.31006 0.22944-0.17983 0.09612-0.41238 0.15193-0.23254 0.05891-0.5271 0.05891-0.15503 0-0.29456-0.0186-0.13643-0.0186-0.26045-0.04961-0.12092-0.03411-0.22324-0.07751-0.09922-0.04651-0.17983-0.09922-0.04651-0.02791-0.06821-0.06511-0.0186-0.04031-0.0186-0.08992 0-0.0186 0.0031-0.04961 0.0031-0.03411 0.0093-0.07131 0.0062-0.03721 0.0155-0.07751 0.0093-0.04341 0.0217-0.07441 0.0155-0.03411 0.03411-0.05271 0.0217-0.0217 0.04651-0.0217 0.02791 0 0.09922 0.04961 0.07441 0.04651 0.19224 0.10542 0.11782 0.05581 0.27595 0.10542 0.16123 0.04651 0.36897 0.04651 0.26045 0 0.44958-0.08062 0.19224-0.08062 0.31626-0.20464 0.12402-0.12712 0.18293-0.27905 0.06201-0.15503 0.06201-0.30696 0-0.12402-0.04651-0.23254-0.04341-0.10852-0.14263-0.18604-0.09612-0.08062-0.25425-0.12712-0.15503-0.04651-0.37517-0.04651h-0.43098q-0.04961 0-0.07751-0.02481-0.0248-0.0279-0.0248-0.08682 0-0.0217 0.0031-0.05581 0.0062-0.03411 0.0155-0.06511 0.0093-0.03411 0.0217-0.06821 0.0155-0.03411 0.03411-0.06201 0.0217-0.0279 0.04651-0.04341 0.02481-0.0155 0.05891-0.0155h0.35037q0.22944 0 0.42168-0.06821 0.19224-0.07131 0.32866-0.19224 0.13953-0.12402 0.21704-0.28525 0.07751-0.16123 0.07751-0.34416 0-0.22014-0.12712-0.34727-0.12402-0.12712-0.41548-0.12712-0.17673 0-0.33796 0.05581-0.16123 0.05271-0.29146 0.11782-0.13022 0.06201-0.22324 0.11782-0.08992 0.05581-0.12712 0.05581-0.02791 0-0.04341-0.02481-0.0155-0.02791-0.0155-0.07441 0-0.0248 0.0062-0.07131t0.0186-0.09922q0.0155-0.05271 0.03721-0.10232 0.02481-0.04961 0.05581-0.08062 0.03411-0.03411 0.13332-0.08992 0.09922-0.05891 0.24185-0.11162 0.14263-0.05581 0.31936-0.09302 0.17983-0.04031 0.36897-0.04031 0.24495 0 0.42788 0.05891 0.18604 0.05581 0.30696 0.16433 0.12092 0.10542 0.17983 0.26045 0.06201 0.15193 0.06201 0.34106 0 0.21704-0.07131 0.40928-0.06821 0.18914-0.19844 0.33796-0.12712 0.14883-0.30386 0.25735-0.17673 0.10542-0.38757 0.15193v0.0062q0.20464 0.0217 0.34726 0.09922 0.14573 0.07442 0.23564 0.18604 0.08992 0.10852 0.13022 0.24495 0.04031 0.13332 0.04031 0.27285z" fill="#1a1a1a" stroke-width=".052917" aria-label="N=3"/><g fill="none" stroke="#000" stroke-width=".2"><path transform="translate(9.7721 27.033)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/><path transform="translate(23.721 18.98)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/><path transform="translate(23.721 35.087)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/><path transform="translate(37.67 27.033)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/><path transform="translate(37.67 43.14)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/><path transform="translate(23.721 51.194)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/><path transform="translate(9.7721 43.14)" d="m28.931 44.689-4.6497 8.0535h-9.2994l-4.6497-8.0535 4.6497-8.0535h9.2994z"/><path d="m30.591 74.423-0.29766-1.0666h-1.8852l-0.30592 1.0666h-1.0087l1.5999-5.4033h1.4221l1.5999 5.4033zm-1.2278-4.4111-0.71107 2.5135h1.4139z" fill="#1a1a1a" stroke-width=".052917" aria-label="A"/><path d="m55.401 90.53v-5.4033h1.7446q0.92191 0 1.3808 0.32246 0.46302 0.32246 0.46302 0.97565 0 0.20257-0.04961 0.39688-0.04548 0.19017-0.14469 0.3514-0.09922 0.16123-0.24805 0.28525-0.14883 0.12402-0.3514 0.1943 0.20257 0.03307 0.38447 0.13229 0.18604 0.09508 0.32246 0.25218 0.14056 0.15296 0.21911 0.3638 0.08268 0.21084 0.08268 0.47129 0 0.82682-0.55397 1.2444-0.55397 0.41341-1.5999 0.41341zm2.5301-3.9274q0-0.15296-0.04961-0.27699-0.04961-0.12402-0.16123-0.21084-0.10749-0.08682-0.28112-0.13229-0.1695-0.04961-0.41341-0.04961h-0.61598v1.4304h0.61598q0.24805 0 0.41755-0.05788 0.17363-0.06201 0.28112-0.16536 0.11162-0.10749 0.1571-0.24391 0.04961-0.13642 0.04961-0.29352zm-0.81029 3.0965q0.24391 0 0.42581-0.06201 0.18604-0.06201 0.31006-0.1695 0.12402-0.11162 0.18604-0.26045 0.06615-0.14883 0.06615-0.31833 0-0.3514-0.26458-0.54984-0.26045-0.19844-0.80202-0.19844h-0.63252v1.5586z" fill="#1a1a1a" stroke-width=".052917" aria-label="B"/><g stroke="#000" stroke-width=".2"><path d="m29.402 76.911v6" marker-end="url(#o)"/><path d="m43.353 68.722v6" marker-end="url(#h)"/><path d="m43.353 84.829v6" marker-end="url(#a)"/><path d="m33.577 68.842 5.1962-3" marker-end="url(#f)"/><path d="m33.781 85.302 5.1962-3" marker-end="url(#b)"/><path d="m47.73 77.249 5.1962-3" marker-end="url(#d)"/><path d="m33.781 74.249 5.1962 3" marker-end="url(#m)"/><path d="m47.73 66.195 5.1962 3" marker-end="url(#i)"/><path d="m57.302 76.775v6" marker-end="url(#n)"/><path d="m33.781 90.356 5.1962 3" marker-end="url(#l)"/><path d="m47.73 82.302 5.1962 3" marker-end="url(#k)"/><path d="m47.73 93.356 5.1962-3" marker-end="url(#c)"/></g></g><path d="m26.96 59.719q-0.0093 0.06201-0.03721 0.10542t-0.06511 0.07131q-0.03411 0.02791-0.07441 0.04031-0.04031 0.0124-0.08061 0.0124h-0.20154q-0.08062 0-0.13643-0.0186-0.05581-0.0186-0.09922-0.06201-0.04031-0.04651-0.07442-0.11782-0.031-0.07441-0.06821-0.18294l-0.75344-2.1394q-0.07751-0.22944-0.15503-0.45579-0.07441-0.22944-0.14573-0.45889h-0.0062q-0.04031 0.25425-0.08682 0.5054-0.04651 0.25115-0.09612 0.50229l-0.46509 2.3378q-0.0062 0.02481-0.02481 0.04341-0.0155 0.0186-0.04961 0.03101-0.03101 0.0093-0.08372 0.0155-0.04961 0.0093-0.12092 0.0093-0.07131 0-0.12092-0.0093-0.04651-0.0062-0.07131-0.0155-0.02481-0.0124-0.03411-0.03101-0.0062-0.0186 0-0.04341l0.73794-3.7021q0.0248-0.12402 0.10232-0.17673 0.08062-0.05271 0.16123-0.05271h0.24495q0.07441 0 0.13022 0.0155 0.05581 0.0155 0.09612 0.05581t0.07131 0.10542q0.03101 0.06201 0.06821 0.16123l0.75964 2.1673q0.07131 0.20154 0.13953 0.40308 0.07131 0.20154 0.13953 0.40618h0.0062q0.04341-0.25425 0.09302-0.5271 0.05271-0.27285 0.10232-0.5271l0.43718-2.1735q0.0062-0.02481 0.0217-0.04031 0.0155-0.0186 0.04651-0.03101 0.03101-0.0124 0.07751-0.0186 0.04961-0.0062 0.12402-0.0062 0.07131 0 0.11782 0.0062 0.04961 0.0062 0.07441 0.0186 0.02791 0.0124 0.03721 0.03101 0.0093 0.0155 0.0062 0.04031zm3.606-1.0697q0 0.0186-0.0031 0.04961t-0.0124 0.06821q-0.0062 0.03721-0.0186 0.07441-0.0124 0.03411-0.03411 0.06511-0.0186 0.02791-0.04651 0.04651-0.0248 0.0186-0.05581 0.0186h-2.3378q-0.04031 0-0.06511-0.02791-0.02481-0.0279-0.02481-0.08992 0-0.03411 0.0093-0.08682 0.0093-0.05581 0.02791-0.10542 0.0217-0.05271 0.05271-0.08992 0.03411-0.03721 0.08372-0.03721h2.3409q0.04341 0 0.06201 0.03101 0.0217 0.03101 0.0217 0.08372zm0.24185-1.2061q0 0.0217-0.0031 0.05271t-0.0124 0.06511q-0.0062 0.03411-0.0186 0.07131-0.0124 0.03721-0.03411 0.06821-0.0186 0.02791-0.04651 0.04961-0.0248 0.0186-0.05891 0.0186h-2.3378q-0.03721 0-0.06201-0.0279-0.02481-0.02791-0.02481-0.09302 0-0.03411 0.0093-0.08682t0.02791-0.10232q0.0217-0.05271 0.05271-0.08992 0.03411-0.03721 0.08372-0.03721h2.3409q0.04341 0 0.06201 0.03101 0.0217 0.0279 0.0217 0.08061zm2.7316 2.1704q0 0.0186-0.0062 0.05271-0.0031 0.03411-0.0124 0.07131-0.0093 0.03411-0.02481 0.07131-0.0124 0.03721-0.03411 0.06511-0.0186 0.0279-0.04341 0.04651-0.0248 0.0186-0.05581 0.0186h-2.2169q-0.04031 0-0.06821-0.0093-0.02791-0.0093-0.04341-0.02481-0.0155-0.0186-0.02481-0.04031-0.0062-0.0248-0.0062-0.05581t0.0031-0.08062q0.0062-0.04961 0.02481-0.10852 0.0186-0.05891 0.05581-0.11782 0.03721-0.06201 0.10232-0.11782l1.0325-0.90537q0.24185-0.21084 0.41548-0.39377 0.17673-0.18604 0.29456-0.34416 0.12092-0.16123 0.19224-0.29456 0.07131-0.13642 0.11162-0.24805 0.04031-0.11162 0.05271-0.20154 0.0124-0.09302 0.0124-0.16433 0-0.07441-0.02481-0.15813-0.0217-0.08682-0.08061-0.16123-0.05581-0.07441-0.16123-0.12402-0.10542-0.04961-0.26665-0.04961-0.17673 0-0.33796 0.05271-0.16123 0.05271-0.29146 0.11782-0.13022 0.06201-0.22014 0.11782-0.08682 0.05271-0.12092 0.05271-0.03101 0-0.04961-0.03101t-0.0186-0.08992q0-0.02481 0.0031-0.05271 0.0062-0.03101 0.0093-0.06511 0.0062-0.03411 0.0155-0.06821 0.0124-0.03411 0.02481-0.06511 0.0155-0.03101 0.03101-0.05891 0.0186-0.03101 0.04031-0.05271 0.03411-0.03411 0.13333-0.08992 0.10232-0.05581 0.24495-0.10852t0.31626-0.08992q0.17363-0.04031 0.35967-0.04031 0.29766 0 0.49299 0.08372t0.30696 0.21084q0.11472 0.12712 0.15813 0.27595 0.04651 0.14883 0.04651 0.28215 0 0.12712-0.0186 0.26045-0.0186 0.13332-0.07441 0.28215-0.05271 0.14573-0.15193 0.31006-0.09612 0.16433-0.25425 0.35657-0.15503 0.18914-0.37827 0.41238-0.22014 0.22014-0.5271 0.48059l-0.77515 0.66352h1.7115q0.05271 0 0.07441 0.04031 0.0217 0.03721 0.0217 0.08682z" fill="#1a1a1a" stroke-width=".052917" aria-label="N=2"/></g></svg>
Write a function that outputs the number of ways the bee can crawl from cell `A` to the opposite cell `B`.
**Input data:**
_The function receives a single number N - the size of the hexagonal field `2 β€ N β€ 200`._
**Output data:**
_The function should output a single integer - the number of ways._
**Example:**
```python
the_bee(2) --> 11
the_bee(3) --> 291
the_bee(5) --> 259123
```
**Code length limit:**
_To prevent hardcoding, your code cannot exceed `1 000` characters._
If you have the desire and time, I would be very grateful if you can help in the development of this kata, to translate, or whatever else. I can be contacted via [Telegram](https://t.me/Egor_Arhipovm).
If you want to solve our problems, they are here: [From Singularity Hub Community](https://www.codewars.com/collections/from-singularity-hub-community) | algorithms | def the_bee(n):
cells = [0] * (2 * n + 1)
cells[n] = 1
for i in range(1, 4 * n - 2):
for j in range(i % 2 + 1, 2 * n, 2):
cells[j - 1] += cells[j]
cells[j + 1] += cells[j]
return cells[n]
| The Bee | 6408ba54babb196a61d66a65 | [
"Algorithms",
"Mathematics",
"Matrix",
"Puzzles",
"Performance",
"Dynamic Programming"
] | https://www.codewars.com/kata/6408ba54babb196a61d66a65 | 5 kyu |
Your task is to find the maximum number of queens that can be put on the board so that there would be one single unbeaten square (ie. threatened by no queen on the board).
The Queen can move any distance vertically, horizontally and diagonally.
## Input
The queens(n) function takes the size of the chessboard.
`$n\in\Z$`, so it can be negative, and values can go up to `$141^{1000}$`.
## Output
* The maximum number of queens to leave one single unbeaten square
* Return `0` if `n` is negative.
## Examples
* `$n=4 \rightarrow 6\ queens $`
* `$n=5 \rightarrow 12\ queens $`
Good luck ) | games | def queens(n):
return (n - 2) * (n - 1) if n >= 3 else 0
| Finding queens on the board | 64060d8ab2dd990058b7f8ee | [
"Algorithms"
] | https://www.codewars.com/kata/64060d8ab2dd990058b7f8ee | 7 kyu |
To earn a huge capital, you need to have an unconventional mindset. Of course, with such a complex job, there must also be special mechanisms for recreation and entertainment. For this purpose, the casino came up with a special domino set. Ordinary dominoes are a set of different combinations of two tiles, each displaying `0` to `6` points. And this set is a similar combination of tiles, but the number of points on each can be from zero to a set value that depends on the intellectual level of the players. There are all kinds of tile combinations in this dice set, but none of them must be repeated (combinations such as `2 | 5` and `5 | 2` are considered the same).

When making this set of dominoes, the manufacturer faced the problem of counting the total number of points on all dominoes. This is due to the fact that the dominoes are decorated with diamonds, which are dots on the tiles and the cost of which must be estimated during manufacture.
**Input data**:
_The function receives a parameter n, which indicates the maximum number of points on one domino tile._
**_Test values are 0 < n < 1000_**
**Output data**:
_Your function should return the optional number of diamond stones to be made for a given set of dice._
**Example:**
For dominoes where the maximum possible number on the knuckle is 2, the possible knuckles will be as follows --> `0 | 1`, `0 | 2`, `1 | 1`, `1 | 2`, `2 | 2`
therefore, the sum of all values on the knuckles will be `1 + 2 + 1 + 1 + 1 + 2 + 2 + 2 = 12`
```python
2 --> 12
3 --> 30
20 --> 4620
```
```rust
2 --> Some(12)
3 --> Some(30)
20 --> Some(4620)
```
Help me write a program that solves this problem.
If someone is interested, you can read the rules of the domino game here ;)
[Domino game](https://www.enchantedlearning.com/dominoes/rules.shtml)
If you have the desire or time, I would be very grateful if you can help in the development of this kata, to translate, or whatever else with me can be contacted via [Telegram](https://t.me/Egor_Arhipovm) | algorithms | def dots_on_domino_bones(n):
if n < 0:
return - 1
return (n + 2) * (n + 1) * n / / 2
| Dots on Domino's Bones | 6405f2bb2894f600599172fd | [
"Mathematics",
"Games",
"Algorithms"
] | https://www.codewars.com/kata/6405f2bb2894f600599172fd | 7 kyu |
# Problem Description
```
,@@@@@@@@@@@@@@@,
@@@& @@@@
*@@ (@@@@@* /@@@@@/ @@,
@@ @@@ @@@ @@
@@ (@@ @@/ @@
%@ #@# @@ %@( @%
@@ @@ &@@@@@@@@@@@ @@ @@
@@ @@ @@@ @@ @@@ @@ @@
@, @@ @@@ @@ @@ ,@
@@ @ @@@@@@@ @ @@
@@ /@ @@@@@@@ @, @@
@@ @ @@ @@@ @ @@
@. @@ @@@ @@ *@@ @@ ,@
@@ @& #@@@ @@ %@@@ @@ @@
@@ @@ .@@@@@@@@, @@ @@
@@ &@* @@ *@& @@
@@ @@@ @@& @@
@@ @@@ @@@ @@
%@@ @@@@@% %@@@@@ @@%
@@@/ /@@@
%@@@@@@@@@@@@@@@%
```
This Kata is the first in the [Do a Smart Guess](https://www.codewars.com/collections/640a8a62431f2d14217eef5f) collection series.
After a long RPG campaign with your friends, you come across a guardian of a great treasure, a chest full of gold coins! As nothing in life is easy, the guardian says that he will only deliver the treasure if you guess the number of gold coins present in the chest. For this, he gives the following tips:
* `$1$`. If the number of coins were divided between `$m_1$` people, `$a_1$` coins would be left.
* `$2$`. If the number of coins were divided between `$m_2$` people, `$a_2$` coins would be left.
* `$3$`. If the number of coins were divided between `$m_3$` people, `$a_3$` coins would be left.
```math
\vdots
```
* `$N$`. If the number of coins were divided between `$m_N$` people, `$a_N$` coins would be left.
Of course `$m_i$` is always a positive integer and `$0 \leq a_i \lt m_i$`.
To ensure that a solution for the number of coins always exists, the guardian always chooses values of `$m$` that are pairwise relatively prime, that is:
```math
\text{gcd}(m_i, m_j)=1 \quad \forall i \neq j, 1 \leq i,j \leq N
```
(`$\text{gcd}$` is the Greatest Common Divisor function).
# Your Task
Given the guardian information, write the function `number_of_coins` that returns the minimum number of gold coins in the chest.
~~~if:python
This function receives information in the form of a list of tuples:
```python
[(a1, m1), (a2, m2), ... , (aN, mN)]
```
~~~
**Example:**
Suppose that the tips from the guardian are:
* `$1$`. If the number of coins were divided between `$2$` people, `$1$` coin would be left.
* `$2$`. If the number of coins were divided between `$5$` people, `$2$` coins would be left.
So, the minimum number of gold coins is 7, because 7 is the smallest number that when divided by 2 has remainder 1 and when divided by 5 has remainder 2. Thus:
~~~if:python
```python
number_of_coins([(1, 2), (2, 5)]) = 7
```
~~~
# Performance Requirements
Consider that the input will be always valid, and the maximum input length will be 15 (that is, the guardian will give at most 15 tips, `$1 \leq N \leq 15$`).
The `$m_i$` values will be always less than `$10^{20}$`, so the minimum number of gold coins can be quite large. However, that shouldn't be a problem for your algorithm.
If you liked this Kata, try the next one in this series: [Find Out the Number of Grains of Sand!](https://www.codewars.com/kata/640ab019431f2d0be07ef67a).
Have fun coding and please don't forget to vote and rank this kata! :-)
| games | from functools import reduce
def number_of_coins(tips):
# Let's do some math magic to get our total coin count
M = reduce(lambda x, y: x * y[1], tips, 1)
# Time to collect all these shiny coins!
s = sum([coin * (M / / tip) * pow((M / / tip), - 1, tip) for coin, tip in tips])
return s % M # We gotta make sure we don't break the bank, unless we're playing Monopoly!
| Find Out the Number of Gold Coins! | 6402d27bf4a0b7d31c299043 | [
"Mathematics",
"Number Theory"
] | https://www.codewars.com/kata/6402d27bf4a0b7d31c299043 | 5 kyu |
You need to hire a catering company out of three for lunch in a birthday party. The first caterer offers only a `basic buffet` which costs $15 per person. The second one has an `economy buffet` at $20 per person and the third one has a `premium buffet` at $30 per person. The third one gives a 20% discount if the number of persons to be served is greater than 60. You want to spend the maximum that fits into the budget.
The function takes two arguments denoting the budget in $ and the number of people. Return 1, 2 or 3 for the three caterers as per the above criteria.
Return -1 if there are no people or the budget is lower than the cost of buffets from the first caterer.
Number of orders is always equal to number of people.
**For example,**
```budget, people => (400, 25) will return 1.
budget, people => (200, 9) will return 2.
budget, people => (300, 9) will return 3 and so on.
```
Goodluck :)
Check my other katas:
<a href="https://www.codewars.com/kata/5a8059b1fd577709860000f6">Alphabetically ordered </a>
<a href="https://www.codewars.com/kata/5a805631ba1bb55b0c0000b8">Case-sensitive! </a>
<a href="https://www.codewars.com/kata/5a805d8cafa10f8b930005ba">Find Nearest square number </a>
<a href="https://www.codewars.com/kata/5a9a70cf5084d74ff90000f7">Not prime numbers </a> | reference | def find_caterer(budget, people):
if people != 0:
pp = budget / people
if pp < 15:
return - 1
elif pp < 20:
return 1
elif pp < 24 or (pp < 30 and people <= 60):
return 2
else:
return 3
return - 1
| Find your caterer | 6402205dca1e64004b22b8de | [
"Fundamentals"
] | https://www.codewars.com/kata/6402205dca1e64004b22b8de | 7 kyu |
# Adjust barbell
## Kata overview
Olympic weightlifting is a sport in which athletes compete in lifting a barbell from the ground to overhead, with the aim of successfully lifting the heaviest weights.
The purpose of this kata is to simulate a Olympic barbell loader, changing the weights from lift to lift.
### Task
Write a function that returns a string with instructions on how to adjust the barbell, given a start and end weight.
### Input
* The start weight of a barbell in kg (integer)
* The end weight of a barbell in kg (integer)
Weights are always between 25 - 274 kg (both included).
The start weight always differs from the end weight.
### Output
A string with instructions on how to adjust the barbell, in the form ```strip c, load B, load c, load g```.
The instructions should not contain unnecessary steps.
See output details further below.
## Barbell details
A barbell consists of three parts:
* Bar
* Discs
* Collars
The bar weighs 20 kg and uses character ```-```. The bar is 40 characters long.
Discs are loaded and secured by collars on the sleeve of the bar. The bar is loaded with the heaviest discs first and then the lighter discs loaded in descending order of weight toward the outer edge of the bar. The following discs are used. Discs are loaded from the 10th character from the outer edge of the bar.
```
WEIGHT COLOR CHAR
25 kg red R
20 kg blue B
15 kg yellow Y
10 kg green G
5 kg white W
2.5 kg red r
2 kg blue b
1.5 kg yellow y
1 kg green g
0.5 kg white w
```
In order to secure the discs to the bar, each bar must be equipped with two (2) collars. Collars weigh 2.5 kg each. Collars use character ```c```, and are positioned outward of discs of 2.5 kg or more, and inward of discs of 2 kg or less.
Some examples of loaded barbells and their total weight.
```
WEIGHT BARBELL
25 kg ---------c--------------------c---------
26 kg --------wc--------------------cw--------
34 kg -------bcr--------------------rcb-------
35 kg --------cW--------------------Wc--------
47 kg -------gcG--------------------Gcg-------
58 kg -------ycY--------------------Ycy-------
124 kg -----bcrBR--------------------RBrcb-----
225 kg -----cRRRR--------------------RRRRc-----
267 kg ---gcBRRRR--------------------RRRRBcg---
```
The barbell is loaded symmetrically, using as little discs as possible.
Some examples of incorrectly loaded barbells and their total weight.
```
WEIGHT BARBELL
47 kg --------cB--------------------cb-------- (asymmetric)
47 kg ------wwcG--------------------Gcww------ (ww is more discs than g)
```
## Output details
The instructions are a comma-separated list of steps. Each step consists of two parts:
1. ```strip``` or ```load```
2. The character used for the disc or collar
Some example steps:
* Removing a collar: ```strip c```
* Adding three 25 kg discs: ```load R, load R, load R```
* Removing a 1.5 kg disc: ```strip y```
Some example instructions:
* From 25 kg to 26 kg: ```load w```
* From 25 kg to 34 kg: ```strip c, load r, load c, load b```
* From 124 kg to 267 kg: ```strip b, strip c, strip r, strip B, load R, load R, load R, load B, load c, load g```
* From 200 kg to 100 kg: ```strip c, strip r, strip G, strip R, strip R, load G, load r, load c```
## Weightlifting series
This kata is part of a series of kata with increasing difficulty:
1. [Barbell weight](https://www.codewars.com/kata/6400aa17431f2d89c07eea75)
2. [Load a barbell](https://www.codewars.com/kata/6400c3ebf4a0b796602988a6)
3. [Adjust barbell](https://www.codewars.com/kata/6400caeababb193c64d664d1) | reference | disc_weight = {"R": 25, "B": 20, "Y": 15, "G": 10, "W": 5,
"r": 2.5, "b": 2, "y": 1.5, "g": 1, "w": .5, "c": 2.5, "-": 0}
def adjust_barbell(weight_start, weight_end):
discs, discs_stb = get_discs(weight_start - 25), get_discs(weight_end - 25)
while discs and discs_stb and discs[- 1] == discs_stb[- 1]:
discs, discs_stb = discs[: - 1], discs_stb[: - 1]
steps = [f"strip { disc } " for disc in discs]
steps += [f"load { disc } " for disc in discs_stb[:: - 1]]
return ", " . join(steps)
def get_discs(weight):
discs = []
while weight > 0:
for disc in disc_weight:
if weight >= disc_weight[disc] * 2:
if disc_weight[disc] < 2.5 and "c" not in discs:
discs . append("c")
discs . append(disc)
weight -= disc_weight[disc] * 2
break
discs = discs + ["c"] if "c" not in discs else discs
discs = "" . join(discs[:: - 1])
return discs
| Adjust barbell | 6400caeababb193c64d664d1 | [
"Strings",
"Mathematics"
] | https://www.codewars.com/kata/6400caeababb193c64d664d1 | 6 kyu |
# Load a barbell
## Kata overview
Olympic weightlifting is a sport in which athletes compete in lifting a barbell from the ground to overhead, with the aim of successfully lifting the heaviest weights.
The purpose of this kata is to load an Olympic barbell.
### Task
Write a function that returns a string representation of a barbell, given its weight.
### Input
The weight of a barbell in kg (integer).
Weights are always between 25 - 274 kg (both included).
### Output
A string representation of the barbell, in the form ```---gcBRRRR--------------------RRRRBcg---```.
The barbell is loaded symmetrically, using as little discs as possible.
## Barbell details
A barbell consists of three parts:
* Bar
* Discs
* Collars
The bar weighs 20 kg and uses character ```-```. The bar is 40 characters long.
Discs are loaded and secured by collars on the sleeve of the bar. The bar is loaded with the heaviest discs first and then the lighter discs loaded in descending order of weight toward the outer edge of the bar. The following discs are used. Discs are loaded from the 10th character from the outer edge of the bar.
```
WEIGHT COLOR CHAR
25 kg red R
20 kg blue B
15 kg yellow Y
10 kg green G
5 kg white W
2.5 kg red r
2 kg blue b
1.5 kg yellow y
1 kg green g
0.5 kg white w
```
In order to secure the discs to the bar, each bar must be equipped with two (2) collars. Collars weigh 2.5 kg each. Collars use character ```c```, and are positioned outward of discs of 2.5 kg or more, and inward of discs of 2 kg or less.
Some examples of loaded barbells and their total weight.
```
WEIGHT BARBELL
25 kg ---------c--------------------c---------
26 kg --------wc--------------------cw--------
34 kg -------bcr--------------------rcb-------
35 kg --------cW--------------------Wc--------
47 kg -------gcG--------------------Gcg-------
58 kg -------ycY--------------------Ycy-------
124 kg -----bcrBR--------------------RBrcb-----
225 kg -----cRRRR--------------------RRRRc-----
267 kg ---gcBRRRR--------------------RRRRBcg---
```
Some examples of incorrectly loaded barbells and their total weight.
```
WEIGHT BARBELL
47 kg --------cB--------------------cb-------- (asymmetric)
47 kg ------wwcG--------------------Gcww------ (ww is more discs than g)
```
## Weightlifting series
This kata is part of a series of kata with increasing difficulty:
1. [Barbell weight](https://www.codewars.com/kata/6400aa17431f2d89c07eea75)
2. [Load a barbell](https://www.codewars.com/kata/6400c3ebf4a0b796602988a6)
3. [Adjust barbell](https://www.codewars.com/kata/6400caeababb193c64d664d1) | reference | ELEMENTS = [('R', 25), ('B', 20), ('Y', 15), ('G', 10), ('W', 5),
('r', 2.5), ('c', 0), ('b', 2), ('y', 1.5), ('g', 1), ('w', 0.5)]
SIDE, CENTER = 10, 20
BAR, COLLAR = 20, 2.5
def load_barbell(W):
W -= BAR + 2 * COLLAR
side = []
for c, w in ELEMENTS:
n, W = divmod(W, 2 * w) if w else (1, W)
side . append(c * int(n))
side = "" . join(side). ljust(SIDE, '-')
return side[:: - 1] + '-' * CENTER + side
| Load a barbell | 6400c3ebf4a0b796602988a6 | [
"Strings",
"Mathematics"
] | https://www.codewars.com/kata/6400c3ebf4a0b796602988a6 | 6 kyu |
# Barbell weight
## Kata overview
Olympic weightlifting is a sport in which athletes compete in lifting a barbell from the ground to overhead, with the aim of successfully lifting the heaviest weights.
The purpose of this kata is to compute the weight of an Olympic barbell.
### Task
Write a function that computes the barbell weight.
### Input
A string representation of a barbell, in the form ```---gcBRRRR--------------------RRRRBcg---```.
Weights are always between 25 - 274 kg (both included).
### Output
The weight of the barbell in kg (integer).
## Barbell details
A barbell consists of three parts:
* Bar
* Discs
* Collars
The bar weighs 20 kg and uses character ```-```. The bar is 40 characters long.
Discs are loaded and secured by collars on the sleeve of the bar. The bar is loaded with the heaviest discs first and then the lighter discs loaded in descending order of weight toward the outer edge of the bar. The following discs are used. Discs are loaded from the 10th character from the outer edge of the bar.
```
WEIGHT COLOR CHAR
25 kg red R
20 kg blue B
15 kg yellow Y
10 kg green G
5 kg white W
2.5 kg red r
2 kg blue b
1.5 kg yellow y
1 kg green g
0.5 kg white w
```
In order to secure the discs to the bar, each bar must be equipped with two (2) collars. Collars weigh 2.5 kg each. Collars use character ```c```, and are positioned outward of discs of 2.5 kg or more, and inward of discs of 2 kg or less.
Some examples of loaded barbells and their total weight.
```
WEIGHT BARBELL
25 kg ---------c--------------------c---------
26 kg --------wc--------------------cw--------
34 kg -------bcr--------------------rcb-------
35 kg --------cW--------------------Wc--------
47 kg -------gcG--------------------Gcg-------
58 kg -------ycY--------------------Ycy-------
124 kg -----bcrBR--------------------RBrcb-----
225 kg -----cRRRR--------------------RRRRc-----
267 kg ---gcBRRRR--------------------RRRRBcg---
```
## Weightlifting series
This kata is part of a series of kata with increasing difficulty:
1. [Barbell weight](https://www.codewars.com/kata/6400aa17431f2d89c07eea75)
2. [Load a barbell](https://www.codewars.com/kata/6400c3ebf4a0b796602988a6)
3. [Adjust barbell](https://www.codewars.com/kata/6400caeababb193c64d664d1) | reference | ELEMENTS = {'-': 0, 'c': 2.5, 'R': 25, 'B': 20, 'Y': 15, 'G': 10,
'W': 5, 'r': 2.5, 'b': 2, 'y': 1.5, 'g': 1, 'w': 0.5, }
BAR = 20
def barbell_weight(barbell):
return BAR + sum(map(ELEMENTS . __getitem__, barbell))
| Barbell weight | 6400aa17431f2d89c07eea75 | [
"Strings",
"Mathematics"
] | https://www.codewars.com/kata/6400aa17431f2d89c07eea75 | 7 kyu |
In this kata, you need to write a function that takes a string and a letter as input and then returns the index of the second occurrence of that letter in the string. If there is no such letter in the string, then the function should return -1. If the letter occurs only once in the string, then -1 should also be returned.
Examples:
```Python
second_symbol('Hello world!!!','l') --> 3
second_symbol('Hello world!!!', 'A') --> -1
```
```cpp
secondSymbol('Hello world!!!','l') --> 3
secondSymbol('Hello world!!!', 'A') --> -1
```
```javascript
secondSymbol('Hello world!!!','l') --> 3
secondSymbol('Hello world!!!', 'A') --> -1
```
```haskell
secondSymbol "Hello world!!!" 'l' --> 3
secondSymbol "Hello world!!!" 'A' --> -1
```
Good luck ;) And don't forget to rate this Kata if you liked it. | reference | def second_symbol(s, c):
return s . find(c, s . find(c) + 1)
| Find the index of the second occurrence of a letter in a string | 63f96036b15a210058300ca9 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/63f96036b15a210058300ca9 | 7 kyu |
# Jumps in a cycle
A cycle `$[a_1, \dots, a_n]$` can be written in a extended form with a jump rate equal to 1 as `$a_1 \rightarrow a_2\rightarrow ... \rightarrow a_n\rightarrow a_1 \rightarrow ... \rightarrow a_n ...$`
Given a jump rate `k` and starting in the first element, you must find the number of jumps you have to take in order to reach the same element.
<u><strong>ASSUMPTION:</strong></u> The elements in the cycle are distinguishable.
## Examples
[1, 5, 7, 8, 9] and jump rate 1, then `$1 \rightarrow 5\rightarrow 7\rightarrow 8\rightarrow 9 \rightarrow 1$`. That is, 5 jumps.
[1, 5, 7, 8, 9] and jump rate 2, then `$1 \rightarrow 7\rightarrow 9\rightarrow 5 \rightarrow 8 \rightarrow 1$`. That is, 5 jumps.
[1, 5, 1] and jump rate 2, then `$1 \rightarrow 1\rightarrow 5\rightarrow 1$`. That is, 3 jumps.
## Input
- cl: (list) the list with the cycle. `$2\leq cl\leq2^{30}$`
- k: (int) the jump rate. `$1\leq k\leq2^{40}$`
## Output
(int) The number of jumps in order to reach the same first element in the cycle. | games | from math import gcd
def get_jumps(cycle_list, k):
l = len(cycle_list)
return l / / gcd(l, k)
| Jumps in a cycle #1 | 63f844fee6be1f0017816ff1 | [
"Mathematics",
"Puzzles",
"Performance"
] | https://www.codewars.com/kata/63f844fee6be1f0017816ff1 | 7 kyu |
# The Challenge
Given two musical note names between A0 and C8, return the interval separating them as a positive integer.
## Examples
`getInterval('F4', 'B4')` should return `4`.
`getInterval('G3', 'G4')` should return `8`.
`getInterval('A7', 'B6')` should return `7`.
# Some Background
Musicians often refer to pitchs using a combination of note name and octave, using the standard piano keyboard as a reference.
## Note Names
The seven note names are C, D, E, F, G, A and B. These names then repeat in the next octave all the way up the keyboard.
## Octave numbers
The lowest note on the piano is A0. The octave number goes up at C, so the first three notes are A0, B0, and C1. The octaves are numbered all the way up to C8, which is the highest note on the piano.
## Intervals
Intervals are named for the distance, first note inclusive, between the lower note and the higher note. **This distance is measured not in semitones or whole tones, but rather in note names spanned.**
## Examples
So, for example, the distance between C4 and E4 is 3 because it includes C4, D4 and E4. The distance between A6 and E6 is 4 because it spans E6, F6, G6 and A6. Note that the distance between a note and itself is 1. | algorithms | def get_interval(* notes):
n1, n2 = ('CDEFGAB' . index(n[0]) + 7 * int(n[1]) for n in notes)
return 1 + abs(n1 - n2)
| Music Theory: Find the Melodic Interval Between Two Notes | 63fa8aafe6be1f57ad81729a | [
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/63fa8aafe6be1f57ad81729a | 7 kyu |
#### In this Kata you must calulate the number of bounces a ball makes when shot between two walls
---
# Task Details:
+ Mr Reecey has bought a new ball cannon and he lives in a tower block
+ He wants to calulate the number of bounces between the two towers before he shoots his shot
+ The gun is set up to fire with a velocity v, on the tower block height h and the width between them as w
+ The gun is set up parrallel to the horizontal
#### In this diagram the ball bounces twice:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="141.55208mm"
height="251.08958mm"
viewBox="0 0 141.55208 251.08958"
version="1.1"
id="svg5"
inkscape:version="1.1.1 (3bf5ae0d25, 2021-09-20)"
sodipodi:docname="dessin.svg"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<sodipodi:namedview
id="namedview7"
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1.0"
inkscape:pageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:document-units="mm"
showgrid="false"
inkscape:zoom="0.77771465"
inkscape:cx="408.24742"
inkscape:cy="570.26057"
inkscape:window-width="1723"
inkscape:window-height="1111"
inkscape:window-x="476"
inkscape:window-y="176"
inkscape:window-maximized="0"
inkscape:current-layer="layer1" />
<defs
id="defs2" />
<g
inkscape:label="Calque 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(2.8990119,2.6257348)">
<image
width="141.55208"
height="251.08958"
preserveAspectRatio="none"
xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAhcAAAO1CAYAAADdescZAAAABHNCSVQICAgIfAhkiAAAIABJREFU
eJzs3Wd8VGXeh/HfJJlMOqkQEkroCaGEIgpIFRRBQV3LwgKLvSICLjb2AXZZC65LUVfFgrAqawEU
kKKCFAUslBC69BBKElJIbzPPC9YopuOZkuT6vkpO7nv458PzLJfnnDljstlsNqHOevo/j+rzDR+U
fp+yfK9shYGSJDf/Ywq97urSnw3rP0rPjpnn8BkBwBE6X7FPyYdalX5/MMmkAD9PJ05Ud7k5ewDY
z2/DYlj/UfJwt5R+723x17D+o0q//3zDB3r6P486dEYAQN1DXNRR5YVFeWclnh0zj8AAABiKuKiD
Xlo+s1ph8bPyAuOl5TPtOiMAoO4iLuqgycOnauyIxyRV/z6KXwfG2BGPafLwqXadEQBQd3k4ewDY
x89xUJNIeHbMPI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1+SOW+8mIOHjs2dj96SJ6Y/lK8e
/90M6L3xn6ABgEoSF21cTaeafOsfL8jAvrvmxrsuz70P35q+OwzIeV+4JMcd8NlUVVVVeiIAbEBc
tAN1tV3yxY98JV/8yFcqPQUANsszFwBAUeICAChKXAAARYkLAKAocQEAFCUuAICixAUAUJS4AACK
EhcAQFHiAgAoSlwAAEWJCwCgKHEBABQlLgCAosQFAFCUuAAAihIXAEBR4gIAKEpcAABFiQsAoChx
AQAUJS4AgKL+H7VaON6Mnzk/AAAAAElFTkSuQmCC
"
id="image929"
x="-2.8990119"
y="-2.6257348" />
</g>
</svg>
# Technicalities:
+ There are 5 fixed tests and 100 random tests
+ SI units are used for height, width, velocity and g (m, m, m/s, m/s^2 respectively)
+ Mr Reecey uses g = 9.81, ignores air resistance and assumes elastic collisions
+ The ball is modelled as very small
+ Also, remember to return the number of bounces as an integer
| games | g = 9.81
def bounce_count(h, w, v):
t = (2 * h / g) * * 0.5 # time it takes to reach the floor
return (v * t) / / w # number of bounces between walls
| Tower Bouncing | 63f9ec524362170065e5c85b | [
"Physics"
] | https://www.codewars.com/kata/63f9ec524362170065e5c85b | 7 kyu |
Django is a famous back-end framework written in Python. It has a vast list of features including the creation of database tables through "models". You can see an example of such model below:
```
class Person(models.Model):
first_name = models.CharField()
last_name = models.CharField()
```
Apart from creating a table it can perform validation, generate HTML forms, and so on. This is possible thanks to metaclasses. Normally there are better solutions than using metaclasses, but they can be of great help in creating powerful framework interfaces. This goal of this kata is to learn and understand how such frameworks works.
Your task is to implement a class `Model` and classes for its fields to support functionality like in the following example:
```
class User(Model):
first_name = CharField(max_length=30)
last_name = CharField(max_length=50)
email = EmailField()
is_verified = BooleanField(default=False)
date_joined = DateTimeField(auto_now=True)
age = IntegerField(min_value=5, max_value=120, blank=True)
user1 = User(first_name='Liam', last_name='Smith', email='[email protected]')
user1.validate()
print(user1.date_joined) # prints date and time when the instance was created
print(user1.is_verified) # prints False (default value)
user1.age = 256
user1.validate() # raises ValidationError - age is out of range
user2 = User()
user2.validate() # raises ValidationError - first three fields are missing and mandatory
```
The classes which inherit from `Model` should:
* support creation of fields using class-attribute syntax
* have a `validate` method which checks whether all fields are valid
The field types you should implement are described below. Each of them also has parameters `blank` (default `False`), which determines whether `None` is allowed as a value, and `default` (default `None`) which determines the value to be used if nothing was provided at instantiation time of the Model.
* `CharField` - a string with `min_length` (default `0`) and `max_length` (default `None`) parameters, both inclusive if defined
* `IntegerField` - an integer with `min_value` (default `None`) and `max_value` (default `None`) parameters, both inclusive if defined
* `BooleanField` - a boolean
* `DateTimeField` - a datetime with an extra parameter `auto_now` (default `False`). If `auto_now` is `True` and no default value has been provided, the current datetime should be used automatically at Model instantion time.
* `EmailField` - a string in the format of `[email protected]` where `address`, `subdomain`, and `domain` are sequences of alphabetical characters with `min_length` (default `0`) and `max_length` (default `None`) parameters
Each field type should have its own `validate` method which checks whether the provided value has the correct type and satisfies the length/value constraints.
| reference | import datetime
import re
class ValidationError (Exception):
pass
class Field:
def __init__(self, default=None, blank=False):
self . name = ''
self . _default = default
self . blank = blank
@ property
def default(self):
if callable(self . _default):
return self . _default()
return self . _default
def validate(self, value):
if not self . blank and value is None:
raise ValidationError(self . name, 'missing value')
if value is not None and not self . is_type_ok(value):
raise ValidationError(self . name, 'wrong type')
def is_type_ok(self, value):
return True
class CharField (Field):
def __init__(self, min_length=0, max_length=None, * * kwds):
super(CharField, self). __init__(* * kwds)
self . min_length = min_length
self . max_length = max_length
def validate(self, value):
super(CharField, self). validate(value)
if value is not None and self . min_length and len(value) < self . min_length:
raise ValidationError(self . name, 'too short')
if value is not None and self . max_length and len(value) > self . max_length:
raise ValidationError(self . name, 'too long')
def is_type_ok(self, value):
return isinstance(value, str)
class EmailField (CharField):
def validate(self, value):
super(EmailField, self). validate(value)
if value is not None and not re . match(r'[.a-z]+@[a-z]+\.[a-z]{2,6}', value):
raise ValidationError(self . name, 'not valid e-mail')
class BooleanField (Field):
def is_type_ok(self, value):
return type(value) == bool
class DateTimeField (Field):
def __init__(self, auto_now=False, * * kwds):
if auto_now and kwds . get('default') is None:
kwds['default'] = datetime . datetime . now
super(DateTimeField, self). __init__(* * kwds)
self . auto_now = auto_now
def is_type_ok(self, value):
return isinstance(value, datetime . datetime)
class IntegerField (Field):
def __init__(self, min_value=None, max_value=None, * * kwds):
super(IntegerField, self). __init__(* * kwds)
self . min_value = min_value
self . max_value = max_value
def validate(self, value):
super(IntegerField, self). validate(value)
if value is not None and self . min_value and value < self . min_value:
raise ValidationError(self . name, 'too small')
if value is not None and self . max_value and value > self . max_value:
raise ValidationError(self . name, 'too big')
def is_type_ok(self, value):
return type(value) == int
class ModelMeta (type):
def __new__(meta, class_name, bases, class_dict):
new_class_dict = {}
for attribute_name, attribute in class_dict . items():
if not isinstance(attribute, Field):
new_class_dict[attribute_name] = attribute
continue
attribute . name = attribute_name
new_class_dict . setdefault('_attributes_', {}). setdefault(
attribute_name, attribute)
return super(ModelMeta, meta). __new__(meta, class_name, bases, new_class_dict)
class Model (metaclass=ModelMeta):
_attributes_ = {}
def __init__(self, * * kwds):
for attr in self . _attributes_ . values():
setattr(self, attr . name, kwds . get(attr . name, attr . default))
def validate(self):
for attr in self . _attributes_ . values():
attr . validate(getattr(self, attr . name))
| Metaclasses - Simple Django Models | 54b26b130786c9f7ed000555 | [
"Object-oriented Programming",
"Metaprogramming",
"Backend"
] | https://www.codewars.com/kata/54b26b130786c9f7ed000555 | 3 kyu |
We are storing numbers in the nodes of a binary tree. The tree starts at the root node. The root has two child nodes, its leftchild and rightchild. Each of those nodes also has two child nodes, and so on, until we reach the leaf nodes, nodes that have no children. Each node stores one nonnegative integer. The value at every non-leaf node is supposed to be the sum of its two children. But the value at one node is incorrect. Find this node.
Example: Consider the tree below. Note that 13 is the sum of 6 and 7, but the value 15 is incorrect, because 15 != 5 + 9 and 27 != 13 + 15. Clearly the 15 should be changed to 14.
```
27
/ \
13 15
/ \ / \
6 7 5 9
```
The tree will always be <b>full</b> (all non-leaf nodes have exactly 2 children) and <b>perfect</b> (all leaves are on the bottom level). If we consider the root as level 1, its children as level 2, their children as level 3, and so on, the tree will contain at least 3 levels (and no more than 10). <b>If the incorrect value occurs on the leaf level, then the *right* child will always be the incorrect one.</b>
The tree is provided as a list or array (as appropriate to the language), with the nodes in breath-first order. So:<br>
The root is element 0, its leftchild is element 1 and its rightchild is element 2;<br>
Element 1's leftchild is element 3 and its rightchild is element 4;<br>
Element 2's leftchild is element 5 and its rightchild is element 6, and so on.
Your function should return the index of the incorrect node and the value that it should be changed to. In a language that doesn't allow multiple values to be returned, the Solution Setup shows what type to return (e.g. in Java an array of two integers, in C# a tuple of two integers).
Examples:
If the tree is [27, 13, 15, 6, 7, 5, 9], the function should return 2,14.
If the tree is [21, 9, 10, 4, 5, 4, 6, 2, 2, 1, 4, 1, 3, 2, 4], the function should return 0,19.
If the tree is [29, 13, 16, 5, 8, 9, 1], the function should return 6,7.<br>
This is because of the condition "if the incorrect value occurs on the leaf level, then the right child will always be the incorrect one." Since 9 + 1 != 16, the 1 must be changed to 7, rather than changing the 9 to 15.
SOURCE: Programming Competition at the Midwest Instructional Computing Symposium, 2018.
If you like this kata, check out harder binary tree problems,
like [Complete Binary Tree](https://www.codewars.com/kata/5c80b55e95eba7650dc671ea)
and [Sort binary tree by levels](https://www.codewars.com/kata/52bef5e3588c56132c0003bc) .
| reference | def find_incorrect_value(T):
troubles, end = [], len(T) / / 2
for i, v in enumerate(T[: end]):
l = 2 * i + 1
if T[l] + T[l + 1] != v:
troubles . append((i, l + 1))
match troubles:
case[(0, r)]: return 0, T[1] + T[2] # wrong root
case[(i, r)]: return r, T[i] - T[r - 1] # wrong "right" leaf
case[_, (i, r)]: return i, T[r - 1] + T[r] # non leaf & non root
| Finding the Incorrect Value in a Binary Tree | 63f13a354a828b0041979359 | [
"Binary Trees",
"Arrays"
] | https://www.codewars.com/kata/63f13a354a828b0041979359 | 6 kyu |
You are given 2 two-digit numbers. You should check if they are similar by comparing their numbers, and return the result in %.
Example:
1) compare(13,14)=50%;
2) compare(23,22)=50%;
3) compare(15,51)=100%;
4) compare(12,34)=0%.
~~~if:c
In C language you should return P_100, P_50 and P_0 instead of strings "100%", "50%", "0%"
~~~ | algorithms | def compare(a, b):
fir = sorted(str(a))
sec = sorted(str(b))
return '100%' if fir == sec else '50%' if fir[0] in sec or fir[1] in sec else '0%'
| Compare 2 digit numbers | 63f3c61dd27f3c07cc7978de | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/63f3c61dd27f3c07cc7978de | 7 kyu |
## intro
The D'Hondt method, also called the Jefferson method or the greatest divisors method, is a method for allocating seats in parliaments among federal states, or in party-list proportional representation systems.
It belongs to the class of highest-averages methods.
You can read more about that [here](https://en.wikipedia.org/wiki/D%27Hondt_method)
## task
Your task is, given a number of seats for allocate and a list with the number of votes of each party, return a list with the number of seats of each of them has won.
Efficiency is relevant, only solutions with a single iteration on the vote list are supported.
## quick explanation
The method consists of allocating a determined number of points to a list of values by no directly proportional.
If you have to distribute n points you must divide all the initials values into the values in the interval [1,n] both inclusive.
Then you must choose the n greater results previously calculated and give one point to the source value that provides it.
In case of tie, the choosen result must be the one that comes from a minor divisor (that has been done before). The second tiebreaker must be the one that comes from the leftmost element.
## example
For example, if you want to distribute 8 points into values [100000,80000,30000,20000] first divide each value by 1,2,3,4,5,6,7,8:
* A (100000) - > 100000, 50000, 33333, 25000, 20000, 16666, 14285, 12500
* B (80000) - > 80000, 40000, 26666, 20000, 16000, 13333, 11428, 10000
* C (30000) - > 30000, 15000, 10000, 7500, 6000, 5000, 4285, 3750
* D (20000) - > 20000, 10000, 6666, 5000, 4000, 3333, 2857, 2500
Now, you must select the 8 highest values
* A (100000) - > **_100000_**, **_50000_**, **_33333_**, **_25000_**, 20000, 16666, 14285, 12500
* B (80000) - > **_80000_**, **_40000_**, **_26666_**, 20000, 16000, 13333, 11428, 10000
* C (30000) - > **_30000_**, 15000, 10000, 7500, 6000, 5000, 4285, 3750
* D (20000) - > 20000, 10000, 6666, 5000, 4000, 3333, 2857, 2500
We selected 10000 (A), 80000 (B), 50000 (A),40000 (B), 33333 (A), 30000 (C) 26666 (B) and 25000 (A) as solution.
The result is [4,3,1,0] | algorithms | def distribute_seats(num_seats, votes):
res = [0 for _ in votes]
for z in range(num_seats):
mi, _ = max(enumerate(votes), key=lambda p: p[1] / (res[p[0]] + 1))
res[mi] += 1
return res
| D'Hondt method | 63ee1d8892cff420d2c869af | [
"Algorithms"
] | https://www.codewars.com/kata/63ee1d8892cff420d2c869af | 6 kyu |
# Clustering corrupted banks
You work in the Fraud Tracking Organization (FTO) and one of the teams have found a list of corrupted banks. A corrupted bank, in simple words, is a bank that has been tracked lending money to itself. These banks will suffered a penalty fee based on the amount of banks that are in the same clusters. You have two tasks: cluster the corrupted banks and obtain the accumulated reward of the penalty fee.
### Data
The FTO gives you a list of tuples where a tuple `$(i,j)$` means the bank `$i$` lends money to bank `$j$`.
### <u>Assumptions</u>
- Each bank lends money to exactly 1 bank.
- Every bank receives money only from 1 bank. That is, the loans are one-to-one.
For example, `[(1,3), (4,6), (3,1), (6,7), (7,4), (8,8)]` is a possible list of corrupted banks since each bank only lends to one bank and only receives once.
Note that lists of corrupted banks such as `[(1, 3), (2, 3), (3, 1)]` are not possible because the bank 3 is receiving a loan more than once (the assumption 2 is violated). Or in `[(1, 3), (1, 2), (2, 1)]` every bank is receiving just once but the bank 1 is lending more than once (assumption 1 is violated).
### Clustering
Given the list of corrupted banks, you have to cluster them in self-loan cycles so each bank in a cluster, eventually, lends money to itself. Using the example above, you can see the followings clusters: `$\{1,3\}$`, `$\{4,6, 7\}$` and `$\{8\}$`.
### Accumulated reward
The penalty fee is quite simple. Each bank must pay 2 million dollars power to the number of banks in their cluster. Following the example above, the banks `$1,3$` have to pay `$2^2 = 4$` million dollars each. Banks `$\{4,6, 7\}$` must pay `$2^3 = 8$` million dollars each, and the bank `$8$` pays 2 million dollar. Therefore, the accumulated reward the FTO will receive is 34 million dollars.
### Input
The list given to you will satisfy the <u><strong>assumptions</strong></u> and it will be at least 1 bank (be aware it could be thousands of banks).
corrupted_banks: (list) a list of tuples where each tuple `$(i,j)$` means bank `$i$` lends to bank `$j$`. `$i,j$` are integers.
### Output
(int) The accumulated reward the FTO will receive in million dollars (for example, returning 32 means 32 million dollars).
| algorithms | def get_reward(banks: list[tuple[int, int]]):
fees = 0
G = dict(banks)
while G:
n, (i, j) = 1, G . popitem()
while j != i:
n, j = n + 1, G . pop(j)
fees += n * 2 * * n
return fees
| Clustering corrupted banks | 63e9a2ef7774010017975438 | [
"Data Structures",
"Algorithms",
"Set Theory"
] | https://www.codewars.com/kata/63e9a2ef7774010017975438 | 6 kyu |
# The area between the vertex of the parabola and x-axis
## 1-) Warning
If you don't know about the following topics, you will have problems in this kata.
- _Quadratic equations_
- _Parabola_
- _Integral_
## 2-) Explanation
- I will give you 3 values as input in the kata.
These are a , b , c. The value of a will never be given as 0.
These values are the coefficients of the following equation.
```math
f(x) = ax^2 + bx + c
```
- The graph of this equation is a parabola.
- This kata asks you for the area between the vertex of the parabola and x-axis.
- Don't forget area isn't negative.
## 3-) Details
- If the equation hasn't real roots, you should return 0.
Because there isn't any area.
- If the equation has 2 equal real roots, you should return 0. Because 0 is the real area.
- If the equation has 2 unequal real root, you should return the real area.
For example
```
The real area: 35.265720 ---> return 35.265720
```
- Given values is definitely between -4000 with 4000. Because the result should be under the DOUBLE_MAX value.
- I set up the tolerance to 10<sup>-6</sup> for the decimal errors.
## _Letter for you_
__If you like this kata, don't forget to vote please. Take easy...__
# -founded by theprotagonist
| algorithms | def area(a, b, c):
return (d := b * * 2 - 4 * a * c) > 0 and d * * 1.5 / (6 * a * a)
| The area between the vertex of the parabola and x-axis | 63ecc21e12797b06519ad94f | [
"Mathematics"
] | https://www.codewars.com/kata/63ecc21e12797b06519ad94f | 6 kyu |
A researcher is studying cell division in a large number of samples. Counting the cells in each sample is automated, but when she looks at the data, she immediately notices that something is wrong.
The data are arrays of integers corresponding to the number of cells in the sample over time. The first element `data[0]` is the initial count. The next element `data[1]` is the cell count at a later time. `data[2]` is the next count, and so on.
The cells are reproducing, so the elements of the array are supposed to be non-decreasing (there is no cell death), but the automatic cell counter has undercounted. In fact, the researcher has verified that the counter undercounts by `1` at random. The error rate is unknown.
Your task is to create a new non-decreasing array that is minimally different from the `data` array. For example, if the `data = [1, 1, 2, 2, 1, 2, 2, 2, 2]` then the returned array should be `[1, 1, 2, 2, 2, 2, 2, 2, 2]` because `data[4] < data[3]` is clearly an error.
The first entry of the array is correct, and does not require an adjustment.
The array will never be empty.
~~~if:lambdacalc
### Encodings
purity: `LetRec`
numEncoding: `Scott`
export constructors `nil, cons` and deconstructor `foldl` for your `List` encoding.
~~~ | reference | from itertools import accumulate
def cleaned_counts(data):
return [* accumulate(data, max)]
| Noisy Cell Counts | 63ebadc7879f2500315fa07e | [
"Arrays",
"Logic"
] | https://www.codewars.com/kata/63ebadc7879f2500315fa07e | 7 kyu |
In atomic chess (https://en.wikipedia.org/wiki/Atomic_chess) all captures result in an "explosion" which destroys all pieces other than pawns in the 9 squares around and including the square where the capture takes place. The capturing piece and the captured piece are destroyed, whether they are pawns or not.
For example, suppose the white knight on f3 in the following position, (denoted **N**), captures the black pawn on e5 (denoted **p**).
```
8 rnbqkb.r
7 pppp.ppp
6 .....n..
5 ....p...
4 ....P...
3 .....N..
2 PPPP.PPP
1 RNBQKB.R
abcdefgh
```
This causes the N and p, as well as the black knight **n** on f6, to be destroyed. The white pawn **P** on e4 is not affected. The position now is:
```
8 rnbqkb.r
7 pppp.ppp
6 ........
5 ........
4 ....P...
3 ........
2 PPPP.PPP
1 RNBQKB.R
abcdefgh
```
A capture that results in the enemy king being destroyed immediately wins the game! Therefore a king can never capture, because it would destroy itself.
Write a function that takes a chess position and a move and returns the resulting atomic chess position. A move that is not a capture is handled using regular chess rules (https://en.wikipedia.org/wiki/Rules_of_chess).
DETAILS:
(1) Positions are represented as 2-d lists. Uppercase letters denote white pieces and lowercase black. Empty squares are indicated using **"."** (a single period). E.g. the first position above is
```
[ ["r","n","b","q","k","b",".","r"],
["p","p","p","p",".","p","p","p"],
[".",".",".",".",".","n",".","."],
[".",".",".",".","p",".",".","."],
[".",".",".",".","P",".",".","."],
[".",".",".",".",".","N",".","."],
["P","P","P","P",".","P","P","P"],
["R","N","B","Q","K","B",".","R"] ]
```
(2) Moves are denoted using the initial square and destination square, with **"-"** indicating a regular move and **"x"** a capture. E.g. the capture described above is **f3xe5**. If instead the white knight returned to its home square, that would be **f3-g1**.
(3) You do NOT need to verify that the given move is legal. And you will not be given moves that involve castling, pawn promotion, or en-passant. You do not need to detect whether check or mate results from playing the move. Just return the resulting position (as a 2-d list).
Enjoy exploding! | games | def make_atomic_move(position, move):
j, i, x, l, k = move
i, j, k, l = 8 - int(i), ord(j) - 97, 8 - int(k), ord(l) - 97
position[i][j], position[k][l] = '.', position[i][j]
if x == 'x':
for u in range(max(0, k - 1), min(8, k + 2)):
for v in range(max(0, l - 1), min(8, l + 2)):
if k == u and l == v or position[u][v] not in "pP":
position[u][v] = '.'
return position
| Atomic Chess | 63deb6b0acb668000f87f01b | [
"Strings",
"Lists"
] | https://www.codewars.com/kata/63deb6b0acb668000f87f01b | 6 kyu |
# Background
After being inspired by Marie Kondo's teachings on minimalism, you've decided to apply her principles to your computer science work. You've noticed that while keyboard has 104 keys your hands only have ten fingers, and two palms. and so you've made the decision to write code that contains no more than 12 unique characters. Your goal is to help others find the same joy and ergonomic benefits you have found in writing minimalist code.
# Task
Write a Python function joy that takes in a string containing valid, but unjoyful Python code and returns a string containing equivalent, minimalist code with no more than 12 unique characters.
your code should contain no more then 12 unique characters
# Input
A string of python code (len(code) < 10^6), representing the input unjoyful Python code.
# Output
A string representing the equivalent python code, minimalist code that contains no more than 12 unique characters.
Example
```python
a = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9
```
has thirteen chars explicitly: '1','2','3','4','5','6','7','8','9',' ','=','+',and 'a'
here is an example of equivalent joyful code:
```python
a = 45
```
this code only has 5 chars explicitly: '4','5',' ','=', and 'a'
# Notes
* Spaces, new lines, and tabs are considered characters in the code, but end of file is not.
* Your code should have no more than 12 unique characters and as such might be difficult to read, please post your auxilery code in a comment to your answer
* if you think you are cheating, you are not
* For an extra challenge you may want to get the solution under 10 unique chars :) | games | exec(bytes((0b1101010, 0b1101111, 0b1111001, 0b111101, 0b1101100, 0b1100001, 0b1101101, 0b1100010, 0b1100100, 0b1100001, 0b100000, 0b1000011, 0b111010, 0b100111, 0b1100101, 0b1111000, 0b1100101, 0b1100011, 0b101000, 0b1100010, 0b1111001, 0b1110100, 0b1100101, 0b1110011, 0b101000, 0b101000, 0b100111, 0b101011, 0b100111, 0b101100, 0b100111, 0b101110, 0b1101010, 0b1101111, 0b1101001,
0b1101110, 0b101000, 0b1101101, 0b1100001, 0b1110000, 0b101000, 0b1100010, 0b1101001, 0b1101110, 0b101100, 0b1000011, 0b101110, 0b1100101, 0b1101110, 0b1100011, 0b1101111, 0b1100100, 0b1100101, 0b101000, 0b101001, 0b101011, 0b1100010, 0b100111, 0b100000, 0b100000, 0b100111, 0b101001, 0b101001, 0b101011, 0b100111, 0b101001, 0b101001, 0b101001, 0b100111, 0b100000, 0b100000)))
| Joyful Transpiler | 63d4b700bce90f0024a9ca19 | [
"Puzzles",
"Restricted"
] | https://www.codewars.com/kata/63d4b700bce90f0024a9ca19 | 5 kyu |
## <span style="color:#0ae">Task</span>
There is a single-digit [seven segment display](https://en.wikipedia.org/wiki/Seven-segment_display). The display has a problem: there is exactly one dead segment. The dead segment is either always on or always off (we don't know in advance the type of defect).
The display can either be completely blank or show numbers from 0 to 9 (inclusive).
```
How numbers appear on the display:
_ _ _ _ _ _ _ _
| | | _| _| |_| |_ |_ | |_| |_|
|_| | |_ _| | _| |_| | |_| _|
```
Given some numbers/blanks shown on display, try to determine the dead segment.
Note: **all numbers look good on display**, but we know that there is a dead segment.
#### <span style="color:#0ae">Segment names</span>
<svg width="142" height="212">
<rect x="40" y="16" width="62" height="20" style="fill:rgb(192,192,192);stroke-width:1" />
<rect x="106" y="26" width="20" height="77" style="fill:rgb(192,192,192);stroke-width:1" />
<rect x="106" y="109" width="20" height="77" style="fill:rgb(192,192,192);stroke-width:1" />
<rect x="40" y="176" width="62" height="20" style="fill:rgb(192,192,192);stroke-width:1" />
<rect x="16" y="109" width="20" height="77" style="fill:rgb(192,192,192);stroke-width:1" />
<rect x="16" y="26" width="20" height="77" style="fill:rgb(192,192,192);stroke-width:1" />
<rect x="40" y="96" width="62" height="20" style="fill:rgb(192,192,192);stroke-width:1" />
<text x="66" y="33" fill="rgb(112,0,0)" font-size="20px" font-weight="bold" textLength="13" lengthAdjust="spacingAndGlyphs">a</text>
<text x="110" y="72" fill="rgb(112,0,0)" font-size="20px" font-weight="bold" textLength="13" lengthAdjust="spacingAndGlyphs">b</text>
<text x="110" y="155" fill="rgb(112,0,0)" font-size="20px" font-weight="bold" textLength="13" lengthAdjust="spacingAndGlyphs">c</text>
<text x="66" y="194" fill="rgb(112,0,0)" font-size="20px" font-weight="bold" textLength="13" lengthAdjust="spacingAndGlyphs">d</text>
<text x="20" y="155" fill="rgb(112,0,0)" font-size="20px" font-weight="bold" textLength="13" lengthAdjust="spacingAndGlyphs">e</text>
<text x="22" y="72" fill="rgb(112,0,0)" font-size="20px" font-weight="bold" textLength="9" lengthAdjust="spacingAndGlyphs">f</text>
<text x="66" y="111" fill="rgb(112,0,0)" font-size="20px" font-weight="bold" textLength="13" lengthAdjust="spacingAndGlyphs">g</text>
</svg>
## <span style="color:#0ae">Restrictions</span>
Your code should not be longer than **107 bytes**.
## <span style="color:#0ae">Input</span>
##### <span style="color:#0ae">⬬</span> `d` *[list of strings]*
Each element of the list is a 11-chars string that represents a number shown on display. Format: (3 rows, 3 chars per row) ` a ` `fgb` `edc` (the 1st and 3rd chars of the first row are always spaces). Each segment is represented by a char:
- off: space (`' '`)
- on: `'_'` (a,d,g) or `'|'` (b,c,e,f)
Examples:
```python
8: ' _ \n|_|\n|_|'
```\
_
|_|
|_|'''
```
```python
4: ' \n|_|\n |'
```\
|_|
|'''
```
All inputs are valid; there is always at least one string.
## <span style="color:#0ae">Output</span>
- *[string]* or `None`
If the dead segment can be determined:
- the name of dead segment (e.g. `'a'`, `'c'`);
otherwise:
- `None`
## <span style="color:#0ae">Examples</span>
```
|_|
|
```
Input: `[' _ \n| |\n|_|']`
Output `None` (only one number, it can be any segment...)
```
|
|
_
|_
|_|
```
Input: `[' \n |\n |', ' _ \n|_ \n|_|']`
Output: `'c'` (now we know which segment is dead)
```
_
_|
_|
(blank)
_
_|
|_
```
Input: `[' _ \n _|\n _|', ' \n \n ', ' _ \n _|\n|_ ']`
Output: `'f'` (the dead segment can also be off)
| reference | def dead_segment(d): return (h: = [None] + [e[0] for e in zip(' a \nfgb\nedc', * d) if len({* e}) == 2])[len(h) < 3]
| Broken 7-segment display - dead segment [code golf] | 63b9e30e29ba4400317a9ede | [
"Logic",
"Fundamentals",
"Restricted"
] | https://www.codewars.com/kata/63b9e30e29ba4400317a9ede | 5 kyu |
In https://www.codewars.com/kata/63d6dba199b0cc0ff46b5d8a, you were given an integer `n >= 1` and asked to find the determinant of the `n`-by-`n` matrix `m` with elements `m[i][j] = i * j, 1 <= i,j <= n`.
This task is identical, but the matrix elements are given by `m[i][j] = i ** j`; that is, with power instead of multiplication. Also, the case `n = 0` will be tested. Return your answer modulo `1 000 000 007`.
<h1>Code Limit</h1>
No more than 62 characters. Reference solution is 59 characters, so there should be some leeway.
<h1>Inputs</h1>
A non-negative integer `n <= 800`. There will be a few fixed tests plus 400 random tests within this range. | reference | ritual = r = lambda n, p = 1: n < 2 or n * * p * r(n - 1, p + 1) % (10 * * 9 + 7)
| [Code Golf] A Powerful Ritual | 63dab5bfde926c00245b5810 | [
"Mathematics",
"Matrix",
"Restricted"
] | https://www.codewars.com/kata/63dab5bfde926c00245b5810 | 6 kyu |
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Story</summary>
As a child, <a href="https://en.wikipedia.org/wiki/Monsieur_Hulot">Mr. Hulot </a> was a happy boy who loved playing games all by himself. He used to walk around in the city by nightfall, and when he saw an interesting building, he would take pictures of it from different angles. He would then go home and try to figure out how many rooms were lit, based on the windows that are lit on the pictures. This was his <a href="https://www.imdb.com/title/tt0062136/">Playtime (1967)</a>.
</details>
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Task</summary>
##### "Given an array of pictures takes from a building at nightfall, can you help little Hulot figure out how many rooms were lit?"
#### Input
##### pictures
- a 3d-array containing 4 pictures, one for each side of a building in the following order, facing: North, West, South, East (assume all buildings are blocks with 4 sides)
- each picture is a 2d-array containing bits, each representing a window at the associated row and column, that shows a room that is either lit <code>1</code> or not <code>0</code>.
- each room has 1 window for every side that it is anchored to
- each room has a size of 1 unit in height, width and length
- rooms do not let light pass to other rooms, there are walls between them
#### Output
- return a non negative integer with the number of rooms that were lit in the building
- we only care about rooms that Hulot could see, so no rooms inside the building without a window to look outside
#### Directions
##### When looking down at the building from a helicopter, we get the following directions.
```
N
+--+
W | | E
+--+
S
```
</details>
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Examples</summary>
##### The examples show each of the 4 sides of a building from a slight perspective, to give an idea about the architecture of the building.
#### Open Studio
```
pictures: [[[1]], [[1]], [[1]], [[1]]]
return: 1
North
+---+
+---+|
| 1 |+
+---+
West
+---+
+---+|
| 1 |+
+---+
South
+---+
+---+|
| 1 |+
+---+
East
+---+
+---+|
| 1 |+
+---+
```
#### Exclusive Lofts
```
pictures: [[[1],[0],[0]], [[1],[0],[0]], [[1],[0],[0]], [[1],[0],[0]]]
return: 1
North
+---+
+---+|
| 1 ||
| 0 ||
| 0 |+
+---+
West
+---+
+---+|
| 1 ||
| 0 ||
| 0 |+
+---+
South
+---+
+---+|
| 1 ||
| 0 ||
| 0 |+
+---+
East
+---+
+---+|
| 1 ||
| 0 ||
| 0 |+
+---+
```
#### Half Open Studios
```
pictures: [[[1, 1, 0]], [[0]], [[0, 1, 1]], [[1]]]
return: 2
North
+---------+
+---------+|
| 1 1 0 |+
+---------+
West
+---+
+---+ |
+---+ +
| 0 | +
+---+
South
+---------+
+---------+|
| 0 1 1 |+
+---------+
East
+---+
+---+ |
+---+ +
| 1 | +
+---+
```
#### Lofts
```
pictures: [[[1, 1, 0], [1, 0, 1]], [[0], [1]], [[0, 1, 1], [1, 0, 1]], [[1], [1]]]
return: 4
North
+---------+
+---------+|
| 1 1 0 ||
| 1 0 1 |+
+---------+
West
+---+
+---+ |
+---+ |
| 0 | +
| 1 | +
+---+
South
+---------+
+---------+|
| 0 1 1 ||
| 1 0 1 |+
+---------+
East
+---+
+---+ |
+---+ |
| 1 | +
| 1 | +
+---+
```
#### Studios
```
pictures: [[[1, 0]], [[0, 1]], [[1, 1]], [[1, 1]]]
return: 3
North
+------+
+------+ |
| 1 0 | +
+------+
West
+------+
+------+ |
| 0 1 | +
+------+
South
+------+
+------+ |
| 1 1 | +
+------+
East
+------+
+------+ |
| 1 1 | +
+------+
```
#### Appartments
```
pictures: [[[1, 1], [1, 0]], [[1, 1, 1], [0, 1, 1]], [[1, 0], [1, 0]], [[0, 1, 1], [0, 1, 1]]]
return: 9
North
+------+
+------+ |
+------+ |
| 1 1 | +
| 1 0 | +
+------+
West
+---------+
+---------+ |
| 1 1 1 | |
| 0 1 1 | +
+---------+
South
+------+
+------+ |
+------+ |
| 1 0 | +
| 1 0 | +
+------+
East
+---------+
+---------+ |
| 0 1 1 | |
| 0 1 1 | +
+---------+
```
</details> | reference | def count_rooms(Ps):
for i in range(2):
if len(Ps[i][0]) == 1:
return sum(map(sum, Ps[i ^ 1]))
return sum(sum(sum(i and v for i, v in enumerate(row))
for row in face)
for face in Ps)
| Hulot's Playtime | 63d53ca9cce9531953e38b6e | [
"Fundamentals",
"Arrays",
"Geometry"
] | https://www.codewars.com/kata/63d53ca9cce9531953e38b6e | 6 kyu |
## Task
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Task</summary>
##### "Given a positive integer <code>n</code>, return a string representing the front side of a wigwam (Cheyenne style) associated with it."
### Input
##### n
- A positive number representing the magnitude of the wigwam.
- Wigwams can get huge, so range of <code>n</code> is <code>3 ≤ n ≤ 100</code>
### Output
- Return the front side of a wigwam as string.
- Rows are delimited by a newline <code>'\n'</code> and all rows have same length.
- Characters used: <code>'/', '\\', ' ', '_', '-', 'βΎ', ':', 'Β°', 'Β₯'</code>.
- Make sure to include the corrrect amount of leading and trailing whitespace where necessary.
- Be aware there are recurring patterns of ornaments <code>'Β°'</code> on the wigwam.
- Wigwams have an entrance.
- Code length limited to <code>2000</code> characters to prevent hardcoding.
```
'*' shows whitespace to give a better impression how to render the wigwam
n = 5 ****\*/****
*****Β₯*****
****/Β°\****
***/:::\***
**/:_:_:\**
*/:Β°/βΎ\Β°:\*
/:_/***\_:\
```
</details>
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Puzzle</summary>
##### "Can you figure out the pattern and extend wigwams for <code>n > 12</code>?"
```
--------------------------------
wigwam n
--------------------------------
\ / 3
Β₯
/Β°\
//βΎ\\
// \\
\ / 4
Β₯
/Β°\
/:::\
/:/βΎ\:\
/:/ \:\
\ / 5
Β₯
/Β°\
/:::\
/:_:_:\
/:Β°/βΎ\Β°:\
/:_/ \_:\
\ / 6
Β₯
/Β°\
/:::\
/:_:_:\
/:-:Β°:-:\
/:Β°:/βΎ\:Β°:\
/:-:/ \:-:\
\ / 7
Β₯
/Β°\
/:Β°:\
/:_:_:\
/:-:Β°:-:\
/:_:_:_:_:\
/:Β°::/βΎ\::Β°:\
/:_:_/ \_:_:\
\ / 8
Β₯
/Β°\
/:::\
/:Β°:Β°:\
/:-:Β°:-:\
/:_:_:_:_:\
/:-:::::::-:\
/:Β°:_:/βΎ\:_:Β°:\
/:-:::/ \:::-:\
\ / 9
Β₯
/Β°\
/:::\
/:_:_:\
/:Β°:Β°:Β°:\
/:_:_:_:_:\
/:-:::::::-:\
/:_:_:_Β°_:_:_:\
/:Β°::::/βΎ\::::Β°:\
/:_:_:_/ \_:_:_:\
\ / 10
Β₯
/Β°\
/:::\
/:_:_:\
/:-:Β°:-:\
/:Β°:_:_:Β°:\
/:-:::::::-:\
/:_:_:_Β°_:_:_:\
/:-:::::::::::-:\
/:Β°:_:_:/βΎ\:_:_:Β°:\
/:-:::::/ \:::::-:\
\ / 11
Β₯
/Β°\
/:Β°:\
/:_:_:\
/:-:Β°:-:\
/:_:_:_:_:\
/:Β°:::::::Β°:\
/:_:_:_Β°_:_:_:\
/:-:::::::::::-:\
/:_:_:_:_:_:_:_:_:\
/:Β°::::::/βΎ\::::::Β°:\
/:_:_:_:_/ \_:_:_:_:\
\ / 12
Β₯
/Β°\
/:::\
/:Β°:Β°:\
/:-:Β°:-:\
/:_:_:_:_:\
/:-:::::::-:\
/:Β°:_:_Β°_:_:Β°:\
/:-:::::::::::-:\
/:_:_:_:_:_:_:_:_:\
/:-:::::::Β°:::::::-:\
/:Β°:_:_:_:/βΎ\:_:_:_:Β°:\
/:-:::::::/ \:::::::-:\
...
```
</details>
Good luck!
<small>Too easy for you, try code golfing it.</small>
| games | def draw_wigwam(n):
def colons(x): return f':-: { ":" * x } ' [: x]
def zigs(x): return ':_' * (x + 1 >> 1)
def fold(left): return f'/ { left } : { left [:: - 1 ] } \\'
def on_side(i): return n > 4 and i > 2
def above_door(i): return i < n
def dots(i, j, di, dj, go):
while go(i):
bd[i][j] = 'Β°'
i += di
j += dj
S, body = 2 * n + 1, (fold(colons(i) if i & 1 else zigs(i))
for i in range(n))
bd = [[* row . center(S)] for row in ("\\ /", "Β₯", * body)]
bd[n][n - 1: n + 2] = '/βΎ\\'
bd[n + 1][n - 2: n + 3] = '/ \\'
dots(n, 3, - 4, 4, on_side)
dots(2, n, 3, 0, above_door)
dots(n, S - 4, - 4, - 4, on_side)
return '\n' . join(map('' . join, bd))
| Cheyenne Wigwam | 63ca4b3af1504e005da0f25c | [
"Algorithms",
"Puzzles",
"ASCII Art",
"Strings"
] | https://www.codewars.com/kata/63ca4b3af1504e005da0f25c | 5 kyu |
## Problem
Given a list of linear or affine functions `$y_i=a_i x + c_i$` (represented as tuples `$(a_i,c_i)$`), compute the sum of absolute value of the functions: `$\Sigma\lvert y_i \lvert$` and return the result as a series of sorted intervals, defined as 4-uples: `$(x_{start,j} ,x_{end,j},a_j,c_j)$`.
## Example:
Given the two equations:
* `$y=0,25 x -3$` (red in the figure below)
* `$y=-x+1$` (blue in the figure below)
The resulting function `$\lvert 0,25 x -3 \lvert + \lvert -x+1 \lvert$` (green in the figure below) is defined with 3 intervals:
- `$y=-1,25 x + 4$` on `$[-β,1]$`
- `$y= 0,75 x + 2$` on `$[1,12]$`
- `$y= 1,25 x - 4$` on `$[12,+β]$`
<svg xmlns="http://www.w3.org/2000/svg" id="Layer_1" x="0" y="0" version="1.1" viewBox="0 0 800 800" style="width:400px;height:400px" xml:space="preserve"><style>.st1,.st2,.st3{fill:none;stroke:#000;stroke-width:2;stroke-miterlimit:20;stroke-opacity:.2}.st2,.st3{stroke-opacity:.25}.st3{stroke-width:3;stroke-opacity:.9}.st4{fill:none;stroke:#fff;stroke-width:6}.st5{font-family:'ArialMT'}.st6{font-size:28px}.st7,.st8{fill:none;stroke:#c74440;stroke-width:5;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:20;stroke-opacity:.9}.st8{stroke:#2d70b3}.st10{fill:#c60505}.st11{fill:#0661c4}.st12{fill:#368404}</style><g transform="scale(2)"><path id="background-6e957e33" fill="#fff" d="M0 0h400v400H0z"/><g id="graphpaper-6e957e33"><g id="grid-6e957e33"><path d="M17.5 0v400M44.5 0v400M72.5 0v400M100.5 0v400M156.5 0v400M183.5 0v400M211.5 0v400M239.5 0v400M267.5 0v400M295.5 0v400M322.5 0v400M350.5 0v400M378.5 0v400M0 387.5h400M0 360.5h400M0 332.5h400M0 304.5h400M0 276.5h400M0 248.5h400M0 193.5h400M0 165.5h400M0 137.5h400M0 109.5h400M0 82.5h400M0 54.5h400M0 26.5h400" class="st1"/><path d="M267.5 0v400M0 360.5h400M0 82.5h400" class="st2"/></g><g id="axis-6e957e33"><path id="yaxis-6e957e33" d="M129 0v400" class="st3"/><path id="xaxis-6e957e33" d="M0 222h400" class="st3"/><text class="st4 st5 st6" transform="matrix(.5 0 0 .5 115.96 237.449)">0</text><text class="st5 st6" transform="matrix(.5 0 0 .5 115.96 237.449)">0</text><text class="st4 st5 st6" transform="matrix(.5 0 0 .5 259.975 237.449)">10</text><text class="st5 st6" transform="matrix(.5 0 0 .5 259.975 237.449)">10</text><g><text class="st4 st5 st6" transform="matrix(.5 0 0 .5 103.513 364.462)">-10</text><text class="st5 st6" transform="matrix(.5 0 0 .5 103.513 364.462)">-10</text></g><g><text class="st4 st5 st6" transform="matrix(.5 0 0 .5 108.175 86.436)">10</text><text class="st5 st6" transform="matrix(.5 0 0 .5 108.175 86.436)">10</text></g></g></g><g id="expressions-6e957e33"><path id="sketch-6e957e33" d="M-.5 295l400-100" class="st7"/><path id="sketch-6e957e33_1_" d="M-.5 78.5l327 327" class="st8"/><path id="sketch-6e957e33_2_" fill="none" stroke="#388c46" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="20" stroke-opacity=".9" stroke-width="5" d="M-.5 4.6h0l142.6 178.3L295.4 67.8 354-5.5"/></g></g><path d="M124.4 586.2c0 8-3 12.3-8.1 12.3-4.6 0-7.7-4.3-7.7-12 0-7.8 3.4-12.2 8.1-12.2 4.9.1 7.7 4.5 7.7 11.9zm-12.7.4c0 6.1 1.9 9.5 4.8 9.5 3.2 0 4.8-3.8 4.8-9.8 0-5.8-1.5-9.5-4.8-9.5-2.8.1-4.8 3.4-4.8 9.8z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 1 1.2 1.9 1.8 2.8h.1c.6-1 1.2-1.9 1.7-2.9l2.4-3.7h3.4l-5.9 8.4 6.1 9h-3.6l-2.6-3.9c-.7-1-1.3-2-1.9-3h-.1l-1.8 3-2.5 3.9H412l6.2-8.9-5.9-8.5h3.6zM446.1 352.5v2.3h-8.9v-2.3h8.9zM457.2 359.8c.9.6 3 1.5 5.2 1.5 4.1 0 5.3-2.6 5.3-4.5 0-3.3-3-4.7-6-4.7h-1.8v-2.4h1.8c2.3 0 5.2-1.2 5.2-4 0-1.9-1.2-3.5-4.1-3.5-1.9 0-3.7.8-4.7 1.5l-.8-2.3c1.2-.9 3.6-1.8 6.1-1.8 4.6 0 6.7 2.7 6.7 5.6 0 2.4-1.4 4.5-4.3 5.5v.1c2.9.6 5.2 2.7 5.2 6 0 3.7-2.9 7-8.5 7-2.6 0-4.9-.8-6.1-1.6l.8-2.4zM478.8 336.4v36h-2.4v-36h2.4zM501.4 344.3v8.5h8.1v2.2h-8.1v8.5h-2.3V355H491v-2.2h8.1v-8.5h2.3zM524.1 336.4v36h-2.4v-36h2.4zM537.2 352.5v2.3h-8.9v-2.3h8.9zM546.7 343l-4.1 2.2-.6-2.4 5.1-2.7h2.7v23.4h-3.1V343zM560.8 346l2.5 3.7c.6 1 1.2 1.9 1.8 2.8h.1c.6-1 1.2-1.9 1.7-2.9l2.4-3.7h3.4l-5.9 8.4 6.1 9h-3.6l-2.6-3.9c-.7-1-1.3-2-1.9-3h-.1l-1.8 3-2.5 3.9H557l6.2-8.9-5.9-8.5h3.5zM592.9 344.3v8.5h8.1v2.2h-8.1v8.5h-2.3V355h-8.1v-2.2h8.1v-8.5h2.3zM618.6 343l-4.1 2.2-.6-2.4 5.1-2.7h2.7v23.4h-3.1V343zM634.1 336.4v36h-2.4v-36h2.4z" class="st12"/></g></svg>
<div style="font-size:75%;color:gray;font-style:italic;">(Picture by <a href="https://www.codewars.com/users/5a8590a2ba1bb5d22c00011f">awesomead</a>)</div><br>
Hence the result:
```python
# inf = float('inf')
[(-inf, 1.0, -1.25, 4.0), (1.0, 12.0, 0.75, 2.0), (12.0, inf, 1.25, -4.0)]
```
## Inputs
* Input list length: `1 <= size <= 1000`
* Coefficients: `-1000 <= a <= 1000`, `-1000 <= c <= 1000`.
## Outputs
* Sorted list of 4 elements tuples
* Empty ranges must be excluded
* Floats are compared with a tolerance of `0.1` in the tests so you don't need to worry about floating point errors
| algorithms | from math import inf
def expand(lst):
intervals = [(- inf, inf, 0.0, 0.0)]
for a, c in lst:
x0, a, c = (inf, 0.0, abs(c)) if a == 0 else (- c /
a, - a, - c) if a > 0 else (- c / a, a, c)
i, o = next((i, o) for i, o in enumerate(intervals) if o[0] <= x0 <= o[1])
intervals = [(u, v, x + a, y + c) for u, v, x, y in intervals[: i]] + \
[(o[0], x0, o[2] + a, o[3] + c)] * (x0 > o[0]) + \
[(x0, o[1], o[2] - a, o[3] - c)] * (x0 < o[1]) + \
[(u, v, x - a, y - c) for u, v, x, y in intervals[i + 1:]]
return intervals
| Expand Absolute Values | 60bcabf6b3a07c00195f774c | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/60bcabf6b3a07c00195f774c | 5 kyu |
### Sudoku Background
Sudoku is a game played on a 9x9 grid. The goal of the game is to fill all cells of the grid with digits from 1 to 9, so that each column, each row, and each of the nine 3x3 sub-grids (also known as blocks) contain all of the digits from 1 to 9.
More info at: http://en.wikipedia.org/wiki/Sudoku
### Sudoku Solution Validator
Write a function that accepts a Sudoku board, and returns true if it is a valid Sudoku solution, or false otherwise. The cells of the input Sudoku board may also contain 0's, which will represent empty cells. Boards containing one or more zeroes are considered to be invalid solutions.
### Examples
```
Valid board:
5 3 4|6 7 8|9 1 2
6 7 2|1 9 5|3 4 8
1 9 8|3 4 2|5 6 7
-----+-----+-----
8 5 9|7 6 1|4 2 3
4 2 6|8 5 3|7 9 1
7 1 3|9 2 4|8 5 6
-----+-----+-----
9 6 1|5 3 7|2 8 4
2 8 7|4 1 9|6 3 5
3 4 5|2 8 6|1 7 9
```
```
Invalid board:
This column has two 3's
v
This cell has a 0 > 0 3 4|6 7 8|9 1 2
6 7 2|1 9 5|3 4 8
1 9 8|3 4 2|5 6 7
-----+-----+-----
8 5 9|7 6 1|4 2 3
4 2 6|8 5 3|7 9 1
7 1 3|9 2 4|8 5 6
-----+-----+-----
This box has /9 6 1|5 3 7|2 8 4
two 3's >| 2 8 3|4 1 9|6 3 5 < This row has two 3's
\3 4 5|2 8 6|1 7 9
```
### Details
- All inputs are guaranteed to be 2D boards of size 9x9 with possible values in range 0-9.
- Rows, columns and blocks (3x3 small squares) must contain each number from range 1-9 exactly once.
- User solution must not modify input boards.
~~~if:lambdacalc
### Encodings
purity: `LetRec`
numEncoding: `Scott`
export constructors `nil, cons` for your `List` encoding
export deconstructor `if` for your `Boolean` encoding
### Performance
There are 18 Example tests and 14 + 25 Submit tests. Performance can be a bottleneck.
~~~ | reference | def validate_sudoku(board):
elements = set(range(1, 10))
# row
for b in board:
if set(b) != elements:
return False
# column
for b in zip(* board):
if set(b) != elements:
return False
# magic squares
for i in range(3, 10, 3):
for j in range(3, 10, 3):
if elements != {(board[q][w]) for w in range(j - 3, j) for q in range(i - 3, i)}:
return False
return True
| Sudoku board validator | 63d1bac72de941033dbf87ae | [
"Algorithms",
"Games"
] | https://www.codewars.com/kata/63d1bac72de941033dbf87ae | 6 kyu |
# Set Reducer
### Intro
These arrays are too long! Let's reduce them!
### Description
Write a function that takes in an array of integers from 0-9, and returns a new array:
* Numbers with no identical numbers preceding or following it returns a 1: ``2, 4, 9 => 1, 1, 1``
* Sequential groups of identical numbers return their count: ``6, 6, 6, 6 => 4``
*Example*
``[0, 4, 6, 8, 8, 8, 5, 5, 7] => [1, 1, 1, 3, 2, 1]``
Your function should then repeat the process on the resulting array, and on the resulting array of that, **until it returns a single integer**:
``[0, 4, 6, 8, 8, 8, 5, 5, 7] =>
[1, 1, 1, 3, 2, 1] =>
[3, 1, 1, 1] =>
[1, 3] =>
[1, 1] =>
[2]``
When your function has reduced the array to a single integer following these rules, it should return that integer.
``[2] => 2``
### Rules and assertions
* All test arrays will be 2+ in length
* All integers in the test arrays will be positive numbers from 0 - 9
* You should return an integer, not an array with 1 element
### Visual example
 | algorithms | from itertools import groupby
def set_reducer(inp):
while len(inp) > 1:
inp = [len(list(b)) for a, b in groupby(inp)]
return inp[0]
| Set Reducer | 63cbe409959401003e09978b | [
"Recursion",
"Algorithms",
"Logic",
"Arrays"
] | https://www.codewars.com/kata/63cbe409959401003e09978b | 7 kyu |
# Description
You can paint an asperand by pixels in three steps:
1. First you paint the inner square, with a side of ```k```.
2. Then you need to paint one pixel, that's laying diagonally relative to the inner square that you just painted ( _the bottom-right corner of the inner square is touching the top-left corner of the pixel_ ). Let's call it the "bridge".
3. Finally, you will need to paint the outer shape, connected diagonally to the "bridge" ( _see the picture for more information_ ).
Here are some examples of this:

Your task is to find the number of pixels that need to be painted, for different `k`:
```javascript
k = 1 => 11
k = 2 => 18
k = 3 => 26
k = 4 => 34
# Limitations are 1 β€ k β€ 1e9
```
_The idea for this kata was taken from the Ukrainian Informatics Olympiad 2023._ | games | def count_pixels(k): return 8 * k + 2 + (k < 2)
| Asperand pixel counting | 63d54b5d05992e0046752389 | [
"Algebra",
"Puzzles"
] | https://www.codewars.com/kata/63d54b5d05992e0046752389 | 7 kyu |
# Boole
[Wikipedia](https://en.wikipedia.org/wiki/George_Boole): George Boole ( 1815 β 1864 ) was a largely self-taught English mathematician, philosopher, and logician. He is best known as the author of _The Laws of Thought_ ( 1854 ), which contains Boolean algebra.
[More Wikipedia](https://en.wikipedia.org/wiki/Boolean_data_type): The `Boolean` is a data type that has one of two possible values. It is named after George Boole.
This kata is about _encoding_ `Boolean`s. The above tells us the essence of a `Boolean` is that it can take on either one of exactly two values. Usually, these are named `True` and `False`, but they might be `Yes` and `No`, `"True"` and `"False"`, `0` and `1`, `spin up` and `spin down`, or any two distinct values you wish to use.
Computers are commonly thought of as working in binary, but even the binary digits ( bits ) of your laptop are encodings. `0` might be a high voltage and `1` a low voltage, or `0` might be spin down and `1` spin up in your expensive latest IBM quantum-superlaptop.
Taking things up another level of abstraction, your favourite programming language might have generic enumerated data types, like
```
Colour = Red | Orange | Yellow | Green | Blue | Purple
```
or
```
Answer = Yes | No
```
Notice how `Answer` looks exactly like a `Boolean` ? In actual fact, `Answer` _is_ a `Boolean` data type: it allows for exactly two values. `Answer` is an _encoding_ of a `Boolean`, though it is usually written as `Boolean = False | True`. The encoding of the, Platonian if you will, `Boolean` does not matter; the meaning we assign to the values means the encoding is for all practical purposes transparent; the encoded and the underlying values are identical as long as we agree on the encoding. In other words, an encoding is an isomorphism.
Little interlude on enumerated data types: `Red` .. `Purple`, `Yes` and `No` are called `Constructor`s. They can be nullary values, like here, or they might wrap ( an ) other value(s), adding information to their argument(s), as in `Pair Red Purple` or `Pair Yes Yes`. ( This kata will restrict itself to nullary `Constructor`s. ) Note that even a nullary `Constructor` adds information to its zero arguments; in this case, the `Constructor` itself is all the information.
"as long as we agree on the encoding" means we are free to _choose_ an ( any ) encoding, as long as our audience agrees with us on it. Dear audience, let us agree to encode our `Boolean`s as functions, because (1) we can, (2) it works, and (3) it only requires very basic maths; it requires no hardware and no additional levels of encodings. Now invoke Dana Scott.
# Scott
[Wikipedia](https://en.wikipedia.org/wiki/Dana_Scott): Dana Scott ( 1932 - ) is an American logician. His work on automata theory earned him the Turing Award in 1976.
[More Wikipedia](https://en.wikipedia.org/wiki/Mogensen%E2%80%93Scott_encoding): Scott encoding is a way to represent ( recursive ) data types in the lambda calculus. Church encoding performs a similar function.
In the lambda calculus, all we have are variables and functions, but fortunately we agreed on encoding `Boolean`s as functions, so we're good. So how does Scott encoding work?
We have `Boolean = False | True`. The `Constructor`s are `False` and `True`.
For every `Constructor`, define a curried<sup>*</sup> function that takes as many arguments as there are `Constructor`s ( keeping arguments in order of their enumeration in the type definition ), and returns one of them:
```javascript
False = f => t => f
True = f => t => t
```
```python
false = lambda f: lambda t: f
true = lambda f: lambda t: t
```
<sup>*</sup> [this kata](https://www.codewars.com/kata/currying-functions-multiply-all-elements-in-an-array), and the linked video, explain currying.
`False` and `True` are _encodings of_ the two possible `Boolean`s, but in shorthand, they _are_ the two possible `Boolean`s. Whenever we encounter either value, we know there's an abstract Platonian Form of truthiness, and whenever we encounter the Platonian form, we know we can encode it. So from now on, let's ignore the difference between encoding and underlying value; whenever we speak of `Boolean`s, we mean the encodings. Because there is no real difference.
Still, `False` and `True` are _functions_ here. Because they are encoded, we can call them, with arguments. If you write the functions `False` and `True`, the Example Tests will feed them arguments and inspect the answers.
# Fire the Nukes or Keep the Peace ?
So what do you do with `Boolean`s? You make choices to do things.
if False then fire(nukes) else keep(peace) ;
if True then pay(bigMoney) else ridicule(seller) ;
Or you choose between two simple values.
if False then Champagne else Water ;
if True then Rich else Poor ;
It doesn't matter what the options are, but it is convenient for them to be of the same type. In that case, the whole thing is an _expression,_ of the same type as the choices, be it `SideEffect` ( verb ), `Thing` ( noun ), or `Property` ( adjective ).
`then` and `else` have no semantic meaning of their own, so it is possible to write a curried function call
if (boolean) (x) (y)
where `boolean` is a `Boolean` variable and `x, y` are variables, arbitrarily but identically typed.
How would that `function if` look? Have a look at the Example Tests, see how it's used, what outputs it expects for what inputs, and write it.
# This concludes today's lecture.
Boolean algebra is left as an exercise for the reader. There is a [kata](https://www.codewars.com/kata/church-booleans) on it, which uses Church encoding instead of Scott encoding - for `Boolean`s the two differ only in the ordering of the `Constructor`s and thus the ordering of the arguments.
[Next time](https://www.codewars.com/kata/scott-orderings-and-more): `Ordering`, `Unit` and `Void`. `Ordering`s have _three_ possible values ( `LT, EQ, GT` or `< 0, == 0, > 0` ); `Unit` has _one_ ( `Unit` or `()` ); `Void` has _none_ and is quite the brain-wrecker. | algorithms | def false(a): return lambda b: a
def true(a): return lambda b: b
def iff(x): return lambda a: lambda b: x(b)(a)
| Scott Booleans | 63d1ba782de94107abbf85c3 | [
"Data Structures",
"Functional Programming"
] | https://www.codewars.com/kata/63d1ba782de94107abbf85c3 | 7 kyu |
> Skip ```Situation``` and go straight to ```Task``` if you care not about the story (all you need to solve the kata will be contained under "Task").
> The answers are hidden to prevent users from figuring out the solution from the results of the tests.
<h1> Situation </h1>
Every year, in an ancient civilization, all the villagers would gather for the ritual that would ensure their survival. <br>
All of the sheep in the village would be arranged in a square grid. Then, a sacrifice to the gods would be performed, granting the people **food and riches**. <br>
However, their rewards for the sacrifice *weren't always the same*, **largely depending on the layout of the sheep**.
Unbeknownst to the villagers, the gods had a very systematic method for rewarding them.
> Our generosity towards you humans shall be proportional to the **determinant of the matrix** formed by the sheep you provide us.
One day, a new emperor, ***"Yushi.py the II"***, decides on a new formation for the sheep, believing it would bring great riches to his reign. <br>
The sheep would be placed in the following manner: <br>
- Consider a matrix with rows and columns with indices beginning at 1 and the first square in the upper left corner.
- The number of sheep in a given square shall be the product of the indices of the rows and the columns.
- In more programmer friendly words: <br>
The elements of a matrix ```m``` are such that ```m[i][j] = (i + 1) * (j + 1)```.
Here are the formations used in the first three rituals:
```python
[1] [1, 2] [1, 2, 3]
[2, 4] [2, 4, 6]
[3, 6, 9]
```
As a historian, you stumble across this civilization and wish to try to explain their sudden decay after the rule of their new emperor. <br>
To do so, you decide to determine the riches received by the villagers, according to the new disposition of sheep decided by ***Yushi.py the II***. <br><br>
<h1> Task </h1>
Let's say a matrix ```m``` exists such that the value of each square is the **product of the indices of the rows and columns**, considering that the indices start at 1 and the first square is in the upper left corner.
Examples of the matrix:
```python
n = 1 -> [1] n = 2 -> [1, 2] n = 3 -> [1, 2, 3]
[2, 4] [2, 4, 6]
[3, 6, 9]
```
Given ```n```, the size of the square matrix, your task is to create a function, ```ritual```, that returns the determinant of the matrix.
***Do not return the matrix; return its determinant*** <br><br>
<h1> Input </h1>
You will be given a positive integer ```n```, meaning, don`t worry about input validation. <br><br>
<h1> Maximum Length </h1>
The length of your code must not exceed ```19``` characters. <br><br>
<h1> Random Tests </h1>
There will be a total of 100 random tests. They will be separated into 4 categories: small, medium, big, and huge tests, with 25 tests each; their range is: <br>
- Small: ```1 <= n <= 9```
- Medium: ```10 <= n <= 1_000```
- Big: ```100_000 <= n <= 1_000_000```
- Huge: ```2 ** 32 <= n <= 2 ** 64``` | algorithms | ritual = 1 . __eq__
| [Code Golf] An Interesting Ritual | 63d6dba199b0cc0ff46b5d8a | [
"Mathematics",
"Matrix",
"Restricted"
] | https://www.codewars.com/kata/63d6dba199b0cc0ff46b5d8a | 7 kyu |
[Previously in the paper and pencil series...](https://www.codewars.com/kata/639d78b09547e900647a80c7)
Story (Which you could skip)
------
As you finished researching the languages of humans, you walked across the maths history of humans. However, you have to prove yourself to the human beings that you are smart enough and qualified to understand their math. They are telling you to find formulas for a single 'x^2' sequence
***
### Task
Write a function with 3 parameter of integers, representing the first 3 terms of the single 'x^2' sequence, with that, you have to return a list/tuple which contains the formula of this sequence and the next two numbers. The input will always be valid. You should form your formula in the normal way that you write it out (e.g. You don't write x^2+1x+0, but instead you do x^2+x...)
### Input
3 parameters representing the first 3 terms of a quadratic sequence.
### Output
A tuple / array, with the quadratic formula and fourth, fifth term of the sequence.
### Example
~~~if:javascript,typescript
```javascript
[4, 9, 16] ---> ['x^2+2x+1', 25, 36]
[1, 4, 9] ---> ['x^2', 16, 25]
```
~~~
```text
(4,9,16) ---> ('x^2+2x+1',25,36)
(1,4,9) ---> ('x^2',16,25)
```
### Precondition
```text
number of tests = 666
x^2+bx+c
-500<=b,c<=500
```
### Notes
+ this is my second time making a kata, please help me to spot any issues, thank you!
+ all tests will be in this form: x^2+bx+c
+ any translations will be appreciated!
+ wish everyone a happy Chinese new year! | games | # I hate formatting equations
def quadratic_formula(y1, y2, _):
b = y2 - y1 - 3
c = y1 - b - 1
s = f"x^2 { '' if b == 0 else '+x' if b == 1 else '-x' if b == - 1 else f' { b : + d } x' }{ '' if c == 0 else f' { c : + d } ' } "
return s, 16 + 4 * b + c, 25 + 5 * b + c
| #Paper and pencil 2: Finding the formula of a single 'x'^2 sequence and the next terms | 63bd8cc3a78e0578b608ac80 | [
"Puzzles",
"Mathematics",
"Algebra",
"Logic"
] | https://www.codewars.com/kata/63bd8cc3a78e0578b608ac80 | 6 kyu |
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Task</summary>
##### "There is a game, where four letters <code>A, B, C, D</code> are surrounded by numbers. Each letter wants to score as much points as possible, while the numbers are moving around them."
```
Example of a game grid
07004
0 A 0
0D7B8
5 C 4
02000
```
### Input
##### numbers
- an array of non negative integers representing the points available to score
### Output
- return a map / dictionary with the scores for each letter when the game ended (see solution setup of your language for more details)
### Initial Setup
- 17 non negative integers are available, of which 16 on the border and the last one in the center
- going from left to right in the array of numbers, each border number starts the game on the perimeter, starting at the top-left corner, and going in a clockwise direction
- the game is played by 4 letters: <code>A, B, C, D</code>
- the letters have fixed positions in the game, respectively at the top, right, bottom and left of the center number
- all letters touch 1 border number and the center number
- at least 1 number with value <code>0</code> is guaranteed to be available
- all numbers have a value: <code>0 <= n <= 9</code>
- the game is played in rounds and at the end of each round, numbers move to the next position
```
Example:
numbers: [0,7,0,0,4,0,8,4,0,0,0,2,0,5,0,0,7]
game:
07004
0 A 0
0D7B8
5 C 4
02000
```
### Structure
- letters start with a score of <code>0</code> and want to score points
- as long as the objective has not been reached, the game is played in consecutive rounds
- each round has the following structure:
- letters try to score points
- numbers make progress
- objective is checked
- return game result when objective is met
- continue with next round otherwise
#### Letters trying to score points
- the actions of each letter are independant from those of another, meaning the order in which letters are picked to score points is irrelevant
- a letter has to obey by the following rules:
- (note that an actual game consists of 4 letters, while these examples may contain fewer)
- if the number on the border which is aligned with the center and the letter, and the center are both <code>0</code>, no points can be scored because no points are available to score
```
00000
0 A 0
0 0 0
0 0
00000
```
- if the number on the border which is aligned with the center and the letter, and the center are both different from <code>0</code>, no points can be scored because this letter is currently blocked by those numbers
```
00500
0 A 0
0 2 0
0 0
00000
```
- if the number on the border which is aligned with the center and the letter is <code>0</code> and the center number isn't:
- the letter scores the amount of the center number (<code>A: +2, B: +2</code> in example)
- the border number becomes the center number subtracted by one (<code>border numbers of A and B: (2 - 1) = 1</code> in example)
- the center number gets reset to <code>0</code>, but only <b>after</b> all numbers have tried scoring in this round
```
00000 00100
0 A 0 0 A 0
0 2B0 -> 0 0B1
0 0 0 0
00000 00000
```
- if the center number is <code>0</code> and the number on the border which is aligned with the center and the letter isn't:
- the letter scores the amount of the border number (<code>A: +4, B: +3</code> in example)
- the center number is increased with the border number subtracted by one (<code>center: (4 - 1) + (3 - 1) = 5</code> in example), but only <b>after</b> all numbers have tried scoring in this round, and the resulting value in the center will be the sum of moves performed by the individual letters
- the border number gets reset to <code>0</code>
```
00400 00000
0 A 0 0 A 0
0 0B3 -> 0 5B0
0 0 0 0
00000 00000
```
#### Numbers make progress
- the border numbers rotate clockwise
- the center number is stationary, so it doesn't move
```
Example:
Note that the last number is the center number, it remains fixed as last element in the array.
numbers before rotation: [0,3,0,0,4,0,8,4,0,0,0,2,0,5,0,1,7]
numbers after rotation : [1,0,3,0,0,4,0,8,4,0,0,0,2,0,5,0,7]
```
#### Checking objective
- the game ends when either:
- at least one letter reached a score of <code>100</code> or more
- all numbers have been decreased to <code>0</code>
</details>
<details>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Tutorial</summary>
##### Let's walk through the first sample test, and see how the game progresses step by step.
```
numbers: [0,0,2,2,0,1,0,0,0,0,0,0,1,0,0,0,0]
game:
00220
0 A 1
0D0B0
0 C 0
10000
score at end of game: { A: 4, B: 3, C: 3, D: 3 }
round score
------------------------------------------------
round 1: { A: 2, B: 0, C: 0, D: 0 }
00002
0 A 0
0D1B1
1 C 0
00000
round 2: { A: 3, B: 0, C: 1, D: 1 }
00000
0 A 2
1D0B0
0 C 1
00000
round 3: { A: 3, B: 0, C: 1, D: 2 }
00000
0 A 0
0D0B2
0 C 0
00001
round 4: { A: 3, B: 2, C: 1, D: 2 }
00000
0 A 0
0D1B0
0 C 0
00010
round 5: { A: 4, B: 3, C: 2, D: 3 }
00000
0 A 0
0D0B0
0 C 0
00100
round 6: { A: 4, B: 3, C: 3, D: 3 }
00000
0 A 0
0D0B0
0 C 0
00000
```
</details>
<details>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Examples</summary>
##### These examples correspond to the sample tests. For each test, a visual representation of the initial game setup is provided, together with the total score of each letter when the game ends, and the expected result to return. Use the rules described in section <b>Game -> Structure</b> to pass the tests.
#### Sample Test 1
```
numbers: [0,0,2,2,0,1,0,0,0,0,0,0,1,0,0,0,0]
game:
00220
0 A 1
0D0B0
0 C 0
10000
score at end of game: { A: 4, B: 3, C: 3, D: 3 }
```
#### Sample Test 2
```
numbers: [0,2,0,2,0,0,2,0,0,0,0,2,0,1,2,0,0]
game:
02020
0 A 0
2D0B2
1 C 0
02000
score at end of game: { A: 5, B: 12, C: 7, D: 9 }
```
#### Sample Test 3
```
numbers: [0,0,1,1,2,1,0,0,0,0,0,0,0,0,0,0,2]
game:
00112
0 A 1
0D2B0
0 C 0
00000
score at end of game: { A: 2, B: 6, C: 5, D: 4 }
```
#### Sample Test 4
```
numbers: [0,7,0,0,4,0,8,4,0,0,0,2,0,5,0,0,7]
game:
07004
0 A 0
0D7B8
5 C 4
02000
score at end of game: { A: 118, B: 94, C: 110, D: 120 }
```
</details>
<details>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Input Constraints</summary>
- no specific performance criteria, though make sure to guard against infinite loops
- reference solution solves all test cases < 1 second
- random tests
- 200 sparse random tests with 0 <= max number <= 1
- 200 dense random tests with 0 <= max number <= 1
- 200 sparse random tests with 0 <= max number <= 2
- 200 dense random tests with 0 <= max number <= 2
- 200 sparse random tests with 0 <= max number <= 5
- 200 dense random tests with 0 <= max number <= 5
- 200 sparse random tests with 0 <= max number <= 9
- 200 dense random tests with 0 <= max number <= 9
</details> | games | BORDERS = {'A': 2, 'B': 6, 'C': 10, 'D': 14}
def play(nums):
nums = nums[:]
center = nums . pop()
scores = {k: 0 for k in BORDERS}
while all(v < 100 for v in scores . values()) and (any(nums) or center):
scored = 0
for c, i in BORDERS . items():
b = nums[i]
if bool(center) ^ bool(b):
scores[c] += center + b
scored = 1
if center:
for c, i in BORDERS . items():
if not nums[i]:
nums[i] = center - 1
if scored:
center = 0
else:
for c, i in BORDERS . items():
if nums[i]:
center += nums[i] - 1
nums[i] = 0
nums = nums[- 1:] + nums[: - 1]
return scores
| Letters and Numbers Game | 63c1d93acdd8ca0065e35963 | [
"Puzzles",
"Games",
"Arrays"
] | https://www.codewars.com/kata/63c1d93acdd8ca0065e35963 | 6 kyu |
## SITUATION
One day, as you wake up, you have a terrible realization:<br>
*You have **magically**Β time-traveled, going all the way back to high school.*
Ignoring the weird scientific implications of this event, you focus on what's truly important: **HOMEWORK**
You see, your teacher has handed out hours' worth of math assignments for you. However, you have better things to do, such as trying to figure out how you even ended up in this situation.
Using your retained knowledge, in order to save time, you decide to create a program to do your homework for you, even if it takes way longer than just being a normal person and doing it yourself. <br>
## TASK
~~~if:javascript,typescript
Write a function / method called `polynomialProduct()`, which takes two strings representing polynomials as input and returns another string representing the product of those polynomials.
~~~
~~~if-not:javascript,typescript
Write a function / method called `polynomial_product()`, which takes two strings representing polynomials as input and returns another string representing the product of those polynomials.
~~~
## INPUT
You will be given two strings of the form: `ax^n + bx^n-1 + cx^n-2 ... + hx^2 + ix + j`.
Where `a, b, c, ..., i, j` and `n` are integers.<br>
For example: `4x^3 - x^2 + 7x - 1` and `x^2 - 2x + 1`
#### Special Cases:
- The variable won't always be x; it may be u, v, A, or **any other ascii letter** (character code: 65 to 90 and 97 to 122). However, the variable is **always consistent** between the polynomials.<br> You might get `u^2 - 1` and `2u + 1` as well as `A^3 - A` and `2A^2 + 8`, but never `3x^2 - x` and `2y + 1`.
- If the coefficient of a term is `1`, then it will simply **not show up**, unless it's the constant term. <br> For example,`u^3 - u^2 + u - 1` or `u^2 + u + 1`
- If the coefficient of a term is `0`, then, the whole term will, simply, **not show up**.<br> For example,`2H^2 + 1` or `3H^3 - 4H`
## OUTPUT
Return a string representing a polynomial of the form: `ax^n + bx^n-1 + cx^n-2 ... + hx^2 + ix + j`.
For example, given `x^2 + 2x + 1` and `x + 1`, return `x^3+3x^2+3x+1`
#### Rules for formatting the answer:
- Your answer should not contain whitespace; all the terms, must, be together.<br> For example, `s^2+2s+1` instead of `s^2 + 2s + 1`
- When the coefficient of a term is `1` or `-1`, it shouldn't show up, unless it's the constant term.<br> For example, `-x^2+x-1` instead of `-1x^2+1x-1`
- When the coefficient of a term is `0`, the whole term shouldn't appear in the answer.<br> For example, `2Y^3+Y` instead of `2Y^3+0Y^2+Y+0`
- The terms should be in order from the highest degree to the lowest, from left to right. <br> For example, `a^4+2a^2+1` instead of `1+2a^2+a^4`
- The variable used for the answer should be the **same as the input**; don't go turning every variable into x's.<br> For example, given `b^2 + 1` and `9b - 2`, return `9b^3-2b^2+9b-2` rather than `9x^3-2x^2+9x-2`.
### EXAMPLES
~~~if:javascript,typescript
```javascript
polynomialProduct("u^2 + 2u+1", "u + 1") -> "u^3+3u^2+3u+1"
polynomialProduct("x^2", "3x - 1") -> "3x^3-x^2"
polynomialProduct("2", "4y - 4") -> "8y-8"
polynomialProduct("-4r^2 + 1", "-1") -> "4r^2 - 1"
polynomialProduct("1", "p^3") -> "p^3"
polynomialProduct("1", "-1") -> "-1"
polynomialProduct("0", "2 - x") -> "0"
polynomialProduct("-1", "0") -> "0"
polynomialProduct("v^2 - 1+3v^3", "1+v^2") -> "3v^5+v^4+3v^3-1"
```
~~~
~~~if-not:javascript
```
polynomial_product("u^2 + 2u+1", "u + 1") -> "u^3+3u^2+3u+1"
polynomial_product("x^2", "3x - 1") -> "3x^3-x^2"
polynomial_product("2", "4y - 4") -> "8y-8"
polynomial_product("-4r^2 + 1", "-1") -> "4r^2 - 1"
polynomial_product("1", "p^3") -> "p^3"
polynomial_product("1", "-1") -> "-1"
polynomial_product("0", "2 - x") -> "0"
polynomial_product("-1", "0") -> "0"
polynomial_product("v^2 - 1+3v^3", "1+v^2") -> "3v^5+v^4+3v^3-1"
```
~~~
### RANDOM TESTS
- `0 <= exponents <= 4500`
- `-85000 <= coefficients <= 85000`
`20` small tests<br>
`30` medium tests<br>
`20` big tests<br>
`5` really big tests<br>
This kata isn't focused on performance. However, don't go writing spaghetti code just because of this; you can still timeout if your code is poorly written.
| algorithms | from collections import defaultdict
def extract(c: str, section: str) - > tuple[int, int]:
try:
return (0, int(section))
except ValueError:
pass
if section . startswith('-'):
mul = - 1
section = section . replace('-', '+')
else:
mul = 1
section = section . replace('+', "")
if c not in section:
pow = 0
else:
if '^' in section:
(section, b) = section . split('^')
pow = int(b)
else:
pow = 1
section = section . replace(c, "")
mul = mul * (int(section) if section else 1)
return (pow, mul)
class Polynomial:
def __init__(self, c: str, d: dict[int, int]):
self . d = d . copy()
self . c = c
def __mul__(self, other):
c = self . c or other . c
res = defaultdict(int)
for (p1, m1) in self . d . items():
for (p2, m2) in other . d . items():
res[p1 + p2] += m1 * m2
return Polynomial(c, dict(res))
def unparse(self):
sections = sorted(self . d . items(), reverse=True)
parts = [unparse_section(* k) for k in sections]
parts = [i . replace('x', self . c) for i in parts if i]
return "+" . join(parts). replace("+-", "-") or "0"
def unparse_section(pow, mul) - > str | None:
if mul == 0:
return None
p = str(mul) + 'x' if mul != 1 else 'x'
p = p . replace("-1x", "-x")
if pow == 0:
p = str(mul)
if pow > 1:
p += f"^ { pow } "
return p
def parse(pol):
c = next((i for i in pol if i not in "1234567890+- "), "")
parts = pol . replace(" ", ""). replace(
"+", " +"). replace("-", " -"). split()
parts2 = [extract(c, i) for i in parts]
print(parts2)
return Polynomial(c, dict(parts2))
def polynomial_product(polynomial_1: str, polynomial_2: str) - > str:
return (parse(polynomial_1) * parse(polynomial_2)). unparse()
| Multiplying Polynomials | 63c05c1aeffe877458a15994 | [
"Mathematics",
"Strings",
"Regular Expressions"
] | https://www.codewars.com/kata/63c05c1aeffe877458a15994 | 4 kyu |
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Problem Description</summary>
When dealing with multidimensional coordinates in a kata, we sometimes want to keep track of which cells have already been visited. In Python this is easy, we just use a tuple <code>(y, x)</code>. In javascript, however, there is no tuple. An alternative that comes to mind is to use an array <code>[y, x]</code>.
```javascript
const h = new Set();
h.add([0, 1]);
console.log(h.has([0, 1])); // false :-(
```
Unfortunately, that won't work. Some users resort to making a string key instead <code>"${y},${x}"</code>. While this works, it's unwanted overhead. Specially if we want to restore the original coordinates from that key, we need some string parsing and string to number mapping.
Luckely, if the sizes of the dimensions are known, we can just use some plain maths to encode our multidimensional coordinates into a single number, containing all the information we need about the location of a cell in a higher dimensional structure, like a matrix.
Here's an example for a 9x9 sudoku grid.
```
| 0 1 2 3 4 5 6 7 8 We can use the width as multiplier for 'y' and add the col 'x' to get
----------------------------- a single number.
0| 0 1 2 3 4 5 6 7 8
1| 9 10 11 12 13 14 15 16 17 Examples: cell (y = 1, x = 3) -> n = 1 * 9 + 3 = 12
2| 18 19 20 21 22 23 24 25 26 cell (x = 8, x = 8) -> n = 8 * 9 + 8 = 80
3| 27 28 29 30 31 32 33 34 35
4| 36 37 38 39 40 41 42 43 44
5| 45 46 47 48 49 50 51 52 53
6| 54 55 56 57 58 59 60 61 62
7| 63 64 65 66 67 68 69 70 71
8| 72 73 74 75 76 77 78 79 80
```
</details>
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Task</summary>
##### "You are expected to encode and decode a point given the dimensions of the structure it is part of."
## Encode
##### "Given the dimensions as an array of positive integers and a point as an array of non negative integers, each representing a coordinate in the respective dimension, return the encoded point as a non negative integer."
- dimensions: array of positive integers
- <code>1 <= array length <= 10</code>
- <code>1 <= dimension size <= 10000</code>
- from left to right we get from the highest to the lowest dimension
- point: array of non negative integers, each representing a coordinate in the respective dimension
- <code>0 <= coordinate value < respective dimension size</code>
- from left to right we get from the coordinate of the highest to that of the lowest dimension
- all integers are of type <code>BigInt</code>
- all input will be valid (correct data type, in bounds of the dimensions)
### Algorithm
- in order to build the encoded point, we start from <code>0</code> and add the encoded value for each of the coordinates of the point
- the encoded value for a coordinate is its value times the product of all lower dimension sizes
- if you reach the coordinate of the lowest dimension, its value is the encoded value
## Decode
##### "Given the dimensions as an array of positive integers and an encoded point as non negative integer, return the point as an array of non negative integers, each representing a coordinate in the respective dimension."
- dimensions: array of positive integers
- <code>1 <= array length <= 10</code>
- <code>1 <= dimension size <= 10000</code>
- from left to right we get from the highest to the lowest dimension
- encoded point: non negative integer, representing the encoded point
- <code>0 <= encoded point < product of sizes of all dimensions</code>
- all integers are of type <code>BigInt</code>
- all input will be valid (correct data type, in bounds of the dimensions)
### Algorithm
Decoding is the inverse process of encoding. So when calling the following operations, the original point should be provided whichever the value of dimensions or point.
```
decode(dimensions, encode(dimensions, point)) == point
```
</details>
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Examples</summary>
### Encode
```
dimensions point encoded point
[10] [0] 0
[10] [7] 7
[5, 10] [2, 0] 20
[9, 9] [8, 8] 80
[7, 5, 10] [1, 2, 3] 73
[10, 5, 10, 8] [6, 1, 2, 3] 2499 (explained below)
```
#### Explanation
```
point: [6, 1, 2, 3] and dimensions: [10, 5, 10, 8]
encoded point: start by 0
add 6 times 5 * 10 * 8 = 2400
add 1 time 10 * 8 = 80
add 2 times 8 = 16
add 3
+ -------------------------------
0 + 2400 + 80 + 16 + 3 = 2499
```
</details> | algorithms | def encode(d: list[int], p: list[int]) - > int:
e = 0
for i in range(len(p)):
e = e * d[i] + p[i]
return e
def decode(d: list[int], e: int) - > list[int]:
p = [0] * len(d)
for i in range(len(d) - 1, - 1, - 1):
p[i] = e % d[i]
e / /= d[i]
return p
| Multidimensional Coordinate Encoding | 63be67b37060ec0a8b2fdcf7 | [
"Algorithms",
"Arrays",
"Mathematics"
] | https://www.codewars.com/kata/63be67b37060ec0a8b2fdcf7 | 6 kyu |
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Introduction</summary>
Let's draw mountain bike trails!
```
_--_ _
-__ _-βΎβΎβΎ- -
__ _--βΎ βΎβΎ _--_ _
-__ -βΎ βΎ---βΎ -__ _-βΎβΎβΎ- -
βΎ-βΎ __ _--βΎ βΎβΎ
-__ -βΎ βΎ---βΎ
βΎ-βΎ
```
</details>
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Task</summary>
##### "Given an array of numbers representing a mountain bike trail, render that trail as string."
### Input
##### trail
- an array containing integer numbers (-2 <= number <= 2)
- the first number determines the token to use in the starting <b>tile</b>
- each next number represents a delta height in <b>sub tiles</b> to draw the next token relative to the previous one
### Output
- return a string representing the mountain bike trail. The string is delimited with a newline <code>'\n'</code>. All lines have the same width. Leading and trailing whitespace is important.
- tokens used in the string: <code>'_', '-', 'βΎ', ' '</code>
- the trail is rendered with a 3D-effect (see examples at the end of the Specification)
### Input Constraints
- Beginner Trails
- 100 random tests with 10 <= size <= 20
- Novice Trails
- 100 random tests with 20 <= size <= 30
- Extreme Trails
- 100 random tests with 30 <= size <= 40
- 100 chaotic random tests with 40 <= size <= 50
</details>
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Specification</summary>
- The output string can be viewed at in rows and columns.
- A tile represents a cell at a given row and column.
- A tile can hold 3 different values, depending on which sub tile is used:
- sub tile <code>0</code>: <code>'_'</code> (underscore)
- sub tile <code>1</code>: <code>'-'</code> (dash)
- sub tile <code>2</code>: <code>'βΎ'</code> (upperscore)
- if no sub tile is used: <code>' '</code> (whitespace)
- there can always be at most 1 sub tile used per tile (there will be no conflicts)
- Any number in the trail is a delta value added to the previous number.
- Any accumulated number <i>modulo 3</i> represents the sub tile that is being used in a tile.
```
Examples:
Notice that we sometimes need to create an additional row to render all sub tiles.
trail sub tile values rendered ('*' as whitespace)
[0, 1, -1] [0, 1, 0] _-_
[1, 1, -1] [1, 2, 1] -βΎ-
[2, 1, -1] [2, 3, 2] *_*
βΎ βΎ
[0, -1, 1] [0, -1, 0] _*_
*βΎ*
[1, -1, 1] [1, 0, 1] -_-
[2, -1, 1] [2, 1, 2] βΎ-βΎ
[0, 1, 1] [0, 1, 2] _-βΎ
**_
[1, 1, 1] [1, 2, 3] -βΎ*
*_-
[2, 1, 1] [2, 3, 4] βΎ**
```
- To draw the trail, a 3D-effect must be created
- draw the bottom part of trail
- draw the same pattern 2 tiles higher and 1 tile to the right
- make sure to align both patterns in a way there is no unwanted padding
```
trail sub tile values rendered ('*' as whitespace)
*_-_
****
[0, 1, -1] [0, 1, 0] _-_*
*_*_
**βΎ*
[0, -1, 1] [0, -1, 0] _*_*
*βΎ**
* _-
*βΎ**
*_-*
[2, 1, 1] [2, 3, 4] βΎ***
```
- Beginner, Novice, Extreme trails are distinguished by steepness of hills, dells and ramps. They do not differ in the way you should render them.
</details>
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Examples</summary>
##### The examples can also be found in the sample tests. Note that an asterisk '*' is used to show whitespace in the examples below.
#### Beginner Trail
```
trail: [-2, 1, 0, 0, -1, 1, 0, 0, -1, -1, 0, 0]
return: *-βΎβΎβΎ-βΎβΎβΎ-___
*************
-βΎβΎβΎ-βΎβΎβΎ-___*
```
#### Novice Trail
```
trail: [1, -1, 0, 0, -1, 1, 1,
0, 0, 0, 0, -2, -1, -1,
0, -1, -1, 0, 1, 1, 0,
0, -1, -1, 0]
return: *-___*_-----**************
*****βΎ******βΎ-__****___***
-___ _-----*****βΎ--βΎ***βΎ--
****βΎ******βΎ-__****___****
***************βΎ--βΎ***βΎ--*
```
</details> | reference | from itertools import accumulate
TILES = "_-βΎ"
def draw_trail(trail):
hs = [* accumulate(trail)]
min_h = min(hs)
base = min_h - min_h % 3
but = min_h / / 3
up = max(hs) / / 3
H = up - but + 3
blank = ' ' * (len(trail) + 1)
board = [list(blank) for _ in range(H)]
for j, h in enumerate(hs):
i = H - 1 - (h - base) / / 3
board[i][j] = board[i - 2][j + 1] = TILES[h % 3]
return '\n' . join(map('' . join, board))
| Mountain Bike Trail | 63bd62e60634a6006a1b53c0 | [
"Fundamentals",
"Strings",
"ASCII Art",
"Geometry"
] | https://www.codewars.com/kata/63bd62e60634a6006a1b53c0 | 6 kyu |
<img align="right" alt="" style="margin: 1em" src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/LED_Digital_Display.jpg/320px-LED_Digital_Display.jpg">
## <span style="color:#0ae">Task</span>
There is a multi-digit [seven segment display](https://en.wikipedia.org/wiki/Seven-segment_display). The display has a little problem: there is exactly one dead segment in the whole display. The dead segment is either always on or always off (we don't know in advance the type of defect).
```
How digits appear on a correctly working display: minus:
_ _ _ _ _ _ _ _
| | | _| _| |_| |_ |_ | |_| |_| _
|_| | |_ _| | _| |_| | |_| _|
```
```
Example: 0-4 with top segment always on/always off:
_ _ _ _ _
| | | _| _| |_| | | | _| _| |_|
|_| | |_ _| | |_| | |_ _| |
```
The display (ignoring dead segment) can either
- be completely blank,
or
- show an integer number `$n$`, `$-10^{d-1} \lt n \lt 10^d$` where *d* is the number of digits of display.
All numbers are right-aligned. The minus sign, if present, immediately precedes the number. No leading zeroes (but a single zero in the rightmost digit is allowed).
Given some numbers/blanks as they appear on display, try to determine the dead segment.
#### <span style="color:#0ae">Segment names</span>

*Note: in this kata segment names are lowercase, "dp" is not used.*
## <span style="color:#0ae">Input</span>
##### <span style="color:#0ae">⬬</span> `display` *[list of strings]*
Each element of the list is a 3-rows string that represents a number (of blank) shown on display. Each row is 4*d*-1 chars long (*d* = number of digits of display).
In each row, chars from 4*k* to 4*k*+2 (inclusive) belong to digit *k*+1, where digit 1 is the leftmost digit and digit *d* is the rightmost one. Chars 4*k*+3 (used to separate digits) are always spaces.
The format is (from 1st to 3rd row): ` a ` `fgb` `edc` (the 1st and 3rd chars of the first row are always spaces). Each segment is represented by a char:
- off: space (`' '`)
- on: `'_'` (a,d,g) or `'|'` (b,c,e,f)
Examples:
```python
50 on a 2-digits display: ' _ _ \n|_ | |\n _| |_|'
'''\
_ _
|_ | |
_| |_|'''
```
```python
-42 on a 4-digits display: ' _ \n _ |_| _|\n | |_ '
'''\
_
_ |_| _|
| |_ '''
```
All inputs are valid.
Number of strings: 1β6.
Size of display: 1β8 digits.
## <span style="color:#0ae">Output</span>
- *[string]* or `None`
If the dead segment can be determined:
- a 2-chars string containing the name of the segment (lowercase) and the number of the digit (1 = leftmost), e.g.: `'a3'`, `'g1'`, ``e5'`);
otherwise:
- `None`
## <span style="color:#0ae">Examples</span>
```
_
| |
|_|
```
Input: `[' _ \n| |\n|_|']`
Output `None` ("g" always off or an other segment always on?)
```
|
_|
```
Input: `[' \n |\n _|']`
Output: `'d1'` (the bottom segment should be off, no other options)
```
_
| _|
|_
```
Input: `[' _ \n | _|\n |_ ']`
Output: `None` ("12" with "c1" off or "2" wih "b1" on?)
```
_
_ | |
|_|
_ _
_| _|
|_ _|
```
Input: `[' _ \n _ | |\n |_|', ' _ _ \n _| _|\n|_ _|']`
Output: `'g1'` ("-0" is not allowed, and it can't be "-8" because "g2" works)
| reference | def is_num(s):
try:
return str(int(s)) == s
except:
return not s
def dead_segment(displays):
A = (1, 5, 8, 7, 6, 3, 4)
B = {0: ' ', 64: '-', 63: 0, 6: 1, 91: 2, 79: 3,
102: 4, 109: 5, 125: 6, 7: 7, 127: 8, 111: 9}
def P(d): return is_num('' . join(str(B . get(e, '?'))
for e in d). lstrip())
def Q(d): return [sum((d[e / / 3][j + e % 3] > ' ') << i for i, e in enumerate(A)) for j in range(0, len(d[0]), 4)]
def R(d, s): return all(P(f) or P((e ^ (d == i) * (1 << s)
for i, e in enumerate(f))) for f in U)
def S(d, s): return all((e[d] ^ U[0][d]) >> s & 1 < 1 for e in U)
U = [Q(d . split('\n')) for d in displays]
V = [chr(s + 97) + str(d + 1) for d in range(len(U[0]))
for s in range(7) if R(d, s) and S(d, s)]
if len(V) == 1:
return V[0]
| Broken 7-segment display - challenge edition | 63b325618450087bfb48ff95 | [
"Logic",
"Fundamentals"
] | https://www.codewars.com/kata/63b325618450087bfb48ff95 | 3 kyu |
## Task
Given an non-empty list of non-empty uppercase words, compute the minimum number of words, which, when removed from the list, leaves the rest of the list in strictly ascending lexicographic order.
#### Examples:
["THE","QUICK","BROWN","FOX","JUMPS","OVER","THE","LAZY","DOG"] should return 4, because removing "THE", "QUICK", "LAZY" & "DOG" leaves the sorted list ["BROWN","FOX","JUMPS","OVER","THE"].
["JACKDAW","LOVE","MY","BIG","SPHINX","OF","QUARTZ"] should return 2, because removing "BIG" & "SPHINX" leaves the sorted list ["JACKDAW","LOVE","MY","OF","QUARTZ"].
["A","A","A","A"] should return 3, because equal elements are NOT regarded as sorted, so all but one of them need to be removed.
#### Source: Midwest Instructional Computing Symposium 2011 http://micsymposium.org/
Somewhat similar, but harder, kata are [Make an increasing sequence](https://www.codewars.com/kata/5848f4f2d8543bf3c7000602) and [Find the Longest Increasing or Decreasing Combination in an Array](https://www.codewars.com/kata/5715508de1bf8174c1001832) | algorithms | from bisect import bisect_left
def sort_by_exclusion(words):
# last[i] represents the last element of
# the smallest subsequence of size i
last = ['']
for word in words:
idx = bisect_left(last, word)
if idx == len(last):
last . append(word)
else:
last[idx] = word
return len(words) - len(last) + 1
| Sorting by Exclusion | 63bcd25eaeeb6a3b48a72dca | [
"Sorting",
"Algorithms",
"Dynamic Programming"
] | https://www.codewars.com/kata/63bcd25eaeeb6a3b48a72dca | 6 kyu |
<h2>Introduction</h2>
<p>Graphs are simply another way to represent data. There are many different kinds of graphs and innumerable applications for them. You can find many examples of graphs in your everyday life, from road maps to subway systems. One special type of graph that we will be focusing on is the star graph, which has real-world applications such as the star network, a way of designing a computer network.
</p>
<h2>The Task</h2>
<p>For this problem, the graph will be undirected, consisting of a number of nodes and undirected edges. Additionally, the graph is given as a star graph. For this problem, a star graph of n nodes has n-1 edges and one and only one node has degree greater than one, all other nodes have degree equal to one (degree of a node of an undirected graph is simply the number of edges the node is a part of). The node to search for is the node with degree greater than one. All the other nodes with degree one must have one, and only one edge to the node with degree greater than one.</p>
<p>Additionally, a star graph can be thought of as a special kind of undirected tree with n-1 leaf nodes and 1 non-leaf node (thus, any two nodes in the star graph have one and only one path between them). Let the sole non-leaf node be the center node. It is guaranteed there is one and only one node in the graph which is a center node. The center node has an edge to all other nodes. All the other nodes must have one, and only one edge to the center node.
</p>
<p>For this problem, there will be nodes with integer labels from 1 to n, where n is the number of nodes. Additionally, you will be be given a list of edges of length n-1, where each edge, (n1,n2), is a tuple denoting an edge exists between n1 and n2. </p>
<p>Write a function that given the list of edges, returns the <b>center</b> of the star graph as an integer. There will not be any performance tests, only tests for correctness, and length of the list of edges is guaranteed to be >=3 and not exceed 1000.
</p>
<h2>Example</h2>
<p>You are given edges [(1,5),(4,5),(5,2),(3,5)].
<br><br>
Since 5 is the only node to have an edge to all other nodes, it is the center of the star graph.
<br><br>
Return 5.</p>
| reference | def center(edges):
a, b = edges[0]
return a if a in edges[1] else b
| Find Center of Star Graph | 63b9aa69114b4316d0974d2c | [
"Graph Theory"
] | https://www.codewars.com/kata/63b9aa69114b4316d0974d2c | 7 kyu |
## Task
Given two positive integers <code>m (width)</code> and <code>n (height)</code>, fill a two-dimensional list (or array) of size <code>m-by-n</code> in the following way:
- (1) All the elements in the first and last row and column are 1.
- (2) All the elements in the second and second-last row and column are 2, excluding the elements from step 1.
- (3) All the elements in the third and third-last row and column are 3, excluding the elements from the previous steps.
- And so on ...
## Examples
Given m = 5, n = 8, your function should return
```
[[1, 1, 1, 1, 1],
[1, 2, 2, 2, 1],
[1, 2, 3, 2, 1],
[1, 2, 3, 2, 1],
[1, 2, 3, 2, 1],
[1, 2, 3, 2, 1],
[1, 2, 2, 2, 1],
[1, 1, 1, 1, 1]]
```
Given m = 10, n = 9, your function should return
```
[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 2, 2, 2, 2, 2, 2, 2, 2, 1],
[1, 2, 3, 3, 3, 3, 3, 3, 2, 1],
[1, 2, 3, 4, 4, 4, 4, 3, 2, 1],
[1, 2, 3, 4, 5, 5, 4, 3, 2, 1],
[1, 2, 3, 4, 4, 4, 4, 3, 2, 1],
[1, 2, 3, 3, 3, 3, 3, 3, 2, 1],
[1, 2, 2, 2, 2, 2, 2, 2, 2, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
```
[Bird mountain](https://www.codewars.com/kata/5c09ccc9b48e912946000157) generalizes this kata in a fun way.
| reference | def create_box(m, n): # m and n positive integers
return [[min([x + 1, y + 1, m - x, n - y]) for x in range(m)] for y in range(n)]
| The 'spiraling' box | 63b84f54693cb10065687ae5 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/63b84f54693cb10065687ae5 | 7 kyu |
## tl;dr-
```
It's connect4 but optimized, the board is MxM and you need to connect N.
Given a game move by move, determine which move is a winning move.
Turn order is random.
```
The other day I programmed a connect four game, and I thought to myself- this is nice, but
faster = better... So how can I optimize this?
The only issue was that there's no reason to optimize something thatβs already fast enough, and my solution was plenty fast... Or should I say plenty fast in normal circumstances?
That's right, we're going to use huge boards! And it's no longer Connect four now itβs Connect N.
I'm also going to change the rules a bit:
# TASK
First you are given a board size, and a win condition.
Then you are given moves, one at a time.
You need to play out the moves and determine wether or not that move was a winning move.
The game *does not* end after a win!
Continue playing and see which moves make another N in a row.
(The next N in a row can contain pieces from the previous N in a row)
Each move contains a `column` (0-indexed) and a `player`,
which means that `player` has put a piece in `column`
eg:
```python
game = MegaConnect4(10, 4)
# this means that we are making a new game with a board size of 10x10,
# and you need to connect 4 to win
game.add_move("Bob", 3)
# Bob places a piece in column 3
game.add_move("Joe", 5)
# Joe places a piece in column 5
game.add_move("Joe", 6)
# once more Joe places a piece in column 6
```
If the move was a winning move, add_move should return True,
otherwise it should return False
Note- there are only 2 players and the turn order is random.
# RULES
There is a square board (size x size)
and a given goal (win_condition).
During each turn a random player places one of his pieces in a certain column,
the piece then falls to the bottom of that column.
Each player who gets `win_condition` pieces in a consecutive
row, column, or diagonal wins, BUT DOESN'T END THE GAME
# Notes
* Don't focus on small optimizations, you're going to need a smart algorithm.
* Don't forget to remove all the prints from your code before attempting!
* None of the board sizes will ever be 0
# If you are having trouble solving this kata or you already solved it, check these out:
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/6KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/5864f90473bd9c4b47000057" target="_blank">Connect Four - placing tokens</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/5KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/586c0909c1923fdb89002031" target="_blank">Connect 4</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/5KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/5b442a063da310049b000047" target="_blank">NxN Connect X</a></span>
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/4KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/56882731514ec3ec3d000009" target="_blank">Connect Four</a></span>
# If you want to check out my other kata:
<span style="display: flex !important;"><img style="margin:0px;" src="https://raw.githubusercontent.com/adrianeyre/codewars/master/Ruby/Authored/4KYU.png" alt="Rank"/> <a href="https://www.codewars.com/kata/6108f2fa3e38e900070b818c" target="_blank">Snafooz solver</a></span>
| games | from collections import defaultdict
class MegaConnect4:
def __init__(self, board_size, win_condition):
self . height = [0] * board_size
self . lines = {k: defaultdict(lambda: defaultdict(dict)) for k in [
(1, 0), (0, 1), (1, 1), (- 1, 1)]}
self . get_coords = {
(1, 0): lambda x, y: (y, x),
(0, 1): lambda x, y: (x, y),
(1, 1): lambda x, y: (y - x, (y + x) / / 2),
(- 1, 1): lambda x, y: (y + x, (y - x) / / 2),
}
self . win = win_condition
def add_move(self, player, col):
x, y = col, self . height[col]
self . height[col] += 1
won = False
for k in [(1, 0), (0, 1), (1, 1), (- 1, 1)]:
p, q = self . get_coords[k](x, y)
l, r = q, q + 1
d = self . lines[k][player][p]
if l in d:
l = d[l]
del d[d[l]]
del d[l]
if r in d:
r = d[r]
del d[d[r]]
del d[r]
d[l], d[r] = r, l
won |= r - l >= self . win
return won
| Mega Connect 4 | 6250122a983b3500358fb671 | [
"Games",
"Puzzles",
"Logic",
"Performance"
] | https://www.codewars.com/kata/6250122a983b3500358fb671 | 4 kyu |
<img align="right" alt="" style="margin: 1em" src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Seven_segment_01_Pengo.jpg/243px-Seven_segment_01_Pengo.jpg">
## <span style="color:#0ae">Task</span>
There is a single-digit [seven segment display](https://en.wikipedia.org/wiki/Seven-segment_display). The display has a problem: there can be from 0 to 7 (all) "*reversed*" segments. A reversed segment is on when it should be off, and off when it should be on.
The display shows numbers from 0 to 9 (inclusive). If there are reversed segments, numbers may look strange.
```
How numbers appear on a correctly working display: 0-5 with top segment reversed:
_ _ _ _ _ _ _ _ _ _
| | | _| _| |_| |_ |_ | |_| |_| | | | _| _| |_| |_
|_| | |_ _| | _| |_| | |_| _| |_| | |_ _| | _|
```
Given some numbers as they appear on display, try to determine which segments are reversed.
#### <span style="color:#0ae">Segment names</span>

*Note: in this kata segment names are lowercase, "dp" is not used.*
## <span style="color:#0ae">Input</span>
##### <span style="color:#0ae">⬬</span> `display` *[list of strings]*
Each element of the list is a 11-chars string that represents a number shown on display. Format: (3 rows, 3 chars per row) ` a ` `fgb` `edc` (the 1st and 3rd chars of the first row are always spaces). Each segment is represented by a char:
- off: space (`' '`)
- on: `'_'` (a,d,g) or `'|'` (b,c,e,f)
Examples:
```python
8: ' _ \n|_|\n|_|'
```\
_
|_|
|_|'''
```
```python
4: ' \n|_|\n |'
```\
|_|
|'''
```
All inputs are valid; there is always at least one string.
## <span style="color:#0ae">Output</span>
- *[string]* or `None`
If the set of reversed segments can be determined:
- a lowercase string containing the names of reversed segments in alphabetical order (e.g. `''`, `'a'`, `'ceg'`, `'abcdefg'`);
otherwise:
- `None`
## <span style="color:#0ae">Examples</span>
```
_
|_| | |
|_ |
```
Input: `[' \n|_|\n|_ ', ' _ \n| |\n |']`
Output: `None` (it could be *2,1* with *a,f* reversed, or *1,2* with *c,d,e,f,g* reversed)
```
_ _
|_| | | |
|_| |_| |
```
Input: `[' _ \n|_|\n|_|', ' _ \n| \n|_|', ' \n| |\n |']`
Output: `'g'` (*0,6,4* with *g* reversed, no other options)
| reference | SEGMENTS = {0b1111110, 0b0110000, 0b1101101, 0b1111001, 0b0110011,
0b1011011, 0b1011111, 0b1110000, 0b1111111, 0b1111011}
def segment_to_number(s): return int(
'' . join('01' [s[i] != ' '] for i in (1, 6, 10, 9, 8, 4, 5)), 2)
def number_to_letters(n): return '' . join(
c for c, b in zip('abcdefg', f' { n :0 7 b } ') if b == '1')
def reversed_segments(display: list[str]) - > str | None:
encoded = set(map(segment_to_number, display))
it = (i for i in range(2 * * 7) if {s ^ i for s in encoded} <= SEGMENTS)
res = next(it)
return None if next(it, False) else number_to_letters(res)
| Broken 7-segment display - reversed segments | 63b5ce67e226b309f87cdefe | [
"Logic",
"Fundamentals"
] | https://www.codewars.com/kata/63b5ce67e226b309f87cdefe | 6 kyu |
I have four positive integers, A, B, C and D, where A < B < C < D. The input is a list of the integers A, B, C, D, AxB, BxC, CxD, DxA in some order. Your task is to return the value of D.
~~~if:lambdacalc
### Encodings
purity: `LetRec`
numEncoding: `BinaryScott`
export constructors `nil, cons` for your `List` encoding
~~~ | reference | def alphabet(ns):
a, b, c1, c2, _, _, _, cd = sorted(ns)
return cd / c2 if a * b == c1 else cd / c1
| The alphabet product | 63b06ea0c9e1ce000f1e2407 | [
"Logic"
] | https://www.codewars.com/kata/63b06ea0c9e1ce000f1e2407 | 7 kyu |
This kata wants you to perform a lattice multiplication. This is a box multiplication, which will be explained below. However, this has a twist. Instead of adding the diagonals together, you would return a 2D list cotaining the diagonals, for example, 13x28 would return:
[[4], [6, 2, 8], [0, 2, 0], [0]]

## Description
To solve a lattice multiplication when multiplying an <i>k</i>-digit number by an <i>m</i>-digit number:
1. Draw a <i>k</i> by <i>m</i> grid, and write the numbers to the top and right.
2. Draw a line from the top-right to bottom-left corner in each box in the grid.
3. To fill up each box, find the digits that lead to that box, and multiply them. If the resulting number is only one-digit, append a 0 at the beginning to make it two digits. Afterwards, put the units digit on the bottom-right corner of that box and the tens digit on the top-right corner.
4. There should be diagonals appearing in the grid. To get the answer, add up all the numbers on the diagonals, from right to left (because carrying might be needed), and then resulting in a number. However, this process is not needed in this kata, and returning a list of diagonals would suffice.
A more detailed method and explanation is on [Wikipedia](https://en.wikipedia.org/wiki/Lattice_multiplication).
## Input
2 integers, <i>a</i> and <i>b</i>.
## Output
A list of diagonals from right to left, with each diagonal ordered from top to bottom. | algorithms | def lattice(a, b):
res = {}
for i, x in enumerate(map(int, str(b))):
for j, y in enumerate(map(int, str(a))):
res[i + j] = res . get(i + j, []) + [x * y / / 10]
for j, y in enumerate(map(int, str(a))):
res[i + j + 1] = res . get(i + j + 1, []) + [x * y % 10]
return [res[k] for k in sorted(res, reverse=True)]
| Lattice multiplication | 63b5951092477b0b918ff24f | [
"Mathematics"
] | https://www.codewars.com/kata/63b5951092477b0b918ff24f | 6 kyu |
## Introduction
The game of Yahtzee is played by rolling five 6-sided dice, and scoring the results in a number of ways. For the purpose of this kata, the upper section of Yahtzee gives you six possible ways to score a roll. 1 times the number of 1s in the roll, 2 times the number of 2s, 3 times the number of 3s, and so on up to 6 times the number of 6s. For instance, consider the roll ```[2, 3, 5, 5, 6]```. If you scored this as 1s, the score would be 0, since there are no 1s in the roll. If you scored it as 2s, the score would be 2, since there's one 2 in the roll. Scoring the roll in each of the six ways gives you the six possible scores: ```0 2 3 0 10 6```.
The maximum here is 10 (2x5), so your result should be 10.
You are given a Yahtzee dice roll, represented as a list with ```k``` integers from ```1``` to ```10000```. Your task is to find the maximum possible score for this roll in the upper section of the Yahtzee score card. Here's what that means.
## Examples
```python
yahtzee_upper([2, 3, 5, 5, 6]) => 10 #5*2=10 - there is two numbers 5, and that gives as 10
yahtzee_upper([1, 1, 1, 1, 3]) => 4 #1*4=4, while 3*1=3 - there is four numbers 1, and that gives as 4, while one number 3 gives as 3
yahtzee_upper([1, 1, 1, 3, 3]) => 6
yahtzee_upper([15, 9, 9, 8, 9]) => 27
yahtzee_upper([1654, 1654, 5099, 3086, 1654, 5099, 2274,
1654, 1654, 1654, 1654, 1654, 3086, 4868, 1654, 4868, 1654,
3086, 4868, 3086]) => 16540 #1654*10=16540 - large example - there is ten numbers 1654, and that gives as 16540
```
```cpp
yahtzee_upper({2, 3, 5, 5, 6}) => 10 //5*2=10 - there is two numbers 5, and that gives as 10
yahtzee_upper({1, 1, 1, 1, 3}) => 4 //1*4=4, while 3*1=3 - there is four numbers 1, and that gives as 4, while one number 3 gives as 3
yahtzee_upper({1, 1, 1, 3, 3}) => 6
yahtzee_upper({15, 9, 9, 8, 9}) => 27
yahtzee_upper({1654, 1654, 5099, 3086, 1654, 5099, 2274,
1654, 1654, 1654, 1654, 1654, 3086, 4868, 1654, 4868, 1654,
3086, 4868, 3086}) => 16540 //1654*10=16540 - large example - there is ten numbers 1654, and that gives as 16540
```
## Limitations
The tests will use following numbers:
Number of rolls: ```50 < k < 5000``` | games | def yahtzee_upper(dice: list) - > int:
return max([dice . count(x) * x for x in set(dice)])
| Yahtzee upper section scoring | 63b4758f27f8e5000fc1e427 | [
"Algorithms",
"Arrays",
"Games",
"Game Solvers"
] | https://www.codewars.com/kata/63b4758f27f8e5000fc1e427 | 7 kyu |
# Story
It is the Chinese New Year Eve. You are at your Chinese friend's house.
When he says: "It is one hour left."
You look at your watch, it is `22:00`.
So you ask him, here is the reason.
___
# Using Earthly Branches for Time
In the traditional system using [Earthly Branches](https://en.wikipedia.org/wiki/Earthly_Branches), a day is started by `23:00`.
Earthly Branches contain `12` characters:
```
ε δΈ ε―
ε― θΎ° ε·³ ε ζͺ η³ ι
ζ δΊ₯
```
Not only [for the years](https://www.codewars.com/kata/62cc917fedc75c95ef961ad1), it also can be used for the time.
The day starts with `ε`, 2 hours later become `δΈ`, then `ε―
`, and so on.
* `ε`: 23:00 - 0:59
* `δΈ`: 1:00 - 2:59
* `ε―
`: 3:00 - 4:59
and so on.
___
# Task:
Given a time as a string(`hh:mm`), return the `Earthly Branch` for that time.
The string would use 24-hours. It may have leading zero for `minute`, but no leading zero for `hour`.
___
# Examples (input -> output)
```
23:00 -> ε
0:00 -> ε
1:00 -> δΈ
2:59 -> δΈ
3:00 -> ε―
```
___
Note: The system called `ζθΎ°/ζΆθΎ°` in Chinese, but I found that google translation and the name wikipedia used in Earthly Branch are different, so just ignore the English name for it... | reference | def what_branch(time):
倩干ε°ζ― = "εδΈδΈε―
ε―
ε―ε―θΎ°θΎ°ε·³ε·³εεζͺζͺη³η³ι
ι
ζζδΊ₯δΊ₯ε"
m, s = map(int, time . split(":"))
t = m * 60 + s
return 倩干ε°ζ―[t / / 60]
| Using Earthly Branches for Time | 63b3cebaeb152e12268bdc02 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/63b3cebaeb152e12268bdc02 | 7 kyu |
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Story</summary>
Let's fast forward to the year 2048. Earth resources are scarcer then ever before. If humanity wants to survive, we need to migrate to outer space. UCA, a corporation specialised in planetary drilling, hired me to scout for a field expert. We have several forward bases on the Moon. Reconnaissance teams have recently reported promising locations for building settlements on the surface of the Moon. Our drills are already in place, but we need more data before we can give a go to start the drilling operation. This is where you, our field expert, come in ...
</details>
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Task</summary>
##### "Given a satellite image of the surface of the Moon showing a possible location for building a settlement, with our drills already in place, calculate how long it will take to complete the drilling operation."
```
Satellite image from archive:
Β΄`:->>....xxxx..****..****..****.XX.
Β΄`:===>...xxxx..****..****..****.@@.
Β΄`:->>....xxxx..****..****..****.XX.
```
### Input
- canvas: a string, representing a satellite image of the surface of the Moon. The image is delimited by new line <code>'\n'</code> and all lines have the same length. Material visible on the image:
- drill components:
- cabine: <code>Β΄`:</code>
- drill arm: <code>-</code> or <code>=</code>
- drill head: <code>></code>
- surface:
- solid ground: <code>.</code>
- soft rock: <code>*</code>
- medium rock: <code>x</code>
- hard rock: <code>X</code>
- very hard rock: <code>@</code>
### Output
- return a non-negative integer, representing the number of weeks it would take for our drills to excavate the entire area shown on the satellite image. An area is completely excavated if all rocks have been drilled.
</details>
<details>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Surface</summary>
- each surface tile has a starting strength that corresponds to the default strength for its surface type
- drilling the tile decreases the strength by the drill's attack (more about that in section Drill)
- once the strength reaches 0, the tile is accessible for the drill to move to
- as long as the surface has a positive strength, it is not accessible to move to
- negative strength is not possible
```
Surface Type Char Strength
solid ground '.' 0
soft rock '*' 1
medium rock 'x' 2
hard rock 'X' 3
very hard rock '@' 4
```
</details>
<details>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Drill</summary>
We distinguish between 2 types of drills, the <i>drillatronino</i> and the <i>drillatron</i>.
### drillatronino
- the smallest drill, takes only 1 row
- starts with its cabin: <code>Β΄`:</code>
- followed by a drill arm and drill head (example arm: <code>--</code>, example head: <code>>></code>)
- the arm shows the power of the drill
- <code>-</code>: power = 1
- <code>=</code>: power = 2
- repetitions don't change the power, only the position of the drill
- at least one arm piece available
- the head shows the speed of the drill
- <code>></code>: speed = 1
- <code>>></code>: speed = 2
- <code>>>></code>: speed = 3
- no additional repetitions possible
- the damage the drill can do is calculated as follows:
- <code>attack drill = power * speed</code>
- <code>damage to surface = max(0, strength tile - attack drill)</code>
```
Examples drillatronino
#1: regular
on canvas Β΄`:->
power 1
speed 1
attack 1
example drilling Β΄`:->@ (takes 4 cycles to escavate)
- cycle 0: '@' strength = 4
- cycle 1: '@' strength = 3 (-1)
- cycle 2: '@' strength = 2 (-1)
- cycle 3: '@' strength = 1 (-1)
- cycle 4: '@' strength = 0 (-1)
#2: double speed
on canvas Β΄`:->>
power 1
speed 2
attack 2
example drilling Β΄`:->>@ (takes 2 cycles to escavate)
- cycle 0: '@' strength = 4
- cycle 1: '@' strength = 2 (-2)
- cycle 2: '@' strength = 0 (-2)
#3: double power
on canvas Β΄`:=>
power 2
speed 1
attack 2
example drilling Β΄`:=>@ (takes 2 cycles to escavate)
- cycle 0: '@' strength = 4
- cycle 1: '@' strength = 2 (-2)
- cycle 2: '@' strength = 0 (-2)
#4: triple speed
on canvas Β΄`:->>>
power 1
speed 3
attack 3
example drilling Β΄`:->>>@ (takes 2 cycles to escavate)
- cycle 0: '@' strength = 4
- cycle 1: '@' strength = 1 (-3)
- cycle 2: '@' strength = 0 (-3, capped at 0)
#5: double speed, double power
on canvas Β΄`:=>>
power 2
speed 2
attack 4
example drilling Β΄`:=>>@ (takes 1 cycle to escavate)
- cycle 0: '@' strength = 4
- cycle 1: '@' strength = 0 (-4)
```
### drillatron
- comprised of 2 or more drillatroninos
- each drillatronino has its own row, and own configuration of drill arm (type and size) and drill head
- no gaps in rows between drillatroninos
- moves as one part, meaning if any drillatronino is still drilling while others aren't, movement is postponed until that drillatronino has finished
```
Examples drillatron
#1 #2 #3
Β΄`:->>> Β΄`:==>> Β΄`:==>>
Β΄`:==>> Β΄`:--> Β΄`:==>>
Β΄`:->>> Β΄`:=>
Β΄`:-->
Β΄`:==>>
```
</details>
<details>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Drilling Cycle</summary>
- a drilling cycle takes 1 week
- during a drilling cycle the following steps are executed in order:
- excavate surface
- move (if possible) 1 tile from left to right
- if no more rocks to be escavated, terminate; else, next cycle
```
Examples
#1: drillatronino drilling
canvas Β΄`:->.x..
cycles required 3
- cycle 1: nothing to drill, move to right
- cycle 2: drill 'x', its strength decreases from 2 to 1
- cycle 3: drill 'x', its strength decreases from 1 to 0
#2: drillatron drilling
canvas Β΄`:->X*..
Β΄`:=>@x..
cycles required 4
- cycle 1:
- drill 1: drill 'X', its strength decreases from 3 to 2
- drill 2: drill '@', its strength decreases from 4 to 2
- cycle 2:
- drill 1: drill 'X', its strength decreases from 2 to 1
- drill 2: drill '@', its strength decreases from 2 to 0
- cycle 3:
- drill 1: drill 'x', its strength decreases from 1 to 0
- drill 2: wait for drill 1 to finish
- both drills are done -> move one step to the right
- cycle 4:
- drill 1: drill '*', its strength decreases from 1 to 0
- drill 2: drill 'x', its strength decreases from 2 to 0
- both drills are done -> all rocks have been drilled
.. much more examples available in Sample Tests
```
</details>
<details>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Canvas</summary>
- the canvas is a rectangular shape consisting of surface tiles and 1 big drillatron positioned at the left of the canvas
- the drillatron occupies the entire height of the canvas, and has a drillatronino attached on each row
```
Β΄`:->>...xxx..XXx
Β΄`:-->...***..@@.
Β΄`:=>....***.....
```
</details>
<details>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Input Constraints</summary>
- 50 tests with 1 <= drills <= 1 and 10 <= canvas width <= 20
- 50 tests with 2 <= drills <= 3 and 10 <= canvas width <= 20
- 50 tests with 2 <= drills <= 3 and 20 <= canvas width <= 50
- 50 tests with 4 <= drills <= 8 and 10 <= canvas width <= 20
- 50 tests with 4 <= drills <= 8 and 75 <= canvas width <= 95
</details>
Good luck!
| algorithms | from itertools import count
from dataclasses import dataclass
ROCK_TO_SOLIDITY = dict(zip(".*xX@", range(5)))
@ dataclass
class Drill:
row: list[int]
damage: int
i: int = 0
_movable: bool = False
@ classmethod
def build(cls, s: str):
speed = s . count('>')
power = '-' in s or 2 * ('=' in s)
row = [ROCK_TO_SOLIDITY[c]
for c in s[s . index('>') + speed:]. rstrip('.')]
return cls(row, power * speed)
@ classmethod
def pool_worker(cls, land: str):
drills = [* map(Drill . build, land . splitlines())]
return lambda action: [action(d) for d in drills]
def work(self):
if self . i < len(self . row) and self . row[self . i]:
self . row[self . i] = max(0, self . row[self . i] - self . damage)
self . _movable = self . i >= len(self . row) or not self . row[self . i]
def move(self): self . i += 1
def done(self): return self . i >= len(self . row)
def movable(self): return self . _movable
def drill(canvas):
pool = Drill . pool_worker(canvas)
for rnd in count():
pool(Drill . work)
if all(pool(Drill . done)):
return rnd
if all(pool(Drill . movable)):
pool(Drill . move)
| Lunar Drilling Operation | 63ada5a5779bac0066143fa0 | [
"Algorithms",
"Puzzles",
"Strings",
"Mathematics",
"ASCII Art"
] | https://www.codewars.com/kata/63ada5a5779bac0066143fa0 | 5 kyu |
# Maximum different differences
Assume `$A$` is a strictly increasing array of positive integers with `$n$` elements:
```math
A = [a_1, a_2, ..., a_n] \text{ such that } a_1 < a_2<a_3<\dots<a_n
```
The difference array of `$A$` is `$[a_2-a_1, a_3-a_2, \dots, a_n-a_{n-1}]$`
That is,
`$D = [d_1, d_2, \dots, d_{n-1}]$` such that `$d_i = a_{i+1}-a_i$`.
For example,
```math
1.\hspace{2mm} A=[1,2,3,4] \Rightarrow D=[1,1,1]\\
2.\hspace{2mm} A=[1,3,4,10] \Rightarrow D=[2,1,6]
```
Denote the <strong><i>characteristic</i></strong> as the number of different elements in the array `$D$`.
Following above examples, the characteristic of the first example is 1, since the array only contains the element `$\{1\}$`. In the second example, the characteristic is 3 : `$\{1, 2, 6\}$`.
Given the last element of a strictly increasing array `$A$`, i.e. `$a_n$`, find the maximum possible characteristic. Note the size of `$A$` is less or equal than `$a_n$`.
For example, if `$a_n = 7$`, some examples that you could think of are:
```math
1.\hspace{2mm} A=[1,2,3,4,5,6,7] \Rightarrow D=[1,1,1,1,1,1]\\
2.\hspace{2mm} A=[1,2, 7] \Rightarrow D=[1, 5]\\
3.\hspace{2mm} A=[2,3,5, 7] \Rightarrow D=[1,2,2]\\
4.\hspace{2mm} A=[1,4,5, 7] \Rightarrow D=[3, 1, 2]\\
```
The characteristic of the first example is 1 (it only has one different element: `$\{1\}$` in `$D$`), in the second and third one the characteristic is 2 and in the last one, the characteristic is 3. If you try any other possible `$A$`, you won't find a characteristic greater than 3. Thus, the answer is 3.
## Input
`$a_n$`: (int) The maximum/last element of `$A$`. `$2\leq a_n \leq 2^{200}$`
## Output
(int) The maximum possible characteristic based on `$a_n$`
<strong> Note:</strong> Be aware of the size of `$a_n$` and the precision when working with big numbers. Find an optimal solution | games | from math import isqrt
def max_df(a_n: int) - > int:
return (isqrt(8 * a_n) - 1) / / 2
| Maximum different differences | 63adf4596ef0071b42544b9a | [
"Mathematics",
"Puzzles",
"Performance"
] | https://www.codewars.com/kata/63adf4596ef0071b42544b9a | 7 kyu |
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Task</summary>
##### "Given a list walls closing in at you, can you make it past those walls without being hit?"
### Input
- walls: an array of 2-ples, each 2-ple storing non-negative numbers representing the distance of the walls closing in at you from each side (north, south) respectively to the center of the room.
### Output
- return a boolean indicating whether it is possible to run past the walls without being hit.
</details>
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Specification</summary>
- You stand at the west side of a rectangular room, right in the centre of the north and south side
- Your goal is to reach the east side of the room
- You can only move in a straight line across the room parallel to north and south side
- Walls are closing in at you from both the north and south side of the room
- Walls stop once they hit the center of the room (distance to north side = distance to south side)
- You and the walls move at the same speed
- You get hit by a wall if you are on the same tile as a wall
- If a wall reaches a tile ahead of you, you cannot make it past that wall anymore
- The distances of opposing walls in each 2-ple can differ
</details>
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Input Constraints</summary>
- 50 tests with 1 <= number of walls <= 4
- 50 tests with 5 <= number of walls <= 15
- 50 tests with 16 <= number of walls <= 50
- 50 tests with 51 <= number of walls <= 100
- 0 <= starting distance of walls to center of room <= 120
</details>
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Examples</summary>
In the examples below, you start on tile <code>A</code> and want to reach tile <code>B</code>. You have to walk across the center of the room <code>-</code>. Walls <code>W</code> are closing in on you from the north and south.
#### Walk in the park
```
walls: [[7, 7], [7, 7], [7, 7], [7, 7]]
expected: true
steps:
start 1 2 3 4 end
WWWW WWWW WWWW WWWW WWWW WWWW
.... WWWW WWWW WWWW WWWW WWWW
.... .... WWWW WWWW WWWW WWWW
.... .... .... WWWW WWWW WWWW
.... .... .... .... WWWW WWWW
.... .... .... .... .... WWWW
.... .... .... .... .... ....
A----B A...B .A..B ..A.B ...AB ....A
.... .... .... .... .... ....
.... .... .... .... .... WWWW
.... .... .... .... WWWW WWWW
.... .... .... WWWW WWWW WWWW
.... .... WWWW WWWW WWWW WWWW
.... WWWW WWWW WWWW WWWW WWWW
WWWW WWWW WWWW WWWW WWWW WWWW
```
#### Close call
```
walls: [[2, 2], [3, 3], [4, 4]]
expected: true
steps:
start 1 2 3 end
WWW WWW WWW WWW WWW
WW. WWW WWW WWW WWW
W.. WW. WWW WWW WWW
... W.. WW. WWW WWW
A---B A--B WA.B WWAB WWWA
... W.. WW. WWW WWW
W.. WW. WWW WWW WWW
WW. WWW WWW WWW WWW
WWW WWW WWW WWW WWW
```
#### So close .. but we can't make it
```
walls: [[2, 2], [3, 3], [3, 4]]
expected: false
steps:
start 1 2 end
WWW WWW WWW WWW
WWW WWW WWW WWW
W.. WWW WWW WWW
... W.. WWW WWW
A---B A--B WA.B WWXB <-- X is position the north wall hits us
... W.. WW. WWW
W.. WW. WWW WWW
WW. WWW WWW WWW
WWW WWW WWW WWW
```
#### We stand no chance
```
walls: [[3, 3], [1, 1], [3, 3]]
expected: false
steps:
start end
WWW WWW
.W. WWW
.W. .W.
A---B AW-B <-- A is blocked by walls
.W. .W.
.W. WWW
WWW WWW
```
</details>
| algorithms | def can_escape(walls):
return all(a > i < b for i, (a, b) in enumerate(walls, 1))
| Hurry up, the walls are closing in! | 63ab271e96a48e000e577442 | [
"Algorithms",
"Mathematics",
"Arrays"
] | https://www.codewars.com/kata/63ab271e96a48e000e577442 | 7 kyu |
### Intro
Your friend recently started learning how to play a guitar. He asked for your help to write a program that will help to find frets for each note on the guitar.
## Main task:
He wants to enter 2-4 parameters: `note, exact, string and position`.
All inputs will be valid.
1) note - "name" of the note. There are 12 names: `'A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'`. They are represents all octave semitones.
2) exact - boolean parameter. If it's true, you should find only exact same 'high' notes (See 'little tip' below in the description). If it's false - return all notes frets with the same name.
3) string [only for exact === true] - number of the string for current note. `1 <= string <= 6`.
4) position [only for exact === true] - every string contain `1` or `2` notes with the same name (I will explain later). This parameter defines exactly what note should be chose.
Depending on `exact` value, return all frets with same note name or exactly the same notes.
```if:python
Output format: `[(string, fret), (string, fret), (string,fret), ...]`.
```
```if-not:python
Output format: `[[string, fret], [string, fret], [string,fret], ...]`.
```
Where `1 <= string <= 6` and `0 <= fret <= 22`. Both are integers. Frets could be placed in any order in the output array.
## SOME MUSICAL THEORY:
Guitar neck has 22-24 frets (in this Kata we will use 22-frets guitar). This means each string contains 23 semitones: open string (is 0 fret) plus 22 frets.
In this Kata guitar has standard tuning. It describes what name has each string on 0 fret (open string). Standard tuning: EBGDAE (from 1st string to 6th).
"Difference" between two adjacent notes from the 'notes list' equals a semitone. "Difference" between strings equals 5 semitones, except B-G strings with 4 semitones difference.
Short piece of the guitar neck, to show you how it looks like:
| string\freat| | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | ... |
| -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- |
| | | | | | | | | | | | | | | | | |
| 1| | E | F | F# | G | G#| A | A# | B | C | C# | D | D# | E | F | ... |
| 2| | B | C | C# | D | D#| E | F | F# | G | G# | A | A# | B | C | ... |
| 3| | G | G# | A | A# | B | C | C# | D | D# | E | F | F# | G | G# | ... |
| 4| | D | D# | E | F | F#| G | G# | A | A# | B | C | C# | D | D# | ... |
| 5| | A | A# | B | C | C#| D | D# | E | F | F# | G | G# | A | A# | ... |
| 6| | E | F | F# | G | G#| A | A# | B | C | C# | D | D# | E | F | ... |
Let me explain `position` parameter meaning. The notes with the same name could be found on the string once or twice. Let `position = 1` be for left note (smaller fret) and `position = 2` is for right note if such exist (bigger fret). Take a look at this example:
| string\freat| | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | ... |
| -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- |
| | | | | | | | | | | | | | | | | |
| 1| | `E` | *F* | F# | G | G#| A | A# | B | C | C# | D | D# | `E` | *F* | ... |
The notes with the same names marked: `'E'`: `(1, 0)` and `(1, 12)`, `'F'`: `(1, 1)` and `(1, 13)` and so on.
### A little tip
To understand what should function return, think about notes as about vibration frequency. So if you should return exactly same note, you have to find frets that represent same vibration frequency.
You can image that with math. Let the input is getFrets("E", true, 1, 1). So we need to find same frets for note 'E' on the 1st string 1st position. It's position is `(1, 0)` - `(string, fret)`. Let call it `x`. We know the "difference" between strings equals 5 semitones. So `(2, 0) = 'B' on 2nd string = x - 5`.
Then we should go right on this string, adding 1 semitone for each step. `C = x - 4`, `C# = x - 3`, `D = x -2`, `D# = x -1`, `E = x`. So `(2, 5) = (1, 0)` and so on.
Take a look at this example:
| string\freat| | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | ... |
| -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- |
| | | | | | | | | | | | | | | | | |
| 1| | `E` | F | F# | G | G#| A | A# | B | C | C# | D | D# | E | F | ... |
| 2| | B | C | C# | D | D#| `E` | F | F# | G | G# | A | A# | B | C | ... |
| 3| | G | G# | A | A# | B | C | C# | D | D# | `E` | F | F# | G | G# | ... |
| 4| | D | D# | E | F | F#| G | G# | A | A# | B | C | C# | D | D# | ... |
| 5| | A | A# | B | C | C#| D | D# | E | F | F# | G | G# | A | A# | ... |
| 6| | E | F | F# | G | G#| A | A# | B | C | C# | D | D# | E | F | ... |
I marked the same note. So for getFrets("E", true, 1, 1) we should return frets that represent the same note as `(1, 0)`.
```if:python
The answer is: `[(1, 0), (2, 5), (3, 9), (4, 14), (5, 19)]`.
```
```if-not:python
The answer is: `[[1, 0], [2, 5], [3, 9], [4, 14], [5, 19]]`.
``` | games | STRINGS = 'EBGDAE'
NOTES = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#']
def get_frets(note, exact, * string_position):
if exact:
s0, p = string_position
f0 = (NOTES . index(note) -
NOTES . index(STRINGS[s0 - 1])) % 12 + (p - 1) * 12
return [(s, f) for s in range(1, 7) if 0 <= (f := f0 + (s - s0) * 5 + (s0 > 2 and s < 3) - (s > 2 and s0 < 3)) <= 22]
return [(s, f) for s, n in enumerate(STRINGS, 1) for f in range(23) if NOTES[(NOTES . index(n) + f) % 12] == note]
| Guitar #1: Find the frets | 5fa49cfb19923f00299eae22 | [
"Puzzles"
] | https://www.codewars.com/kata/5fa49cfb19923f00299eae22 | 6 kyu |
You and your friends want to rent a house for the new year, but the problem is that people can go for a different number of days. It is necessary to calculate the amount that each person must pay, depending on how many days he is going to live in this house. The amount per person is the rental price divided by the number of people living in the house on a given day. Rent paid every time someone leaves the house
Write a function that takes an array with the number of days each person will live in the house (the length of the array is the total number of people) and the rent per apartment per day. The function should return a dictionary where the key will be the number of days, and the value will be the amount that the person must deposit.
The amount must be rounded up each time rent is paid. That is, every time someone leaves the house. Should be rounded up to the next whole number.
Example:
```python
person = [7, 7, 7, 7, 1, 1, 2, 4, 5, 6]
house_price = 100
result = calculate_cost_per_person(person, house_price)
# result == {1: 10, 2: 23, 4: 52, 5: 69, 6: 89, 7: 114}
``` | algorithms | from collections import Counter
from math import ceil
def calculate_cost_per_person(array: list[int], rental: int) - > dict[int, int]:
res, days, rest, last = {}, Counter(array), len(array), 0
for k in sorted(days):
res[k] = res . get(last, 0) + ceil(rental / rest * (k - last))
rest, last = rest - days[k], k
return res
| New year house rental | 63aa7b499c53c5af68e86a86 | [
"Algorithms"
] | https://www.codewars.com/kata/63aa7b499c53c5af68e86a86 | 6 kyu |
# Underload interpreter
Underload is an esoteric programming language. It is a stack based, turing complete language that works based on strings. Strings are the only datatype in Underload.
## Commands
- `(x)`: An underload string:
- Starts with an opening parenthesis `(`, and pushes all characters after the starting `(` and before the closing parenthesis `)` as a string.
- Parentheses that come after the first `(` *must* be matched, and a matched `)` will not end the string.
- An Underload program can only contain balanced parentheses i.e. `(()` is an invalid program.
- If all parentheses in a string are not correctly matched, you must raise an Exception.
- `:`: Duplicate the top element of the stack.
- `!`: Remove the top element of the stack.
- `~`: Swap the top two elements in the stack.
- `*`: Concatenate the top element of the stack to the end of the second element of the stack.
- The top element and second element are both popped and the concatenated string is pushed in their place.
- This is *ordinary string concatenation*, if the top of the stack is `["(a)","(b)"]`, the resulting stack should be `["(a)(b)"]`.
- `a`: Enclose the top element of the stack in a set of parentheses.
- `^`: Include the top element of the stack into the program after this command. The top element is popped.
- The string must be inserted *after* the position of the `^` command being executed.
- For example, if the code is `^a*` and the top of the stack is `"S~!"`, then the code becomes `^S~!a*`, and execution continues starting with `S`.
- `S`: Pop the top element of the stack, and output it (no newline). In the case of this challenge, you will have to
store the output every time `S` is called, and return it as a single string at the end of the program.
Code is interpreted from left to right.
Commands not mentioned in the command list must be ignored.
**Stack underflow** is a condition where a command is run, but there are no arguments on the stack to use for it.
You do not need to handle stack underflow.
The program ends when it reaches the end of the code.
You can learn more about Underload from its [Esolangs Wiki](https://esolangs.org/wiki/Underload) page. | algorithms | def matches_brackets(s):
c = 0
for v in s:
if v == "(":
c += 1
if v == ")":
c -= 1
if c < 0:
return False
return c == 0
def take_until_close(itr):
res, c = "", 0
for v in itr:
if v == ")" and not c:
return res
if v == ")":
c -= 1
if v == "(":
c += 1
res += v
def underload(code):
if not matches_brackets(code):
raise Exception("Parenthesis don't match")
stack, output = [], ""
def iter_code(code):
code = iter(code)
for v in code:
if v == "(":
stack . append(take_until_close(code))
continue
yield v
if v == "^":
yield from iter_code(stack . pop())
for command in iter_code(code):
if command == ":":
stack . append(stack[- 1])
if command == "!":
stack . pop()
if command == "~":
stack . append(stack . pop(- 2))
if command == "*":
v = stack . pop()
stack[- 1] += v
if command == "a":
stack[- 1] = f"( { stack [ - 1 ]} )"
if command == "S":
output += stack . pop()
return output
| Underload Interpreter | 632c4222a1e24b480d9aae0d | [
"Interpreters",
"Esoteric Languages",
"Algorithms",
"Tutorials"
] | https://www.codewars.com/kata/632c4222a1e24b480d9aae0d | 5 kyu |
## Description
You are given four tuples. In each tuple there is coordinates x and y of a point. There is one and only one line, that goes through two points, so with four points you can have two lines: first and second tuple is two points of a first line, thirs and fourth tuple is two points of the second line. Your task is to find and return a tuple with x and y coordinates of lines crossing point.
Numbers can be positive as well as negative, integer or floats. Your answer shouldn't be rounded!!
Note, that if two lines are the same ( have infinite crossing points ) or parallel ( have no crossing points ), you will need to return ```None```.

## Examples
``` python
find_the_crossing((5,3), (10,4), (5,7.5), (10,7)) => (20, 6) #from the graphic above
find_the_crossing((5,3), (10,4), (20,6), (0,2)) => -1 #edge case for two identical lines
find_the_crossing((5,3), (10,4), (5,5), (10,6)) => -1 #edge case for two parallel lines
```
## Tests
There will be example tests, random tests and tests on big numbers.
**Example tests** are pre programmed tests for debugging.
**Random tests** are generated randomly, where ```-1000 β€ x β€ 1100```. There is still will some with parallel and identical lines.
**Tests on big numbers** are random tests where ```-1000000000 β€ x β€ 1000000000``` | games | def find_the_crossing(a, b, c, d):
a11, a12, b1 = b[1] - a[1], a[0] - b[0], a[0] * \
(b[1] - a[1]) + a[1] * (a[0] - b[0])
a21, a22, b2 = d[1] - c[1], c[0] - d[0], c[0] * \
(d[1] - c[1]) + c[1] * (c[0] - d[0])
det = a11 * a22 - a12 * a21
return ((b1 * a22 - a12 * b2) / det, (a11 * b2 - b1 * a21) / det) if det != 0 else None
| Find the crossing ( graphic calculations ) | 63a5b74a9803f2105fa838f1 | [
"Algebra",
"Mathematics",
"Linear Algebra",
"Graphics"
] | https://www.codewars.com/kata/63a5b74a9803f2105fa838f1 | 6 kyu |
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Preface</summary>
This is the first of (hopefully) a series of kata's about military units in the Roman Army. This kata concerns the <a href="https://en.wikipedia.org/wiki/Contubernium_(Roman_army_unit)">Contubernium</a>, which is the basic military unit. Only infantry units are in scope.
</details>
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Task</summary>
##### "Given the formation of one or more Contubernium units, render those units as string."
### Input
- formation: a <code>'-'</code> delimited string containing the formation type, size of unit, and amount of units. For instance, <code>'A-8-1'</code> is the standard Contubernium unit standing at attention.
- formation type: char <code>'A'</code> or <code>'M'</code>
- <code>'A'</code>: standing at (A)ttention
- <code>'M'</code>: (M)arching
- size: an even positive number representing the amount of soldiers in a single military unit
- count: a positive number representing the amount of military units
### Output
- return a <code>'\n'</code> delimited string, with rows of equal size, representing the units positioned conform the specified formation. Characters used in the output:
- <code>'.'</code>: ground
- <code>'/'</code>: stride (during march)
- <code>'\\'</code>: location of a soldier
- <code>'Β΄'</code>: identifies a legionary
- <code>'Β¨'</code>: identifies a decanus
</details>
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Input Constraints</summary>
- size will always be even (because of pair forming when marching)
- 50 tests with 2 <= size <= 10 and 1 <= count <= 2
- 50 tests with 2 <= size <= 10 and 3 <= count <= 6
- 50 tests with 10 <= size <= 20 and 1 <= count <= 2
- 50 tests with 10 <= size <= 20 and 10 <= count <= 20
- 50 tests with 45 <= size <= 50 and 45 <= count <= 50
</details>
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Specification</summary>
### Soldiers
- legionary: the standard soldier
- decanus: the ranking officer of a Contubernium
- all soldiers are always rendered by 2 tiles:
- left: their identifier
- right: their location (and body)
```
---------------------
soldiers
---------------------
Β΄\ legionary
Β¨\ decanus
```
### Contubernium
- the Contubernium is the basic military unit
- it usually consists of 7 legionaries and 1 decanus (size = 8), together they are the contubernales
### Formations
- both formations described below are in 2D perspective. The main direction is <code>β</code>.
- for both formations, render a rectangle big enough to contain the formation while allowing a padding of 1 ground tile in all directions (up, down, left, right)
- there are sample tests for each of the examples described below
#### standing at Attention
- within one unit:
- legionaries are standing horizontally next to eachother with 1 tile beteen them
- the decanus stands across (β) the middle legionary with 1 tile between them
- between units:
- there are 3 tiles between the right-most legionary of a unit and the left-most legionary of the next unit
```
---------------------
standing at attention
---------------------
A-2-1 A-2-2
...... ..........
...Β΄\. ...Β΄\..Β΄\.
...... ..........
.Β¨\... .Β¨\..Β¨\...
...... ..........
A-4-1 A-4-2
........ ................
.Β΄\Β΄\Β΄\. .Β΄\Β΄\Β΄\..Β΄\Β΄\Β΄\.
........ ................
.Β¨\..... .Β¨\......Β¨\.....
........ ................
A-8-1 A-8-2
................ ................................
.Β΄\Β΄\Β΄\Β΄\Β΄\Β΄\Β΄\. .Β΄\Β΄\Β΄\Β΄\Β΄\Β΄\Β΄\..Β΄\Β΄\Β΄\Β΄\Β΄\Β΄\Β΄\.
................ ................................
.....Β¨\......... .....Β¨\..............Β¨\.........
................ ................................
```
#### Marching
- within one unit:
- legionaries are walking in pairs, with 1 tile between each member of pair
- the decanus forms a pair with one of the legionaries, and takes left position from our point of view
- each pair walks in a straight line (β) behind the pair in front of them
- legionaries that don't have another person within 2 tiles to the right, have their stride visible
- between units:
- there is 1 tile between the last pair of a unit and the first pair of the next unit
```
---------------------
marching
---------------------
M-2-1 M-2-2
.........
...Β¨\Β΄\/.
....... .........
.Β¨\Β΄\/. .Β¨\Β΄\/...
....... .........
M-4-1 M-4-2
...........
.....Β΄\Β΄\/.
....Β¨\Β΄\/..
........ ...........
..Β΄\Β΄\/. ..Β΄\Β΄\/....
.Β¨\Β΄\/.. .Β¨\Β΄\/.....
........ ...........
M-8-1 M-8-2
...............
.........Β΄\Β΄\/.
........Β΄\Β΄\/..
.......Β΄\Β΄\/...
......Β¨\Β΄\/....
.......... ...............
....Β΄\Β΄\/. ....Β΄\Β΄\/......
...Β΄\Β΄\/.. ...Β΄\Β΄\/.......
..Β΄\Β΄\/... ..Β΄\Β΄\/........
.Β¨\Β΄\/.... .Β¨\Β΄\/.........
.......... ...............
```
</details>
| reference | def draw(formation):
def A(u, n):
u -= 1
if u == 1:
ls = ".." + ".Β΄\\." * n
d = n * ".Β¨\\." + ".."
else:
ls = n * ('.' + "Β΄\\" * u + '.')
d = n * ("Β¨\\" . center(u - 1 << 1, '.') + "....")
return (g := '.' * len(d)), ls, g, d, g
def M(u, n):
def line(i, is_g, is_d):
if is_g:
return '.' * s
kind = "´¨" [is_d] + "\\´\\/"
return kind . ljust(i + 5, '.'). rjust(s, '.')
l = u / / 2 + 1
s = 5 + n * l
return (line(i, i % l == 0, (i + 1) % l == 0) for i in range(n * l + 1))
k, * un = formation . split('-')
return "\n" . join(locals()[k](* map(int, un)))
| Roman Army Formations: Contubernium | 63a489ce96a48e000e56dda0 | [
"Fundamentals",
"Strings",
"ASCII Art",
"Geometry",
"Mathematics"
] | https://www.codewars.com/kata/63a489ce96a48e000e56dda0 | 5 kyu |
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Task</summary>
##### "Given a positive integer <code>n</code>, return a string representing the box associated with it."
- Boxes can get huge fast, so range of <code>n</code> is <code>1 - 20</code> (upper limit included/excluded depending on language).
- Rows are delimited by a newline <code>'\n'</code> and all rows have same length.
- Make sure to include the corrrect amount of leading and trailing whitespace where necessary.
- Characters used in box: <code>'|', '_', ' '</code>.
- Keep an eye out on performance of your solution.
- Code length limited to <code>2000</code> characters to prevent hardcoding.
</details>
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Puzzle</summary>
Can you figure out the pattern and extend boxes for <code>n > 4</code>?
```
---------------------------------
n box height width
---------------------------------
_
1 |_| 2 3
_ _
2 | _| 3 5
|_|_|
_ _ _
3 | _| 5 7
| _|_|
| | _|
|_|_|_|
_ _ _ _
4 | _| 9 9
| _|_|
| | _|
| _|_|_|
| | _|
| | _|_|
| | | _|
|_|_|_|_|
```
</details>
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Alignment</summary>
In the example below, whitespace is replaced by <code>'*'</code> to give an idea where to draw whitespace.
```
*_*_*_*
|****_|
|**_|_|
|*|**_|
|_|_|_|
```
</details>
Good luck!
| algorithms | def draw(n):
if n == 1:
return '\n' . join([" _ ", "|_|"])
inside = draw(n - 1). splitlines()
return "\n" . join(
"| " [i < 1] + "_ " [0 < i < 2 * len(inside) - 2] + "| " [i < len(inside)] +
row[1:] for i, row in enumerate(inside + inside[1:])
)
| Boxes in boxes | 63a2cf5bd11b1e0016c84b5a | [
"Algorithms",
"ASCII Art",
"Performance",
"Strings",
"Puzzles",
"Memoization",
"Recursion",
"Mathematics",
"Dynamic Programming"
] | https://www.codewars.com/kata/63a2cf5bd11b1e0016c84b5a | 5 kyu |
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Task</summary>
##### "Given a positive integer <code>n</code>, return a string representing the pyramid associated with it."
Pyramids can get huge, so range of <code>n</code> is <code>1 - 100</code>. Rows are delimited by a newline <code>'\n'</code> and all rows have same length. Make sure to include the corrrect amount of leading and trailing whitespace where necessary. Be aware there is also a recurring pattern of whitespace inside the pyramid.
- Characters used in pyramid: <code>'/', '\\', ' ', '_', ':', '|', '.', 'Β΄'</code>.
- Code length limited to <code>1000</code> (C#: <code>2000</code>) characters to prevent hardcoding.
```
'*' shows whitespace to give a better impression how to render the pyramid
n = 3 *******./\*****
****.Β΄\/__\****
*.Β΄\Β΄\/__:_\***
\*\Β΄\/_|__|_\**
*\Β΄\/|__|__|_\*
**\/__|__|__|_\
```
</details>
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Puzzle</summary>
##### "Can you figure out the pattern and extend pyramids for <code>n > 5</code>?"
```
--------------------------------------------------
pyramid n properties
--------------------------------------------------
./\ 1 height: 2
\/__\ width: 5
./\ 2 height: 4
.Β΄\/__\ width: 10
\Β΄\/__:_\
\/_|__|_\
./\ 3 height: 6
.Β΄\/__\ width: 15
.Β΄\Β΄\/__:_\
\ \Β΄\/_|__|_\
\Β΄\/|__|__|_\
\/__|__|__|_\
./\ 4 height: 8
.Β΄\/__\ width: 20
.Β΄\Β΄\/__:_\
.Β΄\ \Β΄\/_|__|_\
\Β΄\Β΄\Β΄\/|__|__|_\
\Β΄\Β΄\/__|__|__|_\
\Β΄\/_|__|__|__|_\
\/|__|__|__|__|_\
./\ 5 height: 10
.Β΄\/__\ width: 25
.Β΄\Β΄\/__:_\
.Β΄\ \Β΄\/_|__|_\
.Β΄\Β΄\Β΄\Β΄\/|__|__|_\
\ \Β΄\Β΄\Β΄\/__|__|__|_\
\Β΄\Β΄\Β΄\/_|__|__|__|_\
\Β΄\Β΄\/|__|__|__|__|_\
\Β΄\/__|__|__|__|__|_\
\/_|__|__|__|__|__|_\
...
./\ 8 height: 16
.Β΄\/__\ width: 40
.Β΄\Β΄\/__:_\
.Β΄\ \Β΄\/_|__|_\
.Β΄\Β΄\Β΄\Β΄\/|__|__|_\
.Β΄\ \Β΄\Β΄\Β΄\/__|__|__|_\
.Β΄\Β΄\Β΄\Β΄\Β΄\Β΄\/_|__|__|__|_\
.Β΄\ \Β΄\Β΄\Β΄\Β΄\Β΄\/|__|__|__|__|_\
\Β΄\Β΄\Β΄\Β΄\Β΄\Β΄\Β΄\/__|__|__|__|__|_\
\Β΄\Β΄\Β΄\Β΄\Β΄\Β΄\/_|__|__|__|__|__|_\
\Β΄\Β΄\Β΄\Β΄\Β΄\/|__|__|__|__|__|__|_\
\Β΄\Β΄\Β΄\Β΄\/__|__|__|__|__|__|__|_\
\Β΄\Β΄\Β΄\/_|__|__|__|__|__|__|__|_\
\Β΄\Β΄\/|__|__|__|__|__|__|__|__|_\
\Β΄\/__|__|__|__|__|__|__|__|__|_\
\/_|__|__|__|__|__|__|__|__|__|_\
...
```
</details>
Good luck!
<small>Too easy for you, try code golfing it.</small>
| games | def draw_pyramid(n):
mid = ['', '__', '__:_'] + [['', '|_', '_'][i % 3] + '_|_' * (i * 2 / / 3) for i in range(3, n * 2)]
return '\n' . join(
[' ' * (n * 3 - i * 3 - 2) + '.' + ('Β΄\\ \\' + 'Β΄\\' * (i - 2) if i > 2 and i % 2 else 'Β΄\\' * i) + '/' + mid[i] + '\\' + ' ' * (n * 2 - i - 1) for i in range(n)] +
[' ' * (i - n) + ('\\ ' + '\\Β΄' * (n * 2 - i - 2) if i > 1 and i == n and i % 2 else '\\Β΄' *
(n * 2 - i - 1)) + '\\/' + mid[i] + '\\' + ' ' * (n * 2 - i - 1) for i in range(n, n * 2)]
)
| Pyramide d'Azkee | 63a31f7d66ad15f77d5358b9 | [
"Algorithms",
"Puzzles",
"ASCII Art",
"Strings",
"Geometry"
] | https://www.codewars.com/kata/63a31f7d66ad15f77d5358b9 | 5 kyu |
Have you ever gotten tired of having to type out long function chains? I mean, seriously, look at this thing:
<!-- Translators - add something for your language! -->
```python
print(list(map(len,list(strings))))
```
What if there was a way to shorten the process, so we all can still be productive, even when we're lazy?
Presenting **function shorthand!**
```
print>list>map>len list>strings
```
---
## How-to:
You are given a string that you need to parse into normal functions (also returned as a string.)
- Function applications are represented with `>`: things after it are considered arguments:
Given | Return
---------------------
fn>1 | fn(1)
- Carrots can be nested or empty, but won't double up:
fn>fn>1 | fn(fn(1))
fn> | fn()
// ">>" does not appear
- Each space ` ` is replaced with a comma. However, if a space is separating the function and first argument, it is removed, along with any extra blanks:
fn > 1 2 | fn(1,2)
fn >1 fn>3| fn(1,fn(3))
fn> fn> 2| fn(fn(2))
- Functions containing nested functions will order them last, as `>` gets priority:
fn1 > 1 fn2 > 3 4 | fn(1,fn2(3,4))
// fn1 contains 1 and fn2.
// fn2 contains 3 and 4.
- Newlines won't be given: all input will be on the same line as one big chain.
---
# Task summarized:
Given a string of `functions` in **function shorthand**, return the string translated to normal function format.
---
**Technical Notes about Input:**
- **All inputs** will be valid (no unbalanced parentheses, multiple carrots in a row, or `(,)`).
- **Inputs** will all be one whole function chain.
- **Arguments** follow variable-esque syntax, but you might see a couple variables that start with a numbers.
- **Functions** will follow the same variable-ish rules that arguments do. Function words (like `fn`) won't always be seen as functions, sometimes you might recive things like `fn(fn)`.
**Please raise an issue if you see any invalid functions that snuck by!!** | games | from functools import reduce
# Kinda ironic isn't it?
def fn_shorthand(functions):
return ',' . join(reduce("{1}({0})" . format, map(str . strip, reversed(functions . split(">")))). split())
| Function Shorthand | 639f4307531bc600236012a2 | [
"Strings",
"Puzzles",
"Algorithms"
] | https://www.codewars.com/kata/639f4307531bc600236012a2 | 6 kyu |
Douglas Hofstadter is mainly known for his Pulitzer Prize winning book [GΓΆdel, Escher, Bach](https://en.wikipedia.org/wiki/G%C3%B6del,_Escher,_Bach). One common idea he explores in his books is self similarity and strange loops. He describes a unique sequence with special qualities as the composition of two known sequences, namely, square numbers and triangular numbers:
* Square numbers: `1, 4, 9, 16, 25, ...` --> formula: `$x * x$`
* Triangular numbers: `1, 3, 6, 10, 15, 21, ...` --> formula: `$(x * (x+1)) / 2$`
Hofstadter wrote them down in order (note: each element is marked with `s` for *square* and `t` for *triangular*):
```
1, 1, 3, 4, 6, 9, 10, 15, 16, 21, 25, ...
s, t, t, s, t, s, t, t, s, t, s, ...
```
When a number appears in both sequences (e.g. `1, 36`), the *square* value always precedes the *triangular*:
```
1, 1, 3, ..., 28, 36, 36, 45, ...
s, t, t, ..., t, s, t, t, ...
not
t, s, t, ..., t, t, s, t, ...
```
Notice the number of *triangular* elements between the *square* values! If we were to generalize this observation, we might ask: *how many triangular numbers between successive squares?*
This gives a special sequence: `2, 1, 2, 1, 1, ...` Can you explore the rest?
## Task
Complete the function that can return an **infinite stream** of values representing the number of triangular numbers between successive squares.
~~~if:lambdacalc
## Encodings
purity: `LetRec`
numEncoding: `BinaryScott`
export deconstructors `head, tail` for your `Stream` encoding
## Performance
`Submit` tests expect `20 000` values in time.
~~~ | algorithms | # see: https://oeis.org/A006338
from itertools import count
def special_sequence(sqrt2=2 * * 0.5):
for n in count(1):
yield round((n + 1) * sqrt2) - round(n * sqrt2)
| Number Sequence Rabbit Hole | 63a249a9e37cea004a72dee9 | [
"Puzzles",
"Mathematics"
] | https://www.codewars.com/kata/63a249a9e37cea004a72dee9 | 6 kyu |
Story
------
In 22022, a disaster wiped out human beings. A team of alien archaeologists wanted to find out more about languages of human beings. However, when it comes to English, they only see letters with numbers. You are the leader of this group, with your master-alien-mind, you figured out the numbers mean the sum of words, now you just have to figure out the value of each number!
***
Task
======
Write a function with a string parameter, consisting of ONLY lowercase letters, and seperated by spaces. Use the test cases to figure out what each lowercase value represents, and return the sum of the words in list/tuple (depending on language). The letters represent values from 1-26.
Input
------
a string of words, seperated by spaces.
Output
------
A list/tuple representing the sum of words.
#### Example
```python
"i am fine thank you" ---> [24, 32, 73, 61, 32]
```
### Precondition
```python
number of tests = 160
30<=number of words<=60
2<=length of words<=20
```
### Notes
+ the alphabets' values are not in the alphabetical order.
+ any translations will be appreciated!
+ You can definitely solve the value of each word in example test cases, it's guaranteened.
+ Only try to solve this kata when you have at least 1 hour of time | games | from collections import Counter
tmp = """\
test.assert_equals(sum_words('i am fine thank you'), [24, 32, 73, 61, 32])
test.assert_equals(sum_words('do you have a clue yet'), [14, 32, 70, 13, 57, 52])
test.assert_equals(sum_words('i bet some of you guys still got no idea'), [24, 38, 78, 35, 32, 54, 106, 28, 11, 64])
test.assert_equals(sum_words('gta san andreas'), [31, 40, 101])
test.assert_equals(sum_words('sensei believes in you'), [123, 158, 25, 32])
test.assert_equals(sum_words('if you want to give up look at test cases'), [49, 32, 42, 22, 67, 23, 57, 25, 73, 95])
test.assert_equals(sum_words('oddb cat doti getff ahhn'), [21, 32, 50, 91, 54])
test.assert_equals(sum_words('jhhib jkjkac anttle emcmd'), [69, 54, 83, 72])
test.assert_equals(sum_words('pigu que ner'), [53, 39, 45])
test.assert_equals(sum_words('stand uqe var llw lex aay zot'), [56, 39, 48, 60, 54, 43, 30])
"""
to_solve, solved = {}, {}
for line in tmp . splitlines():
words, values = line[30: - 1]. split("'), ")
for w, v in zip(words . split(), eval(values)):
to_solve[frozenset(w)] = (v, Counter(w))
while to_solve:
for k, (v, c) in [* to_solve . items()]:
if len(k) == 1:
x = next(iter(k))
solved[x] = v / / c[x]
del to_solve[k]
for k, (v, c) in [* to_solve . items()]:
if (u := k & solved . keys()):
if len(u) < len(k):
to_solve[frozenset(k - solved . keys())] = (v -
sum(solved[x] * c[x] for x in u), c)
del to_solve[k]
def sum_words(s):
return [sum(solved[c] for c in w) for w in s . split()]
| #Paper and pencil: Figure out the value of letters by sum of words. | 639d78b09547e900647a80c7 | [
"Strings",
"Logic",
"Ciphers",
"Puzzles"
] | https://www.codewars.com/kata/639d78b09547e900647a80c7 | 6 kyu |
## Description
You will have to write a function that takes ```total``` as an argument, and returns a list. In this list there should be one or more nested lists; in each of them - three natural numbers ( including 0 ), so that the sum of this three numbers equals ```total```, and the product of this numbers ends with us much zeroes as possible.
You will need to find all solutions. The ```total``` will be from 1 to 500, so you can use bruteforce. Feel free to create programm that can work not only for 3, but for any amount of numbers!
Note that you have to output only **unique** sets of numbers in **ascending** order.
## Examples
```python
zero_count(407) = [[32, 125, 250]] # 32, 125 and 250 is the only three numbers with sum of 407, that after multiplication have 6 zeroes. Other numbers have less
zero_count(199) = [[10, 64, 125], [24, 25, 150], [24, 50, 125], [24, 75, 100], [34, 40, 125]] # there is 5 possible solutions
zero_count(3) = [[0, 0, 3], [0, 1, 2]] # 2 solutions, each of them give 1 trailing zero
``` | algorithms | def zero_count(sum):
most = 0
res = []
for x in range(sum / / 3 + 1):
for y in range(x, (sum - x) / / 2 + 1):
z = sum - x - y
count = len(p := str(x * y * z)) - len(p . rstrip("0"))
if count == most:
res . append([x, y, z])
elif count > most:
most = count
res = [[x, y, z]]
return res
| Zero count in product | 639dd2efd424cc0016e7a611 | [
"Fundamentals",
"Algebra"
] | https://www.codewars.com/kata/639dd2efd424cc0016e7a611 | 6 kyu |
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Task</summary>
##### "Given a plane and numbers on or around that plane, return the coordinates of those numbers."
### Input
- plane: a string, representing a plane in 2D perspective. The string is delimited by newline <code>'\n'</code> and each line has the same length. The string contains numbers, ranging from <code>0</code> to at most </code>9</code>. There will be at least 1 and at most 10 numbers in the string. Numbers will not contain gaps and always start with <code>0</code>. If, for instance, there are 3 numbers, they will be <code>[0, 1, 2]</code>. Those numbers can be in the plane or around it. The coordinate system around the plane is the same as in the plane.
### Output
- return an array of 2-ples, with each 2-ple representing the Y- and X-coordinates of the corresponding number in that array. For instance, <code>[[0, 0], [1, 0]]</code> represents coordinates <code>[0, 0]</code> for number <code>0</code> and coordinates <code>[1, 0]</code> for number <code>1</code>.
</details>
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Coordinate System</summary>
The plane is a 2D perspective of a 2D plane, with Y-coordinates going <code>β</code> (length) an X-coordinates going <code>β</code> (width).
```
2D perspective of a plane
/ / / / Y-coords β
/ / / / X-coords β
/ / / /
```
The zero point <code>[0, 0]</code> is located at the bottom left edge, this point is anchored to our view of the plane.
```
Zero point
/ / / / p -> [0, 0]
/ / / /
/p/ / /
```
Points across the Y-axis have the same X-coordinate.
```
Points across Y-axis
/2/ / / 0 -> [0, 0]
/1/ / / 1 -> [1, 0]
/0/ / / 2 -> [2, 0]
```
Points across the X-axis have the same Y-coordinate.
```
Points across X-axis
/ / / / 0 -> [0, 0]
/ / / / 1 -> [0, 1]
/0/1/2/ 2 -> [0, 2]
```
Points can be outside the plane, but only their X-coordinates, the Y-range is fixed. We should look at it from a rectangular frame. All points within that frame are eligible, if they do not collide with a raster or location where an extended raster would be.
```
Points outside of the plane Rectangular frame around the plane
1/ / / / 0 -> [1, -1] +-/-/-/-/ - -> all valid locations for points
0/ / / /3 1 -> [2, -1] -/-/-/-/- + -> all invalid locations for points
/ / / /2 2 -> [0, 3] /-/-/-/-+
3 -> [1, 3]
```
You will <b>always</b> receive a valid plane and valid points. Examples of invalid situations:
```
Points cannot be on the raster, or outside the plane where the raster would be if we extend the plane
/ / 1 / 0 -> invalid, point on raster
0 / / / 1 -> invalid, point on raster
/ / / / 2 2 -> invalid, point on raster
Points cannot be out of bounds of Y-axis
1 1 -> invalid, Y too big
/ / /
/ / /
0 0 -> invalid, Y too low
The plane is not aligned properly to the bottom-left edge
/ / /
/ / /
0/ / / 0 -> invalid, the raster should be here
```
</details>
| algorithms | def find_coords(plane):
arr = plane . split('\n')
d = {}
for y, row in enumerate(arr[:: - 1]):
for x, char in enumerate(row, - y):
if char . isdigit():
d[int(char)] = ((y, (x - 1) / / 2))
return [d[i] for i in range(len(d))]
| 2D Coordinates Finder! | 639ac3ded3fb14000ed38f31 | [
"Algorithms",
"Strings",
"Geometry",
"Mathematics"
] | https://www.codewars.com/kata/639ac3ded3fb14000ed38f31 | 7 kyu |
Sami is practicing her aim with her bow and is shooting some balloons in the air. On each balloon, they have different numbers written on them which represent their size. She would like to pop the balloon highest in the air that also has the most balloons of the same size present. If there is a tie, then she will instead pop the balloon of the size highest in the air. Do you think you can output which balloon she pops on each shot?
You will be provided an array of the balloons as integers (the integers representing the sizes) in lowest to highest order in the air. You will also be given an integer _**pops**_, which will be the number of pops that Sami will execute.
Constraints
---
0 < _**pops**_ <= number of elements in _**balloons**_
10 <= number of elements in _**balloons**_ <= 500
1 <= balloon size <= 1000
Example
---
```
pops = 4
balloons = [5, 7, 5, 7, 4, 5]
pop #1: 5
pop #2: 7
pop #3: 5
pop #4: 4
return: [5, 7, 5, 4]
```
Explanation
---
For pop #1, we return 5 because it is the most frequent, the list now becomes {5, 7, 5, 7, 4}. In pop #2, we return 7, since 5 and 7 are the most frequent, but 7 is the highest, so we pop 7. The list now becomes {5, 7, 5, 4}. In pop #3, we pop 5 since itβs the most frequent. The list now becomes {5, 7, 4}. In pop #4, we pop 4 since all balloons now have the same count (here: 1), but the balloon of size 4 is the highest in the air. | games | from collections import Counter
def freq_stack(pops, balloons):
lst = []
cntr = Counter()
for i, b in enumerate(balloons):
cntr[b] += 1
lst . append((- cntr[b], - i, b))
return [b for _, _, b in sorted(lst)[: pops]]
| Popping Balloons | 633b8be2b5203f003011d79e | [
"Algorithms",
"Puzzles",
"Data Structures"
] | https://www.codewars.com/kata/633b8be2b5203f003011d79e | 6 kyu |
```if-not:rust
<b>Write two functions, one that converts standard time to decimal time and one that converts decimal time to standard time.</b>
```
```if:csharp
<ul><li>One hour has 100 minutes (or 10,000 seconds) in decimal time, yet its duration is the same as in standard time. Thus a decimal minute consists of 36 standard seconds, which is 1/100 of an hour.</li>
<li>Working time is usually rounded to integer decimal minutes. Thus one standard minute equals 0.02 decimal hours, while two standard minutes equal 0.03 decimal hours and so on.</li>
<li>The terms "normal" and "standard" time are considered synonymous in this kata, just like the terms "decimal" and "industrial" time.</li>
<li><code>ToIndustrial(time)</code> should accept either the time in minutes as an integer or a string of the format "h:mm". Minutes will always consist of two digits in the tests (e.g., "0:05"); hours can have more. Return a float that represents decimal hours (e.g. 1.75 for 1h 45m). Round to a precision of two decimal digits - do not simply truncate!</li>
<li><code>ToNormal(time)</code></code>should accept a float representing decimal time in hours.
Return a string that represents standard time in the format "h:mm".</li>
<li>There will be no seconds in the tests. We'll neglect them for the purpose of this kata.</li>
</ul>
```
```if:rust
<b>Write three functions, two that convert standard time to decimal time with different input types and one that converts decimal time to standard time.</b>
<ul><li>One hour has 100 minutes (or 10,000 seconds) in decimal time, yet its duration is the same as in standard time. Thus a decimal minute consists of 36 standard seconds, which is 1/100 of an hour.</li>
<li>Working time is usually rounded to integer decimal minutes. Thus one standard minute equals 0.02 decimal hours, while two standard minutes equal 0.03 decimal hours and so on.</li>
<li>The terms "normal" and "standard" time are considered synonymous in this kata, just like the terms "decimal" and "industrial" time.</li>
<li><code>to_industrial(time)</code> should accept the time in minutes as an integer, <code>string_to_industrial(time)</code> should accept a string of the format "h:mm". Minutes will always consist of two digits in the tests (e.g., "0:05"); hours can have more. Return a float that represents decimal hours (e.g. 1.75 for 1h 45m). Round to a precision of two decimal digits - do not simply truncate!
</li>
<li><code>to_normal(time)</code> should accept a float representing decimal time in hours.
Return a string that represents standard time in the format "h:mm".</li>
<li>There will be no seconds in the tests. We'll neglect them for the purpose of this kata.</li>
</ul>
```
```if:ruby,python
<ul><li>One hour has 100 minutes (or 10,000 seconds) in decimal time, yet its duration is the same as in standard time. Thus a decimal minute consists of 36 standard seconds, which is 1/100 of an hour.</li>
<li>Working time is usually rounded to integer decimal minutes. Thus one standard minute equals 0.02 decimal hours, while two standard minutes equal 0.03 decimal hours and so on.</li>
<li>The terms "normal" and "standard" time are considered synonymous in this kata, just like the terms "decimal" and "industrial" time.</li>
<li><code>to_industrial(time)</code> should accept either the time in minutes as an integer or a string of the format "h:mm". Minutes will always consist of two digits in the tests (e.g., "0:05"); hours can have more. Return a float that represents decimal hours (e.g. 1.75 for 1h 45m). Round to a precision of two decimal digits - do not simply truncate!
</li>
<li><code>to_normal(time)</code> should accept a float representing decimal time in hours.
Return a string that represents standard time in the format "h:mm".</li>
<li>There will be no seconds in the tests. We'll neglect them for the purpose of this kata.</li>
</ul>
```
```if:java,cpp,javascript,typescript,kotlin,r,coffeescript
<ul><li>One hour has 100 minutes (or 10,000 seconds) in decimal time, yet its duration is the same as in standard time. Thus a decimal minute consists of 36 standard seconds, which is 1/100 of an hour.</li>
<li>Working time is usually rounded to integer decimal minutes. Thus one standard minute equals 0.02 decimal hours, while two standard minutes equal 0.03 decimal hours and so on.</li>
<li>The terms "normal" and "standard" time are considered synonymous in this kata, just like the terms "decimal" and "industrial" time.</li>
<li><code>toIndustrial(time)</code> should accept either the time in minutes as an integer or a string of the format "h:mm". Minutes will always consist of two digits in the tests (e.g., "0:05"); hours can have more.
Return a double that represents decimal hours (e.g. 1.75 for 1h 45m). Round to a precision of two decimal digits - do not simply truncate!
</li>
<li><code>toNormal(time)</code> should accept a double representing decimal time in hours.
Return a string that represents standard time in the format "h:mm".</li>
<li>There will be no seconds in the tests. We'll neglect them for the purpose of this kata.</li>
</ul>
```
<br/>
<details><summary>Flavor text (click to expand)</summary>
Calculations with time units can be confusing, because we are used to calculating in the decimal system in every day use. An hour, however, consists of sixty minutes, which in turn consist of sixty seconds each.
When dealing with multiple entries of measured time - for example, in a working time recording - it can get hard to correctly sum up the total. A seemingly natural algorithm is to add up hours and minutes separately, then divmod the minutes with 60 to get additional complete hours and remaining minutes.
In Germany, some companies use decimal time (in German: "Industriezeit" or "Industriestunden") to keep track of working hours, which makes it a lot easier to calculate multiple entries.</details>
<br/>
```if:java,cpp,javascript,typescript,kotlin,r,coffeescript
<h1>Examples:</h1>
<code>toIndustrial(1) => 0.02</code><br/>
<code>toIndustrial("1:45") => 1.75</code><br/>
<code>toNormal(0.33) => "0:20"</code><br/>
```
```if:ruby,python
<h1>Examples:</h1>
<code>to_industrial(1) => 0.02</code><br/>
<code>to_industrial("1:45") => 1.75</code><br/>
<code>to_normal(0.33) => "0:20"</code><br/>
```
```if:rust
<h1>Examples:</h1>
<code>to_industrial(1) => 0.02</code><br/>
<code>string_to_industrial("1:45") => 1.75</code><br/>
<code>to_normal(0.33) => "0:20"</code><br/>
```
<i>Please leave a rating if you liked this kata!</i>
| reference | def to_industrial(time):
if isinstance(time, str):
h, m = map(int, time . split(':'))
return h + round(m / 60, 2)
return round(time / 60, 2)
def to_normal(time):
return f' { int ( time )} : { str ( round ( time % 1 * 60 )). zfill ( 2 )} '
| Decimal Time Conversion | 6397b0d461067e0030d1315e | [
"Fundamentals",
"Algorithms",
"Date Time",
"Strings"
] | https://www.codewars.com/kata/6397b0d461067e0030d1315e | 7 kyu |
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Task</summary>
You're watching a swimming race and like to draw the current situation in the race. You are given the <i>indices </i> of each of the contestants, and the <i>length</i> of each lane. There are as much lanes as there are indices provided.
#### Input
- indices: an array containing integers (positive, negative and/or 0); each index represents the progress of the corresponding contestant.
- <code>0</code>: there is no contestant, so the lane is empty
- <code>positive</code>: the progress a contestant has made so far, counting from the start
- <code>negative</code>: the progress a contestant has made, counting back from the finish
- length: the length of each lane in the pool.
#### Output
- return a string displaying the swimming race; each lane is separated with a new line <code>'\n'</code>. Make sure to use the correct amount of leading and trailing white space for each lane. All lanes need to be of identical length.
</details>
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Race</summary>
- for each lane that has a contestant, that contestant performs the actions below; note that actions marked with <code>[p]</code> are only accessible by positive indices, and those marked by <code>[n]</code> only by negative indices. Other actions are accessible by all integers, except zero:
- [p] go on the mark (always on right side of the pool)
- [p] get set
- [p] jump into the water
- [p] swim a couple of strokes under water
- [p] surface from the water
- repeat:
- swim across
- turn
- swim back
- [n] finish (always on right side of the pool)
- [n] get out of the pool
- for each lane that has a contestant, there are two officials watching over the contestant: <code>p</code> on the left side, <code>q</code> on the right side; their job is to watch over how the contestants make their turn, and the one on the right also verifies the finish.
</details>
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Puzzle Goals</summary>
##### Since this is a puzzle, I can't give away too much. Example tests are your best friend.
- figure out the starting position of positive and negative indices
- figure out the different actions and how to draw these (go to mark, get set, jump, swim underwater, surface, swim, approach turn, turn, push away, finish, celebrate, leave pool, walk away, other?)
- figure out the positions of the officials, depending on position of the swimmer, and maybe other events?
</details>
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Input Constraints</summary>
- 100 random tests with 2 <= lane count <= 2 and 10 <= lane length <= 20
- 100 random tests with 4 <= lane count <= 4 and 10 <= lane length <= 20
- 100 random tests with 8 <= lane count <= 8 and 10 <= lane length <= 20
- 100 random tests with 1 <= lane count <= 8 and 10 <= lane length <= 20
</details>
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Examples</summary>
##### It's a puzzle, hit that 'Train' button.
One example can be spoiled here:
```
indices: [0, 0, 0, 0]
length: 10
return:
../~~~~~~~~~~//.. /1
../~~~~~~~~~~//.. /2
../~~~~~~~~~~//.. /3
../~~~~~~~~~~//.. /4
```
Okay, just to give you an idea about what to expect:
```
race just started
p./~~~~~~~~~~~~~~~~~~~<//q. /1
p./~~~~~~~~~~~~~~~~~~~<//q. /2
p./~~~~~~~~~~~~~~~~~~~<//q. /3
p./~~~~~~~~~~~~~~~~~~~~x/q. /4
p./~~~~~~~~~~~~~~~~~~~~x/q. /5
p./~~~~~~~~~~~~~~~~~~~<//q. /6
p./~~~~~~~~~~~~~~~~~~--//.q /7
p./~~~~~~~~~~~~~~~~~<<o//q. /8
all contestants have already swum one length and are now on the way back
p./~~~~~~~-x~~~~~~//.q /1
p./~~~~~~~~~-x~~~~//.q /2
p./~~~~~~~~~~~-x~~//.q /3
p./~~~~~~~~-x~~~~~//.q /4
p./~~~~~~~~~~~-x~~//.q /5
p./~~~~~~~~~~~-x~~//.q /6
p./~~~~~~~~~~~-x~~//.q /7
p./~~~~~~~-x~~~~~~//.q /8
```
</details>
| games | def swimming_pool(indices, length):
def draw_lane(index):
k, r = divmod(index + 5 * (index < 0), length)
i, s = special_args[index] if - 5 < index < 8 else normal_args[r]
t, s = k & 1, [s, s . translate(str . maketrans("<>", "><"))][k & 1]
prefix = ["p.p" [t and 0 < r < 5:][: 2], ".."][- length <= index <= 0]
middle = replace(template[::(- 1) * * t], i + 2 * t, s)[::(- 1) * * t]
suffix = index and "q.q" [
t or index in {- 5, - 2, - 1, 1} or not r or r > 4:][: 2] or ".."
return f" { prefix } / { middle . replace ( 'x' , 'xX' [ index == - 3 and clear_win ])}{ suffix } "
normal_args = ((- 6, "-x"), (- 5, "-x"), (- 4, ">x"),
(- 5, "<<o"), (- 4, "x<"))
normal_args += tuple((- 5 - i, "x-") for i in range(length - 5))
special_args = ((- 3, "~"), (- 1, "x"), (- 2, "x"),
(- 5, "<<o"), (- 3, "<"), (- 4, "--"))
special_args += ((- 5, "--"), (- 8, "<x-"), (- 5, "-x="),
(- 4, ">x"), (- 3, "ox"), (- 3, "</x"))
template = f" { '~' * length } //"
def replace(t, i, s): return t[: i] + s + t[i + len(t) + len(s):]
clear_win = sum(- 4 < index < 0 for index in indices) == 1
return "\n" . join(
f" { ' ' * ( len ( indices ) - 1 - i )}{ draw_lane ( index )} / { i + 1 }{ ' ' * i } "
for i, index in enumerate(indices)
)
| Swimming Race | 6394d7573c47cb003d3253ec | [
"Puzzles",
"ASCII Art",
"Strings",
"Logic"
] | https://www.codewars.com/kata/6394d7573c47cb003d3253ec | 5 kyu |
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Task</summary>
##### "You're standing on a cliff. Will you jump or not?"
#### Input
- setting: a string portraying the cliff and its surroundings. The setting represents a 2d portrait view at the cliff, where layers are separated by a newline `'\n'`. The following characters are used to represent objects in the setting:
- cliff `'#'`
- ground `'x'`
- air `'.'`
- water `'~'`
- you, the jumper `'Y'`.
#### Output
- return an array containing 2-ples of integers, each 2-tuple consisting of the number of units to jump down and the number of units to jump sideways (right = positive number, left = negative number); add a 2-ple for each possible jump you could make, order does not matter; return an empty array if no possible jump could be made
</details>
<details>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Specification</summary>
#### Your qualities / shortcomings / behaviors
- you can jump at most 2 units in horizontal direction
- you can jump at most 2 units in vertical direction if the surface below the target location is solid (ground or cliff)
- you can jump at most 4 units in vertical direction if the surface below the target location is shallow water (water with a depth of 1 unit)
- you can jump at most 8 units in vertical direction if the surface below the target location is deep water (water with a depth of 2 units or more)
- you will never jump from more than 8 units in vertical direction
- if you can't see the surface below you, you don't jump
- you cannot jump over other cliffs next to you or onto higher cliffs next to you
#### Positions before jumping
- you are always standing on top of the cliff, but possibly with some cliffs to the left or right of you at person height
- it may be the case that zero, one or multiple jumps are possible from the starting location
- a jump is only valid when you jump at least 1 unit down and at least 1 unit sideways; Height of the jump is measured from where you stand to where you hit either solid surface or water. So falling into the water does not count as jumping height.
#### Positions after jumping
- a jump ends when landing on a solid surface (ground or cliff), in shallow water, in deep water on water level when the vertical distance of the jump was not more than 4 units, or in deep water 1 unit below water level if the vertical distance of the jump was more than 4 units
- note that you land ___on___ solid surface, or ___in___ water; so when jumping `n` units down, you will end up `n` units lower when landing on solid surface, `n + 1` units lower if you hit shallow water or deep water if `n` is lower than 5, or `n + 2` units down when landing in deep water when `n` is higher than 4.
#### Physics
- air can't go under water
- water can't lean on air, it will always be contained; it can be on the same level as solid surface though (like a beach); it can also be on same level as the jumper
- once you jump, you cannot change horizontal direction mid air
</details>
<details>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Examples</summary>
##### All examples are available in the sample tests
#### No jumps possible
```
setting before jump
#1 return [] because you won't jump if you can't even see the surface
.......
..Y....
###....
###....
###....
#2 return [] because left you'll crash into the ground, and right you'll crash in shallow water
..Y....
.###...
.##....
.##....
.##....
.##....
x###~~~
#3 return [] because you are not near any edge of the cliff
..Y....
#####..
###....
###~~~~
#4 return [] because the water is on the same surface as you are standing
...Y....
~~~##~~~
#5 return [] because you are blocked, but you had no options to jump anyway
.......
.Y#....
###....
###....
###....
#6 return [] because you are blocked from jumping to the ground to the right
.......
.Y#....
###....
###xx~~
###xxxx
```
#### One or more jumps possible in 1 horizontal direction
```
setting before jump possible settings after jump
#1 return [[2,1], [3,2]]
..Y.... ....... .......
###.... ###.... ###....
###.... ###Y... ###....
####~~~ ####~~~ ####Y~~
#2 return [[2,2]]
.Y..... .......
###.... ###....
###.... ###Y...
####~~~ ####~~~
#3 return [[4,1]]
..Y.... .......
###.... ###....
###.... ###....
###.... ###....
###~xxx ###Yxxx
#4 return [[1,1], [4,2]]
.Y..... ....... .......
##..... ##Y.... ##.....
###.... ###.... ###....
###.... ###.... ###....
###~~~~ ###~~~~ ###Y~~~
#5 return [[4,1], [4,2]]
..Y.... ....... .......
###.... ###.... ###....
#...... #...... #......
#...... #...... #......
xx~~~~~ xx~Y~~~ xx~~Y~~
xxxx~~~ xxxx~~~ xxxx~~~
#6 return [[6,2]]
.Y..... .......
###.... ###....
###.... ###....
###.... ###....
###.... ###....
###~~~~ ###~~~~
###~~~~ ###Y~~~
#7 return [[9,2]]
.Y..... .......
###.... ###....
###.... ###....
###.... ###....
###.... ###....
###.... ###....
###.... ###....
###.... ###....
###~~~~ ###~~~~
###~~~~ ###Y~~~
```
#### One or more jumps possible in both horizontal direction
```
setting before jump possible settings after jump
#1 return [[2,-2], [2,1], [3,2]]
...Y... ....... ....... .......
..##... ..##... ..##... ..##...
..##... .Y##... ..##Y.. ..##...
~####~~ ~####~~ ~####~~ ~####Y~
#2 return [[2,-2], [3,1]]
..Y... ...... ......
.##... .##... .##...
~##... Y##... ~##...
~##... ~##... ~##Y..
~###.. ~###.. ~###..
#3 return [[4,-2], [4,2]]
..Y.... ....... .......
.###... .###... .###...
.#..... .#..... .#.....
.#..... .#..... .#.....
~xx~~~~ Yxx~~~~ ~xx~Y~~
~xxxx~~ ~xxxx~~ ~xxxx~~
#4 return [[4,-2], [9,2]]
..Y.... ....... .......
.###... .###... .###...
.###... .###... .###...
.###... .###... .###...
~###... Y###... .###...
~###... ~###... .###...
~###... ~###... .###...
~###... ~###... .###...
~###~~~ ~###~~~ ~###~~~
~##~~~~ ~###~~~ ~###Y~~
```
</details>
| games | def evaluate_jump(setting):
res, setting = [], setting . split("\n")
h, w = len(setting), len(setting[0])
y0 = next(i for i, r in enumerate(setting) if 'Y' in r)
x0 = setting[y0]. index('Y')
if y0 + 1 == h:
return res
def invalid(y, x): return y < 0 or x < 0 or y >= h or x >= w
def at(y, x): return '.' if invalid(y, x) else setting[y][x]
def go(dx):
if abs(dx) > 2:
return
x1, dy = x0 + dx, 0
if x1 < 0 or x1 >= w:
return
if at(y0, x1) != '.':
return
go(dx + (- 1 if dx < 0 else 1))
while at(y0 + dy + 1, x1) == '.' and dy < 9:
dy += 1
if dy == 0 or dy > 8:
return
if dy > 2 and at(y0 + dy + 1, x1) in "#x":
return
if dy > 4 and at(y0 + dy + 1, x1) == "~" and at(y0 + dy + 2, x1) != "~":
return
if dy > 4 and at(y0 + dy + 1, x1) == "~" and at(y0 + dy + 2, x1) == "~":
dy += 1
if at(y0 + dy + 1, x1) == "~":
dy += 1
res . append((dy, dx))
for dx in [- 1, 1]:
go(dx)
return res
| Cliff Jumping | 639382e66d45a7004aaf67fe | [
"Puzzles",
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/639382e66d45a7004aaf67fe | 5 kyu |
**No French knowledge is needed for this kata!**
*A note for the people who do know French: this kata will skip the step of turning the verb into it's Nous form, to maintain simplicity. That means verbs like Manger will be Mangais, instead of Mangeais. Oh, and no Γͺtre ;-)*
---
## Details ##
*(You may skip this part)*
When speaking/writing French, you use **Lβimparfait** *(the imperfect tense)* to describe continuous or habitual actions in the past.
For example, you would use l'imparfait to translate `"I was thinking"`, because thinking is an action that happens over a length of time. You wouldn't use l'imparfait to translate `"I won the boss battle"`, as it's an action that happens once.
Think of it as the French equivalent of our Past Progressive.
## Task ##
Given a simple French phrase, consisting of a subject and a verb in its infinitive form, you need to turn it into **L'imparfait**, using the table below. To conjugate a sentence in l'imparfait, drop the last two letters of the verb and replace it with the correct ending based on the subject.
Here are the endings to replace the verb with:
| Subject | Verb Ending |
| -------------------------------- | ----------- |
| `Je` *(I)* | `-ais` |
| `Tu` *(You)* | `-ais` |
| `Il/Elle/On` *(He/She/It or We)* | `-ait` |
| `Nous` *(We)* | `-ions` |
| `Vous` *(You or Y'all)* | `-iez` |
| `Ils/Elles` *(They)* | `-aient` |
Let's say you want to translate `I was walking` to French:
1. Take the subject + infinitive: `Je marcher`
2. Remove the last two letters: `Je march`
3. Apply the correct ending: `Je marchais`
You get `Je marchais`, which can be checked with our handy dandy [google translate](https://translate.google.com/?sl=fr&tl=en&text=Je%20marchais&op=translate).
## Examples ##
```
Je manger --> Je mangais
Tu dormir --> Tu dormais
Elle coder --> Elle codait
Il livrer --> Il livrait
On parler --> On parlait
Nous aller --> Nous allions
Vous partir --> Vous partiez
Ils jouer --> Ils jouaient
Elles gagner --> Elles gagnaient
``` | reference | endings = {
'Je': 'ais',
'Tu': 'ais',
'Il': 'ait',
'Elle': 'ait',
'On': 'ait',
'Nous': 'ions',
'Vous': 'iez',
'Ils': 'aient',
'Elles': 'aient'
}
def to_imparfait(verb_phrase):
return verb_phrase[: - 2] + endings[verb_phrase . split()[0]]
| French Imparfait Conjugation | 6394c1995e54bd00307cf768 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/6394c1995e54bd00307cf768 | 7 kyu |
While writing some code, you ran into a problem. Your code runs very slowly, because you need to run many functions.
You do a bit of troubleshooting and notice that you are not draining your system's resources.
Write a function that, given a list of "slow" functions, will return the sum of the results without waiting for each function to complete individually. | games | from concurrent . futures import *
def task_master(a):
with ThreadPoolExecutor(max_workers=len(a)) as executor:
return sum(executor . map(lambda f: f(), a))
| Task master | 639242518e28a700283f68ee | [
"Threads"
] | https://www.codewars.com/kata/639242518e28a700283f68ee | 6 kyu |
Create a tcp socket that listens on port 1111 on local host,
When a user connects to the socket, the following should happen:
- If the user sends a string containing only the word "exit", the socket and connection should close and the function should end.
- For any other string the user sends, the server should send a copy of the string back to the user.
you can assume short strings all ending in "\n" other than "exit"
| reference | from socket import create_server
def socket_server():
with create_server(('127.0.0.1', 80), reuse_port=True) as s:
with s . accept()[0] as t:
while True:
bs = t . recv(0xDEAD)
if bs == b'exit':
break
t . send(bs)
| Basic socket server | 6390ea74913c7f000d2e95cd | [
"Backend"
] | https://www.codewars.com/kata/6390ea74913c7f000d2e95cd | 6 kyu |
There is a socket listening on port 1111 of local host.
The socket either belongs to a server that sends back anything you send to it,
or to a server that reverses anything you send to it.
Create a function that does the following:
- Connects to the socket on port 1111.
- Sends one packet to the server.
- Receives one packet from the server.
- Returns `True` if the server is the regular type (i.e., it sends back the same packet that was sent to it), or `False` if the server is the reversing type (i.e., it reverses the packet that was sent to it).
Make sure to close the socket after you are done using it. If you time out while trying to connect, it is likely that you did not connect, send, receive, and close the socket in the correct order.
Happy coding! | reference | from socket import create_connection
def socket_client():
with create_connection(('127.0.0.1', 1111)) as s:
s . send(b'ab')
return s . recv(2) == b'ab'
| Simple Socket Client | 639107e0df52b9cb82720575 | [
"Networks"
] | https://www.codewars.com/kata/639107e0df52b9cb82720575 | 7 kyu |
You are given an input (n) which represents the amount of lines you are given, your job is to figure out what is the **maximum** amount of perpendicular bisectors you can make using these lines.
``Note: A perpendicular bisector is one that forms a 90 degree angle``
```
n will always be greater than or equal to 0
```
Examples with 3 and 4 lines

| reference | def perpendicular(n):
return n * n / / 4
| Perpendicular lines | 6391fe3f322221003db3bad6 | [
"Fundamentals",
"Algorithms",
"Geometry"
] | https://www.codewars.com/kata/6391fe3f322221003db3bad6 | 7 kyu |
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Introduction</summary>
Everybody loves to code golf. Well, maybe not everybody, but some people do. This kata is <b>not</b> directed to such people.
</details>
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Task</summary>
Given a bunch of user submissions to a code golf kata, and a minimum amount of submissions required to process the input, render a string containing information about the code golf champions.
***Code Golf Champion***
A code golf champion is a user that at any given moment holds the record (shortest code length), with that moment starting when at least "minimum submission count" submissions have been submitted, as we don't want early birds to take credit just because there aren't enough submissions yet.
**Input**
***submissions***
An array containing the user submissions to a code golf kata, in chronological order of submission timestamp, oldest first. Each user submission is a (2-)tuple consisting of two elements: the name of the user (string), and the length of the code (integer). An example of two submissions: <code>[["Tim",45], ["Jeff",42]]</code>.
***minimum submission count***
An integer representing the minimum amount of submissions required to start tracking code golf champions: <code>1 <= minimum submission count</code>. If there are fewer submissions than this parameter, there can be no result outputted. While the number of submissions is within this parameter, we don't start tracking champions just yet. From the moment we hit this threshold, the users with the current best code lengths are the initial champions.
**Output**
A string representing information about the code golf champions. If the number of submissions is smaller than "minimum submission count", return an empty string. In other cases, the expected output is a <code>; </code> delimited string concatenating information about each champion, in order of best code length of any of the submissions of the respective user. On tie, order on user that first submitted a submission of that code length.
Note that not all users are champions. Only those that at some point after "minimum submission count" submissions to the kata have held or still hold the record. This means, once "minimum submission count" submissions have been submitted, we start with the current record holder(s) as first champions.
For each champion, render the user name, concatenated with <code> - </code> and then the code lengths of all submissions of that user that at some point were a record in the kata, in ascending order, delimited by <code>, </code>. If for some code lengths, the user made multiple submissions that were a record at the time of submission, show them as one code length, with the number of such submissions between parentheses.
A note about whitespace: use a blank space after each <code>,</code> after each <code>;</code> around each <code>-</code> and before each <code>(</code>.
***examples output***
β’ "Joanne - 22" -> Joanne is the only champion, with a record submission of code length 22
β’ "Joanne - 22, 23" -> Joanne is the only champion, with a record submission of code length 22, but also had at one point a record submission of length 23
β’ "Mark - 21; Joanne - 22, 23 (2)" -> Mark is the current champion, with a record submission of length 21. Joanne at some point had a record submission of length 22, and 2 record submissions of length 23 before that.
</details>
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Example Tests</summary>
These tests are available in the sample test cases, among others.
```
// too few submissions
renderChampions([["Tim",45], ["Jeff",42]], 3) -> ""
// Joanne has the record of length 22, but also had the record of 23 after 1 submission
renderChampions([["Joanne",23], ["Joanne",22]], 1) -> "Joanne - 22, 23"
// Joanne has the record of length 22, which is the best result after 2 submissions
renderChampions([["Joanne",23], ["Joanne",22]], 2) -> "Joanne - 22"
// Jane has the record of length 34, but John had the record of length 35 after 1 submission
renderChampions([["John",35], ["Jane",34]], 1) -> "Jane - 34; John - 35"
// Jane has the record of length 34, as John's attempt was in the initial 2 submissions and got overshadowed by Jane's attempt
renderChampions([["John",35], ["Jane",34]], 2) -> "Jane - 34"
// John has the record of length 114, but he also has 2 record submissions of length 117, note that his 3th 117 does not count, as a better record was made by Jane in between of length 115.
renderChampions([["Jane",118], ["John",117], ["John",117], ["Jane",115], ["John",117], ["John",114]], 2) -> "John - 114, 117 (2); Jane - 115"
```
</details>
| reference | from collections import defaultdict, Counter
from operator import itemgetter
def render_champions(submissions, n_min):
if len(submissions) < n_min:
return ''
best = min(map(itemgetter(1), submissions[: n_min]))
record = defaultdict(list)
order = defaultdict(list)
for name, n in submissions:
if n <= best:
best = n
order[n]. append(name)
record[name]. append(n)
def best_submission_then_best_order(name):
top = record[name][- 1]
return top, order[top]. index(name)
def format_people(name):
grp = Counter(reversed(record[name]))
perfs = ', ' . join(
str(size) if n == 1 else f' { size } ( { n } )' for size, n in grp . items())
return f' { name } - { perfs } '
ordered = sorted(record, key=best_submission_then_best_order)
return '; ' . join(map(format_people, ordered))
| Render the Code Golf Champions | 638e399a2d712300309cf11c | [
"Arrays",
"Strings",
"Sorting"
] | https://www.codewars.com/kata/638e399a2d712300309cf11c | 5 kyu |
Let `$f(n) = \dbinom{n+1}{2}$`, with non-negative integer n.
`$\dbinom{n}{k}$` is [Binomial coefficient](https://en.wikipedia.org/wiki/Binomial_coefficient).
You need to represent the given number `N` like this:
`$N = f(i) + f(j) + f(k)$`, actually, it is possible `$\forall N \in β$`.
For example:
```
34 = f(0) + f(3) + f(7) = f(2) + f(4) + f(6)
69 = f(0) + f(2) + f(11) = f(2) + f(6) + f(9)
```
As you can see, there can be multiple representations for a given value of `N`, so return **any one valid representation** ```[f(i), f(j), f(k)]``` **in an array, in any order**.
The tests will check that your solution contains exactly 3 integer binomial coefficients that sum to the given value of `N`.
```
represent(34) = [0, 6, 28] = [28, 0, 6] ... all equivalent
represent(34) = [3, 10, 21] = [10, 21, 3] ... all equivalent
```
In this kata all the tests will be with
`$
1 \leqslant N \leqslant 2^{666}
$`
Good luck! | algorithms | from itertools import count
from random import randint
from gmpy2 import is_prime
def represent(n: int) - > int:
"""
with some algebra I found that:
(i+1)C2 + (j+1)C2 + (k+1)C2 = N is equivalent to (2i+1)^2 + (2j+1)^2 + (2k+1)^2 = 8N+3
so the new goal is to find 3 odd squares (A^2 + B^2 + C^2) that sum of 8N + 3
i do this by choosing an odd value of A (starting from 1) and computing it x := 8*N+3 - A^2
x will be congruent to 2 mod 8 because A^2 (an odd square) is always congruent to 1 mod 8
this means that x // 2 is congruent to 1 mod 4
i proceed if x // 2 is also a prime because this guarantees that a valid B and C can be found
otherwise i go back and choose the next odd value A can take
this assumes that for any natural number of the form 8*n+3,
there exists a prime less than or equal to 4*n+1 congruent to 1 mod 4
fortunately this holds
sources on representing a number as a sum of three squares (most useful sources first):
https://math.stackexchange.com/questions/483101/rabin-and-shallit-algorithm
https://crypto.stackexchange.com/questions/61961/sum-of-two-squares-problem
https://mathoverflow.net/questions/110239/is-there-an-algorithm-for-writing-a-number-as-a-sum-of-three-squares
"""
def gcd_complex(a, b, c, d):
while not (c == d == 0):
k = c * c + d * d
e = round((a * c + b * d) / k)
f = round((b * c - a * d) / k)
g = a - c * e + d * f
h = b - c * f - d * e
a, b, c, d = c, d, g, h
return a, b
def two_odd_squares(x):
x / /= 2
if not is_prime(x):
return None, None
t = (x - 1) / / 4
while True:
s = pow(randint(1, x - 1), t, x)
if s * s % x == x - 1:
break
a, b = sorted(map(abs, gcd_complex(x, 0, s, 1)))
a, b = b - a, a + b
return a, b
target = 8 * n + 3 - 1 * * 2
for A in count(1, 2):
B, C = two_odd_squares(target)
if (B, C) != (None, None):
i, j, k = map(lambda t: (t - 1) / / 2, (A, B, C))
f_i, f_j, f_k = map(lambda t: t * (t + 1) / / 2, (i, j, k))
return [f_i, f_j, f_k]
target -= 4 * A + 4
| My favorite number is III, so... | 638f6152d03d8b0023fa58e3 | [
"Mathematics",
"Algorithms",
"Number Theory",
"Performance"
] | https://www.codewars.com/kata/638f6152d03d8b0023fa58e3 | 3 kyu |
A Carmichael number is defined as a number N that is composite and yet passes Fermat primality test, i.e. `M**(N-1) == 1 (mod N)`, for all M relatively prime to N.
Find a Carmichael number that satisfies the following:
* It is a product of *seven* prime numbers.
* Its prime factors are between `10**7` and `10**9`.
Submit the prime factorization of such a number. | games | # Most clutched solution I found: (p[-1] - 1) // (p[0] - 1) = 4 / 3
primes = [24284400 * k + 1 for k in (24, 30, 33, 36, 38, 39, 40)]
| A giant Carmichael number | 638edc41458b1b00165b138b | [
"Mathematics",
"Number Theory",
"Performance"
] | https://www.codewars.com/kata/638edc41458b1b00165b138b | 3 kyu |
You need to count the number of prime numbers less than or equal to some natural ```n```.
For example:
```
count_primes_less_than(34) = 11
count_primes_less_than(69) = 19
count_primes_less_than(420) = 81
count_primes_less_than(666) = 121
```
- In this kata all the tests will be with `$ 1 \leqslant n \leqslant 10^{10}$`
- Code length limited to <code>3000</code> characters to avoid hardcoding.
Good luck! | algorithms | # https://en.wikipedia.org/wiki/Prime-counting_function
from math import isqrt
from functools import cache
from bisect import bisect
import sys
sys . setrecursionlimit(10 * * 5)
# https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
def rwh_primes(n):
""" Returns a list of primes < n """
sieve = [True] * n
for i in range(3, int(n * * 0.5) + 1, 2):
if sieve[i]:
sieve[i * i:: 2 * i] = [False] * ((n - i * i - 1) / / (2 * i) + 1)
return [2] + [i for i in range(3, n, 2) if sieve[i]]
PRIMES = rwh_primes(10 * * 7)
@ cache
def phi(m, n):
if n == 1 or m < 1:
return (m + 1) / / 2
p = PRIMES[n - 1]
# https://ideone.com/SnhEQA
if p * p >= m and m < PRIMES[- 1]:
return bisect(PRIMES, m) - n + 1
return phi(m, n - 1) - phi(m / / p, n - 1)
def pi(m):
if m <= PRIMES[- 1]:
return bisect(PRIMES, m)
n = pi(int((m + 0.5) * * (1 / 3)))
mu = pi(isqrt(m)) - n
return phi(m, n) + n * (mu + 1) + mu * (mu - 1) / / 2 - 1 - sum(pi(m / / PRIMES[n + k]) for k in range(mu))
count_primes_less_than = pi
| Prime counting | 638c92b10e43cc000e615a07 | [
"Mathematics",
"Recursion",
"Algorithms",
"Memoization",
"Performance",
"Number Theory"
] | https://www.codewars.com/kata/638c92b10e43cc000e615a07 | 3 kyu |
The code consists of four unique digits (from `0` to `9`).
Tests will call your solution; you should answer with an array of four digits.
Your input is number of matches (the same digit in the same place) with your previous answer. For the first call input value is `-1` (i.e. each new test starts with input `-1`)
You have to find the code in `16` calls or less. You are the best. Do it.
## For example
```if:javascript,php,haskell,python,lua
The code is `[1, 2, 3, 4]`
1st call `return [1, 3, 4, 5]` will give `1` match in next input
2nd call `return [1, 2, 3, 0]` will give `3` matches in next input
3rd call `return [1, 2, 3, 4]` will not give `4` matches in next input, because you're the champion!
```
```if:csharp,java,vb,
The code is `{1, 2, 3, 4}`
1st call `return new [] {1, 3, 4, 5}` will give `1` match in next input
2nd call `return new [] {1, 2, 3, 0}` will give `3` matches in next input
3rd call `return new [] {1, 2, 3, 4}` will not give `4` matches in next input, because you're the champion!
```
## P.S.
If the task seems too difficult, try [this game](https://www.goobix.com/games/guess-the-number/) with almost the same rules first. | games | import itertools
def guess(n):
if n == - 1:
# Start by guessing the first code in the list
guess . remaining_codes = list(itertools . permutations(range(10), 4))
guess . prev_guess = guess . remaining_codes[0]
else:
# Remove any code from the list that would not produce the same number of matches
guess . remaining_codes = [code for code in guess . remaining_codes
if sum(a == b for a, b in zip(code, guess . prev_guess)) == n]
# Choose the next code in the list and guess it
guess . prev_guess = guess . remaining_codes[0]
return list(guess . prev_guess)
guess . remaining_codes = None
guess . prev_guess = None
| Digits | 638b042bf418c453377f28ad | [
"Algorithms"
] | https://www.codewars.com/kata/638b042bf418c453377f28ad | 5 kyu |
You have a natural number ```m```.
You need to write a function ```f(m)``` which finds the smallest positive number ```n``` such that
`$
n^n\equiv 0 \mod m
$`.
In other words `$n^n$` is divisible by ```m```.
For example:
```
f(13) = 13
f(420) = 210
f(666) = 222
f(1234567890) = 411522630
```
In this kata all the tests will be with
`$
1 \leqslant m \leqslant 10^{24}
$`
Keep in mind that ```n <= m```, so iterating over ```n``` and cheking ```pow(n,n,m) == 0``` in total for `$O(nlog(n))$` operations is not an option.
| algorithms | from collections import Counter
from math import ceil, gcd, log, prod
from random import randrange
from gmpy2 import is_prime
def pollard_rho(n):
while True:
x, c = randrange(1, n), randrange(1, n)
def f(x): return (x * x + c) % n
y = f(x)
while (d := gcd(abs(x - y), n)) == 1:
x, y = f(x), f(f(y))
if d != n:
return d
def factor(n):
if is_prime(n):
return Counter([n])
return factor(r := pollard_rho(n)) + factor(n / / r)
def f(m):
if m == 1:
return 1
factors = factor(m)
product, max_order = prod(factors), max(factors . values())
return min((m := product * * k) * ceil(max_order / k / m)
for k in range(1, int(log(max_order, product)) + 2))
| The smallest n such that n^n mod m = 0 | 638b4205f418c4ab857f2692 | [
"Mathematics",
"Algorithms",
"Number Theory",
"Performance"
] | https://www.codewars.com/kata/638b4205f418c4ab857f2692 | 3 kyu |
Let `$f(n) = \displaystyle\sum_{k=0}^{n} 2^k k^2$`
You need to calculate this sum, but since the answer can be large, return `$ f(n)$` mod `$m$`, where `$m = 10^9 + 7$`.
For example:
```
f(3) mod m = 90
f(420) mod m = 118277878
f(666) mod m = 483052609
f(1111111111111) mod m = 284194637
```
In this kata all the tests will be with `$2 \leqslant n \leqslant 10^{18}$`.
Good luck!
| reference | M = 10 * * 9 + 7
def f(n: int) - > int:
# g(x) = sum(x^k, k = 0..n)
# Then sum(k^2 * x^2, k = 0..n) = x^2 g''(x) + x(g'(x) - 1) + x
# g'(2) = (n - 1) * 2^n + 1
# g''(2) = ...
def g2(n): return (n * n * pow(2, n, M) - 3 * n *
pow(2, n, M) + pow(2, n + 2, M) - 4) * pow(2, M - 2, M)
def g1(n): return pow(2, n, M) * (n - 1) + 1
return (4 * g2(n) + 2 * (g1(n) - 1) + 2) % M
# Wolfram Alpha:
return 2 * (pow(2, n, M) * (n * n - 2 * n + 3) - 3) % M
| Can you sum? | 638bc5d372d41880c7a99edc | [
"Mathematics",
"Algorithms",
"Number Theory",
"Performance"
] | https://www.codewars.com/kata/638bc5d372d41880c7a99edc | 6 kyu |
You have a natural number ```d```.
You need to write a function ```f(d)``` which finds the smallest positive number ```n``` having ```d``` divisors .
For example:
```
f(1) = 1
f(3) = 4
f(60) = 5040
f(420) = 9979200
```
In this kata all the tests will be with ```1 <= d <= 10000```
Keep in mind that ```n``` can be on the order of `$10^{300}$`, so iterating over ```n``` and finding the divisors in total for `$O(n\sqrt{\mathstrut n})$` operations is not an option.
Good luck! | algorithms | from math import isqrt
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37,
41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
def g(n, i):
p = primes[i]
m = p * * (n - 1)
for d in range(2, isqrt(n) + 1):
if n % d == 0:
m = min(m, p * * (d - 1) * g(n / / d, i + 1), p * * (n / / d - 1) * g(d, i + 1))
return m
def f(n): return g(n, 0)
| The smallest number with a given number of divisors | 638af78312eae9a23c9ec5d6 | [
"Mathematics",
"Recursion",
"Algorithms",
"Number Theory",
"Performance"
] | https://www.codewars.com/kata/638af78312eae9a23c9ec5d6 | 4 kyu |
Fractals are fun to code, so let's make some.
Your task is to write a function that recursively generates an ASCII fractal.
- The function will take a `list[str]` representing rows of a seed pattern and an `int` number of iterations
- The seed pattern will be a rectangle containing two types of characters, `*` and `.`
- Each new iteration, every `*` in the starting seed is replaced by a copy of the last iteration.
- Empty space is filled with `.`
```
Example for the seed pattern:
***
*.*
***
1st iteration:
***
*.*
***
2nd iteration:
*********
*.**.**.*
*********
***...***
*.*...*.*
***...***
*********
*.**.**.*
*********
3rd iteration:
***************************
*.**.**.**.**.**.**.**.**.*
***************************
***...******...******...***
*.*...*.**.*...*.**.*...*.*
***...******...******...***
***************************
*.**.**.**.**.**.**.**.**.*
***************************
*********.........*********
*.**.**.*.........*.**.**.*
*********.........*********
***...***.........***...***
*.*...*.*.........*.*...*.*
***...***.........***...***
*********.........*********
*.**.**.*.........*.**.**.*
*********.........*********
***************************
*.**.**.**.**.**.**.**.**.*
***************************
***...******...******...***
*.*...*.**.*...*.**.*...*.*
***...******...******...***
***************************
*.**.**.**.**.**.**.**.**.*
***************************
```
- Input patterns will always be rectangular.
- For values of i < 1 or seeds with rows that are all empty strings, return `[]`.
- Your function will be tested on both fixed and random inputs.
# Tests
- Your solution must be efficient, as random tests will be on up to 9x9 input seeds
- There are 60 random tests with a seed of size 2 x n (n ranges from 0-9 and there are 5 tests for each value of n, each having i ranging from 0-4)
- There are 25 random tests with seed n x n where n ranges from 5-9. i = 4
| algorithms | def fractalize(seed, i):
if i <= 1:
return seed
star = fractalize(seed, i - 1)
dot = [row . replace('*', '.') for row in star]
return [
'' . join(rowrow)
for row in seed
for rowrow in zip(* (star if c == '*' else dot for c in row))
]
| Recursive ASCII Fractals | 637874b78ee59349c87b018d | [
"Mathematics",
"Algorithms",
"Geometry",
"ASCII Art",
"Performance"
] | https://www.codewars.com/kata/637874b78ee59349c87b018d | 5 kyu |
We have an endless chessboard, and on each cell there is a number written in a spiral.
16γ
€γ
€15γ
€γ
€14γ
€γ
€13γ
€γ
€12
17γ
€γ
€4 γ
€γ
€3 γ
€γ
€2 γ
€γ
€11
18γ
€γ
€5 γ
€γ
€0 γ
€γ
€1 γ
€γ
€10
19γ
€γ
€6 γ
€γ
€7 γ
€γ
€8 γ
€γ
€9γ
€γ
€...
20γ
€γ
€21γ
€γ
€22γ
€γ
€23γ
€γ
€24γ
€γ
€25
And we have a knight. A normal chess knight moves +1 to one axis and +2 to the other. But this knight moves +n to one axis and +m to the other.
And this knight has two more rules:
He cannot move to the same square twice, and he only moves to the smallest available square.
For example, an ordinary knight (n=1, m=2) starts his journey like this:
0 -> 9 -> 2 -> 5 -> 8 -> ...
But someday he will reach a cell from which he will not be able to get out without violating the rule, it is this last cell that the function must return. For this case it 2083
**Performance requirements:**
Values of `m` up to `300_000_000` will be tested in fixed tests. Multiple random tests with `m` up to `20_000`. You will always have `0 < n < m`. | games | def trapped_cell(n: int, m: int) - > int:
def spiral(x, y):
u, v = (x, y) if abs(x) <= abs(y) else (y, x)
return v * (4 * v - [1, 3][y < x]) + [- u, u][y < x]
x, y = 0, 0
visited = set([(x, y)])
while True:
ps = [(x + dx, y + dy) for dx, dy in ((- n, - m), (n, - m), (- n, m), (n, m),
(- m, - n), (m, - n), (- m, n), (m, n)) if (x + dx, y + dy) not in visited]
if not ps:
return spiral(x, y)
x, y = min(ps, key=lambda p: spiral(p[0], p[1]))
visited . add((x, y))
| The Trapped Odd Knight | 63890d2ef418c49d4c7f50cc | [
"Algorithms",
"Combinatorics",
"Puzzles",
"Performance"
] | https://www.codewars.com/kata/63890d2ef418c49d4c7f50cc | 5 kyu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.