description stringlengths 38 154k | category stringclasses 5
values | solutions stringlengths 13 289k | name stringlengths 3 179 | id stringlengths 24 24 | tags listlengths 0 13 | url stringlengths 54 54 | rank_name stringclasses 8
values |
|---|---|---|---|---|---|---|---|
A number of single men and women are locked together for a longer while in a villa or on an island, for the sake of a TV show. Because they spend quite some time together, all of them seek a partner to date. They are all shallow people, and they only care about looks, aka physical attractiveness when it comes to dating... | algorithms | from typing import Tuple
import pandas as pd
class Person:
@ staticmethod
def sort_key(person: 'Person') - > Tuple[int, int]:
# Sort by descending rating and ascending number of pre-allocated partners
return (- person . rating, len(person . partners))
def __init__(self, sex, ratin... | Dating with hypergamy | 5f304fb8785c540016b9a97b | [
"Algorithms"
] | https://www.codewars.com/kata/5f304fb8785c540016b9a97b | 5 kyu |
> **NOTE:** This a harder version of prsaseta's kata [1 Dimensional cellular automata](https://www.codewars.com/kata/5e52946a698ef0003252b526). If you are unable to solve this, you may catch the gist of the task with that one!
# Basic idea of (1D) cellular automata
Imagine we have a list of ones and zeros:
```
1 0 1... | algorithms | import numpy
import scipy . ndimage as i
a = numpy . array
evolve = e = lambda M, R, s: s and e(a([a(r). size == i . correlate(
2 * a(M) - 1, 2 * a(r) - 1, int, 'wrap') for r in R]). any(0). tolist(), R, s - 1) or M
| 2D Cellular Automata [Code Golf] | 5e8886a24475de0032695b9e | [
"Mathematics",
"Restricted",
"Algorithms",
"Cellular Automata"
] | https://www.codewars.com/kata/5e8886a24475de0032695b9e | 5 kyu |
## What is an ASCII Art?
ASCII Art is art made of basic letters and symbols found in the ascii character set.
### Example of ASCII Art (by Joan Stark)
```
_ _ / _
(')-=-(') __|_ {_}
__( " )__ |____| ... | games | def bus_animation(bn, bs, fc, fs):
b = ['' . join(x[0] + x[1] * (bn - 1) + x[2]) + ' ' * (fs - 17 - 5 * (bn - 1)) for x in [
[' ________', '_____', '_____ '],
['| | ', '| ', '| | \ '],
['|___|____', '|____', '|_|___\ '],
['| ', ' ', '| | \\'],
['`--(o)(o)', '-----', "--... | Bus ASCII-Art Animation | 61db0b0d5b4a78000ef34d1f | [
"ASCII Art",
"Puzzles"
] | https://www.codewars.com/kata/61db0b0d5b4a78000ef34d1f | 6 kyu |
## Task
Consider an n-th-degree polynomial with integer coefficients:
```math
x^n + a_1*x^{n-1} + ... + a_{n-1}*x + a_n
```
Let's call this polynomial compact if it has only **integer** roots which are **non-repeating** and **non-zero** and `$|a_n|$` is minimal.
Your task is to find the maximum and minimum values... | games | def first_coefficient(n): return (k: = n % 2 * ~ n >> 1, - k)
| Compact polynomial | 61daff6b2fdc2a004328ffe4 | [
"Fundamentals",
"Puzzles",
"Mathematics"
] | https://www.codewars.com/kata/61daff6b2fdc2a004328ffe4 | 6 kyu |
# Task
You are given an array `a` of positive integers and an intger `k`. You may choose some integer `X` and update `a` several times, where to update means to perform the following operations:
```
pick a contiguous subarray of length not greater than the given k;
replace all elements in the picked subarray with the ... | games | def array_equalization(a, k):
totals, ends = {}, {}
for i, n in enumerate(a):
if n not in ends:
totals[n], ends[n] = 0, - 1
if i < ends[n]:
continue
count = (i - ends[n] - 1 + k - 1) / / k
totals[n] += count
ends[n] = max(i, ends[n] + count * k)
return min(t + (len(a) - e... | Simple Fun #125: Array Equalization | 58a3c836623e8c72eb000188 | [
"Puzzles"
] | https://www.codewars.com/kata/58a3c836623e8c72eb000188 | 5 kyu |
[The Vigenère cipher](https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher) is a classic cipher that was thought to be "unbreakable" for three centuries. We now know that this is not so and it can actually be broken pretty easily.
**How the Vigenère cipher works**:
The basic concept is that you have a `message` and a `... | algorithms | def get_key_length(cipher_text, max_key_length):
# count the occurences where there is a match when shifting the sequence by a offset
offsets = [len([d for d in zip(cipher_text, cipher_text[offset:]) if d[0] == d[1]])
for offset in range(1, max_key_length)]
# get the offset that generated... | Cracking the Vigenère cipher, step 1: determining key length | 55d6afe3423873eabe000069 | [
"Strings",
"Cryptography",
"Ciphers",
"Algorithms"
] | https://www.codewars.com/kata/55d6afe3423873eabe000069 | 4 kyu |
You are organizing a soccer tournament, so you need to build a matches table.
The tournament is composed by 20 teams. It is a round-robin tournament (all-play-all), so it has 19 rounds, and each team plays once per round. Each team confront the others once in the tournament (each match does not repeat in the tournamen... | algorithms | def build_matches_table(t):
teams, ans = [* range(1, t + 1)], []
for _ in range(t - 1):
teams = [teams[0]] + teams[2:] + [teams[1]]
ans += [[(teams[i], teams[t - i - 1]) for i in range(0, t, 2)]]
return ans
| Organize a Round-robin tournament | 561c20edc71c01139000017c | [
"Arrays",
"Logic",
"Algorithms"
] | https://www.codewars.com/kata/561c20edc71c01139000017c | 4 kyu |
I have started studying electronics recently, and I came up with a circuit made up of 2 LEDs and 3 buttons.
Here 's how it works: 2 buttons (`red` and `blue`) are connected to the LEDs (`red` and `blue` respectively). Buttons pressing pattern will be remembered and represented through the LEDs when the third button is... | games | def button_sequences(seqR, seqB):
pattern, state = '', ''
def toBool(seq): return [i == '1' for i in seq]
for red, blue in zip(toBool(seqR), toBool(seqB)):
if red and state == 'R' or blue and state == 'B':
continue
state = 'R' if red else 'B' if blue else ''
pattern += state
retu... | Button sequences | 5bec507e1ab6db71110001fc | [
"Strings",
"Games",
"Puzzles"
] | https://www.codewars.com/kata/5bec507e1ab6db71110001fc | 6 kyu |
#### Task
ISBN stands for International Standard Book Number.
For more than thirty years, ISBNs were 10 digits long. On January 1, 2007 the ISBN system switched to a 13-digit format. Now all ISBNs are 13-digits long. Actually, there is not a huge difference between them. You can convert a 10-digit ISBN to a 13-digit ... | algorithms | def isbn_converter(isbn):
s = '978' + isbn . replace('-', '')[: - 1]
m = sum(int(d) * (1 + 2 * (i & 1)) for i, d in enumerate(s)) % 10
return f'978- { isbn [: - 1 ] }{ m and 10 - m } '
| Convert ISBN-10 to ISBN-13 | 61ce25e92ca4fb000f689fb0 | [
"Algorithms",
"Regular Expressions",
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/61ce25e92ca4fb000f689fb0 | 6 kyu |
You work at a lock situated on a very busy canal. Boats have queued up at both sides of the lock and your managers are asking for an update on how long it's going to take for all the boats to go through the lock.
Boats are queuing in order and they must go into the lock in that order. Multiple boats can go into the lo... | algorithms | def canal_mania(a, b, w):
m = 0
while len(a) + len(b) > 0:
for q in [a, b]:
n = 0
while len(q) and n + q[0] <= w:
n += q . pop(0)
m += 2 * (n + 1)
return m
| Canal Management | 61c1ffd793863e002c1e42b5 | [
"Algorithms"
] | https://www.codewars.com/kata/61c1ffd793863e002c1e42b5 | 6 kyu |
This kata requires you to write a function which merges two strings together. It does so by merging the end of the first string with the start of the second string together when they are an exact match.
```
"abcde" + "cdefgh" => "abcdefgh"
"abaab" + "aabab" => "abaabab"
"abc" + "def" => "abcdef"
"abc" + "abc" => "abc"... | algorithms | def merge_strings(first, second):
start = 0
stop = len(first)
while True:
if first[start: len(first)] == second[0: stop]:
break
else:
start = start + 1
stop = stop - 1
return first[0: start] + second
| Merge overlapping strings | 61c78b57ee4be50035d28d42 | [
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/61c78b57ee4be50035d28d42 | 7 kyu |
Your task is to implement a ```Miner``` class, which will be used for simulating the mining skill in Runescape. In Runescape, users can click on rocks throughout the game, and if the user has the required mining level, they are able to extract the ore contained in the rock.
In this kata, your ```Miner``` can ```mine``... | reference | class Miner:
def __init__(self, exp=0):
self . level = next(i for i in range(40, 0, - 1) if exp >= EXPERIENCE[i])
self . exp = exp
def mine(self, rock):
lvl, exp = ROCKS[rock]
if self . level >= lvl:
self . exp += exp
if self . level < 40 and self . exp >= EXPERIENCE[self . level... | Runescape Mining Simulator | 61b09ce998fa63004dd1b0b4 | [
"Fundamentals"
] | https://www.codewars.com/kata/61b09ce998fa63004dd1b0b4 | 6 kyu |
**Context**
You are not sure about what you should name your new kata.
Luckily, your friend Tóḿáś has **`$n$`** (`$2≤ n ≤20$`) strings (all lowercase latin alphabet characters), **`$s_0, s_1...s_{n-1}$`**, each with a unique, random length between `$1$` and `$10$`, inclusive.
```if:python
IMPORTANT NOTE: For Python,... | reference | def name(s):
bag = {(0, 0)}
for w in s:
l_, v_ = len(w), sum(bytes(w, 'utf8')) - len(w) * 96
bag |= {(l + l_, v + v_) for l, v in bag}
return max(l for l, v in bag if v <= 10 * l)
| Give your kata a name | 61aa4873f51ce80053a045d3 | [
"Fundamentals"
] | https://www.codewars.com/kata/61aa4873f51ce80053a045d3 | 6 kyu |
Bob has finally found a class that he's interested in -- robotics! He needs help to find out where to put his robot on a table to keep it on the table for the longest.
The size of the table is `n` feet by `m` feet (1 <= n, m <= 10000), and is labeled from 1 to n (top to bottom) and from 1 to m (left to right). Direct... | games | def robot(n, m, s):
x, y, xmin, ymin, xmax, ymax = 0, 0, 0, 0, 0, 0
for cur in s:
y += (cur == 'D') - (cur == 'U')
x += (cur == 'R') - (cur == 'L')
xmin = min(xmin, x)
ymin = min(ymin, y)
xmax = max(xmax, x)
ymax = max(ymax, y)
if xmax - xmin + 1 > m or ymax - ymin + 1 > n:
... | Robot on a Table | 61aa487e73debe0008181c46 | [
"Puzzles",
"Performance"
] | https://www.codewars.com/kata/61aa487e73debe0008181c46 | 6 kyu |
Your task is to write a function, called ```format_playlist```, that takes a list of ```songs``` as input.
Each song is a tuple, of the form ```(song_name, duration, artist)```. Your task is to create a string representation of these songs.
Your playlist should be sorted first by the artist, then by the name of the ... | reference | # Just cleaned it a bit
def format_playlist(songs):
size1 = max((4, * (len(s[0]) for s in songs)))
size2 = max((6, * (len(s[2]) for s in songs)))
border = f"+- { '-' * size1 } -+------+- { '-' * size2 } -+"
def line(
a, b, c): return f"| { a . ljust ( size1 )} | { b . ljust ( 4 )} | { c ... | Format the playlist | 61a87854b4ae0b000fe4f36b | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/61a87854b4ae0b000fe4f36b | 6 kyu |
You have an 8-wind compass, like this:

You receive the direction you are `facing` (one of the 8 directions: `N, NE, E, SE, S, SW, W, NW`) and a certain degree to `turn` (a multiple of 45, between -1080 and 108... | algorithms | DIRECTIONS = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']
def direction(facing, turn):
return DIRECTIONS[(turn / / 45 + DIRECTIONS . index(facing)) % 8]
| Turn with a Compass | 61a8c3a9e5a7b9004a48ccc2 | [
"Algorithms"
] | https://www.codewars.com/kata/61a8c3a9e5a7b9004a48ccc2 | 7 kyu |
### Task
Given a number `N`, determine if the sum of `N` ***consecutive numbers*** is odd or even.
- If the sum is definitely an odd number, return `Odd`.
- If the sum is definitely an even number, return `Even`.
- If the sum can be either odd or even ( depending on which first number you choose ), return `Either... | reference | def odd_or_even(n):
return ("Even", "Either", "Odd", "Either")[n % 4]
| Odd or Even? Determine that! | 619f200fd0ff91000eaf4a08 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/619f200fd0ff91000eaf4a08 | 7 kyu |
### Task:
You are given two sorted lists, with distinct elements. Find the maximum path sum while traversing through the lists.
Points to consider for a valid path:
* A path can start from either list, and can finish in either list.
* If there is an element which is present in both lists (regardless of its index in t... | reference | def max_sum_path(a, b):
i, j, A, B = 0, 0, 0, 0
while i < len(a) and j < len(b):
x, y = a[i], b[j]
if x == y:
A = B = max(A, B)
if x <= y:
i, A = i + 1, A + x
if x >= y:
j, B = j + 1, B + y
return max(A + sum(a[i:]), B + sum(b[j:]))
| Max sum path | 61a2fcac3411ca0027e71108 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/61a2fcac3411ca0027e71108 | 5 kyu |
Given an integer n, we can construct a new integer with the following procedure:
- For each digit d in n, find the dth prime number. (If d=0, use 1)
- Take the product of these prime numbers. This is our new integer.
For example, take 25:
The 2nd prime is 3, and the 5th is 11. So 25 would evaluate to 3*11 = 33.
I... | games | from functools import reduce
PRIMES = [1, 2, 3, 5, 7, 11, 13, 17, 19, 23]
def find_max(n):
s = set()
while n not in s:
s . add(n)
n = reduce(lambda x, d: x * PRIMES[int(d)], str(n), 1)
return max(s)
| Prime Cycles | 5ef1fe9981e07b00015718a8 | [
"Puzzles"
] | https://www.codewars.com/kata/5ef1fe9981e07b00015718a8 | 6 kyu |
# Background
Often times when working with raw tabular data, a common goal is to split the data into groups and perform an aggregation as a way to simplify and draw meaningful conclusions from it. The aggregation function can be anything that reduces the data (sum,mean,standard deviation,etc.). For the purpose of thi... | reference | # Not sure why the set the right order without sorting it but eh, it works
def group(arr, idx):
result, idx2 = {}, set(range(len(arr[0]))) - set(idx)
for row in arr:
key = tuple(map(row . __getitem__, idx))
value = map(row . __getitem__, idx2)
result[key] = list(map(int . __add__, result[key],... | Group-by and Sum | 5ed056c9263d2f001738b791 | [
"Fundamentals"
] | https://www.codewars.com/kata/5ed056c9263d2f001738b791 | 6 kyu |
# Centered pentagonal number
Complete the function that takes an integer and calculates how many dots exist in a pentagonal shape around the center dot on the Nth iteration.
In the image below you can see the first iteration is only a single dot. On the second, there are 6 dots. On the third, there are 16 dots, and o... | reference | def pentagonal(n):
return 1 + 5 * (n - 1) * n / / 2 if n > 0 else - 1
| Centered pentagonal number: | 5fb856190d5230001d48d721 | [
"Performance",
"Logic",
"Fundamentals"
] | https://www.codewars.com/kata/5fb856190d5230001d48d721 | 7 kyu |
You are given an array of 6-faced dice. Each die is represented by its face up.
Calculate the minimum number of rotations needed to make all faces the same.
`1` will require one rotation to have `2`, `3`, `4` and `5` face up, but would require two rotations to make it the face `6`, as `6` is the opposite side of `1`.... | reference | def count_min_rotations(d): return min(
sum((v != i) + (v + i == 7) for v in d) for i in range(1, 7))
| Dice Rotation | 5ff2093d375dca00170057bc | [
"Fundamentals"
] | https://www.codewars.com/kata/5ff2093d375dca00170057bc | 7 kyu |
### Task
You are given a matrix of numbers. In a mountain matrix the absolute difference between two adjecent (orthogonally or diagonally) numbers is not greater than 1. One change consists of increasing a number of the matrix by 1. Your task is to return the mountain matrix that is obtained from the original with the ... | algorithms | def to_mountain(mat):
h, w = len(mat), len(mat[0])
for j in range(h):
for i in range(w):
if j:
mat[j][i] = max(mat[j][i], mat[j - 1][i] - 1)
if i:
mat[j][i] = max(mat[j][i], mat[j][i - 1] - 1)
if j and i:
mat[j][i] = max(mat[j][i], mat[j - 1][i - 1] - 1)
if ... | Mountain map | 617ae98d26537f000e04a863 | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/617ae98d26537f000e04a863 | 4 kyu |
Due to the popularity of a [similar game](https://www.codewars.com/kata/58c21c4ff130b7cab400009e), a hot new game show has been created and your team has been invited to play!
## The Rules
The game rules are quite simple. The team playing (`n` players) are lined up at decreasing heights, facing forward such that each... | games | def guess_colour(guesses, hats):
return "Red" if ((hats + guesses). count("Blue")) % 2 else "Blue"
| Hat Game | 618647c4d01859002768bc15 | [
"Riddles"
] | https://www.codewars.com/kata/618647c4d01859002768bc15 | 6 kyu |
You are given a list of four points (x, y). Each point is a tuple
Your task is to write a function which takes an array of points and returns whether they form a square.
If the array doesn't contain 4 points, return False.
All points coordinates are integers.
Squares can be rotated using a random degree.
<h1>Examp... | reference | from itertools import combinations
from math import dist
def is_square(points: list) - > bool:
# (Number of points = Number of unique points = 4) and (Two kind of distances)
return (len(points) == len(set(points)) == 4) and (len(set(dist(* pair) for pair in combinations(points, 2))) == 2)
| Do the points form a square? | 618688793385370019f494ae | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/618688793385370019f494ae | 6 kyu |
You are given a positive natural number `n` (which is `n > 0`) and you should create a regular expression pattern which only matches the decimal representation of all positive natural numbers strictly less than `n` without leading zeros. The empty string, numbers with leading zeros, negative numbers and non-numbers sho... | reference | def regex_below(n): return (s: = str(n)) and "^(?=[^0])(" + '|' . join(f'( { s [: i ]} [^\D { int ( d )} -9])?\d{{ { len ( s ) - i - 1 } }} ' for i, d in enumerate(s)) + ")$"
| Regex matching all positive numbers below n | 615da209cf564e0032b3ecc6 | [
"Regular Expressions"
] | https://www.codewars.com/kata/615da209cf564e0032b3ecc6 | 5 kyu |
A stranger has lost himself in a forest which looks like a _2D square grid_. Night is coming, so he has to protect himself from wild animals. That is why he decided to put up a campfire.
Suppose this stranger has __four sticks__ with the same length which is equal to __k__. He can arrange them in square grid so that t... | algorithms | from math import sqrt
def is_constructable(area):
'''
Is "area" the sum of two perfect squares?
'''
return any(
sqrt(area - num * * 2). is_integer()
for num in range(int(sqrt(area)) + 1)
)
| Campfire building | 617ae2c4e321cd00300a2ec6 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/617ae2c4e321cd00300a2ec6 | 6 kyu |
- In the planet named Hoiyama, scientists are trying to find the weights of the mountains.
- They managed to find the weights of some mountains.
- But calculating them manually takes a really long time.
- That's why they hired you to develop an algorithm and easily calculate the weights of the mountains.
- Your functi... | algorithms | def mountains_of_hoiyama(w):
return ((w + 1) * * 3 - w * * 2) / / 8 + 1
| Mountains of Hoiyama | 617bfa617cdd1f001a5cadc9 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/617bfa617cdd1f001a5cadc9 | 7 kyu |
Imagine that you went to a zoo and some zoologists asked you for help.
They want you to find the strongest ape of its own kind and there are 4 types of apes in the zoo. (Gorilla, Gibbon, Orangutan, Chimpanzee)
* There will be only one parameter which is a list containing lots of dictionaries.
* Each dictionary will be... | algorithms | def find_the_strongest_apes(apes):
apes . sort(key=lambda a: a['name'])
imt = {'Gorilla': 0, 'Gibbon': 0, 'Orangutan': 0, 'Chimpanzee': 0}
res = {'Gorilla': None, 'Gibbon': None,
'Orangutan': None, 'Chimpanzee': None}
for ape in apes:
k = ape['height'] + ape['weight']
if imt[ap... | Find the Strongest Apes | 617af2ff76b7f70027b89db3 | [
"Lists",
"Sorting",
"Algorithms"
] | https://www.codewars.com/kata/617af2ff76b7f70027b89db3 | 6 kyu |
<h1 align="center">Hit the target</h1>
<em>This is the second part of the kata :3 🎈🎆🎇🎆🎈</em><br>
given a matrix <code>n x n</code> (2-7), determine if the arrow is directed to the target (x). <br>
Now there are one of 4 types of arrows (<code> '^', '>', 'v', '<' </code>) and only one target (<code>x</code>)<... | reference | def solution(mtrx):
return any(i . index('>') < i . index('x') for i in mtrx if '>' in i and 'x' in i) or \
any(i . index('<') > i . index('x') for i in mtrx if '<' in i and 'x' in i) or \
any(i . index('^') > i . index('x') for i in zip(* mtrx) if '^' in i and 'x' in i) or \
any(i . ind... | Game Hit the target - 2nd part | 6177b4119b69a40034305f14 | [
"Matrix",
"Arrays",
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/6177b4119b69a40034305f14 | 6 kyu |
# introduction
## In this kata you can learn
- How to deal with bytes files in python
- Caesar code
- Convert bytes to int
- Few things about PNG format
## Caesar code
In cryptography, a Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code or Caesar shift, is one of the simplest and most wid... | reference | from itertools import islice
def decipher(bs):
bs = iter(bs)
def eat(n): return islice(bs, n)
def decode(size, key): return [(c - key) % 256 for c in eat(size)]
out = [* eat(8)]
for key in bs:
sizeB = decode(3, key)
size = int . from_bytes(sizeB, byteorder='big') + 8
out .... | Break Caesar cipher variation : PNG image | 6174318832e56300079b7d4b | [
"Cryptography",
"Fundamentals"
] | https://www.codewars.com/kata/6174318832e56300079b7d4b | 5 kyu |
## Task
Write a function that can deduce which key was used during a Vigenere cipher encryption, given the resulting ciphertext, and the length of that key.
### Notes
* The input string, as well as the encryption key, will consist of uppercase letters only
* All texts will be in English
___
### Vigenere cipher
(F... | algorithms | from collections import Counter
from string import ascii_uppercase
ALPHABET = ascii_uppercase * 2
FREQUENCY_LETTERS = {
'A': 0.0815, 'B': 0.0144, 'C': 0.0276, 'D': 0.0379, 'E': 0.1311, 'F': 0.0292, 'G': 0.0199,
'H': 0.0526, 'I': 0.0635, 'J': 0.0013, 'K': 0.0042, 'L': 0.0339, 'M': 0.0254, 'N': 0.0710,
... | Breaking the Vigenère Cipher | 544e5d75908f2d5eb700052b | [
"Ciphers",
"Cryptography",
"Algorithms"
] | https://www.codewars.com/kata/544e5d75908f2d5eb700052b | 3 kyu |
Failure on the factory floor!! One box of 'deluxe' ball-bearings has been mixed in with all the boxes of 'normal' ball-bearings! We need your help to identify the right box!
## Information
What you know about the bearings:
- 'deluxe' ball-bearings weigh exactly `11 grams`
- 'normal' ball-bearings weigh exactly `10 gr... | games | # what "best practice" should be about
def identify_bb(boxes, weigh):
boxes_amount = len(boxes)
sample = (box for count, box in enumerate(boxes, 1) for _ in range(count))
sample_weight = weigh(* sample)
sample_amount = triangular(boxes_amount)
deluxe_number = sample_weight % sample_amount - 1
... | Identify Ball Bearings | 61711668cfcc35003253180d | [
"Riddles"
] | https://www.codewars.com/kata/61711668cfcc35003253180d | 6 kyu |
<h2>Task:</h2>
Your job is to write a function, which takes three integers `a`, `b`, and `c` as arguments, and returns `True` if exactly two of the three integers are positive numbers (greater than zero), and `False` - otherwise.
<h2>Examples:</h2>
```python
two_are_positive(2, 4, -3) == True
two_are_positive(-4, 6,... | reference | def two_are_positive(a, b, c):
return sum([a > 0, b > 0, c > 0]) == 2
| Two numbers are positive | 602db3215c22df000e8544f0 | [
"Fundamentals"
] | https://www.codewars.com/kata/602db3215c22df000e8544f0 | 7 kyu |
The workers of CodeLand intend to build a brand new building in the town centre after the end of the 3rd Code Wars.
They intend to build a triangle-based pyramid (tetrahedron) out of cubes.
They require a program that will find the tallest potential height of the pyramid, given a certain number of cubes.
Your functi... | games | def find_height(n):
r = int((n * 6) * * (1 / 3))
return r if r * (r + 1) * (r + 2) / / 6 <= n else r - 1
| The Pyramid of Cubes | 61707b71059070003793bc0f | [
"Mathematics",
"Puzzles"
] | https://www.codewars.com/kata/61707b71059070003793bc0f | 6 kyu |
# Introduction
In this kata, you'll have to write an algorithm that, given a set of input-output examples, synthesizes a Boolean function that takes on the behaviour of those examples. For instance, for the set of input-output examples:
```
(false, false) ↦ false
(false, true) ↦ false
(true, true) ↦ true
```
We c... | algorithms | # the DSL is preloaded, and is constructed as follows:
# variables: Variable(index: int)
# constants: CTrue() ; CFalse()
# binary operators: And(a: BoolFn, b: BoolFn) ; Or(a: BoolFn, b: BoolFn)
# unary operators: Not(a: BoolFn)
# the function beval(fn: BoolFn, vars: list[bool]) -> bool can be used to eval a DSL term
# ... | Synthesize Boolean Functions From Examples | 616fcf0580f1da001b925606 | [
"Algorithms"
] | https://www.codewars.com/kata/616fcf0580f1da001b925606 | 5 kyu |
# Flatten Rows From DataFrame
## Input parameters
1. dataframe: `pandas.DataFrame` object
2. col: target column
## Task
Your function must return a new ``pandas.DataFrame`` object with the same columns as the original input. However, targeted column has in some of its cells a list instead of one single element.You... | reference | import pandas as pd
def flatten(dataframe, col):
return dataframe . explode(col). reset_index(drop=True)
| Pandas Series 104: Flatten Rows From DataFrame | 615bf5f446a1190007bfb9d9 | [
"Lists",
"Data Frames",
"Fundamentals",
"Data Science"
] | https://www.codewars.com/kata/615bf5f446a1190007bfb9d9 | 6 kyu |
Polygons are planar (2-D) shapes with all straight sides.
Web polygons also called Tree polygons are polygons which can be formed by a peculiar sequencing pattern. It results in the formation of rhombus like polygons on a web.
Each 'n' in the sequence causes 'n' branches, these branches can be closed by the number '1'... | algorithms | def webpolygons(a):
stack = [[1, 1, 0]]
for n in a:
if n > 1:
stack . append([n, 1, 0])
elif len(stack) > 1:
branch, prod_, sum_ = stack . pop()
stack[- 1][1] *= branch * prod_
stack[- 1][2] += branch * sum_ + \
branch * ~ - branch / / 2 * prod_ * * 2
while len(... | Web Polygons | 609243c36e796b003e79e6b5 | [
"Algorithms",
"Data Structures",
"Mathematics",
"Geometry"
] | https://www.codewars.com/kata/609243c36e796b003e79e6b5 | 4 kyu |
# Cargo-Bot

Cargo-Bot is a programming videogame consisting of vertical stacks of crates and a claw to move the crates from one stack to another. The aim of the game is to move the crates from an initial position to a desired final position.
The player control... | algorithms | def cargobot(states, programs, max_steps):
def isValid(cmd):
return cmd . flag is None \
or hold and (cmd . flag == 'ANY' or cmd . flag == hold . color) \
or hold is None and cmd . flag == 'NONE'
def pushCmds(i): stk . extend(reversed(programs[i]))
pos, hold, stk, states = 0,... | Cargo-Bot Interpreter | 616a585e6814de0007f037a7 | [
"Interpreters",
"Games",
"Algorithms"
] | https://www.codewars.com/kata/616a585e6814de0007f037a7 | 5 kyu |
You are a barista at a big cafeteria. Normally there are a lot of baristas, but your boss runs a contest and he told you that, if you could handle all the orders with only one coffee machine in such a way that the sum of all the waiting times of the customers is the smallest possible, he will give you a substantial rai... | reference | from itertools import accumulate
def barista(coffees):
return sum(accumulate(sorted(coffees), lambda a, c: a + 2 + c))
| Barista problem | 6167e70fc9bd9b00565ffa4e | [
"Fundamentals",
"Sorting"
] | https://www.codewars.com/kata/6167e70fc9bd9b00565ffa4e | 7 kyu |
There are numbers for which the `$n^{th}$` root equals the sum of their digits. For example:
`$\sqrt[3]{512} = 5+1+2 = 8$`
Complete the function that returns **all** natural numbers (in ascending order) for which the above statement is true for the given `n`, where `2 ≤ n ≤ 50`
#### Note
*To avoid hardcoding the an... | algorithms | def nth_root_equals_digit_sum(n):
answer = []
for x in range(1, 1000):
if sum([int(i) for i in (str(x * * n))]) == x:
answer . append(x * * n)
return answer
| Nth Root Equals Digit Sum | 60416d5ee50db70010e0fbd4 | [
"Algorithms"
] | https://www.codewars.com/kata/60416d5ee50db70010e0fbd4 | 6 kyu |
Little boy Vasya was coding and was playing with arrays. He thought: "Is there any way to generate N-dimensional array"? </br>
Let us help little boy Vasya. Target of this Kata is to create a function, which will generate N-dimensional array. For simplicity all arrays will have the same length.</br>
<h3>Input:</h3>
N:... | reference | def create_n_dimensional_array(n, size):
res = f'level { n } '
for _ in range(n):
res = [res] * size
return res
| Create N-dimensional array | 6161847f52747c0025d0349a | [
"Arrays",
"Recursion",
"Fundamentals"
] | https://www.codewars.com/kata/6161847f52747c0025d0349a | 6 kyu |
# Introduction:
If you liked the _previous_ Kata [_(Sequence Duality and "Magical" Extrapolation)_](https://www.codewars.com/kata/6146a6f1b117f50007d44460), you may also be interested by this one, as -despite being somewhat "more advanced"- it is also based on the following principle:
- Start from an abstract-looking... | reference | class R_e:
def __init__(self, real, epsilon=0):
self . real = real
self . epsilon = epsilon
def __str__(self): # (Not necessary to complete the Kata; but always useful)
return "R_e(" + str(self . real) + ", " + str(self . epsilon) + ")"
def __repr__(self): # (Not necessary to complete th... | "Dual Numbers" and "Automatic" (nth) Derivatives | 615e3cec46a119000efd3b1f | [
"Mathematics",
"Algebra",
"Fundamentals",
"Tutorials"
] | https://www.codewars.com/kata/615e3cec46a119000efd3b1f | 5 kyu |
More difficult version: [Kingdoms Ep2: The curse (normal)](https://www.codewars.com/kata/615b636c3f8bcf0038ae8e8b)
Our King was cursed - He can not pronounce an entire word anymore. Looking for the witch, the inquisition punishes every beautiful and intelligent woman in the Kingdom. Trying to save your wife and to sto... | reference | import re
def translate(s, voc):
return re . sub(r'[\w*]+', lambda m: next(filter(re . compile(m . group(). replace('*', '.')). fullmatch, voc)), s)
| Kingdoms Ep2: The curse (simplified) | 6159dda246a119001a7de465 | [
"Fundamentals",
"Arrays",
"Regular Expressions"
] | https://www.codewars.com/kata/6159dda246a119001a7de465 | 6 kyu |
# Info
Lists are general purpose data structures. In Lambda Calculus, lists can be represented with pairs: the first element of a pair indicates whether the list is empty or not ( as a Church Boolean ), and the second element is another pair of the head and the tail of the list.
Pairs can be represented as a functio... | reference | def PREPEND(vs): return lambda v: PAIR(FALSE)(PAIR(v)(vs))
def BUILD_TAIL(vs): return lambda v: PREPEND(APPEND(TAIL(vs))(v))(HEAD(vs))
def APPEND(vs): return (IS_EMPTY(vs)(PREPEND)(BUILD_TAIL))(vs)
| Lambda Calculus: Lists | 5eecd4a5e5d13e000150e249 | [
"Functional Programming",
"Fundamentals",
"Lists",
"Data Structures"
] | https://www.codewars.com/kata/5eecd4a5e5d13e000150e249 | 5 kyu |
You are given an array of strings that need to be spread among N columns. Each column's width should be the same as the length of the longest string inside it.
Separate columns with `" | "`, and lines with `"\n"`; content should be left-justified.
`{"1", "12", "123", "1234", "12345", "123456"}` should become:
```
1 ... | algorithms | from itertools import zip_longest
def columnize(a, n):
a = [a[i: i + n] for i in range(0, len(a), n)]
b = [max(map(len, x)) for x in zip_longest(* a, fillvalue="")]
return "\n" . join(" | " . join(y . ljust(z) for y, z in zip(x, b)) for x in a)
| Columnize | 6087bb6050a6230049a068f1 | [
"Fundamentals",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/6087bb6050a6230049a068f1 | 6 kyu |
## Task
Implement a function which takes an array of nonnegative integers and returns **the number of subarrays** with an **odd number of odd numbers**. Note, a subarray is a ***contiguous subsequence***.
## Example
Consider an input:
```python
[1, 2, 3, 4, 5]
```
The subarrays containing an odd number of odd number... | algorithms | def solve(arr):
e, o, s = 0, 0, 0
for n in arr:
if n & 1:
e, o = o, e + 1
else:
e += 1
s += o
return s
| Subarrays with an odd number of odd numbers | 6155e74ab9e9960026efc0e4 | [
"Algorithms",
"Performance"
] | https://www.codewars.com/kata/6155e74ab9e9960026efc0e4 | 5 kyu |
Your task is to return the amount of white rectangles in a `NxN` spiral. Your font may differ, if we talk of white rectangles, we talk about the symbols in the top row.
#### Notes:
* As a general rule, the white snake cannot touch itself.
* The size will be at least 5.
* The test cases get very large, it is not feasi... | games | def spiral_sum(n): return (n + 1) * * 2 / / 2 - 1
| Count a Spiral | 61559bc4ead5b1004f1aba83 | [
"Puzzles"
] | https://www.codewars.com/kata/61559bc4ead5b1004f1aba83 | 6 kyu |
This kata is based on the [Socialist distribution](https://www.codewars.com/kata/socialist-distribution) by GiacomoSorbi. It is advisable to complete it first to grasp the idea, and then move on to this one.
___
## Task
You will be given a list of numbers representing the people's resources, and an integer - the min... | algorithms | def distribution(population, minimum):
if (diff := sum(minimum - p for p in population if p < minimum)) == 0:
return population
popul, total = sorted(population, reverse=True), 0
rich = next(k for k, (v, p) in enumerate(
zip(popul, popul[1:]), 1) if (total := total + v) - p * k >= diff)... | Socialist distribution (performance edition) | 5dd08d43dcc2e90029b291af | [
"Algorithms",
"Performance"
] | https://www.codewars.com/kata/5dd08d43dcc2e90029b291af | 5 kyu |
# Narrative
Your task is to create brain for amoeba. You're lucky because this creature doesn't think a lot - all what it wants is food.
```
~* ::
```
Your fellow amoeba floats in 2D primordial soup that looks like a maze. It has no eyes, so it can't see the whole maze, but it... | games | class AmoebaBrain:
def __init__(self):
self . smell = - 1
self . checked = set()
self . back = None
self . X = self . Y = 0
def get_move_direction(self, surrounding, food_smell):
# Current pos is now tested, no need to try it again later
self . checked . add((self . X, self... | Amoeba: Blind Maze | 614f1732df4cfb0028700d03 | [
"Puzzles"
] | https://www.codewars.com/kata/614f1732df4cfb0028700d03 | 5 kyu |
<h3>Electronics #1. Ohm's Law</h3>
This is based on Ohm's Law: V = IR
<br>being:
<br>V: Voltage in volts (V)
<br>I: Current in amps (A)
<br>R: Resistance in ohms (R)
<h3>Task</h3>
Create a function ohms_law(s) that has an input string.
<br>Your get a string in the form:
<br>'2R 10V' or '1V 1A' for example.
<br>Ea... | reference | f = {
'V': lambda d: d['A'] * d['R'],
'A': lambda d: d['V'] / d['R'],
'R': lambda d: d['V'] / d['A']
}
def ohms_law(s):
data = {v[- 1]: float(v[: - 1]) for v in s . split()}
res_key = next(iter(set(f) - set(data)))
value = str(round(f[res_key](data), 6))
return f' { value }{ res... | Electronics #1. Ohm's Law | 614dfc4ce78d31004a9c1276 | [
"Fundamentals"
] | https://www.codewars.com/kata/614dfc4ce78d31004a9c1276 | 7 kyu |
Expansion is performed for a given 2x2 matrix.
```
[
[1,2],
[5,3]
]
```
After expansion:
```
[
[1,2,a],
[5,3,b],
[c,d,e]
]
```
- a = 1 + 2 = 3
- b = 5 + 3 = 8
- c = 5 + 1 = 6
- d = 3 + 2 = 5
- e = 1 + 3 = 4
Final result:
```
[
[1,2,3],
[5,3,8],
[6,5,4]
]
```
## TASK
Let expansion be a function w... | games | import numpy as np
def expansion(matrix, n):
arr = np . array(matrix)
for i in range(n):
new_col = arr . sum(axis=1)
new_row = arr . sum(axis=0)
new_e = np . trace(arr)
new_row = np . append(new_row, new_e). reshape((1, len(arr) + 1))
arr = np . c_[arr, new_col]
ar... | Matrix Expansion | 614adaedbfd3cf00076d47de | [
"Algebra",
"Puzzles",
"Matrix"
] | https://www.codewars.com/kata/614adaedbfd3cf00076d47de | 6 kyu |
Jack's teacher gave him a ton of equations for homework. The thing is they are all kind of same so they are boring.
So help him by making a equation solving function that will return the value of x.
Test Cases will be like this:
```
# INPUT # RETURN
'x + 1 = 9 - 2' # 6
'- 10 = x' # -10
'x - 2 +... | algorithms | def solve(eq):
a, b = eq . replace('x', '0'). split('=')
x = eval(a) - eval(b)
if '- x' in eq:
x *= - 1
return x if eq . index('x') > eq . index('=') else - x
| Value of x | 614ac445f13ead000f91b4d0 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/614ac445f13ead000f91b4d0 | 5 kyu |
[Fischer random chess](https://en.wikipedia.org/wiki/Fischer_random_chess), also known as Chess960, is a variant of chess, invented by Bobby Fischer on June 19, 1996.
The rules are the same as regular chess, but the starting position is randomized according to the **randomization rules** (see below). Note that prior k... | reference | def is_valid(positions):
# get relevant positions
bishop_left = positions . find("B")
bishop_right = positions . rfind("B")
rook_left = positions . find("R")
rook_right = positions . rfind("R")
king = positions . find("K")
# valid if king between rooks and bishops on different color... | Is this a valid Chess960 position? | 61488fde47472d000827a51d | [
"Fundamentals",
"Algorithms",
"Games",
"Strings"
] | https://www.codewars.com/kata/61488fde47472d000827a51d | 7 kyu |
## Task
Given a positive integer, `n`, return the number of possible ways such that `k` positive integers multiply to `n`. Order matters.
**Examples**
```
n = 24
k = 2
(1, 24), (2, 12), (3, 8), (4, 6), (6, 4), (8, 3), (12, 2), (24, 1) -> 8
n = 100
k = 1
100 -> 1
n = 20
k = 3
(1, 1, 20), (1, 2, 10), (1, 4, 5), (1, 5... | algorithms | from scipy . special import comb
def multiply(n, k):
r, d = 1, 2
while d * d <= n:
i = 0
while n % d == 0:
i += 1
n / /= d
r *= comb(i + k - 1, k - 1, exact=True)
d += 1
if n > 1:
r *= k
return r
| Multiply to `n` | 5f1891d30970800010626843 | [
"Mathematics",
"Algebra",
"Performance",
"Algorithms"
] | https://www.codewars.com/kata/5f1891d30970800010626843 | 4 kyu |
## Description:
The Padovan sequence is the sequence of integers P(n) defined by the initial values
P(0)=P(1)=P(2)=1
and the recurrence relation
P(n)=P(n-2)+P(n-3)
The first few values of P(n) are
1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37, 49, 65, 86, 114, 151, 200, 265, ...
## Task
```if:java
The task i... | reference | def padovan(n):
x, y, z = 1, 0, 0
for c in map(int, bin(n)[2:]):
x, y, z = x * x + 2 * y * z, 2 * x * y + y * \
y + z * z, x * z + 2 * y * z + x * z + y * y
if c:
x, y, z = y, z, x + y
return x + y + z
| Big Big Big Padovan Number | 5819f1c3c6ab1b2b28000624 | [
"Performance",
"Algorithms",
"Big Integers"
] | https://www.codewars.com/kata/5819f1c3c6ab1b2b28000624 | 4 kyu |
The goal of this Kata is to build a very simple, yet surprisingly powerful algorithm to extrapolate sequences of _numbers_*
(* in fact, it would work with literally any "[sequence of] _objects that can be added and subtracted_"!)
This will be achieved by using a little Mathematical "trick" (Binomial Transform), which ... | algorithms | def delta(lst):
return [a - b for a, b in zip(lst, lst[1:])]
def dual_seq(lst):
return lst[: 1] + [(lst := delta(lst))[0] for _ in lst[1:]]
def extra_pol(lst, n):
return dual_seq(dual_seq(lst) + [0] * n)
| Sequence Duality and "Magical" Extrapolation (Binomial Transform) | 6146a6f1b117f50007d44460 | [
"Mathematics",
"Algebra",
"Algorithms",
"Tutorials"
] | https://www.codewars.com/kata/6146a6f1b117f50007d44460 | 6 kyu |
You get a list of non-zero integers `A`, its length is always greater than one. Your task is to find such non-zero integers `W` that the weighted sum
```math
A_0 \cdot W_0 + A_1 \cdot W_1 + .. + A_n \cdot W_n
```
is equal to `0`.
Unlike the [first kata](https://www.codewars.com/kata/5fad2310ff1ef6003291a951) in the ... | reference | from math import prod
def weigh_the_list(xs):
p = prod(xs)
return [p / / x for x in xs[: - 1]] + [- p * (len(xs) - 1) / / xs[- 1]]
| Weigh The List #2 | 5fafdcb2ace077001cc5f8d0 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/5fafdcb2ace077001cc5f8d0 | 6 kyu |
***
Nicky has had Myopia (Nearsightedness) since he was born. Because he always wears glasses, he really hates digits `00` and he loves digits 1 and 2. He calls numbers, that don't contain `00` (two consecutive zeros), the Blind Numbers. He will give you `n`, the digit-length of number in 10-adic system, and you need t... | reference | def blind_number(n):
a, b = 1, 3
for _ in range(n):
a, b = b, (a + b) * 2 % 1000000007
return a
| Blind Numbers | 5ee044344a543e001c1765b4 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/5ee044344a543e001c1765b4 | 6 kyu |
# Cubes in the box
Your job is to write a function `f(x,y,z)` to count how many cubes <b>of any size</b> can fit inside a `x*y*z` box. For example, a `2*2*3` box has 12 `1*1*1` cubes, 2 `2*2*2` cubes, so a total of 14 cubes in the end. See the animation below for a visual description of the task!
### Notes:
- `x`,`y`... | reference | def f(x, y, z):
return sum((x - i) * (y - i) * (z - i) for i in range(min(x, y, z)))
| Cubes in the box | 61432694beeca7000f37bb57 | [
"Mathematics",
"Fundamentals",
"Geometry"
] | https://www.codewars.com/kata/61432694beeca7000f37bb57 | 7 kyu |
# Description
Your task in this kata is to solve numerically an ordinary differential equation. This is an equation of the form `$\dfrac{dy}{dx} = f(x, y)$` with initial condition `$y(0) = x_0$`.
## Motivation and Euler's method
The method you will have to use is Runge-Kutta method of order 4. The Runge-Kutta method... | algorithms | def RK4(x0, y0, h, f, x1):
ys, cur = [y0], x0
while cur < x1:
k1 = h * f(cur, ys[- 1])
k2 = h * f(cur + h / 2, ys[- 1] + k1 / 2)
k3 = h * f(cur + h / 2, ys[- 1] + k2 / 2)
k4 = h * f(cur + h, ys[- 1] + k3)
ys . append(ys[- 1] + (k1 + 2 * k2 + 2 * k3 + k4) / 6)
cur += h
retu... | Approximate solution of differential equation with Runge-Kutta 4 | 60633afe35b4960032fd97f9 | [
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/60633afe35b4960032fd97f9 | 6 kyu |
Similar but fairly harder version : [Linked](https://www.codewars.com/kata/540d0fdd3b6532e5c3000b5b)
Create a function that takes a integer number `n` and returns the formula for `$(a+b)^n$` as a string. (**Input --> Output**)
```
0 --> "1"
1 --> "a+b"
2 --> "a^2+2ab+b^2"
-2 --> "1/(a^2+2ab+b^2)"
3 --> "a^3+3a^2b... | games | from math import comb
def formula(n):
return (f'1/( { formula ( - n ) } )' if n < 0 else '1' if not n else
'+' . join(binom(n - i, i) for i in range(n + 1)))
def binom(a, b):
c = comb(a + b, a)
return f" { c if c > 1 else '' }{ term ( 'a' , a ) }{ term ( 'b' , b ) } "
def te... | (a+b)^n | 61419e8f0d12db000792d21a | [
"Mathematics",
"Algebra",
"Strings"
] | https://www.codewars.com/kata/61419e8f0d12db000792d21a | 6 kyu |
You must organize contest, that contains two part, knockout and round-robin.
# **Part 1**
Knockout part goes until we get an odd number of players.
In each round players are paired up; each pair plays a game with the winning player advancing to the next round (no ties). This part continues as long as number of player... | algorithms | from itertools import count, takewhile
from math import isqrt
def find_player_counts(number_of_games):
"""
let games(p) = number of games for p players
let i, k be nonnegative integers
games(2^i * (2k + 1)) = (2^i - 1) * (2k + 1) + (2k + 1) * (2k + 1 - 1) / 2
let n = 2^i - 1
games((n + 1) * (2k + 1)) ... | Number of players for knockout/round-robin hybrid contest (easy mode) | 613f13a48dfb5f0019bb3b0f | [
"Combinatorics",
"Permutations",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/613f13a48dfb5f0019bb3b0f | 5 kyu |
You are doing an excercise for chess class.
Your job given a bishop's start position (`pos1 / startPos`) find if the end position (`pos2 / endPos`) given is possible within `n` moves.
### INPUT :
```
startPos (1st param) ==> The position at which bishop is at
endPos (2nd param) ==> The position at which he is su... | algorithms | def bishop(start, end, moves):
sx, sy = map(ord, start)
ex, ey = map(ord, end)
dx, dy = abs(ex - sx), abs(ey - sy)
return moves > 1 and dx % 2 == dy % 2 or dx == dy and (moves > 0 or dx == 0)
| Bishop Movement checker | 6135e4f40cffda0007ce356b | [
"Games",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/6135e4f40cffda0007ce356b | 6 kyu |
# Task
An employee wishes to resign.
*Do not let him go.*
Locate the entrance to his office so we can send its coordinates to the
orbital obstacle placement service (OOPS).
The floor plan of the office is given as a list (python) or an array (java) of strings.
Walls are marked with a `#` and interior with `.`. Strin... | algorithms | def locate_entrance(office: list) - > tuple:
def is_on_edge(r, c):
try:
return r == 0 or r == len(office) - 1 or \
c == 0 or c == len(office[r]) - 1 or \
office[r][c - 1] == ' ' or office[r][c + 1] == ' ' or \
office[r + 1][c] == ' ' or office[r - 1][c] == ' '
except Index... | Do not let him go | 61390c407d15c3003fabbd35 | [
"Strings",
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/61390c407d15c3003fabbd35 | 6 kyu |
The King organizes the jousting. You are a young human lady and your fiancé is an ogre. Today is his anniversary and he would love to visit the tournament, but it's forbidden for ogres to visit the Kingdom. So you decided to go there, to paint the exact moments of clash of cavalry and to present these paintings to your... | reference | def joust(list_field: tuple, v_knight_left: int, v_knight_right: int) - > tuple:
if v_knight_left == 0 and v_knight_right == 0:
return list_field
len1, len2 = len(list_field[0]), len(list_field[1])
left_point, right_point = 2, len1 - 3
while left_point < right_point:
left_point += v_knight... | Kingdoms Ep1: Jousting | 6138ee916cb50f00227648d9 | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/6138ee916cb50f00227648d9 | 6 kyu |
Hopefully you are familiar with the game of ten-pin bowling! In this kata you will need to calculate the winner of a match between two players.
<h1>Scoring a frame</h1>
Each player will play three frames, consisting of ten attempts to knock down ten pins. At each attempt a player can take either one or two rolls, one ... | games | def score_match(frames):
pts, pins = [[], []], [0, 0]
for f in zip(* frames):
for i, (s, p) in enumerate(map(scoreFrame, f)):
pts[i]. append(s)
pins[i] += p
score1 = [1 + (a > b) - (a < b) for a, b in zip(* pts)]
a, b = pins
scores = [score1 + [a > b], [2 - s for s in score1] + [... | Ten-pin bowling - score the frame | 5b4f309dbdd074f9070000a3 | [
"Puzzles"
] | https://www.codewars.com/kata/5b4f309dbdd074f9070000a3 | 6 kyu |
A "True Rectangle" is a rectangle with two different dimensions and four equal angles.
---
## Task:
In this kata, we want to **decompose a given true rectangle** into the minimum number of squares,
Then aggregate these generated squares together to form **all** the possible true rectangles.
---
## Examples:
>
<img... | games | class Rectangle:
@ staticmethod
def rect_into_rects(length, width):
if width < length:
width, length = length, width
rects = []
while 0 < length < width:
sqs, width = divmod(width, length)
rects += sum(([(d * length, length)] * (sqs - d + 1)
for d in range(2... | Rectangle into Rectangles | 58b22dc7a5d5def60300002a | [
"Puzzles",
"Fundamentals",
"Algorithms",
"Geometry"
] | https://www.codewars.com/kata/58b22dc7a5d5def60300002a | 5 kyu |
Specification pattern is one of the OOP design patterns. Its main use is combining simple rules into more complex ones for data filtering. For example, given a bar menu you could check whether a drink is a non-alcoholic cocktail using the following code:
```
drink = # ...
is_cocktail = IsCocktail()
is_alcoholic = In... | reference | class Meta (type):
def __invert__(self): return Meta(
"", (), {"__new__": lambda _, x: not self(x)})
def __and__(self, other): return Meta(
"", (), {"__new__": lambda _, x: self(x) and other(x)})
def __or__(self, other): return Meta(
"", (), {"__new__": lambda _, x: self(x) o... | Readable Specification Pattern | 5dc424122c135e001499d0e5 | [
"Fundamentals",
"Object-oriented Programming",
"Design Patterns"
] | https://www.codewars.com/kata/5dc424122c135e001499d0e5 | 5 kyu |
# Longest Palindromic Substring (Linear)
A palindrome is a word, phrase, or sequence that reads the same backward as forward, e.g.,
'madam' or 'racecar'. Even the letter 'x' is considered a palindrome.
For this Kata, you are given a string ```s```. Write a function that returns the longest _contiguous_ palindromic s... | algorithms | '''
Write a function that returns the longest contiguous palindromic substring in s.
In the event that there are multiple longest palindromic substrings, return the
first to occur.
'''
def longest_palindrome(s, sep=" "):
# Interpolate some inert character between input characters
# so we only have to ... | Longest Palindromic Substring (Linear) | 5dcde0b9fcb0d100349cb5c0 | [
"Performance",
"Algorithms",
"Puzzles"
] | https://www.codewars.com/kata/5dcde0b9fcb0d100349cb5c0 | 4 kyu |
<!-- Stable Weight Arrangement -->
Here is a simple task. Take an array/tuple of unique positive integers, and two additional positive integers. Here's an example below:
```javascript
const arr = [3,5,7,1,6,8,2,4];
const n = 3; // span length
const q = 13; // weight threshold
```
```python
arr = (3,5,7,1,6,8,2,4)
n = ... | algorithms | def gen(l, p, arr, n, q):
if not p:
yield []
return
for i in p:
if len(l) + 1 < n or sum(l[len(l) - n + 1:]) + arr[i] <= q:
for s in gen(l + [arr[i]], p - set([i]), arr, n, q):
yield [arr[i]] + s
def solver(arr, n, q):
return next(gen([], set(range(len(arr))), ... | Stable Weight Arrangement | 5d6eef37f257f8001c886d97 | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/5d6eef37f257f8001c886d97 | 5 kyu |
Find the lowest-cost Hamiltonian cycle of an undirected graph.
Input is an adjacency matrix consisting of a dictionary of dictionaries of costs, such that `d[A][B]` is the cost going from A to B or from B to A. Output is a sequence of nodes representing the minimum cost Hamiltonian cycle through all nodes. If no such ... | games | def get_minimum_hamiltonian_cycle(adj):
candidates = [((a,), 0) for a in adj]
best_cycle = None
best_cost = float('inf')
len_adj = len(adj)
while candidates:
path, cost = candidates . pop()
for node, c in adj[path[- 1]]. items():
new_cost = cost + c
if node not in path:
... | Coping with NP-Hardness #3: Finding the Minimum Hamiltonian Cycle | 5ee12f0a5c357700329a6f8d | [
"Puzzles"
] | https://www.codewars.com/kata/5ee12f0a5c357700329a6f8d | 5 kyu |
*This is the advanced version of the [Total Primes](https://www.codewars.com/kata/total-primes/) kata.*
The number `23` is the smallest prime that can be "cut" into **multiple** primes: `2, 3`. Another such prime is `6173`, which can be cut into `61, 73` or `617, 3` or `61, 7, 3` (all primes). A third one is `557` wh... | algorithms | from bisect import bisect_left, bisect
sp = set(map(str, PRIMES))
def tp(s):
for x in range(1, len(s)):
if s[: x] in sp and (s[x:] in sp or tp(s[x:])):
return True
return False
TOTAL_PRIMES = [i for i in PRIMES if tp(str(i))]
def total_primes(a, b):
return TOTAL_PRIMES[bis... | Total Primes - Advanced Version | 5d2351b313dba8000eecd5ee | [
"Performance",
"Algorithms"
] | https://www.codewars.com/kata/5d2351b313dba8000eecd5ee | 5 kyu |
# Task
John bought a bag of candy from the shop. Fortunately, he became the 10000000000000000000000th customer of the XXX confectionery company. Now he can choose as many candies as possible from the company's `prizes`. With only one condition: the sum of all the candies he chooses must be multiples of `k`.
Your task... | algorithms | def lucky_candies(a, k):
l = [0] + (k - 1) * [float('-inf')]
for x in a:
l = [max(l[(i - x) % k] + x, y) for i, y in enumerate(l)]
return l[0]
| Simple Fun #314: Lucky Candies | 592e5d8cb7b59e547c00002f | [
"Algorithms",
"Dynamic Programming",
"Performance"
] | https://www.codewars.com/kata/592e5d8cb7b59e547c00002f | 5 kyu |
***note: linear algebra experience is recommended for solving this problem***
## Problem
Spike is studying spreading spores graphs. A spreading spores graph represents an undirected graph where each node has a float amount (possibly negative or fractional) of spores in it. At each step in time, all the initial spore... | algorithms | from typing import Dict, List
from numpy import array
from numpy . linalg import eigvalsh
def get_greatest_spore_multiplier(graph: Dict[int, List[int]]) - > float:
if not graph:
return 0
matrix = array([[x in adj for x in graph] for adj in graph . values()])
return max(eigvalsh(matrix))
| Spreading Spores Graph | 60f3639b539c06001a076267 | [
"Linear Algebra",
"Mathematics",
"Combinatorics",
"NumPy",
"Algorithms",
"Graph Theory"
] | https://www.codewars.com/kata/60f3639b539c06001a076267 | 5 kyu |
You have to write a function that takes for input a 8x8 chessboard in the form of a bi-dimensional array of chars (or strings of length 1, depending on the language) and returns a boolean indicating whether the king is in check.
The array will include 64 squares which can contain the following characters :
```if:c,h... | algorithms | UNITS = {'♝': {"moves": [(1, 1), (1, - 1), (- 1, 1), (- 1, - 1)], "limit": False},
'♜': {"moves": [(1, 0), (0, 1), (- 1, 0), (0, - 1)], "limit": False},
'♟': {"moves": [(1, 1), (1, - 1)], "limit": True},
'♞': {"moves": [(2, 1), (2, - 1), (- 2, 1), (- 2, - 1), (- 1, 2), (1, 2), (- 1, - 2), ... | Is the King in check ? | 5e28ae347036fa001a504bbe | [
"Games",
"Arrays",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5e28ae347036fa001a504bbe | 5 kyu |
Removed due to copyright infringement.
<!---
Little Petya often visits his grandmother in the countryside. The grandmother has a large vertical garden, which can be represented as a set of `n` rectangles of varying height. Due to the newest irrigation system we can create artificial rain above them.
Creating artific... | algorithms | def artificial_rain(garden):
left, area, record = 0, 0, 1
for i in range(1, len(garden)):
if garden[i] < garden[i - 1]:
left = i
elif garden[i] > garden[i - 1]:
area = max(area, record)
record = i - left
record += 1
return max(area, record)
| Artificial Rain | 5c1bb3d8e514df60b1000242 | [
"Algorithms",
"Logic",
"Performance"
] | https://www.codewars.com/kata/5c1bb3d8e514df60b1000242 | 5 kyu |
### You work at a taxi central.
People contact you to order a taxi. They inform you of the time they want to be picked up and dropped off.
A taxi is available to handle a new customer 1 time unit after it has dropped off a previous customer.
**What is the minimum number of taxis you need to service all requests?**
... | algorithms | from heapq import heappush, heappop
def min_num_taxis(requests):
taxis = [- 1]
for start, end in sorted(requests):
if taxis[0] < start:
heappop(taxis)
heappush(taxis, end)
return len(taxis)
| Minimum number of taxis | 5e1b37bcc5772a0028c50c5d | [
"Data Structures",
"Algorithms",
"Priority Queues",
"Scheduling"
] | https://www.codewars.com/kata/5e1b37bcc5772a0028c50c5d | 5 kyu |
## Typed Function overloading
Python is a very flexible language, however one thing it does not allow innately, is the overloading of functions. _(With a few exceptions)_. For those interested, [this existing kata](https://www.codewars.com/kata/5f24315eff32c4002efcfc6a) explores the possibility of overloading object m... | reference | from collections import defaultdict
from functools import wraps
CACHE = defaultdict(lambda: defaultdict(lambda: None))
def overload(* types):
def dec(func):
overloads = CACHE[func . __qualname__]
overloads[types] = func
@ wraps(func)
def wrapper(* a, * * kw):
typs = tuple(type(v) fo... | Function Overloading for Types | 6025224447c8ed001c6d8a43 | [
"Decorator",
"Language Features",
"Metaprogramming"
] | https://www.codewars.com/kata/6025224447c8ed001c6d8a43 | 5 kyu |
I often find that I end up needing to write a function to return multiple values, in this case I would often split it up into two different functions but then I have to spend time thinking of a new function name! Wouldn't it be great if I could use same name for a function again and again...
In this kata your task is ... | reference | from collections import defaultdict
class FuncAdd:
# Good Luck!
funcs = defaultdict(list)
def __init__(self, func):
name = func . __name__
FuncAdd . funcs[name]. append(func)
self . name = name
def __call__(self, * args, * * kwargs):
vals = []
if self . name not in Fu... | Function Addition | 5ebcfe1b8904f400208e3f0d | [
"Fundamentals"
] | https://www.codewars.com/kata/5ebcfe1b8904f400208e3f0d | 5 kyu |
# Basic pseudo-lisp syntax
Let's create a language that has the following syntax (_Backus–Naur form_):
```prolog
<expression> ::= <int> | <func_call>
<digit> ::= '0' | '1' | '2' | ... | '9'
<int> ::= <digit> [<int>]
<name_char> ::= (any character except parentheses and spaces)
<func_name> ::= <name_char> [<func_n... | algorithms | def parse(c, f): return eval(sub(* ' ,', sub('\((\S*) ', r"f['\1'](", c)))
| Lisp-esque parsing [Code Golf] | 5ea1de08a140dc0025b10d82 | [
"Parsing",
"Restricted",
"Algorithms"
] | https://www.codewars.com/kata/5ea1de08a140dc0025b10d82 | 5 kyu |
Your task in this kata is to implement simple version of <a href="https://docs.python.org/2/library/contextlib.html">contextlib.contextmanager</a>.
The decorator will be used on a generator functions and use the part of function before yield as context manager's "enter section" and the part after the yield as "exit se... | reference | # I think this kate could use more tests
class MyClass:
def __init__(self, f): self . gen = f()
def __enter__(self): return next(self . gen)
def __exit__(self, * args): pass
def contextmanager(f):
def wrapper(): return MyClass(f)
return wrapper
| Context manager decorator | 54e0816286522e95990007de | [
"Fundamentals"
] | https://www.codewars.com/kata/54e0816286522e95990007de | 5 kyu |
You are a chess esthete. And you try to find beautiful piece combinations. Given a chess board you want to see how this board will look like by removing each piece, one at a time.
*Note:* after removing a piece, you should put it back to its position, before removing another piece.
Also, you are a computer nerd. No ... | algorithms | def get_without_every_piece(s):
Z = []
for i, x in enumerate(s):
if not x . isalpha():
continue
a, b, c, p, q = s[: i], 1, s[i + 1:], 0, 0
if a and a[- 1]. isdigit():
p, a = int(a[- 1]), a[: - 1]
if c and c[0]. isdigit():
q, c = int(c[0]), c[1:]
Z += [a + st... | Chess Aesthetics | 5b574980578c6a6bac0000dc | [
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/5b574980578c6a6bac0000dc | 6 kyu |
# Task
You are given an sequence of zeros and ones. With each operation you are allowed to remove consecutive equal elements, however you may only remove single elements if no more groups of consective elements remain. How many operations will it take to remove all of the elements from the given sequence?
# Example
... | algorithms | from math import ceil
def array_erasing(lst):
# coding and coding...
dic = []
last = lst[0]
count = 0
for i, j in enumerate(lst):
if j == last:
count += 1
else:
dic . append(count)
last = j
count = 1
dic . append(count)
step = 0
length = len(dic... | Simple Fun #112: Array Erasing | 589d1c08cc2e997caf0000e5 | [
"Algorithms"
] | https://www.codewars.com/kata/589d1c08cc2e997caf0000e5 | 5 kyu |
# Boxlines
Given a `X*Y*Z` box built by arranging `1*1*1` unit boxes, write a function `f(X,Y,Z)` that returns the number of edges (hence, **boxlines**) of length 1 (both inside and outside of the box)
### Notes
* Adjacent unit boxes share the same edges, so a `2*1*1` box will have 20 edges, not 24 edges
* `X`,`Y` an... | reference | def f(a, b, c):
return 3 * (a * b * c) + 2 * (a * b + b * c + a * c) + a + b + c
| Boxlines | 6129095b201d6b000e5a33f0 | [
"Fundamentals",
"Geometry",
"Mathematics"
] | https://www.codewars.com/kata/6129095b201d6b000e5a33f0 | 7 kyu |
# Task
You have a long strip of paper with integers written on it in a single line from left to right. You wish to cut the paper into exactly three pieces such that each piece contains at least one integer and the sum of the integers in each piece is the same. You cannot cut through a number, i.e. each initial number ... | games | def three_split(arr):
need = sum(arr) / 3
result, chunks, current = 0, 0, 0
for i in range(0, len(arr) - 1):
current += arr[i]
if current == 2 * need:
result += chunks
if current == need:
chunks += 1
return result
| Simple Fun #44: Three Split | 588833be1418face580000d8 | [
"Puzzles",
"Performance"
] | https://www.codewars.com/kata/588833be1418face580000d8 | 5 kyu |
## Background Information
### When do we use an URL shortener?
In your PC life you have probably seen URLs like this before:
- https://bit.ly/3kiMhkU
If we want to share a URL we sometimes have the problem that it is way too long, for example this URL:
- https://www.google.com/search?q=codewars&tbm=isch&ved=2ahUKEwj... | algorithms | from itertools import product
from string import ascii_lowercase
def short_url_generator():
for l in range(1, 5):
yield from ('short.ly/' + '' . join(p) for p in product(ascii_lowercase, repeat=l))
class UrlShortener:
short_urls = short_url_generator()
long_to_short = {}
short_to... | URL shortener | 5fee4559135609002c1a1841 | [
"Databases",
"Algorithms",
"Data Structures"
] | https://www.codewars.com/kata/5fee4559135609002c1a1841 | 5 kyu |
Let us go through an example.
You have a string (here a short one):
`s = "GCAGCaGCTGCgatggcggcgctgaggggtcttgggggctctaggccggccacctactgg"`,
with only upper or lower cases letters A, C, G, T.
You want to find substrings in this string. Each substring to find has a label.
The different substrings to find are given in ... | reference | import re
REPL = {'R': '[GA]', 'Y': '[CT]', 'M': '[AC]', 'K': '[GT]', 'S': '[GC]',
'W': '[AT]', 'B': '[CGT]', 'D': '[AGT]', 'H': '[ACT]', 'V': '[ACG]', 'N': '[ACGT]'}
REGIFY = re . compile(f'[ { "" . join ( REPL ) } ]')
def get_pos(base, seq, query):
q = next(re . finditer(
rf' { query } \... | Positions of a substring in a string | 59f3956825d575e3330000a3 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/59f3956825d575e3330000a3 | 5 kyu |
A (blank) domino has 2 squares. Tetris pieces, also called tetriminos/tetrominoes, are made up of 4 squares each. A __polyomino__ generalizes this concept to _n_ connected squares on a flat grid.
Such shapes will be provided as a dictionary of `x` coordinates to sets of `y` coordinates. For example, the domino could b... | algorithms | TRANSFORMS = {
'M': [lambda x, y:(x, - y), lambda x, y:(- x, y), lambda x, y:(y, x), lambda x, y:(- y, - x)],
'C4': [lambda x, y:(y, - x)],
'C2': [lambda x, y:(- x, - y)],
}
GROUPS = (
('D4', {'C4', 'M'}),
('D2', {'C2', 'M'}),
('C4', {'C4'}),
('C2', {'C2'}),
('M', {'M'}),
)
... | Polyomino symmetry | 603e0bb4e7ce47000b378d10 | [
"Algorithms"
] | https://www.codewars.com/kata/603e0bb4e7ce47000b378d10 | 5 kyu |
# Directory tree
Given a string that denotes a directory, and a list (or array or ArrayList, etc, depending on language) of strings that denote the paths of files relative to the given directory, your task is to write a function that produces an _iterable_ (list, array, ArrayList, generator) of strings that, when prin... | reference | from typing import List
def tree(root: str, files: List[str]):
padders = (('├── ', '│ '),
('└── ', ' '))
def dfs(root, tree, pad='', link='', follow=''):
yield pad + link + root
pad += follow
lst = sorted(tree . items(), key=lambda it: (not it[1], it[0]))
for n, (k... | Directory tree | 5ff296fc38965a000963dbbd | [
"Fundamentals"
] | https://www.codewars.com/kata/5ff296fc38965a000963dbbd | 5 kyu |
An array consisting of `0`s and `1`s, also called a binary array, is given as an input.
### Task
Find the length of the longest contiguous subarray which consists of **equal** number of `0`s and `1`s.
### Example
```
s = [1,1,0,1,1,0,1,1]
|_____|
|
[0,1,1,0]
length = 4
```
#... | reference | from itertools import accumulate
def binarray(lst):
d, m = {}, 0
acc = accumulate(lst, lambda a, v: a + (v or - 1), initial=0)
for i, a in enumerate(acc):
if a not in d:
d[a] = i
else:
m = max(m, i - d[a])
return m
| Binary Contiguous Array | 60aa29e3639df90049ddf73d | [
"Algorithms",
"Dynamic Programming",
"Arrays"
] | https://www.codewars.com/kata/60aa29e3639df90049ddf73d | 5 kyu |
__Definition:__ According to Wikipedia, a [complete binary tree](https://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees) is a binary tree _"where every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible."_
The Wikipedia page referenced above also... | reference | def complete_binary_tree(a):
def in_order(n=0):
if n < len(a):
yield from in_order(2 * n + 1)
yield n
yield from in_order(2 * n + 2)
result = [None] * len(a)
for i, x in zip(in_order(), a):
result[i] = x
return result
| Complete Binary Tree | 5c80b55e95eba7650dc671ea | [
"Binary Trees",
"Heaps",
"Data Structures",
"Fundamentals"
] | https://www.codewars.com/kata/5c80b55e95eba7650dc671ea | 5 kyu |
You are provided with the following functions:
```python
t = type
k = lambda x: lambda _: x
```
Write a function `f` that returns the string `Hello, world!`.
The rules are:
* The solution should not exceed 33 lines
* Every line should have at most 2 characters
Note: There is the same [kata](https://www.codewars.co... | games | f \
= \
t(
'', (
),
{'\
f\
':
k('\
H\
e\
l\
l\
o\
,
\
w
o
r
l
d !'
)}
)(
)\
. f
| Multi Line Task: Hello World (Easy one) | 5e41c408b72541002eda0982 | [
"Puzzles"
] | https://www.codewars.com/kata/5e41c408b72541002eda0982 | 5 kyu |
<!--Dots and Boxes Validator-->
<p><span style='color:#8df'><a href='https://en.wikipedia.org/wiki/Dots_and_Boxes' style='color:#9f9;text-decoration:none'>Dots and Boxes</a></span> is a game typically played by two players. It starts with an empty square grid of equally-spaced dots. Two players take turns adding a sing... | algorithms | from itertools import chain
def dots_and_boxes(moves):
nodes = 1 + max(chain . from_iterable(moves))
player, Y = 0, int(nodes * * .5)
pts, grid = [0, 0], [4] * nodes
for a, b in moves:
swap = 1
if a > b:
a, b = b, a
for i in (a, a - Y if b - a == 1 else a - 1):
if i < 0:
... | Dots and Boxes Validator | 5d81d8571c6411001a40ba66 | [
"Games",
"Algorithms"
] | https://www.codewars.com/kata/5d81d8571c6411001a40ba66 | 5 kyu |
# Preface
Billy is tired of his job. He thinks that his boss is rude and his pay is pathetic. Yesterday he found out about forex trading. Now he looks at the charts and fantasizes about becoming a trader and how much money he would make.
# Task
Write a function that accepts a list of price points on the chart and re... | reference | def ideal_trader(prices):
res = 1
for i in range(1, len(prices)):
if prices[i] > prices[i - 1]:
res *= prices[i] / prices[i - 1]
return res
| Ideal Trader | 610ab162bd1be70025d72261 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/610ab162bd1be70025d72261 | 6 kyu |
## Task
Let `S` be a finite set of points on a plane where no three points are collinear. A windmill is the process where an infinite line (`l`), passing through an inital pivot point (`P`), rotates clockwise. Whenever `l` meets another element of `S` (call it `Q`), `Q` takes over as the pivot for `l`. This process co... | algorithms | from math import atan2, pi
def angle(p, q, direction):
return min((a for a in (atan2(p[0]-q[0],p[1]-q[1]), atan2(q[0]-p[0],q[1]-p[1])) if a > direction), default=None)
def windmill(points):
direction = -pi
p = 0, 0
n = 0
while c := m... | Windmill Cycle | 5fe919c062464e001856d70e | [
"Mathematics",
"Geometry",
"Algorithms"
] | https://www.codewars.com/kata/5fe919c062464e001856d70e | 5 kyu |
# Description
You get a list that contains points. A "point" is a tuple like `(x, y)`, where `x` and `y` are integer coordinates. By connecting three points, you get a triangle. There will be `n > 2` points in the list, so you can draw one or more triangles through them.
Your task is to write a program that returns a ... | reference | from itertools import combinations
def area(a, b, c):
return abs(a[0] * (b[1] - c[1]) + b[0] * (c[1] - a[1]) + c[0] * (a[1] - b[1])) / 2
def maxmin_areas(points):
r = list(filter(lambda x: x > 0, map(
lambda p: area(* p), combinations(points, 3))))
return max(r), min(r)
| Triangles made of random points | 5ec1692a2b16bb00287a6d8c | [
"Mathematics",
"Geometry",
"Algorithms",
"Arrays",
"Performance",
"Fundamentals"
] | https://www.codewars.com/kata/5ec1692a2b16bb00287a6d8c | 6 kyu |
[Perfect powers](https://en.wikipedia.org/wiki/Perfect_power) are numbers that can be written `$m^k$`, where `$m$` and `$k$` are both integers greater than 1.
Your task is to write a function that returns the perfect power nearest any number.
#### Notes
* When the input itself is a perfect power, return this number
*... | algorithms | from math import ceil, floor, log2
def closest_power(n):
return (4 if n <= 4 else min(
(f(n * * (1 / i)) * * i
for i in range(2, ceil(log2(n)) + 1)
for f in (floor, ceil)),
key=lambda x: (abs(x - n), x)))
| Closest Perfect Power | 57c7930dfa9fc5f0e30009eb | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/57c7930dfa9fc5f0e30009eb | 6 kyu |
Binary trees can be encoded as strings of balanced parentheses (in fact, the two things are *isomorphic*).
Your task is to figure out such an encoding, and write the two functions which convert back and forth between the binary trees and strings of parentheses.
Here's the definition of binary trees:
```haskell
data T... | reference | from preloaded import Tree, Leaf, Branch
def tree_to_parens(tree: Tree) - > str:
def infix(tree):
node = tree
while getattr(node, 'right', None) is not None:
yield '('
yield from infix(node . left)
yield ')'
node = node . right
return '' . join(infix(tree))
def parens... | Trees to Parentheses, and Back | 5fdb81b71e47c6000d26dc4b | [
"Trees",
"Fundamentals"
] | https://www.codewars.com/kata/5fdb81b71e47c6000d26dc4b | 5 kyu |
# The Situation
In my bathroom, there is a pile of `n` towels. A towel either has the color `red` or `blue`. We will represent the pile as sequence of `red` and `blue`.The leftmost towel is at the bottom of the pile, the rightmost towel is at the top of the pile.
As the week goes by, I use `t` towels. Whenever I grab ... | algorithms | def sort_the_pile(p, t):
for i in t:
if i > 0:
p = p[: - i] + sorted(p[- i:], reverse=True)
return p
| Pile of towels | 61044b64704a9e0036162a1f | [
"Sorting",
"Algorithms"
] | https://www.codewars.com/kata/61044b64704a9e0036162a1f | 6 kyu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.