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 |
|---|---|---|---|---|---|---|---|
# Cubic Tap Code
This works similarly to [Tap Code](https://en.wikipedia.org/wiki/Tap_code) except instead of being mapped onto a 5x5 square, letters are mapped onto a 3x3x3 cube, left to right, top to bottom, front to back with space being the 27th "letter". Letters are represented by a series of taps (represented as... | algorithms | tap_code = "ABC,DEF,GHI|JKL,MNO,PQR|STU,VWX,YZ "
table = {
char: ' ' . join(['.' * k, '.' * j, '.' * i])
for i, face in enumerate(tap_code . split('|'), 1)
for j, line in enumerate(face . split(','), 1)
for k, char in enumerate(line, 1)
}
reverse = {v: k for k, v in table . items()}
def enco... | Cubic Tap Code | 62d1eb93e5994c003156b2ae | [
"Ciphers",
"Algorithms",
"Cryptography"
] | https://www.codewars.com/kata/62d1eb93e5994c003156b2ae | 6 kyu |
# Background
A high flying bird is able to estimate the contours of the ground below.
He sees hills and valleys, he sees plains and mountains.
(But you already know all this because you've solved my [Bird Mountain](https://www.codewars.com/kata/bird-mountain) Kata)
---
But this time our protagonist bird also sees... | algorithms | def dry_ground(terrain, nDays=4):
if not terrain:
return 0, 0, 0, 0
def peak_height(mountain):
lst = [[0] * Y for _ in range(X)]
for x, row in enumerate(mountain):
for y, v in enumerate(row):
here = v == '^'
isBorderOrNoPeak = not (0 < x < X - 1 and 0 < y < Y - 1 and here)
... | Bird Mountain - the river | 5c2fd9188e358f301f5f7a7b | [
"Algorithms",
"Graph Theory"
] | https://www.codewars.com/kata/5c2fd9188e358f301f5f7a7b | 4 kyu |
Image processing is a broad term that tends to be used to group algorithms that work on bidimensional arrays. This definition is often generalized for more dimensions, but we are going to keep it simple for this kata.
A binary image is an image that only has two possible colors on each pixel (normally, white and black... | algorithms | # Approach: A breadth first search (BSF) is applied to the image, where a desired cell is '*'
# The BFS is itterative
import queue
class ConnectedChecker (object):
__WHITE_CELL__ = '*'
# part of the logic to find all connected shapes
@ staticmethod
def __inImage__(i, j, nR, nC):
if 0 <... | Topological Image Processing: 4-Connected Components | 5e452a0a5111c7001faa2a71 | [
"Image Processing",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5e452a0a5111c7001faa2a71 | 5 kyu |
<img src="https://i.imgur.com/ta6gv1i.png?1"/>
# Kata Task
A bird flying high above a mountain range is able to estimate the height of the highest peak.
Can you?
# Example
## The birds-eye view
<pre style='background:black;font-size:20px;line-height:20px;'>
<span style='color:green'>^^^^^^</span>
<span style='c... | reference | def peak_height(mountain):
M = {(r, c) for r, l in enumerate(mountain)
for c in range(len(l)) if l[c] == '^'}
h = 0
while M:
M -= {(r, c)
for r, c in M if {(r, c + 1), (r, c - 1), (r + 1, c), (r - 1, c)} - M}
h += 1
return h
| Bird Mountain | 5c09ccc9b48e912946000157 | [
"Algorithms",
"Graph Theory"
] | https://www.codewars.com/kata/5c09ccc9b48e912946000157 | 5 kyu |
# Number Pyramid:
Image a number pyramid starts with `1`, and the numbers increasing by `1`.
For example, when the pyramid has `5` levels:
```
01
02 03
04 05 06
07 08 09 10
11 12 13 14 15
```
_Define the `center` as the middle number of the middle row._
And the `center` in the abov... | games | def center(n): return ((n + 2) * n + 5) / 8 * (n % 4 == 1)
| [Code Golf] Number Pyramid Series 3 - Center | 62cf27c0bf218d8f23bd1ca1 | [
"Mathematics",
"Restricted"
] | https://www.codewars.com/kata/62cf27c0bf218d8f23bd1ca1 | 6 kyu |
Time to train your knights...
Considere an infinite chessboard... With obstacles on it...
You're provided with a start point and an end point (as tuples `(x,y)`), and a tuple of all coordinates that are blocked by obstacles. Your goal is to find the number of minimal moves required to reach the destination, coming fro... | algorithms | from heapq import *
from collections import defaultdict
from itertools import product
INF, STEP = float('inf'), (2 * 2 + 1) * * .5
K_MOVES = tuple((a, b) for a, b in product(
range(- 2, 3), repeat=2) if abs(a) + abs(b) == 3)
def attack(start, end, obst):
def h(a, b, xF, yF):
a, b = a - xF, b -... | Knight's Attack! | 58e6d83e19af2cb8840000b5 | [
"Algorithms",
"Graph Theory"
] | https://www.codewars.com/kata/58e6d83e19af2cb8840000b5 | 3 kyu |
*<center>I hope you enjoy this kata, and if you want, there's a [more challenging version](https://www.codewars.com/kata/58e6d83e19af2cb8840000b5).</center>*
# Task
Given two positions on an **infinite** chessboard, find the **shortest path** for a **knight** moving from one to the other.
### Input
Two argume... | algorithms | from itertools import product
from math import atan2, pi
MOVES = [(2, 1), (1, 2), (- 1, 2), (- 2, 1),
(- 2, - 1), (- 1, - 2), (1, - 2), (2, - 1)]
KNGIHT = 5 * * .5
CLOCK = 2 * pi
def knight_path(* pnts):
(a, b), (i, j) = pnts
ang = atan2(j - b, i - a)
da, db = min(MOVES, key=smallestAngleWith(ang... | Shortest Knight Path(Infinite Chessboard) | 62287e1766b26a0024b9e806 | [
"Performance",
"Algorithms",
"Graph Theory"
] | https://www.codewars.com/kata/62287e1766b26a0024b9e806 | 4 kyu |
Your friend has a list of ```k``` numbers : ```[a1, a2, a3, ... ak]```.
He is allowed to do the operation which consists of three steps:
1) select two numbers: ```ai``` and ```aj``` (```ai % 2 = 0```)
2) replace ```ai``` with ```ai``` / 2
3) replace ```aj``` with ```aj``` * 2
Help him to find the maximum sum of list ... | games | def divide_and_multiply(n):
s, d = 1, []
for x in n:
b = x & - x
d . append(x / / b)
s *= b
return (sum(d) + max(d) * (s - 1)) % (10 * * 9 + 7)
| Divide and maximize | 62275b5bf6c169002379fa65 | [
"Puzzles",
"Lists",
"Arrays",
"Mathematics"
] | https://www.codewars.com/kata/62275b5bf6c169002379fa65 | 5 kyu |
### Story
There are 100 prisoners in solitary cells. There's a central living room with one light bulb; this bulb is initially off. No prisoner can see the light bulb from his or her own cell. Everyday, the warden picks a prisoner at random, and that prisoner visits the living room. While there, the prisoner can toggle... | games | # Prisoner 0 is the leader
# He always leaves the lightbulb on
# If he found the lightbulb off 100 times, it means everyone visited at least once
# Other prisoners must turn off the lightbulb only if:
# - they never turned it off before
# - it is currently on
# TLDR:
# - turning the lightbulb on means "I visited"
# - d... | 100 prisoners and a light bulb | 619d3f32156bbd000896463c | [
"Riddles",
"Puzzles"
] | https://www.codewars.com/kata/619d3f32156bbd000896463c | 5 kyu |
The national go-kart racing competition is taking place at your local town and you've been called for building the winners podium with the available wooden blocks. Thankfully you are in a wood-rich area, number of blocks are always at least 6.
Remember a classic racing podium has three platforms for first, second and ... | reference | from math import ceil
def race_podium(b):
f = ceil((b) / 3) + 1
s = min(f - 1, b - f - 1)
return s, f, b - f - s
| Race Ceremony | 62cecd4e5487c10028996e04 | [
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/62cecd4e5487c10028996e04 | 7 kyu |
## Overview
Given a 2-dimensional `m * n` rectangular grid with non-negative integer coordinates, can you develop an algorithm that will place the largest possible number, `P`, of points on the grid **without forming ANY right triangles in the resulting configuration of points** ?
Language clarification: depending on... | reference | def most_points(m, n):
return [(0, 0)] if n == m == 1 else [(0, y) for y in range(m > 1, n)] + [(x, 0) for x in range(n > 1, m)]
| Most points without right triangle | 62c75ce198d93d02a42ca7a3 | [
"Puzzles",
"Mathematics",
"Geometry"
] | https://www.codewars.com/kata/62c75ce198d93d02a42ca7a3 | 6 kyu |
Background
==========
This kata is based on the [Magic Triangle](https://en.wikipedia.org/wiki/Magic_triangle_(mathematics)) math puzzle, invented in 1972 by math teacher Terrel Trotter, Jr.
The puzzles have only 2 constraints:
* Each of the digits 1 through 9 can be used only once.
* Every side must sum to the same... | games | from itertools import permutations
# Missing digits
def get_unknown(puzzle):
return set(range(1, 10)) - set(puzzle)
# All possible tries to solve the puzzle
def get_possible(puzzle):
for perm in map(iter, permutations(get_unknown(puzzle))):
yield [x or next(perm) for x in puzzle]
... | Magic Triangle Solutions | 62b2072d62c66500159693ff | [
"Arrays",
"Algorithms",
"Game Solvers",
"Games",
"Mathematics"
] | https://www.codewars.com/kata/62b2072d62c66500159693ff | 6 kyu |
You are given three integer inputs: length, minimum, and maximum.
Return a string that:
1. Starts at minimum
2. Ascends one at a time until reaching the maximum, then
3. Descends one at a time until reaching the minimum
4. repeat until the string is the appropriate length
Examples:
```
length: 5, minimum: 1, maximu... | algorithms | def ascend_descend(l, m, M): return '' . join(
map(str, l * [* range(m, M + 1), * range(M - 1, m, - 1)]))[: l]
| Ascend, Descend, Repeat? | 62ca07aaedc75c88fb95ee2f | [
"Fundamentals",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/62ca07aaedc75c88fb95ee2f | 6 kyu |
## Description
An infinite number of shelves are arranged one above the other in a staggered fashion.<br>
The cat can jump either one or three shelves at a time: from shelf `i` to shelf `i+1` or `i+3` (the cat cannot climb on the shelf directly above its head), according to the illustration:
```
┌────... | algorithms | def solution(start, finish):
return sum(divmod(finish - start, 3))
| Cats and shelves | 62c93765cef6f10030dfa92b | [
"Algorithms"
] | https://www.codewars.com/kata/62c93765cef6f10030dfa92b | 7 kyu |
# Description
---
The term "google dorking" describes the process of using
filters (also called "operators") in google search
queries which limit the search results according to the
used filters. It's a technique often used by "hackers"
in order to find valuable information about a target.
*But thats not what we... | reference | FILTERS = set(FILTERS)
def is_valid(query: str) - > bool:
return all(u . split(':')[0] in FILTERS for u in query . split() if ':' in u)
| Google Dorking - Validating Queries | 62cb487e43b37a5829ab5752 | [
"Regular Expressions"
] | https://www.codewars.com/kata/62cb487e43b37a5829ab5752 | 7 kyu |
_NOTE: It is recommended to complete the [corner case](https://www.codewars.com/kata/62c4ad0e86f0166ec7bb8485) before working on this `edge case`._
___
# Number Pyramid:
Image a number pyramid starts with `1`, and the numbers increasing by `1`.
For example, when the pyramid has 4 levels:
```
1
2 3
4 5 6
7 8 9... | games | def sum_edges(n): return (n, n * (5 * n * n - 3 * n + 10) / 6 - 2)[n > 1]
| [Code Golf] Number Pyramid Series 2 - Sum of Edges | 62c74a39fba7810016e601b1 | [
"Mathematics",
"Restricted"
] | https://www.codewars.com/kata/62c74a39fba7810016e601b1 | 6 kyu |
# Sexagenary Cycle
In trandition East Asia calendar, [Sexagenary Cycle](https://en.wikipedia.org/wiki/Sexagenary_cycle) was used to note the years. It has 2 parts:
[Heavenly Stems](https://en.wikipedia.org/wiki/Heavenly_Stems), (天干)
and
[Earthly Branches](https://en.wikipedia.org/wiki/Earthly_Branches), (地支)
The ... | reference | HEAVENLY_STEMS = '甲乙丙丁戊己庚辛壬癸'
EARTHLY_BRANCHES = '子丑寅卯辰巳午未申酉戌亥'
YEAR = dict(
zip(map('' . join, zip(HEAVENLY_STEMS * 6, EARTHLY_BRANCHES * 5)), range(60)))
def how_old(birth_year, present_year):
a, b = YEAR[birth_year], YEAR[present_year]
return b - a + 60 * (a >= b)
| Sexagenary Cycle (干支): How old am I? | 62cc917fedc75c95ef961ad1 | [
"Fundamentals"
] | https://www.codewars.com/kata/62cc917fedc75c95ef961ad1 | 7 kyu |
You're most likely familiar with Pascal's Triangle. If you aren't, I recommend trying [the kata found here](https://www.codewars.com/kata/52945ce49bb38560fe0001d9) on which this kata is based. The 2-D Pascal's triangle can be generalized to 3-D in the form of Pascal's Pyramid (technically a tetrahedron).
Each layer of... | algorithms | from math import factorial
from functools import lru_cache
f = lru_cache(maxsize=None)(factorial)
def pascal_pyr_layer(n):
return [[f(n - 1) / / f(n - 1 - i) / / f(i - j) / / f(j) for j in range(i + 1)] for i in range(n)]
| Levels of Pascal's Pyramid | 62c7b2ebb8d7c8005e3b1f23 | [
"Arrays",
"Algorithms",
"Mathematics",
"Combinatorics",
"Recursion"
] | https://www.codewars.com/kata/62c7b2ebb8d7c8005e3b1f23 | 6 kyu |
# Async Request Manager
---
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 ov... | reference | import asyncio
async def request_manager(n: int) - > str:
return '' . join(await asyncio . gather(* (send_request() for _ in range(n))))
| Async Requests | 62c702489012c30017ded374 | [
"Asynchronous"
] | https://www.codewars.com/kata/62c702489012c30017ded374 | 6 kyu |
# Number Pyramid
Image a number pyramid starts with `1`, and the numbers increasing by `1`.
For example, when the pyramid has 3 levels:
```
1
2 3
4 5 6
```
And the sum of three corners are:
```
1 + 4 + 6 = 11
```
___
# Input:
You will be given a number `n`, which means how many levels the pyramid has.
`0 <= n... | games | def sum_corners(n): return n * n + 2 * (n > 1)
| [Code Golf] Number Pyramid Series 1 - Sum of Corners | 62c4ad0e86f0166ec7bb8485 | [
"Mathematics",
"Restricted"
] | https://www.codewars.com/kata/62c4ad0e86f0166ec7bb8485 | 7 kyu |
<h1>Task</h1>
Your task is to write a function that takes a range of *Google Sheets* cells as a parameter, and returns an array of addresses of all cells in the specified range.
<img src="https://i.ibb.co/WzVZ4PV/example.png" alt="example" border="0">
#### Notes
* Letters in addresses: from A-Z (_Google Sheets_ s... | algorithms | def get_cell_addresses(cell_range):
x, y = cell_range . split(':')
if x == y:
return []
a, b, c, d = ord(x[0]), abs(int(x[1:])), ord(y[0]), abs(
int(y[1:])) # abs because the tests give some negative values
return [f" { chr ( i )}{ j } " for j in range(b, d + 1) for i in range(a, ... | Get the addresses of all Google Sheets cells in the range | 62c376ce1019024820580309 | [
"Algorithms",
"Arrays"
] | https://www.codewars.com/kata/62c376ce1019024820580309 | 6 kyu |
Implement a generator that, given a pattern, returns strings following such pattern. In this kata a pattern is a string composed of characters, digits, punctuation (except square brackets) and tokens that have to be replaced by the value needed to build the next string in the sequence.<br><br>
There are four types of t... | algorithms | import re
from itertools import *
def string_generator(pattern):
format = re . sub(
'\[.*?\]', '{}', pattern . replace('{', '{{'). replace('}', '}}'))
generators = [generator(x) for x in re . findall(
'\[.*?\]', pattern . replace(' ', ''))]
yield from starmap(format . format, zip(... | String generation by pattern | 62b3356dacf409000f53cab7 | [
"Algorithms",
"Strings",
"Regular Expressions"
] | https://www.codewars.com/kata/62b3356dacf409000f53cab7 | 5 kyu |
[Do the simpler version first!](https://www.codewars.com/kata/618647c4d01859002768bc15)
In this generalized version of the riddle, each 'player' has a hat and must guess what color it is. The players are lined up such that they can see the hats of everyone in front of them, but not their own hat or those of the player... | games | def guess(colours, guesses, hats):
return colours[- sum(colours . index(c) for c in guesses + hats) % len(colours)]
| Extreme Hat Game | 62bf879e8e54a4004b8c3a92 | [
"Riddles"
] | https://www.codewars.com/kata/62bf879e8e54a4004b8c3a92 | 5 kyu |
A common way to teach children how to code is to let them program a robot with a very limited set of instructions, which are executed in an endless loop.
In our case, you have to help a little robot by finding the correct set of instructions, so it can cross a dangerous area with holes.
The robot starts in the upper... | algorithms | from itertools import cycle
def program(field, max_instructions):
dirs, fld = {'R': (0, 1), 'D': (1, 0)}, field . split('\n')
ln = len(fld)
seen = {(0, 0)}
queue = [[(0, 0, '')]]
def is_path(path):
x, y = 0, 0
for p in cycle(path):
x, y = x + dirs[p][0], y + dirs[p][1]
... | Program the robot | 62b0c1d358e471005d28ca7e | [
"Algorithms",
"Graph Theory"
] | https://www.codewars.com/kata/62b0c1d358e471005d28ca7e | 6 kyu |
## Overview
The usual way of dividing a pizza is fair but really boring; you place `n` points evenly spaced around the perimeter of the pizza, then cut towards the centre point - you always obtain a total of `n` equally sized, equally shaped pieces.
Suppose for your next pizza you do the following: you place `n` poin... | reference | def pizza(n): return n * ~ - n * (n * n - 5 * n + 18) / / 24 + 1
| [Code golf] Strange way to divide a pizza | 62bd9616aced6376cc37950e | [
"Mathematics",
"Restricted"
] | https://www.codewars.com/kata/62bd9616aced6376cc37950e | 6 kyu |
### **The Cipher**
1. Take every letter in the one-word message and replace it with its place in the alphabet.:
2. For each number in the list, multiply it by 3 and subtract 5. Repeat this process *n* times.
## Task
Implement two functions, `encrypt()` and `decrypt()`.
#### `encrypt()` (details):
* Input:
* word ... | reference | BASE = ord("a") - 1
def encrypt(word, n):
xs = [x - BASE for x in map(ord, word)]
for _ in range(n):
xs[:] = (x * 3 - 5 for x in xs)
return xs
def decrypt(encrypted_word, n):
xs = encrypted_word[:]
for _ in range(n):
xs[:] = ((x + 5) / / 3 for x in xs)
return "" . join(... | Cipher from math problem | 62bdd252d8ba0e0057da326c | [
"Cryptography",
"Mathematics",
"Ciphers",
"Algorithms"
] | https://www.codewars.com/kata/62bdd252d8ba0e0057da326c | 7 kyu |
> __Randonneuring__ (also known as Audax in the UK, Australia and Brazil) is a long-distance cycling sport with its origins in audax cycling. In randonneuring, riders attempt courses of 200 km or more, passing through predetermined "__controls__" (checkpoints) every few tens of kilometres. Riders aim to complete the co... | reference | from datetime import datetime, timedelta
# Encode the given velocity and interval information
# (Velocity, start kms, stop kms)
FAST = [
(34, 0, 200),
(32, 200, 400),
(30, 400, 600),
(28, 600, 1000),
(26, 1000, 1200),
(25, 1200, 1800),
(24, 1800, 2000),
]
SLOW = [
(20, 0, 60... | Randonneuring control calculator | 62b708450ee74b00589fcaba | [
"Mathematics",
"Date Time",
"Algorithms"
] | https://www.codewars.com/kata/62b708450ee74b00589fcaba | 5 kyu |
<h2> Task </h2>
Let
`$gcd(a, b) = x \\ lcm(a, b) = y \\ a, b \in \N$`
where gcd represents the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor) of two integers and lcm represents the [least common multiple](https://en.wikipedia.org/wiki/Least_common_multiple) of two integers.
Given... | reference | # I mean, they work
def gcd_lcm(x, y):
if y % x == 0:
return x, y
| GCD and LCM | 62b931bcb16c630025076970 | [
"Performance",
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/62b931bcb16c630025076970 | 7 kyu |
This kata is a harder version of this kata: https://www.codewars.com/kata/5727bb0fe81185ae62000ae3
If you haven't done it yet, you should do that one first before doing this one.
You are given a ```string``` of letters that you need to type out. In the string there is a special function: ```[backspace]```. Once you... | algorithms | import re
def solve(s):
stk = []
for m in re . finditer(r'\[backspace\](?:\*(\d*))?|.', s):
if m[0]. startswith('[backspace]'):
n = int(m[1] or 1)
while n and stk:
stk . pop()
n -= 1
else:
stk . append(m[0])
return '' . join(stk)
| Typing series #1 --> the [backspace] function | 62b3e38df90eac002c7a983f | [
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/62b3e38df90eac002c7a983f | 6 kyu |
Farmer Thomas is an edgy teenager who likes to ruin other people's dream of becoming a software engineer. Motivated by this, he attacked the Codewars servers with a strawberry baguette at 8:00 UTC on June 21 2022, and took down the Codewars website for an hour.
However, there was barely anyone online at that time, so ... | algorithms | def attack_plan(user_count, k):
dp = [[[- float("inf")] * 4 for _ in range(k + 1)]
for _ in range(len(user_count) + 1)] # [time][attacks][consecutive]
dp[0][0][0] = 0
for i, count in enumerate(user_count):
for r in range(k + 1):
dp[i + 1][r][0] = max(dp[i + 1][r][0], max(dp[i][r])... | Take Down Codewars! | 62b1860db38ba1739bcaaebf | [
"Dynamic Programming",
"Algorithms",
"Arrays"
] | https://www.codewars.com/kata/62b1860db38ba1739bcaaebf | 5 kyu |
## Story
YouTube had a like and a dislike button, which allowed users to express their opinions about particular content. It was set up in such a way that you cannot like and dislike a video at the same time.
There are two other interesting rules to be noted about the interface:
Pressing a button, which is already act... | games | def like_or_dislike(lst):
state = 'Nothing'
for i in lst :
state = 'Nothing' if i == state else i
return state | Likes Vs Dislikes | 62ad72443809a4006998218a | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/62ad72443809a4006998218a | 7 kyu |
# Consecutive Vowels #
You are given a random string of lower-case letters. Your job is to find out how many ordered and consecutive vowels there are in the given string beginning from `'a'`. Keep in mind that the consecutive vowel to `'u'` is `'a'` and the cycle continues.
Return an integer with the length of the co... | reference | def get_the_vowels(word):
n = 0
for i in word:
if i == "aeiou" [n % 5]:
n += 1
return n
| Consecutive Vowels in a String | 62a933d6d6deb7001093de16 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/62a933d6d6deb7001093de16 | 7 kyu |
Sergeant Ryan is a soldier in the orange army, fighting a war against the green army. One day, while out on patrol, Ryan notices [smoke signals](https://en.wikipedia.org/wiki/Smoke_signal) being used in the forest, presumably by green soldiers. Ryan never enjoyed solving cryptography problems in school, so that's why h... | algorithms | from copy import deepcopy
def decode_smoke_signals(days):
days = deepcopy(days)
decoded = {}
# Keep eliminating signals until the puzzle has been solved
changed = True
while changed:
# Go through day by day and attempt to determine what each signal could be.
changed = False... | Smoke Signals | 62a3855fcaec090025ed2a9a | [
"Ciphers",
"Cryptography",
"Logic"
] | https://www.codewars.com/kata/62a3855fcaec090025ed2a9a | 5 kyu |
Given an integer `n` and two other values, build an array of size `n` filled with these two values alternating.
## Examples
```ruby
5, true, false --> [true, false, true, false, true]
10, "blue", "red" --> ["blue", "red", "blue", "red", "blue", "red", "blue", "red", "blue", "red"]
0, "one", "two" --> []
``... | reference | def alternate(n, first_value, second_value):
return [[first_value, second_value][i % 2] for i in range(n)]
| Length and two values. | 62a611067274990047f431a8 | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/62a611067274990047f431a8 | 7 kyu |
We want to find the area of a set of buildings stacked close to each other.
A matrix (an array of arrays) gives us a description of the building from above, where each number represents the height expressed in cubes `1*1*1`, the cubes are stacked adjacent to each other.
For example:
```
matrix = [[2,1],[2,0]]
In ... | games | import numpy as np
def surface_area(m):
return 2 * np . count_nonzero(m) + sum(abs(np . diff(m, 1, i, 0, 0)). sum() for i in range(2))
| Skyscrapers Area | 62a25309b070a3002f53b684 | [
"Algorithms",
"Arrays"
] | https://www.codewars.com/kata/62a25309b070a3002f53b684 | 6 kyu |
### Description
It is well known that
`$\displaystyle\sum^n_{i=1}i = \frac{1}{2} n^2 + \frac{1}{2} n$`
Which can be rewritten as
`$\displaystyle 1+2+3+4+...n = \frac{1}{2} n^2 + \frac{1}{2} n$`
Also
`$\displaystyle\sum^n_{i=1}i^2 = \frac{1}{3} n^3 + \frac{1}{2} n^2 + \frac{1}{6} n$`
Which can be rewritten as
... | reference | from fractions import Fraction
from functools import lru_cache
from math import comb, factorial
B = [Fraction(1, 1)]
for i in range(1, 141):
B . append(
1 - sum(comb(i, j) * Fraction(B[j], i - j + 1) for j in range(i)))
def build(
i, x, y): return f" { abs ( x )}{ f'/ { y } ' * ( y > 1... | n^k summation | 62a0a24ed518853c3528683f | [
"Mathematics"
] | https://www.codewars.com/kata/62a0a24ed518853c3528683f | 4 kyu |
## Overview
We are going to be studying permutations of `n` distinct elements - for simplicity we shall use the integers from `1` to `n`.
If we start with the integers `1` to `n` in ascending order in a list:
`[1, 2, 3, ..., n-2, n-1, n]`
then, for a given value of `n`, how many permutations of this list are there ... | reference | def permuts(n):
x = [1, 2]
for i in range(n):
x . append(x[- 1] + x[- 2])
return x[n - 1]
| How many permutations where indices change by at most 1 | 629e18298f2d21006516e381 | [
"Fundamentals",
"Algorithms",
"Puzzles",
"Mathematics",
"Discrete Mathematics"
] | https://www.codewars.com/kata/629e18298f2d21006516e381 | 6 kyu |
**Description**
A random place has a currency system that consists of 2 coins
You are given the values of the coins, they can be identical, and they will always be positive.
Find the largest value that any whole number combination of the two
cannot produce
return `-1` if there is no such value or if it is an infini... | reference | from math import gcd
def coins(coin1, coin2):
return - 1 if gcd(coin1, coin2) != 1 else (coin1 - 1) * (coin2 - 1) - 1
| Coins | 620dd259f7b0000017fc7b45 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/620dd259f7b0000017fc7b45 | 6 kyu |
### Introduction
**The Robber Language** (Rövarspråket) is a Swedish *cant* used by children to mislead people not familiar with the language. It's used by kids in several screenplays created by [Astrid Lindgren](https://en.wikipedia.org/wiki/Astrid_Lindgren).
The idea is that every consonant in a sentence is **dupli... | reference | from functools import partial
from re import compile
r1 = partial(compile(r"(?=[a-z])([^aeiou])"). sub, r"\1o\1")
r2 = partial(compile(r"(?=[A-Z])([^AEIOU])"). sub, r"\1O\1")
def robber_encode(sentence):
return r1(r2(sentence))
| The Robber Language | 629e4d5f24b98110a83b2d0d | [
"Fundamentals",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/629e4d5f24b98110a83b2d0d | 7 kyu |
# Task
Create a decorator `@predicate` which allows boolean functions to be conveniently combined using `&`, `|` and `~` operators:
```python
@predicate
def is_even(num):
return num % 2 == 0
@predicate
def is_positive(num):
return num > 0
(is_even & is_positive)(4) # True
(is_even & is_positive)(3) # Fa... | reference | class predicate:
def __init__(self, func): self . f = func
def __call__(self, * a, * * kw): return self . f(* a, * * kw)
def __invert__(self): return self . __class__(lambda * a, * * kw: not self . f(* a, * * kw))
def __or__(self, o): return self . __class__(lambda * a, * * kw: self . f(* a, * *... | Combining predicates | 626a887e8a33feabd6ad8f25 | [
"Decorator",
"Functional Programming",
"Object-oriented Programming"
] | https://www.codewars.com/kata/626a887e8a33feabd6ad8f25 | 5 kyu |
This Kata will consider the situation of a fictional politician, "The Big Guy", or TBG.
TBG's close relative, "The Bagman", travels around the world collecting bribes for TBG.
Because of increased scrutiny, they can no longer use government aircraft to collect the bribes so they
have to pay for private travel. A... | algorithms | from itertools import permutations
def best_route(cities, costs):
nothome = [x for x in cities if x != 'Notgnihsaw']
tbl = {city1: {city2: cost for city2, cost in zip(
cities, row)} for city1, row in zip(cities, costs)}
return min(([* p, 'Notgnihsaw'] for p in permutations(nothome)), key=la... | The Big Guy and The Bagman | 6297d639de3969003e13e149 | [
"Permutations",
"Algorithms"
] | https://www.codewars.com/kata/6297d639de3969003e13e149 | 5 kyu |
### Introduction
In this kata we are going to take a look at how IPv4 packet filtering works using **A**ccess **C**ontrol **L**ists (ACL), specifically using a technique called **wildcard masks** to match based on an IP address or a range of addresses.
A wildcard mask is the **inverse** of the subnet mask:
```
255.25... | reference | from ipaddress import IPv4Address as ip
def match(net_addr: str, wc_mask: str, ipv4_addr: str) - > bool:
return int(ip(net_addr)) | int(ip(wc_mask)) == int(ip(ipv4_addr)) | int(ip(wc_mask))
| Networking 101/5: Access Control using a Wildcard mask | 6294a4d0eb816e36363b9079 | [
"Networks",
"Bits",
"Fundamentals",
"Binary"
] | https://www.codewars.com/kata/6294a4d0eb816e36363b9079 | 6 kyu |
### Introduction
An IPv4 address and its associated subnet mask is often written as
`192.168.0.7 255.255.255.0`. This combination tells us what the *address of the host* is (`192.168.0.7`) and its *network prefix*, in other words *which network* it belongs to (`192.168.0.0`).
Both the IPv4 address and subnet mask is... | reference | from ipaddress import IPv4Network
def network_cidr(ipv4_addr, net_mask):
return str(IPv4Network(f' { ipv4_addr } / { net_mask } ', strict=False))
| Networking 101/4: Determine the IPv4 network prefix in CIDR notation | 628f8211840e153e14346eaa | [
"Networks",
"Bits",
"Fundamentals",
"Binary"
] | https://www.codewars.com/kata/628f8211840e153e14346eaa | 6 kyu |
# Task
I need a wristband. Help me in identifying an actual wristband.
A wristband can have 4 patterns:
**horizontal:** each item in a row is identical.
**vertical:** each item in each column is identical.
**diagonal left:** each item is identical to the one on it's upper left or bottom right.
**diagonal right:** ... | algorithms | def is_wristband(arr):
note = {1, 2, 3, 4}
for i, j in zip(arr, arr[1:]):
if 1 in note and (len(set(i)) != 1 or len(set(j)) != 1):
note . remove(1)
if 2 in note and i != j:
note . remove(2)
if 3 in note and i[: - 1] != j[1:]:
note . remove(3)
if 4 in note and j[: - 1] != i[1... | Wristband Patterns | 62949a3deb816e36363b8ee6 | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/62949a3deb816e36363b8ee6 | 5 kyu |
## Task
Write a function that checks if two non-negative integers make an "interlocking binary pair".
## Interlock ?
* numbers can be interlocked if their binary representations have no `1`'s in the same place
* comparisons are made by bit position, starting from right to left (see the examples below)
* when represen... | algorithms | def interlockable(a, b):
return not a & b
| Interlocking Binary Pairs | 628e3ee2e1daf90030239e8a | [
"Binary",
"Bits",
"Algorithms"
] | https://www.codewars.com/kata/628e3ee2e1daf90030239e8a | 7 kyu |
The target dose for the oral medication *Katamol* has been calculated: <code>d</code> (in mg).
The only options to prescribe the medication are pills of strength <code>a</code> (in mg) or <code>b</code> (in mg), so it may not be possible to prescribe the exact target dose.
For a given target dose <code>d</code>, retu... | reference | def prescribe(d, a, b):
return max(x + (d - x) / / a * a for x in range(0, d + 1, b))
| Pill Pusher | 628e6f112324192c65cd8c97 | [
"Fundamentals"
] | https://www.codewars.com/kata/628e6f112324192c65cd8c97 | 6 kyu |
<h2>Nonogram encoder</h2>
If you're not familiar with nonograms, I recommend you to check this wikipedia page: <a href="https://en.wikipedia.org/wiki/Nonogram">Nonogram - Wikipedia</a>
My friend Alex really likes to solve nonograms, and I've drawn one for him:
<img src="https://i.imgur.com/IwaD1B6.png" width="400" h... | algorithms | import itertools
def pack(m): return tuple(tuple(sum(g)
for k, g in itertools . groupby(r) if k) for r in m)
def encode(nonogram): return (pack(zip(* nonogram)), pack(nonogram))
| Multisize Nonogram Encoder | 629049687438580064f0e6dd | [
"Games",
"Algorithms"
] | https://www.codewars.com/kata/629049687438580064f0e6dd | 5 kyu |
A runner, who runs with base speed ```s``` with duration ```t``` will cover a distances ```d```: ```d = s * t```<br>
However, this runner can sprint for one unit of time with double speed ```s * 2```<br>
After sprinting, base speed ```s``` will permanently reduced by ```1```, and for next one unit of time runner will e... | algorithms | def solution(s, t):
# Sprints are optimally placed at the end of the race
'''
It is always beneficial to sprint at the end of the race
Sprints are optimally placed at the end of the race
e.g. RRRR...(SR)[n]S
We take a run without sprints are keep adding sprints at
the latest possible p... | Chaser's schedule | 628df6b29070907ecb3c2d83 | [
"Logic",
"Algorithms"
] | https://www.codewars.com/kata/628df6b29070907ecb3c2d83 | 6 kyu |
## About ##
In this task, you will write a "determinateValue" function that will determine the value of an element in a matrix.
The matrix should be filled with a zigzag, example matrix 5x5:
```
[
[ 1, 2, 6, 7, 15],
[ 3, 5, 8, 14, 16],
[ 4, 9, 13, 17, 22],
[10, 12, 18, 21, 23],
[11, 19, 20... | algorithms | def determinateValue(x, y, n): return 1 + [y, x][(q := x + y) % 2] + q * (q + 1) / / 2 - max(q - n + 1, 0) * * 2
| [Code Golf] Fill matrix with a zigzag | 628d253eb110f3270a8a1789 | [
"Matrix",
"Algorithms",
"Restricted"
] | https://www.codewars.com/kata/628d253eb110f3270a8a1789 | 5 kyu |
## Overview
In this kata, `n` grains of rice will be initially placed at `n` **distinct** squares on a 2-dimensional rectangular board.
For example, if a particular grain starts on the board square at `x=3` and `y=8` it will be given starting "integer coordinates" `(3,8)`.
To keep things simple, all grains will alwa... | reference | # Return a list of 2-tuples of integers, representing
# the integer coordinates of ALL possible squares that
# satisfy the minimum number of total moves requirement
from statistics import median_low, median_high
def move_grains(grains):
xcoords = [x for x, _ in grains]
ycoords = [y for _, y in grains]
ret... | Move all the grains of rice to a same shared final square | 628d1c71b091df00651f0d83 | [
"Algorithms",
"Puzzles",
"Mathematics",
"Performance"
] | https://www.codewars.com/kata/628d1c71b091df00651f0d83 | 6 kyu |
## Overview
Start with a row of empty boxes, and place `n` bubbles in the left-most box in the row. You may assume there are infinitely many boxes to the right.
At each step, you must pick any box with 2 or more bubbles currently inside it, **merge 2 of the available bubbles in that box** to form a new bubble (thereb... | reference | # The final state is the binary representation of
# the input, n, in reverse i.e. reading from left
# to right gives lsb to msb.
# So number of bubbles in final state in box i
# is equal to b_i from binary repr of n.
# To obtain 1 bubble in box i requires:
# S(i) = 2*S(i-1) + 1 steps with S(0)=0
# Solving the recurrenc... | Merging and moving bubbles along a row of boxes | 628bd39474087000456cd126 | [
"Fundamentals",
"Algorithms",
"Puzzles",
"Mathematics"
] | https://www.codewars.com/kata/628bd39474087000456cd126 | 6 kyu |
Anna and Bob are playing tennis, they want you to show the result of their game.
A game is won when a player scores four (or more) points: 15, 30, 40 and the game-winning point.
Should both players make it 40, then the score is called "DEUCE". Following deuce, a player must win two consecutive points: the first point... | algorithms | def get_status(wins):
A = B = 0
for n in wins:
if n == "Anna":
A += 1
else:
B += 1
if (A > 3 or B > 3) and abs(A - B) > 1:
return f" { n } WINS"
return ("Anna ADVANTAGE" if B + 1 == A > 3 else
"Bob ADVANTAGE" if A + 1 == B > 3 else
["0a", "15a", "30a",... | Give the status of the tennis game | 628b60fcb7d0770ddea8877d | [
"Games",
"Algorithms"
] | https://www.codewars.com/kata/628b60fcb7d0770ddea8877d | 6 kyu |
## OBJECTIVE:
You need to cross a certain section of the field in order to reach your target, but some cells of this field are irradiated with radiation, and you would not want to receive a large dose of radiation after completing your route.
The purpose of this kata is to create a function that takes a list of 10x10 ... | games | from copy import deepcopy
RADIATION_SOURCES = {
# You can easily modify:
# symbol: ((x, y, val), ...), # affected cells and impact value
'A': (
(- 1, - 1, 1), (0, - 1, 1), (1, - 1, 1),
(- 1, 0, 1), (1, 0, 1),
(- 1, 1, 1), (0, 1, 1), (1, 1, 1),
),
'B': (
... | Exposure assessment | 628b633fb7d0770d57a88809 | [
"Algorithms",
"Fundamentals"
] | https://www.codewars.com/kata/628b633fb7d0770d57a88809 | 6 kyu |
### Introduction
An IPv4 address is made up of 32 bits. The bits are divided into four sections called **octets** (groups of eight). Each octet can have a number in the range 0 to 255 (unsigned 8-bit integers).
All IPv4 addresses belong to an **Address Class**. There are five different address classes (A, B, C, D and... | reference | def ipv4_address_class(ipv4_addr):
n = int(ipv4_addr . split(".")[0])
return " EDCBA" [(n <= 127) + (n <= 191) + (n <= 223) + (n <= 239) + (n <= 255)]
| Networking 101/2: Identify the IPv4 address Class | 628ba76a85a2d500649da696 | [
"Networks",
"Bits",
"Fundamentals",
"Binary"
] | https://www.codewars.com/kata/628ba76a85a2d500649da696 | 7 kyu |
### Introduction
Both the IPv4 address and subnet mask is made up of 32 bits. The bits are divided into four sections called octets (groups of eight). Each octet can have a number in the range 0 to 255 (unsigned 8-bit integers).
When learning IPv4 addressing it is essential to know how the Binary Number System works ... | reference | def ipv4_to_binary(ipv4_addr: str) - > str:
return "." . join(f" { octet :0 8 b } " for octet in map(int, ipv4_addr . split(".")))
| Networking 101/1: Convert IPv4 address to Dotted Binary Notation | 6288de23ab7ede0031602521 | [
"Networks",
"Bits",
"Fundamentals",
"Binary"
] | https://www.codewars.com/kata/6288de23ab7ede0031602521 | 6 kyu |
## Overview
Given an alphabet consisting of `a` distinct symbols, how many strings of exact length = `n` are there which use **all** of the `a` distinct symbols **at least once?**
Equivalent reformulation, if you prefer: how many strings are not missing **any** of the `a` distinct symbols?
For example, given the al... | reference | from math import comb
def use_all_symbols(n, a):
return sum((- 1) * * i * comb(a, i) * (a - i) * * n for i in range(a + 1))
| How many strings use all symbols of a given alphabet at least once | 626ec08b40a15e2d250575cf | [
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/626ec08b40a15e2d250575cf | 5 kyu |
Given the name of a [US state or territory](https://en.wikipedia.org/wiki/List_of_states_and_territories_of_the_United_States), return its postal abbreviation. All states, federal districts and inhabited territories will be tested, according to the linked wikipedia page.
***Notes:***
* to spark your creativity, the ... | algorithms | N = "Alab,Alas,Am,Ari,Ark,Ca,Col,Con,De,Di,F,Ge,Gu,H,Id,Il,In,Io,Ka,Ke,L,Mai,Mar,Mas,Mic,Min,Missi,Misso,Mo,Neb,Nev,New H,New J,New M,New Y,North C,North D,Northe,Oh,Ok,Or,Pe,Pu,R,South C,South D,Ten,Tex,U.,Ut,Ve,Vi,Wa,We,Wi,Wy" . split(
",")
C = "AL AK AS AZ AR CA CO CT DE DC FL GA GU HI ID IL IN IA KS KY LA ME ... | US Postal Codes | 60245d013b9cda0008f4da8e | [
"Algorithms",
"Restricted"
] | https://www.codewars.com/kata/60245d013b9cda0008f4da8e | 5 kyu |
## Overview
`n` very naughty Codewars users want to cheat amongst themselves, and share solutions to katas they have solved.
Each of the `n` users was only clever enough to solve 1 distinct kata on their own, and now they would like to know the solutions to **each other's unique kata** that each of the other `n - 1` ... | reference | def optimal_conversations(n):
if n == 2:
return [(1, 2)]
if n == 3:
return [(1, 2), (1, 3), (2, 3)]
# Optimal solution for 4 people
res = [(1, 2), (3, 4), (1, 3), (2, 4)]
# If more than 4 people, just get their information at first and give them the (1, 2, 3, 4) at the end... | Help naughty Codewars users cheat by sharing their solutions to katas | 627183ce5aa8580057592940 | [
"Puzzles",
"Mathematics",
"Logic",
"Combinatorics"
] | https://www.codewars.com/kata/627183ce5aa8580057592940 | 6 kyu |
Simpler and similar kata <a href=http://www.codewars.com/kata/multiperfect-number >here</a>.
A generalization of <a href=https://en.wikipedia.org/wiki/Perfect_number>perfect numbers</a> are (m,k)-perfect number.
It is a series of numbers that satisfy the following condition:
```math
\Huge
\sigma^{m}(n) = kn
```
wher... | algorithms | from functools import cache
from gmpy2 import is_prime, next_prime
@ cache
def σ(m, n):
s, p = 1, 2
while n > 1:
while n % p:
p = n if is_prime(n) else next_prime(p)
i = 1
while n % p == 0:
n / /= p
i += 1
s *= (p * * i - 1) / / (p - 1)
return s if m == 1 else σ(... | (m, k)-Perfect Number | 5597ca93d5b5b37db8000066 | [
"Mathematics",
"Performance",
"Algorithms"
] | https://www.codewars.com/kata/5597ca93d5b5b37db8000066 | 5 kyu |
You are a big fan of Formula 1.
There was a race last week-end, but ... you missed the live TV.
You picked on the internet a list of the **events** during the race, and you want to get your champion's rank at the end of the race.
An event is a pilot ID followed by a type. There are two types of events:
<ul><li>'O' : ... | algorithms | import re
def champion_rank(pilot: int, events: str) - > int:
arr = [i for i in range(1, 21)]
for x in re . findall("\d+ [IO]", events):
r, t = x . split()
if t == 'I':
arr . remove(int(r))
else:
j = arr . index(int(r))
arr[j], arr[j - 1] = arr[j - 1], arr[j]
return arr... | Formula 1 Race | 626d691649cb3c7acd63457b | [
"Algorithms"
] | https://www.codewars.com/kata/626d691649cb3c7acd63457b | 5 kyu |
## Overview
`N` White frogs and `N` Black frogs are placed on either side of a line made up of `2*N + 1` spaces. The 1 "leftover" space is therefore empty, and is at the center of the line.
The `N` White frogs are placed on the left side and all face RIGHTWARDS, and the `N` Black frogs are placed on the right side al... | reference | def white_black_frogs(n):
return '' . join('j' * i + 'wb' [i & 1] for i in range(n)) + '' . join('j' * (n - i) + 'bw' [(i + n) & 1] for i in range(n))
| Help the frogs reach the opposite side of the line | 626d96eb49cb3c7a2f634bbf | [
"Algorithms",
"Puzzles",
"Recursion"
] | https://www.codewars.com/kata/626d96eb49cb3c7a2f634bbf | 6 kyu |
## Overview
In this kata you will be working on a 3x3 chessboard. In each test case you will be given:
- A **starting 3x3 board configuration** with some White and Black Knights on the 3x3 board.
- An **ending 3x3 board configuration** with some White and Black Knights.
Your goal is to determine if you can **reach t... | reference | def is_reachable(s, e):
ss, es = ['' . join(b[y][x] for y, x in [(0, 0), (1, 2), (2, 0), (0, 1),
(2, 2), (1, 0), (0, 2), (2, 1)] if b[y][x] != '_') for b in (s, e)]
return s[1][1] == e[1][1] and ss in es * (1 + (len(es) < 8))
| Configurations of White and Black Knights on a 3x3 chessboard | 626b949b40a15ed6e7055b8f | [
"Fundamentals",
"Algorithms",
"Puzzles",
"Mathematics",
"Performance"
] | https://www.codewars.com/kata/626b949b40a15ed6e7055b8f | 5 kyu |
Wordle is a game where users try to guess a hidden 5 letter word. Feedback is given for each guess, in the form of colored tiles, indicating when letters match or occupy the correct position.
see: https://www.nytimes.com/games/wordle/index.html
### The Brief
Make a function that takes in a 5 letter guess and, compari... | algorithms | def resolver(guess, solution):
letters, answer = {}, ['b'] * len(guess)
for i, (g, s) in enumerate(zip(guess, solution)):
if g == s:
answer[i] = 'g'
else:
letters[s] = letters . get(s, 0) + 1
for i, (g, s) in enumerate(zip(guess, solution)):
if g != s and letters . get(g,... | A Brave New Wordle | 62013b174c72240016600e60 | [
"Algorithms",
"Strings",
"Puzzles"
] | https://www.codewars.com/kata/62013b174c72240016600e60 | 5 kyu |
## Overview
On an n x n chessboard, a standard King can move 1 square at a time in any of the following 8 possible directions:
- up / down / left / right = the 4 possible linear directions
- upleft / upright / downleft / downright = the 4 possible diagonal directions.
Imagine you now have a non-standard **Limited K... | reference | def limited_king(n):
res = n % 3 == 1 and [(0, j) for j in range(n)] or []
for x in range(bool(res), n, 3):
res . extend((k, l) for l in range(n - 1, - 1, - 1)
for k in range(x, x + 2))
if x + 2 != n:
res . extend((x + 2, j) for j in range(n))
return res
| Find a Limited King's Tour on a chessboard | 626868a414c0146ddbe0e6be | [
"Fundamentals",
"Algorithms",
"Puzzles",
"Mathematics"
] | https://www.codewars.com/kata/626868a414c0146ddbe0e6be | 6 kyu |
This Kata is based on [Number of integer partitions](https://www.codewars.com/kata/546d5028ddbcbd4b8d001254).
An *integer partition with distinct parts* of `n` is a decreasing list of positive integers which sum to `n`, in which no number occurs more than once.
For example, there are 3 integer partitions of 5:
```
[5... | algorithms | def partitions(n):
T = [1] + [0] * n
for i in range(1, n + 1):
for j in range(n, i - 1, - 1):
T[j] += T[j - i]
return T[- 1]
| Number of integer partitions with distinct parts | 6267a007e67fba0058725ad2 | [
"Mathematics",
"Algorithms",
"Discrete Mathematics"
] | https://www.codewars.com/kata/6267a007e67fba0058725ad2 | 5 kyu |
### For whom the Bell tolls
Write a function bell that will receive a positive integer and return an array. That's all splaining you receive; what needs to be done you'll have to figure out with the examples below.
```
n => resulting array
1 => [1]
2 => [2, 2]
3 => [3, 4, 3]
4 => [4, 6, 6, 4]
5 => [5, 8, 9, 8,... | games | def bell(n):
return [(i + 1) * (n - i) for i in range(n)]
| For whom the Bell tolls | 62665d43e67fbaf7b37212d2 | [
"Algorithms",
"Logic",
"Puzzles"
] | https://www.codewars.com/kata/62665d43e67fbaf7b37212d2 | 6 kyu |
# Welcome To Pawn Promotion Kata.
In this kata you will write a program that studies a chess board
that contains only two pieces (pawn) and (king).
The pawn is always in the last row
as it will now turn into one of the four pieces
```[queen , rook , bishop , knight]``` in a process called {pawn promotion}.
Your tas... | reference | def promotion(board):
pieces = [(i, j) for i, r in enumerate(board)
for j, p in enumerate(r) if p != ' ']
if not len(pieces) == 2:
return []
a, b = pieces
if a[0] == b[0] or a[1] == b[1]:
return ['queen', 'rook']
if {abs(a[0] - b[0]), abs(a[1] - b[1])} == {1, 2}:
... | Pawn Promotion | 62652939385ccf0030cb537a | [
"Fundamentals"
] | https://www.codewars.com/kata/62652939385ccf0030cb537a | 6 kyu |
## Overview
An eccentric chessboard maker likes to create strange N x N chessboards.
Instead of making all the rows and the columns on his chessboards the same size, he likes to make chessboards with row and columns of varying sizes:
<svg xml:space="preserve" viewBox="0 0 500 500" height="500" width="500" version="1... | reference | def white_black_areas(cs, rs):
r_even, r_odd = sum(rs[1:: 2]), sum(rs[:: 2])
c_even, c_odd = sum(cs[1:: 2]), sum(cs[:: 2])
return (c_odd * r_odd + c_even * r_even, r_even * c_odd + r_odd * c_even)
| Find the total white and black areas in a strange chessboard | 6262f9f7afc4729d8f5bef48 | [
"Fundamentals",
"Algorithms",
"Puzzles",
"Mathematics"
] | https://www.codewars.com/kata/6262f9f7afc4729d8f5bef48 | 6 kyu |
## Task
There are several units in a line, out of your sight. You will be given a list of hints (a list or array of strings) that indicates who is next to who in the queue, and you have to rebuild the queue of people, in appropriate order.
## Example
With these hints,
```
["white has black on his left",
"red has ... | games | def line_up(hints):
graph = dict((a, b) if side == 'right' else (b, a)
for a, _, b, _, _, side in map(str . split, hints))
start = (set(graph) - set(graph . values())). pop()
queue = []
while start:
queue . append(start)
start = graph . get(start)
return queue
| Line up | 625d02d7a071210017c8f0c3 | [
"Arrays",
"Puzzles"
] | https://www.codewars.com/kata/625d02d7a071210017c8f0c3 | 6 kyu |
## Intro:
You may have heard in a math class somewhere that at small values of x, sin(x) can be well approximated by x (ie sin(x) looks linear near 0). This is true, and makes for some pretty slick shortcuts when calculating sin(x) at small x. You may have also heard that sin(x) can be approximated by something call... | reference | from itertools import count
from math import sin
def taylors_sine_terms(x: float, epsilon: float) - > int:
sin_x = sin(x)
approx = 0
fact = 1
for i in count(1):
approx -= (- 1) * * i * x * * (2 * i - 1) / fact
if abs(sin_x - approx) < epsilon:
return i
fact *= 2 * i * (2 * i + 1)
| Taylor's Sine Approximation: How Many Terms? | 615dd90346a119004af6d916 | [
"Fundamentals"
] | https://www.codewars.com/kata/615dd90346a119004af6d916 | 6 kyu |
You will get a list with several scattered numbers
You must check that the sum of the two values on both sides equals the sum of the rest of the list elements
And if not, delete the two elements on the sides and check repeatedly,
until you reach the condition checklist:
The sum of the list without the sides = the s... | reference | def plastic_balance(L):
if L and L[0] + L[- 1] != sum(L[1: - 1]):
return plastic_balance(L[1: - 1])
return L
| Plastic Balance | 625ea5c1a071210065c923af | [
"Fundamentals",
"Algorithms",
"Lists",
"Data Structures",
"Arrays"
] | https://www.codewars.com/kata/625ea5c1a071210065c923af | 7 kyu |
# Xor reduction (medium)
Given two integers, m and n, return the cumulative xor of all positive integers between them, inclusive. E.g. (0, 6), return `0^1^2^3^4^5^6` => `7`.
# Constraints:
0 <= m, n <= 10^15
m > n
# Hints
- Try the [easy variant](https://www.codewars.com/kata/56d3e702fc231fdf72001779) first
- Brute... | games | def xorr(n):
return (n, 1, n + 1, 0)[n % 4]
def xor_reduction(m, n):
return xorr(m - 1) ^ xorr(n)
| Xor reduction (medium) | 625d1c5b2f6c2c00300d97b7 | [
"Algorithms",
"Puzzles"
] | https://www.codewars.com/kata/625d1c5b2f6c2c00300d97b7 | 6 kyu |
Wordle is a game where you try to guess a 5-letter word. https://www.nytimes.com/games/wordle/index.html
After each guess, the color of the tiles (letters) will change to show how close your guess was to the word.
- Green (G) letter: This letter is in the correct position
- Yellow (Y) letter: This letter is present i... | games | from collections import Counter
def wordle(wordlist, guesses):
for g, r in guesses:
z = Counter(d for d, p in zip(g, r) if p != '-')
wordlist = [w for w in wordlist if all((p == 'G') == (c == d) and not (p == '-' and w . count(
d) > z[d]) for c, d, p in zip(w, g, r)) and all(w . count(c) >=... | Wordle! Cheat bot | 6255e6f2c53cc9001e5ef629 | [
"Puzzles"
] | https://www.codewars.com/kata/6255e6f2c53cc9001e5ef629 | 5 kyu |
__Prerequirements__
This kata is the second part of the [Barista Problem](https://www.codewars.com/kata/6167e70fc9bd9b00565ffa4e). I strongly encourage you to solve that one first.
__Context__
You got your RAISE!! YAY!!
But now, time has passed, and a position has opened up for Barista Manager.
__Description__
I... | reference | def barista(coffees, n):
coffees = sorted([v for v in coffees if v])
times = coffees[: n]
for v in coffees[n:]:
times . append(times[- n] + 2 + v)
return sum(times)
| Barista Manager | 624f3171c0da4c000f4b801d | [
"Algorithms"
] | https://www.codewars.com/kata/624f3171c0da4c000f4b801d | 5 kyu |
Create a function mul37 that returns the value of num represented in the form `3 * a + 7 * b`
e.g. ```9``` would return ```3 * 3 + 7 * 0```
e.g. ```10``` would return ```3 * 1 + 7 * 1```
e.g. ```100``` would return ```3 * 3 + 7 * 13```
e.g. ```999``` would return ```3 * 4 + 7 * 141```
Note:
- a and ... | reference | def mul37(num):
k = (2 * num + 6) / / 7
a, b = 7 * k - 2 * num, num - 3 * k
return f'3 * { a } + 7 * { b } '
| Numbers in terms of 3's and 7's | 62524390983b35002c8ff1e5 | [
"Puzzles",
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/62524390983b35002c8ff1e5 | 7 kyu |
## Steganography Part 1
Part 1 of a series using Steganography on RGB image pixels.
Part 2: https://www.codewars.com/kata/6251cba4629507b60a041b0e
---
Steganography is the practice of concealing a message within another medium.
In this case, we'll be taking a message string, and concealing it inside of RGB (Red, ... | reference | def conceal(msg, pixels):
bits = '' . join(f' { ord ( c ) : 0 > 8 b } .' for c in msg)
if len(bits) <= len(pixels) * 3:
bits = iter(bits)
return [[mix(v, next(bits, ".")) for v in p] for p in pixels]
def mix(v, b):
return v if b == "." else v >> 1 << 1 | int(b)
| Steganography Part 1 | 624fc787983b3500648faf11 | [
"Cryptography",
"Fundamentals"
] | https://www.codewars.com/kata/624fc787983b3500648faf11 | 6 kyu |
## Overview
In this kata you will be given:
1. A `string` of `n` inequality symbols; i.e. `>` or `<`
2. `n+1` **distinct** integers.
Your goal is to place **all** of the `n+1` integers into the available positions created by the given `n` inequality symbols, so that **the entire resulting expression is** `True`.
Ju... | reference | def interweave(a, b):
b = sorted(list(b))
i, j, s = 0, len(b) - 1, []
for c in a:
match c:
case '<':
s . append(b[i])
i += 1
case other:
s . append(b[j])
j -= 1
s . append(b[i])
return s
# from itertools import permutations, zip_longest
#
# def interweave(ineq... | Interweave the Inequalities and the Integers | 624dfbc87ee0d200157ad483 | [
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/624dfbc87ee0d200157ad483 | 6 kyu |
Although its use in screening healthy patients is debatable, Prostate Specific Antigen (PSA) is a very useful blood test for following the response of prostate cancer to treatment.
For patients treated with radiation therapy alone for prostate cancer, the PSA tends to take 2-3 years to reach a minimum value (nadir). I... | reference | def recurrence(values):
# let's take the first item as nadir, the previous item is temporarily equal to nadir
prev = nadir = values[0]
counter = 0 # a counter of ever higher successive values
bio = False # 3 consecutive rising PSA values after reaching the nadir value, now it's False
for val in va... | Prostate cancer recurrence rates (ASTRO) | 624e0a4c3e1d7b0031588666 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/624e0a4c3e1d7b0031588666 | 7 kyu |

# Summary:
[Rock, Paper, Scissors](https://en.wikipedia.org/wiki/Rock_paper_scissors) is too boring- let's spice it up a little!
Given an array of possible choices, what player 1 chooses and what player 2 choo... | reference | def winner(choices, p1, p2):
if p1 == p2:
return "Draw!"
r = (choices . index(p2) - choices . index(p1)) % len(choices)
if r == len(choices) / 2:
return "Draw!"
if r < len(choices) / 2:
return "Player 2 won!"
return "Player 1 won!"
| Rock paper scissors infinite | 62443a1ea8fca9002346d72c | [
"Games",
"Puzzles",
"Fundamentals"
] | https://www.codewars.com/kata/62443a1ea8fca9002346d72c | 6 kyu |
The knight is a piece in the game of chess. It may move two squares vertically and one square horizontally or two squares horizontally and one square vertically. For a visual representation of the possible moves, take a look [here](https://en.wikipedia.org/wiki/Knight_(chess)#Movement) (second image).
Given the curre... | games | def next_pos(s): return [f + r for f in 'abcdefgh' for r in '12345678' if ~ int(f + r + s, 24) * * 4 % 577 ^ 4 < 4]
| [Code Golf] Knight's Next Position | 6243819a58ad06b6c663d32b | [
"Restricted",
"Puzzles"
] | https://www.codewars.com/kata/6243819a58ad06b6c663d32b | 6 kyu |
# Superheroes Convention #1 Pandemic
You are organizing the next comic book convention in the famous San Diego Convention Center. Because of a new virus the convention will be just a 2-day event.
Each superhero will have his stand but there is a <strong><u>big problem:</u> </strong>They dont want to share the space w... | algorithms | def is_possible(db: dict) - > bool:
db = dict(db)
stk = list(db)
day = [0] * len(db)
while stk:
a = stk . pop()
if a not in db:
continue
lst = db . pop(a)
day[a] = day[a] or 1
oppDay = day[a] ^ 3
for b in lst:
if day[b] and day[b] != oppDay:
ret... | Superheroes Convention #1 Pandemic | 6202149e89771200306428f0 | [
"Algorithms",
"Puzzles",
"Performance",
"Graph Theory"
] | https://www.codewars.com/kata/6202149e89771200306428f0 | 4 kyu |
# Elevator malfunctioning
The elevator in my building of `n` floors is malfunctioning.
Whenever someone wants to go up, the elevator moves up by `x` floors if it can. If the elevator cannot move up by `x` floors, it stays in te same spot. On the other hand, whenever someone wants to go down, the elevator moves down by ... | algorithms | # return the minimum number of stops, otherwise -1
def get_stops(up, down, n_floors, floor):
visited = {1}
queue = [(1, 0)]
while queue:
fl, stops = queue.pop(0)
if fl == floor: return stops
for f in [fl+up, fl-down]:
if 1 <= f <= n_floors and not f in visited:
... | Elevator malfunctioning | 62396d476f40250024bcfce9 | [
"Data Structures",
"Algorithms",
"Mathematics",
"Puzzles"
] | https://www.codewars.com/kata/62396d476f40250024bcfce9 | 5 kyu |
The 2020 International Society of Hypertension Practice Guidelines describe raised blood pressure (hypertension) and its complications as the leading cause of death in the world at the time of publication. Blood pressure is the measure of the heart's pumping pressure against the blood vessel walls. It is recorded as a... | reference | def c1(p): return (l: = len(p)) > 1 and sum(int(e . split('/')[0]) for e in p) / len(p) >= 140
def c2(p): return (l: = len(p)) > 1 and sum(int(e . split('/')[1]) for e in p) / len(p) >= 90
def c3(p): return any(
int(e . split('/')[0]) >= 180 and int(e . split('/')[1]) >= 110 for e in p)
def hypertensive(P): r... | Diagnosing Hypertension | 621470ede0bb220022c9e396 | [
"Strings",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/621470ede0bb220022c9e396 | 6 kyu |
If you're not familiar with the fantastic culinary delights of the British Isles you may not know about the bread sandwich.
The idea is very simple - if you have a slice of bread between two other slices of bread, then it's a bread sandwich. Additionally, if you have a bread sandwich between two other slices of bread,... | algorithms | def slices_to_name(n):
if isinstance(n, int) and n > 1:
return ' ' . join(n % 2 * ['bread'] + n / / 2 * ['sandwich'])
def name_to_slices(name):
if isinstance(name, str):
n = 2 * name . count('sandwich') + name . count('bread')
if name == slices_to_name(n):
return n
| bread sandwiches | 622a6a822494ab004b2c68d2 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/622a6a822494ab004b2c68d2 | 6 kyu |
Your task here is to write [unit tests](https://en.wikipedia.org/wiki/Unit_testing) for several statements in the following `PhoneBook` class, which manages each user's phone number:
~~~if:python
```python
from collections import UserDict
class PhoneBook(UserDict):
def create(self, name: str, phone_number: str) ... | reference | from unittest import TestCase
class TestPhoneBook (TestCase):
def setUp(self):
# Arrange
self . phone_book = PhoneBook()
def test_create_method(self):
# Act
self . phone_book . create('User', '12345678')
# Assert
self . assertEqual(self . phone_book['User'], '1... | Basic Unit Test Practice | 620bce448e757800242821fe | [
"Fundamentals",
"Tutorials"
] | https://www.codewars.com/kata/620bce448e757800242821fe | 6 kyu |
Popular gambling game **Joker** consists of drawing 6 balls from a drum on which are written numbers
between 1 and 45. The winning joker number is formed from the drawn numbers so that in the same order in which the balls are drawn, we write down their last digits.
For example, if the numbers 12, 35, 1, 2, 23 and 39 ... | reference | def joker_card(joker_nums, ticket_serials):
prize_dict = {
0: 'Losing card',
1: 'Losing card',
2: 'V type',
3: 'IV type',
4: 'III type',
5: 'II type',
6: 'I type'
}
prize = []
joker = list(map(lambda x: str(x)[- 1], joker_nums))[:: - 1]
... | Gambling Game Joker | 621e323a98afab001628d9a0 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/621e323a98afab001628d9a0 | 6 kyu |
Every book has `n` pages with page numbers `1` to `n`. The `summary` is made by adding up the **number of digits** of all page numbers.
Task: Given the `summary`, find the number of pages `n` the book has.
### Example
If the input is `summary=25`, then the output must be `n=17`: The numbers 1 to 17 have 25 digits in ... | algorithms | def amount_of_pages(summary):
# 1-9: 9 = 9 * 1 * 10**0
# 10-99: 180 = 9 * 2 * 10**1
# 100-999: 2700 = 9 * 3 * 10**2
# 1000-9999: 36000 = 9 * 4 * 10**3
# 10000-99999: 450000 = 9 * 5 * 10**4
res = 0
for x in range(1, 6):
y = 9 * x * 10 * * (x - 1)
if summary <= y:
return res + summ... | How many pages in a book? | 622de76d28bf330057cd6af8 | [
"Puzzles",
"Algorithms"
] | https://www.codewars.com/kata/622de76d28bf330057cd6af8 | 6 kyu |
This kata is the performance version of [Don't give me five](https://www.codewars.com/kata/5813d19765d81c592200001a) by [user5036852](https://www.codewars.com/users/user5036852).
Your mission, should you accept it, is to return the count of all integers in a given range which *do not* contain the digit 5 (in base 10 ... | algorithms | import re
def dont_give_me_five(start, end):
def count(n): return int(re . sub(r'5(\d*)', lambda m: '4' + '9' *
len(m[1]), str(n)). translate(str . maketrans("56789", "45678")), 9)
if start > 0:
return count(end) - count(start - 1)
elif end < 0:
retur... | Don't give me five! Really! | 621f89cc94d4e3001bb99ef4 | [
"Algorithms",
"Mathematics",
"Performance"
] | https://www.codewars.com/kata/621f89cc94d4e3001bb99ef4 | 4 kyu |
Alice and Bob are playing a game. There are `$n (1 \leq n \leq 10^{18}) $` cards on the table. The aim of the game is to collect the most cards. The rules:
* if the number of cards is *even*, the players can either take half of the cards from the stack, or only 1 card -- as they choose;
* if the number of cards is *odd... | algorithms | def get_card(n):
if (n % 2 == 0 and (n / / 2) % 2 == 1) or n == 4:
return n / / 2
else:
return 1
def card_game(n):
alice = 0
bob = 0
flag = True
while n > 0:
this_turn = get_card(n)
if flag:
alice += this_turn
else:
bob += this_turn
flag = not flag
n -= th... | Card Game | 61fef3a2d8fa98021d38c4e5 | [
"Mathematics",
"Algorithms",
"Performance"
] | https://www.codewars.com/kata/61fef3a2d8fa98021d38c4e5 | 5 kyu |
## Objective
Create a [rasterized](https://en.wikipedia.org/wiki/Rasterisation) binary image of a triangle.
### Given
- `(x1, y1)`, `(x2, y2)`, and `(x3, y3)` - **Integer** coordinates of triangle vertices.
- `n` - Size of the output image.
### Expected Output
- An `n`-by-`n` image of `1`s and `0`s.
### Details
... | algorithms | def half_plane(p1, p2, p3):
"""
Returns a function that checks the affiliation of a point (x, y)
to a half-plane (defined by point p1, p2) to which point p3 belongs.
If the given three points do not form a triangle (only a straight line),
an exception is raised.
Note that the function... | Rasterize a Triangle | 621ab012ed37430016df15c0 | [
"Geometry",
"Graphics",
"Image Processing",
"Algorithms"
] | https://www.codewars.com/kata/621ab012ed37430016df15c0 | 6 kyu |
## Task
In this task, you need to restore a string from a list of its copies.
You will receive an array of strings. All of them are supposed to be the same as the original but, unfortunately, they were corrupted which means some of the characters were replaced with asterisks (`"*"`).
You have to restore the original... | reference | def assemble(input):
result = list(input[0]) if input else []
for i in input:
for j, k in enumerate(i):
result[j] = k if result[j] == '*' else result[j]
return '' . join(result). replace('*', '#')
| Assemble string | 6210fb7aabf047000f3a3ad6 | [
"Strings",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/6210fb7aabf047000f3a3ad6 | 6 kyu |
It is hypothesized that the self-replicating RNA molecules played an early and central role in the origin of life. For more information, see [The RNA World](https://en.wikipedia.org/wiki/RNA_world).
Through phosphodiester bondings, four kinds of nucleoside triphosphate came together to form a chain that is moderately ... | algorithms | def longest_stem_length(rna):
min_stem, loop_sizes, base_pairs = 4, range(
6, 13), dict(zip('ACGU', 'UGCA'))
lgt, pairs = 0, [(i, i + s + 1) for s in loop_sizes for i in range(
len(rna) - s - 1) if rna[i + s + 1] == base_pairs[rna[i]]]
while pairs:
lgt, pairs = lgt + 1, [(i - 1, j ... | 🧬Cooking life on Proto Earth🌎 | 5fe2ea999fd2140016feec63 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5fe2ea999fd2140016feec63 | 5 kyu |
🚩 What is the flag?
- The flag is hidden in the string variable `FLAG`
- The flag is in the format `FLAG{CAPITAL-LETTERS-WITH-HYPHEN}`
- The flag couldn't be found from the string literal right away... but *You can indeed **see** it somehow!*
- A magic number `16` might help... but how should it be used?
| games | # WTF?
flag = "FLAG{IS-IT-EASY-YET-FUN}"
| What is the flag? | 61efc02e4fd88600343b5c58 | [
"Fundamentals",
"Puzzles",
"Strings"
] | https://www.codewars.com/kata/61efc02e4fd88600343b5c58 | 7 kyu |
### Overview
We often use smiley faces in correspondence with other people. They allow us to quickly show our reaction to the person(s) we are talking to.
But one day you wanted to make your correspondence more joyful. So today you have the opportunity to make it happen.
### Task:
In this kata, your task will be to r... | algorithms | def smile(text):
eyes = [":", ";", "="]
noses = ["", "-", "~"]
mouths = ["[", "("]
mouths_2 = [']', ')']
for eye in eyes:
for nose in noses:
for i, mouth in enumerate(mouths):
face = eye + nose + mouth
face_2 = eye + nose + mouths_2[i]
if face in text:
text = text ... | Make everyone happy :) | 61eeb6e7577f050037b17a2d | [
"Fundamentals",
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/61eeb6e7577f050037b17a2d | 6 kyu |
The Royal Household is opening a new vacancy of microwave oven maid, who will heat up dishes for Queen Elizabeth II. All candidates must pass several very difficult tests and training in boot camp. Good luck, recruit!
### The touchpad test.
On a microwave the maximum number that you can enter for minutes or seconds i... | reference | import re
def toS(m, s): return f' { m }{ s : 0 > 2 } ' . lstrip('0')
def compact(s): return re . sub(r'(.)\1+', r'\1', s)
def cmpS(a, b): return (len(a) > len(b)) - (len(a) < len(b))
def get_best_combination(t):
m, s = divmod(t, 60)
M, S = m - 1, s + 60
a, b = map(toS, (m, M), (s, S)... | Microwave maid Ep1: The touchpad test | 61e1f175fbf3bd002a5528cd | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/61e1f175fbf3bd002a5528cd | 6 kyu |
Let `$f(s) = s_1 \cdot 1 + s_2 \cdot 2 + ... + s_N \cdot N$` where `$N \leq 2 \cdot 10^4$` is the length of an array `$s$`.
In other words, `$f(s) = \sum_{i=1}^{N} s_i \cdot i$`.
Given a sequence of integers, `$a$` (`$-10^9 \leq a_i\leq 10^9$`) and an array of queries, `$qs$`, where each `$qs_i=[l,r]$` (`$l \leq r$`... | algorithms | # -*- coding:utf-8 -*-
# author : utoppia
# description : solutions for codewars.com
# updated at : 2022-02-03 16:19
# -----------------------------------------------------
# Kata UUID : 61e2edfeaf28c2001b57af98
# Title : Subsequence Sums II
# Kyu : 5
# Kata's Sensi: tonylicoding
# Tags : ['Algorithms', 'Mathematics', ... | Subsequence Sums II | 61e2edfeaf28c2001b57af98 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/61e2edfeaf28c2001b57af98 | 5 kyu |
## Setup
Start with an empty square grid that hypothetically goes on forever.
You will be given a list of points (`(x, y)` coordinates) where the initial stones are to be placed which all have a value of `1`.
For example input of `[(0, 0), (1, 0)]` is the initial setup corresponding to two stones side by side.
Whil... | games | from collections import defaultdict
def neighbors(pos):
i, j = pos
return [(i + k, j + l) for k in range(- 1, 2) for l in range(- 1, 2) if k or l]
def first_impossible(elems) - > int:
memo, done = defaultdict(int), set(elems)
def update(p, n):
for pos in neighbors(p):
if pos ... | Stepping Stones Puzzle | 61e1b974eb372a001f719527 | [
"Games",
"Lists",
"Data Structures",
"Puzzles"
] | https://www.codewars.com/kata/61e1b974eb372a001f719527 | 4 kyu |
Welcome to the world of the National Football League!
In the NFL the Triple Crown is given when a receiver has the most receiving yards, the most receiving touchdowns and the most receptions in a single season.
This year Cooper Kupp managed to get it, however it is quite rare because the last one was in 2005 by Stev... | reference | def triple_crown(r):
for i in r:
if all(r[i][k] > r[j][k] for k in r[i] for j in r if i != j):
return i
return 'None of them'
| Triple Crown | 61e173ccbc916700267ef2ae | [
"Fundamentals"
] | https://www.codewars.com/kata/61e173ccbc916700267ef2ae | 7 kyu |
## Problem
The 'water pouring' problem (a.k.a 'two water jug' problem, or the even cooler 'Die Hard with a vengeance' puzzle) is a puzzle involving a finite number of water jugs with integer capacities (in this case, measured in litres). For this problem, we are using only two jugs. Initially, each jug is empty. We wa... | games | def wpp(a, b, n):
z = []
for i in range(b):
c = (a * i) % b
d = min(c + a, b)
z . append((a, c))
z . append((c + a - d, d))
if n in (c + a - d, d):
return z
if c + a >= b:
z . append((c + a - d, 0))
z . append((0, c + a - d))
return []
| Water pouring problem | 61de6142b31ff7000cc27e10 | [
"Algorithms",
"Performance",
"Puzzles",
"Graph Theory"
] | https://www.codewars.com/kata/61de6142b31ff7000cc27e10 | 5 kyu |
# Task
The function `fold_cube(number_list)` should return a boolean based on a net (given as a number list), if the net can fold into a cube.
Your code must be effecient and complete the tests within 500ms.
## Input
Imagine a net such as the one below.
```
@
@ @ @ @
@
```
Then, put it on the table with each ... | games | def fold_cube(nums):
return expand(nums . pop(), set(nums), 1, 2, 3) == {1, 2, 3, - 1, - 2, - 3}
def expand(val, nums, x, y, z):
dirs = {z}
for num in nums . copy():
if abs(val - num) not in (1, 5) or {val % 5, num % 5} == {0, 1}:
continue
nums . discard(num)
diff = val - num
... | Folding a cube | 5f2ef12bfb6eb40019cc003e | [
"Puzzles",
"Algorithms"
] | https://www.codewars.com/kata/5f2ef12bfb6eb40019cc003e | 5 kyu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.