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
## <span style="color:#0ae">Luhn algorithm</span> The *Luhn algorithm* is a simple checksum formula used to validate credit card numbers and other identification numbers. #### Validation - Take the decimal representation of the number. - Starting from rightmost digit and moving left, double every second digit; if th...
games
def lcd(n): return n and ((n * 79 + 4) / / 10 + lcd(n / / 100)) % 10
[Code Golf] Luhn Check Digit
6112e90fda33cb002e3f3e44
[ "Restricted", "Puzzles" ]
https://www.codewars.com/kata/6112e90fda33cb002e3f3e44
6 kyu
Given multiple lists (name, age, height), each of size n : An entry contains one name, one age and one height. The attributes corresponding to each entry are determined by the index of each list, for example entry 0 is made up of ```name[0], age[0], height[0]```. A duplicate entry is one in which the name, age and he...
reference
def count_duplicates(* args): return len(args[0]) - len(set(zip(* args)))
Counting Duplicates Across Multiple Lists
6113c2dc3069b1001b8fdd05
[ "Lists", "Fundamentals" ]
https://www.codewars.com/kata/6113c2dc3069b1001b8fdd05
7 kyu
Before attempting this kata, take a look at [this one](https://www.codewars.com/kata/5713d18ec82eff7766000bb2). Dobble, also known as "Spot it!", is played with a deck of cards where each card contains 8 different figures and any two cards have exactly one figure in common. The total number of distinct figures in a de...
reference
from collections import Counter def missing_cards(cards): cs = Counter(x for c in cards for x in c) y = next(x for x, k in cs . items() if k == 6) r = [[y], [y]] for x in (x for x, k in cs . items() if k == 7): s = set(r[1] + [x]) r[all(len(set(c) & s) <= 1 for c in cards)]. append(x)...
Dobble: Identify the missing cards
610bfdde5811e400274dbf66
[ "Games", "Puzzles", "Algorithms" ]
https://www.codewars.com/kata/610bfdde5811e400274dbf66
5 kyu
# Mirrored Exponential Chunks Using a single function provided with an array, create a new one in the following ways: - Separate array elements into chunks. Each chunk will contain `2^abs(n)` elements where `n` is the "distance" to the median chunk. - The median chunk(s) will have one single element, or will not ap...
algorithms
from collections import deque def mirrored_exponential_chunks(arr): left, median = divmod(len(arr), 2) p, right, mirror = 1, left + median, deque([]) if median: mirror . append(arr[left: right]) while left > 0: p *= 2 mirror . appendleft(arr[max(left - p, 0): left]) mirr...
Mirrored Exponential Chunks
5852d0d463adbd39670000a1
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5852d0d463adbd39670000a1
5 kyu
# Task Write a function with the following properties: - takes two lists - returns a list of all possibilities to pair as many elements as possible from both lists while keeping the order of the elements - output format is a list of lists of tuples, or a list with an empty list, if no pairs are possible - inner lists ...
reference
from itertools import combinations def pair_items(a, b): n = min(len(a), len(b)) return [list(zip(x, y)) for x in combinations(a, n) for y in combinations(b, n)]
Pair items from two lists of different lengths
61055e2cb02dcb003da50cd5
[ "Fundamentals" ]
https://www.codewars.com/kata/61055e2cb02dcb003da50cd5
6 kyu
## Decode the cipher Where ```python # encode: Callable[ [str,int,int], list[int] ] encode = lambda a,b,c:(d:=0)or[(d:=(string.ascii_letters.index(e)+b+c)%(b*c)+d) for e in a] ``` The ciphered string `a` includes only ascii letters and: ```python 3 <= len(a) <= 128 8 <= b <= 256 8 <= c <= 256 ``` Example ```python ...
games
def decode(s, r, a): return "" . join( chr((e := x - t - r - a) + [39, 97][e < 26]) for t, x in zip([0, * s], s))
Decode a cipher - simple
61026860c135de00251c6a54
[ "Ciphers", "Puzzles" ]
https://www.codewars.com/kata/61026860c135de00251c6a54
6 kyu
The 2 main sequences in Mathematics are Arithmetic Progression and Geometric Progression. Those are the sequences you will be working with in this kata. # Introduction A sequence of numbers is called an Arithmetic Progression if the difference between any two consecutive terms is always same. In simple terms, it means...
algorithms
INF = float('inf') def determine_sequence(arr): isArith = len({b - a for a, b in zip(arr, arr[1:])}) == 1 isGeom = len({b / a if a else INF for a, b in zip(arr, arr[1:])}) == 1 return set(arr) != {0} and - 1 + isArith + 2 * isGeom
Sequence Determiner
610159919347db0019cabddc
[ "Algorithms" ]
https://www.codewars.com/kata/610159919347db0019cabddc
7 kyu
Bob works for Yamazon as a barcode scanning specialist. Every day, armed with his trusty laser, his job is to scan barcodes of packages as they pass in front of him on a conveyor belt. One day, his boss Beff Jezos tells him "There's been a big mixup with the new barcodes. We forgot to count every bardcode that had a r...
algorithms
def number_of_duplicate_digits(n): return 9 * 10 * * (n - 1) - 9 * * n
How many double digits?
60fb2e158b940b00191e24fb
[ "Mathematics", "Algorithms", "Puzzles" ]
https://www.codewars.com/kata/60fb2e158b940b00191e24fb
6 kyu
# Task Write a function that determines if the provided sequence of non-negative integers can be represented by a simple graph. [A simple graph](https://mathworld.wolfram.com/SimpleGraph.html#:~:text=A%20simple%20graph%2C%20also%20called,Bronshtein%20and%20Semendyayev%202004%2C%20p.) is a graph without any loops (a ve...
algorithms
# https://en.wikipedia.org/wiki/Erdős–Gallai_theorem#Statement def solution(degrees): degrees = sorted(filter(None, degrees), reverse=True) return not degrees or sum(degrees) % 2 == 0 and all(sum(degrees[: k + 1]) <= k * (k + 1) + sum(min(k + 1, x) for i, x in enumerate(degrees[k + 1:])) for k in range(len(d...
Graph-like Sequence
60815326bbb0150009f55f7e
[ "Sorting", "Algorithms", "Graph Theory" ]
https://www.codewars.com/kata/60815326bbb0150009f55f7e
5 kyu
# A war of mirrors You are presented with a battlefield with ally spaceships, enemies and mirrors (ignore the borders): ``` +----------+ |> A C \| | / B | | D | | | | > E /| +----------+ ``` The symbols are as follows: * Your spaceships are triangle-shaped (like in *Asteroids*!) and have ...
algorithms
SHIPS = dict(zip('<>^v', [(0, - 1), (0, 1), (- 1, 0), (1, 0)])) MIRRORS = {'/': - 1, '\\': 1} def rotate(dx, dy, c): c = MIRRORS[c]; return dy * c, dx * c def laser(lst): X, Y = len(lst), len(lst[0]) out, seen = set(), set() lasers = {(x, y, * SHIPS[c]) for x, r in enumerate(lst) ...
3-2-1 Fire!
5e94456c4af7f4001f2e2a52
[ "Games", "Algorithms" ]
https://www.codewars.com/kata/5e94456c4af7f4001f2e2a52
5 kyu
_yet another easy kata!_ ## Task: [Playfair cipher](https://en.wikipedia.org/wiki/Playfair_cipher) is a digram substitution cipher which unlike single letter substitution cipher encrypts pairs of letters. In this kata, you're going to implement the same. --- <br> ### Input A string `s` and key `key` both cons...
reference
from string import ascii_uppercase as letters import re def encipher(s, key, S=5): def cleanW(s): return s . replace(' ', '') def replKey(m): di = (m[0] + 'X')[: 2] (i, j), (x, y) = (chars[c] for c in di) return (mat[i][(j + 1) % S] + mat[x][(y + 1) % S] if i == x else ma...
Unusual Cipher
5efdde81543b3b00153e918a
[ "Ciphers", "Fundamentals" ]
https://www.codewars.com/kata/5efdde81543b3b00153e918a
5 kyu
given the first few terms of a sequence, can you figure out the formula that was used to generate these numbers, so we can find any term in the sequence? ## Task - write a function that accepts an array of number(the first few terms of a sequence) - your function should return a mapping function that accepts an intege...
algorithms
def solve_sequence(seq): ds = [(seq[:] or [0])] while len(set(seq)) > 1: ds . append(seq := [b - a for a, b in zip(seq, seq[1:])]) def fact(n, l): return n * fact(n - 1, l - 1) if l else 1 terms = [v[0] / / fact(i, i) for i, v in enumerate(ds)] return lambda n: sum(v * fact(n, i) if i else...
Find the nth Term of a Sequence
60f9f0145a54f500107ae29b
[ "Algebra", "Algorithms" ]
https://www.codewars.com/kata/60f9f0145a54f500107ae29b
5 kyu
We have to solve the Diophantine Equation: x<sup>2</sup> + 3y<sup>2</sup> = z<sup>3</sup> So, `x`, `y` and `z`, should be strictly positive integers (`x, y, z > 0`). This equation has a certain number of solutions if the value of `z` is limited. Let's say we want to know the number of solutions when `z` is under or ...
reference
total, memo = 0, [[], [], [], []] for z in range(4, 600): x, z3, tmp = 1, z * * 3, [] while (x2 := x * * 2) < z3: y2, r = divmod(z3 - x2, 3) if r == 0 and (y := y2 * * 0.5) % 1 == 0: tmp . append([x, int(y), z]) total += 1 x += 1 if tmp: tmp . sort(key=lambda t: (sum(t), - ...
Diophantine Equation Solver
57e32bb7ec7d241045000661
[ "Data Structures", "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/57e32bb7ec7d241045000661
6 kyu
### Peel the onion Your function will receive two positive integers ( integers ranging from 1 upward), and return an array. There's logic in there, but all you get are the example test cases to find it. Below overview for your convenience. (And, alright: the function name is a strong hint of what to do.) ``` (s, d) =...
games
def peel_the_onion(s, d): return [i * * d - (i - 2) * * d if i > 1 else 1 for i in range(s, 0, - 2)]
Peel the onion
60fa9511fb42620019966b35
[ "Algorithms", "Puzzles", "Mathematics", "Logic" ]
https://www.codewars.com/kata/60fa9511fb42620019966b35
6 kyu
The task is to find, as fast as you can, a rearrangement for a given square matrix, of different positive integers, that its determinant is equal to ```0```. E.g: ``` matrix = [[2, 1], [3, 6]] determinant = 9 ``` With the arrengament: ``` [[2, 1], [6, 3]] determinant = 0 ``` Create a function ```rearr()``` that receiv...
reference
import numpy as np from itertools import permutations, chain def rearr(matrix): ln = len(matrix) for p in permutations(chain . from_iterable(matrix)): arr = np . reshape(p, (ln, ln)) if np . linalg . det(arr) == 0: return arr . tolist() return - 1
#3 Matrices: Rearrange the matrix
5901aee0af945e3a35000068
[ "Algorithms", "Puzzles", "Linear Algebra", "Fundamentals", "Matrix" ]
https://www.codewars.com/kata/5901aee0af945e3a35000068
5 kyu
We have the following sequences, each of them with a its id (f_): Triangular numbers Tn: ```T(n) = n * (n + 1) / 2``` -------------> ```f3``` Square Numbers Sqn: ```Sq(n) = n * n``` ----------------------------> ```f4``` PentagonalNumbers Pn: ```P(n) = n * (3 * n − 1) / 2``` ------------> ```f5``` Hexagonal Num...
reference
def make_sum_chains(f_, n): return sum(f_(i) * sum(f(i) for f in FUNCTIONS if f != f_) for i in range(1, n + 1))
Chains With Sums and Products
566b4504595b1b2317000012
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/566b4504595b1b2317000012
6 kyu
An equilateral triangle with integer side length `n>=3` is divided into `n^2` equilateral triangles with side length 1 as shown in the diagram below. The vertices of these triangles constitute a triangular lattice with `(n+1)(n+2)/2` lattice points. Base triangle for `n=3`: ![Example](https://projecteuler.net/project/...
games
# Who needs loops? def counting_hexagons(n): x = n / / 3 s0 = x s1 = x * (x - 1) / / 2 s2 = s1 * (2 * x - 1) / / 3 s3 = s1 * s1 m0 = s0 * (n * * 2 - 3 * n + 2) m1 = s1 * (n * * 2 - 9 * n + 11) m2 = s2 * (- 6 * n + 18) m3 = s3 * 9 return (m0 + m1 + m2 + m3) / / 2
Counting hexagons
60eb76fd53673e001d7b1b98
[ "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/60eb76fd53673e001d7b1b98
6 kyu
Different colour pattern lists produce different numerical sequences in colours. For example the sequence [<span style="color:red">'red'</span>, <span style="color:#EEBB00">'yellow''</span>, <span style="color:DodgerBlue">'blue''</span>], produces the following coloured sequence: <span style="color:red"> 1 </span> <s...
reference
from itertools import count, takewhile from collections import Counter from math import ceil def count_col_hits(k, col, rng): a, b = rng na = ceil((- (2 * k + 1) + ((2 * k + 1) * * 2 + 8 * (k + a)) * * .5) / 2) c = Counter(col[(v - 1) % len(col)] for v in takewhile(lambda v: v <= b, (n * (n + 1) /...
Working With Coloured Numbers II
57fb33039610ce3b490000f9
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic", "Strings" ]
https://www.codewars.com/kata/57fb33039610ce3b490000f9
5 kyu
We are given an array of digits (0 <= digit <= 9). Let's have one as an example ```[3, 5, 2]``` ```Step 1```: We form all the possible numbers with these digits ``` [3, 5, 2] (dig_list)----> [2, 3, 5, 23, 25, 32, 35, 52, 53, 235, 253, 325, 352, 523, 532] (generated numbers, gen_num) ``` ```Step 2```: According to `po...
reference
from itertools import accumulate, chain, count, dropwhile, takewhile, islice, permutations def permuted_powerset(digits): l = list(map(str, digits)) c = chain . from_iterable(permutations(l, r) for r in range(1, len(l) + 1)) return dropwhile(0 . __eq__, map(int, map('' . join, c))) def sublis...
Count The Hits Adding Contiguous Powers!
569d754ec6447d939c000046
[ "Fundamentals", "Mathematics", "Permutations", "Sorting", "Logic", "Strings" ]
https://www.codewars.com/kata/569d754ec6447d939c000046
5 kyu
The two integer triangles have something in common: <a href="http://imgur.com/7eXfJXH"><img src="http://i.imgur.com/7eXfJXH.jpg?1" title="source: imgur.com" /></a> <a href="http://imgur.com/oWywzs2"><img src="http://i.imgur.com/oWywzs2.jpg?1" title="source: imgur.com" /></a> In the smaller triangle with sides ```(4,...
reference
from collections import defaultdict from functools import reduce from math import gcd from heapq import * def queuer(n, m): return m * (m + n), n, m MAX_P = 1500000 D_ORD = defaultdict(list) q, seen = [queuer(2, 3)], set((2, 3)) while q: p, n, m = heappop(q) a, b, c = tri = tuple(sorted((n *...
Integer Triangles Having One Angle The Double of Another One
56411486f3486fd9a300001a
[ "Fundamentals", "Algorithms", "Mathematics", "Geometry", "Memoization", "Data Structures" ]
https://www.codewars.com/kata/56411486f3486fd9a300001a
5 kyu
Create a Regular Expression that matches valid [pawn moves](https://en.wikipedia.org/wiki/Chess_piece) from the chess game (using standard Algebraic notation). https://en.wikipedia.org/wiki/Algebraic_notation_(chess) # The notation on the chess board ``` a b c d e f g h ⬜⬛⬜⬛⬜⬛⬜⬛ 8 ⬛⬜⬛⬜⬛⬜⬛⬜ 7 ⬜⬛⬜⬛⬜⬛⬜⬛ 6 ⬛⬜⬛⬜⬛⬜⬛⬜ 5 ...
algorithms
VALID_PAWN_MOVE_REGEX = '([a-h][2-7]|[a-h][18]=[QBNR]|(axb|bx[ac]|cx[bd]|dx[ce]|ex[df]|fx[eg]|gx[fh]|hxg)([2457]|[36](e\.p\.)?|[18](=[QBNR])?))[+#]?$'
Chess Fun # 13 : RegEx Like a Boss #1 : Valid Pawn Moves
5c178c8430f61aa318000117
[ "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/5c178c8430f61aa318000117
5 kyu
A chess position can be expressed as a string using the <a href="https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation"> Forsyth–Edwards Notation (FEN)</a>. Your task is to write a parser that reads in a FEN-encoded string and returns a depiction of the board using the Unicode chess symbols (♔,♕,♘,etc.). The b...
algorithms
map = { "r": "♖", "n": "♘", "b": "♗", "q": "♕", "k": "♔", "p": "♙", "R": "♜", "N": "♞", "B": "♝", "Q": "♛", "K": "♚", "P": "♟", } blank1 = "▇" blank2 = "_" def parse_fen(string): fields = string . split(" ") state = fields[0]. split("/") ...
Chess position parser (FEN)
56876fd23475fa415e000031
[ "Unicode", "Algorithms" ]
https://www.codewars.com/kata/56876fd23475fa415e000031
5 kyu
This kata is an extension and harder version of another kata, [Reflecting Light](https://www.codewars.com/kata/5eaf88f92b679f001423cc66), it is recommended to do that one first. <details> <summary>Reminders from Reflecting Light</summary> Four mirrors are placed in a way that they form a rectangle with corners at coo...
reference
from math import gcd def reflecting_light(max_x, max_y, point, num_reflections): dx, dy = point if dx == 0 or dy == 0: return 0, 0, 0, 0 d = gcd(dx, dy) max_x *= dy / / d max_y *= dx / / d r0 = (max_x + max_y) / / gcd(max_x, max_y) r = min(r0, num_reflections + 1) nx = ...
Reflecting Light V2
5f30a416542ae3002a9c4e18
[ "Geometry", "Mathematics" ]
https://www.codewars.com/kata/5f30a416542ae3002a9c4e18
5 kyu
<h1>Task</h1> Write a program that uses the image of the Tic-Tac-Toe field to determine whether this situation could have occurred as a result of playing with all the rules. Recall that the game of "Tic-Tac-Toe" is played on a 3x3 field. Two players take turns. The first puts a cross, and the second – a zero. It is al...
games
def is_it_possible(field): flag = True ls = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)] num = field . count('X') - field . count('0') dic = {1: ('0', '0', '0'), 0: ('X', 'X', 'X')} if num in [0, 1]: for a, b, c in ls: if (num, (f...
Check that the situation is correct
5f78635e51f6bc003362c7d9
[ "Puzzles" ]
https://www.codewars.com/kata/5f78635e51f6bc003362c7d9
5 kyu
Given a positive integer (n) find the nearest fibonacci number to (n). If there are more than one fibonacci with equal distance to the given number return the smallest one. Do it in a efficient way. 5000 tests with the input range 1 <= n <= 2^512 should not exceed 200 ms.
algorithms
from bisect import bisect FIB = [0, 1] TOP = 2 * * 512 a, b = 1, 1 while FIB[- 1] < TOP: a, b = a + b, a FIB . append(a) def nearest_fibonacci(n): i = bisect(FIB, n) return min(FIB[i - 1: i + 1], key=lambda v: (abs(v - n), v))
Find Nearest Fibonacci Number
5ca22e6b86eed5002812061e
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5ca22e6b86eed5002812061e
5 kyu
## Task You are given two positive integer numbers `a` and `b`. These numbers are being simultaneously decreased by 1 until the smaller one is 0. Sometimes during this process the greater number is going to be divisible (as in with no remainder) by the smaller one. Your task is to tell how many times (starting with `a...
reference
def how_many_times(a, b): if a > b: a, b = b, a if a <= 0: return - 1 if a == b: return a n = b - a return sum(1 + (x < n / x <= a) for x in range(1, min(a, int(n * * 0.5)) + 1) if not n % x)
Minus 1: is divisible?
5f845fcf00f3180023b7af0a
[ "Fundamentals", "Mathematics", "Algorithms", "Performance" ]
https://www.codewars.com/kata/5f845fcf00f3180023b7af0a
5 kyu
*Translations appreciated* # Overview Your task is to decode a qr code. You get the qr code as 2 dimensional array, filled with numbers. 1 is for a black field and 0 for a white field. It is always a qr code of version 1 (21*21), it is always using mask 0 ((x+y)%2), it is always using byte mode and it always has erro...
algorithms
def scanner(qrc): bits = '' . join(str(qrc[x][y] ^ ((x + y) % 2 == 0)) for x, y in ticTocGen()) size = int(bits[4: 12], 2) return '' . join(chr(int(bits[i: i + 8], 2)) for i in range(12, 12 + 8 * size, 8)) def ticTocGen(): x, y, dx = 20, 20, - 1 while y > 13: y...
Decode the QR-Code
5ef9c85dc41b4e000f9a645f
[ "Algorithms" ]
https://www.codewars.com/kata/5ef9c85dc41b4e000f9a645f
6 kyu
Two kingdoms are at war and, thanks to your codewarrior prowesses, you have been named general by one of the warring states. Your opponent's armies are larger than yours, but maybe you can reach a stalemate or even win the conflict if you are a good strategist. You control the **same number of armies as the rival sta...
algorithms
def codewar_result(codewarrior, opponent): armies = sorted(codewarrior, reverse=True) opp = sorted(opponent, reverse=True) wins = 0 while opp: if max(armies) < max(opp): opp . remove(max(opp)) armies . remove(min(armies)) wins -= 1 elif max(armies) > min(opp): target ...
Can you win the codewar ?
5e3f043faf934e0024a941d7
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5e3f043faf934e0024a941d7
6 kyu
According to ISO 8601, the first calendar week (1) starts with the week containing the first thursday in january. Every year consists of 52 calendar weeks (53 in case of a year starting on a Thursday or a leap year starting on a Wednesday). **Your task is** to calculate the calendar week (1-53) from a given date. For ...
algorithms
from datetime import datetime def get_calendar_week(date_string): return datetime . strptime(date_string, "%Y-%m-%d"). isocalendar()[1]
Calendar Week
5c2bedd7eb9aa95abe14d0ed
[ "Date Time", "Algorithms" ]
https://www.codewars.com/kata/5c2bedd7eb9aa95abe14d0ed
6 kyu
<span style="color:orange">*For all those times when your mouth says the opposite of what your brain told it to say...*</span> # Kata Task In this Kata you will write a method to return what you **really** meant to say by negating certain words (adding or removing `n't`) The words to be negated are drawn from this p...
algorithms
import re def correct(m): w, n, v = m . groups() v = v or '' if n: return w + v nt = "N'T" if w . isupper() and (not v or v . isupper()) else "n't" return f" { w }{ nt [ w . lower () == 'can' :]}{ v } " def speech_correction(words, speech): return speech if not words else re . sub(rf"\...
I said the word WOULD instead of WOULDN'T
5b4e9d82beb865d4150000b1
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/5b4e9d82beb865d4150000b1
6 kyu
We are given a certain number ```n``` and we do the product partitions of it. ```[59, 3, 2, 2, 2]``` is a product partition of ```1416``` because: ``` 59 * 3 * 2 * 2 * 2 = 1416 ``` We form a score, ```sc``` for each partition in the following way: - if ```d1, d2, ...., dk``` are the factors of ```n```, and ```f1, f2, ....
reference
from gmpy2 import is_prime from itertools import starmap from collections import Counter from operator import itemgetter, pow def score(L): return sum(starmap(pow, Counter(L). items())) * len(L) def find_spec_prod_part(n, com): def gen(x, d=2): if x == 1: yield [] for y in range(d, min(...
Find Product Partitions With Maximum or Minimum Score
571dd22c2b97f2ce400010d4
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic" ]
https://www.codewars.com/kata/571dd22c2b97f2ce400010d4
4 kyu
You should have done Product Partitions I to do this second part. If you solved it, you should have notice that we try to obtain the multiplicative partitions with ```n ≤ 100 ```. In this kata we will have more challenging values, our ```n ≤ 10000```. So, we need a more optimized a faster code. We need the function ...
reference
def find_factors(nm): res, cur, lnm = [], 2, nm while lnm >= cur * * 2: if lnm % cur == 0: res . append(cur) lnm / /= cur else: cur += 1 return res + [lnm] * (lnm != nm) def prod_int_partII(n, s): fct = find_factors(n) tot, cur, stot, sarr = int(len(fct) > 0), ...
Product Partitions II
5614adad2283aa822f0000b3
[ "Fundamentals", "Data Structures", "Mathematics", "Recursion", "Algorithms" ]
https://www.codewars.com/kata/5614adad2283aa822f0000b3
6 kyu
## Task Someone has used a simple substitution cipher to encrypt an extract from Conan Doyle's <a href="http://www.gutenberg.org/files/1661/1661-h/1661-h.htm">A Scandal in Bohemia</a>. Your task is to find the key they used to encrypt it. ## Specifications The key will be random. The key will work the same for upper...
algorithms
from collections import Counter def order_by_frequency(text): frequencies = Counter(filter(str . islower, text . lower())) return sorted(frequencies, key=frequencies . get, reverse=True) def key(extract, ordered=order_by_frequency(a_scandal_in_bohemia)): table = dict(zip(order_by_frequency(ex...
A Scandal in Bohemia
5f2dcbbd1b69a9000f225940
[ "Ciphers", "Cryptography", "Security", "Strings", "Algorithms" ]
https://www.codewars.com/kata/5f2dcbbd1b69a9000f225940
5 kyu
This is a sequel to [Solve the Grid! Binary Toggling Puzzle](https://www.codewars.com/kata/5bfc9bf3b20606b065000052). You are given a `N x N` grid of switches that are on (`1`) or off (`0`). The task is to activate all switches using a toggle operation. Executing a toggle operation at coordinates (`x`, `y`) will togg...
algorithms
def solve(grid): n0 = len(grid) n = n0 & ~ 1 rs = [0] * n cs = [0] * n for ir in range(n): for ic in range(n): if grid[ir][ic]: rs[ir] ^= 1 cs[ic] ^= 1 res = [(ic, ir) for ir in range(n) for ic in range(n) if not rs[ir] ^ cs[ic] ^ gri...
Advanced binary toggling puzzle
6067346f6eeb07003fd82679
[ "Algorithms", "Puzzles", "Mathematics" ]
https://www.codewars.com/kata/6067346f6eeb07003fd82679
4 kyu
## Our Setup Alice and Bob work in an office. When the workload is light and the boss isn't looking, they play simple word games for fun. This is one of those days! ## Today's Game Alice found a little puzzle in the local newspaper and challenged Bob on how many ways it could be solved using two different words. Bob...
algorithms
from collections import defaultdict WORDS = defaultdict(lambda: defaultdict(list)) for w in words: for i, c in enumerate(w): WORDS[c][i]. append(w) def crossword_2x2(puzzle): def count(a, b): return (a, b, sum(values[c] for c in a + b)) def hasHash(r): return '#' in r def hasLetter(r...
Crossword Puzzle! (2x2)
5c658c2dd1574532507da30b
[ "Puzzles", "Algorithms" ]
https://www.codewars.com/kata/5c658c2dd1574532507da30b
5 kyu
# Story John found a path to a treasure, and while searching for its precise location he wrote a list of directions using symbols `"^"`, `"v"`, `"<"`, `">"` which mean `north`, `east`, `west`, and `east` accordingly. On his way John had to try many different paths, sometimes walking in circles, and even missing the tr...
algorithms
def simplify(p): new_p = [(0, 0)] new_str = '' x = 0 y = 0 for i in p: if i == '<': x -= 1 elif i == '>': x += 1 elif i == '^': y += 1 elif i == 'v': y -= 1 if (x, y) not in new_p: new_p . append((x, y)) new_str += i else: for j i...
The simplest path
56bcafba66a2ab39e6001226
[ "Algorithms" ]
https://www.codewars.com/kata/56bcafba66a2ab39e6001226
6 kyu
An IPv6 address consists of eight parts of four hexadecimal digits, separated by colons (:), for example: ``` 1234:5678:90AB:CDEF:1234:5678:90AB:CDEF ``` As you can see, an IPv6 address is quite long. Luckily, there are a few things we can do to shorten such an address. Firstly, for each of the four-digit parts, we ...
algorithms
def shorten(ip, i=7): ip = ":" + ":" . join([group . lstrip("0") or "0" for group in ip . split(":")]) length = len(ip) while i and len(ip) == length: ip = ip . replace(":0" * i, "::", 1) i -= 1 return ip[1:]. replace(":::", "::")
Shorten IPv6 Address
5735b2b413c205fe39000c68
[ "Algorithms" ]
https://www.codewars.com/kata/5735b2b413c205fe39000c68
6 kyu
In this Kata, we will be taking the first step in solving Nash Equilibria of 2 player games by learning to calculate the Expected Utility of a player in a game of Rock Paper Scissors given the Utilities of the game and the Pure/Mixed Strategy of each Player. Let's first define a few Game Theoretic Definitions: <a hre...
algorithms
def expected_utility(p0, p1, utilities): ln = len(p0) return round(sum(utilities[i][j] * p0[i] * p1[j] for i in range(ln) for j in range(ln)), 2)
Calculating Expected Utility
5543e329a69dcb81b9000111
[ "Algorithms" ]
https://www.codewars.com/kata/5543e329a69dcb81b9000111
6 kyu
Lately you've fallen in love with JSON, and have used it to template different classes. However you feel that doing it by hand is too slow, so you wanted to create a decorator that would do it auto-magically! ## Explanation Your task is to write a decorator that loads a given JSON file object and makes each key-valu...
reference
import json def jsonattr(filepath): def decorate(cls): with open(filepath) as json_file: for name, value in json . load(json_file). items(): setattr(cls, name, value) return cls return decorate
JSON Class Decorator
55b0fb65e1227b17d60000dc
[ "Fundamentals", "Object-oriented Programming" ]
https://www.codewars.com/kata/55b0fb65e1227b17d60000dc
6 kyu
# YOUR MISSION An [octahedron](https://en.wikipedia.org/wiki/Octahedron) is an 8-sided polyhedron whose faces are triangles. Create a method that outputs a 3-dimensional array of an octahedron in which the height, width, and depth are equal to the provided integer `size`, which is equal to the length from one vertex...
algorithms
def create_octahedron(size): if size <= 1 or size % 2 == 0: return [] m = size / / 2 return [[[int(abs(x - m) + abs(y - m) + abs(z - m) <= m) for z in range(size)] for y in range(size)] for x in range(size)]
Blocky Octahedrons
5bfb0d9b392c5bf79a00015a
[ "Algorithms", "Geometry", "Algebra" ]
https://www.codewars.com/kata/5bfb0d9b392c5bf79a00015a
6 kyu
The [earth-mover's distance](https://en.wikipedia.org/wiki/Earth_mover's_distance) is a measure of the dissimilarity of two probability distributions. The unusual name comes from thinking of the probability attached to an outcome _x_ as a pile of dirt located at _x_. The two probability distributions are then regarded ...
reference
from itertools import accumulate def earth_movers_distance(x, px, y, py): values, dx, dy = sorted(set(x + y)), dict(zip(x, px)), dict(zip(y, py)) dist = (b - a for a, b in zip(values, values[1:])) diff = accumulate(dy . get(n, 0) - dx . get(n, 0) for n in values) return sum(d * abs(n) for d, n ...
Earth-mover's distance
58b34b2951ccdb84f2000093
[ "Fundamentals", "Algorithms", "Mathematics", "Arrays" ]
https://www.codewars.com/kata/58b34b2951ccdb84f2000093
6 kyu
### Vaccinations for children under 5 You have been put in charge of administrating vaccinations for children in your local area. Write a function that will generate a list of vaccines for each child presented for vaccination, based on the child's age and vaccination history, and the month of the year. #### The functio...
reference
from itertools import chain TOME = { '8 weeks': ['fiveInOne', 'pneumococcal', 'rotavirus', 'meningitisB'], '12 weeks': ['fiveInOne', 'rotavirus'], '16 weeks': ['fiveInOne', 'pneumococcal', 'meningitisB'], '12 months': ['meningitisB', 'hibMenC', 'measlesMumpsRubella'], '40 months': ['measlesMum...
VaccineNation
577d0a117a3dbd36170001c2
[ "Arrays", "Sorting", "Fundamentals" ]
https://www.codewars.com/kata/577d0a117a3dbd36170001c2
6 kyu
**See Also** * [Traffic Lights - one car](.) * [Traffic Lights - multiple cars](https://www.codewars.com/kata/5d230e119dd9860028167fa5) --- # Overview A character string represents a city road. Cars travel on the road obeying the traffic lights.. Legend: * `.` = Road * `C` = Car * `G` = <span style='color:black;ba...
algorithms
def traffic_lights(road, n): lightsIdx = [(i, 6 * (c != 'G')) for i, c in enumerate(road) if c in 'RG'] car, ref = road . find('C'), road . replace('C', '.') mut, out = list(ref), [road] for turn in range(1, n + 1): for i, delta in lightsIdx: # Update all lights state = (delta + turn)...
Traffic Lights - one car
5d0ae91acac0a50232e8a547
[ "Algorithms" ]
https://www.codewars.com/kata/5d0ae91acac0a50232e8a547
6 kyu
In this Kata, you will be given a number `n` (`n > 0`) and your task will be to return the smallest square number `N` (`N > 0`) such that `n + N` is also a perfect square. If there is no answer, return `-1` (`nil` in Clojure, `Nothing` in Haskell, `None` in Rust). ```clojure solve 13 = 36 ; because 36 is the smalles...
algorithms
def solve(n): for i in range(int(n * * 0.5), 0, - 1): x = n - i * * 2 if x > 0 and x % (2 * i) == 0: return ((n - i * * 2) / / (2 * i)) * * 2 return - 1
Simple square numbers
5edc8c53d7cede0032eb6029
[ "Algorithms" ]
https://www.codewars.com/kata/5edc8c53d7cede0032eb6029
6 kyu
[Sharkovsky's Theorem](https://en.wikipedia.org/wiki/Sharkovskii%27s_theorem) involves the following ordering of the natural numbers: ```math 3 ≺ 5 ≺ 7 ≺ 9 ≺ ... \\ ≺ 2 · 3 ≺ 2 · 5 ≺ 2 · 7 ≺ 2 · 9 ≺ ... \\ ≺ 2^n · 3 ≺ 2^n · 5 ≺ 2^n · 7 ≺ 2^n · 9 ≺ ... \\ ≺ 2^{n+1} · 3 ≺ 2^{n+1} · 5 ≺ 2^{n+1} · 7 ≺ 2^{n+1} · 9 ≺ ... \\...
algorithms
def sharkovsky(a, b): return f(a) < f(b) def f(n, p=0): while n % 2 == 0: n >>= 1 p += 1 return n == 1, p * (- 1) * * (n == 1), n
Sharkovsky's Theorem
5f579a3b34d5ad002819eb9e
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5f579a3b34d5ad002819eb9e
6 kyu
_Yet another easy kata!_ ## Task: You are given a word `target` and list of sorted(by length(increasing), number of upper case letters(decreasing), natural order) unique words `words` which always contains `target`, your task is to find the index(0 based) of `target` in `words`,which would always be in the list. ...
reference
def keyer(w): return (len(w), - sum(map(str . isupper, w)), w) def index_of(words, target): def cmp(i, base=keyer(target)): o = keyer(words[i]) return (o > base) - (o < base) l, h = 0, len(words) while l < h: m = h + l >> 1 v = cmp(m) if not v: return m if ...
Word search
5f05e334a0a6950011e72a3a
[ "Fundamentals" ]
https://www.codewars.com/kata/5f05e334a0a6950011e72a3a
6 kyu
In this Kata you will be given position of King `K` and Bishop `B` as strings on chess board using standard chess notation. Your task is to return a list of positions at which Rook would pin the Bishop to the King. > What is pin? https://en.wikipedia.org/wiki/Pin_(chess) > What is standard chess notation? https://en...
games
def pin_rook(* kb): (_, x, y), (_, i, j) = kb if x == i: return [f"R { x }{ r } " for r in '12345678' if y < j < r or r < j < y] if y == j: return [f"R { r }{ y } " for r in 'abcdefgh' if x < i < r or r < i < x] return []
Chess - Pin with Rook
5fc85f4d682ff3000e1c4305
[ "Puzzles" ]
https://www.codewars.com/kata/5fc85f4d682ff3000e1c4305
6 kyu
[Generala](https://en.wikipedia.org/wiki/Generala) is a dice game popular in South America. It's very similar to [Yahtzee](https://en.wikipedia.org/wiki/Yahtzee) but with a different scoring approach. It is played with 5 dice, and the possible results are: | Result | Points | Rules ...
algorithms
def points(dice): dice = sorted([int(d) for d in dice]) counts = [dice . count(i) for i in range(1, 7)] if 5 in counts: # GENERALA return 50 if 4 in counts: # POKER return 40 if 3 in counts and 2 in counts: # FULLHOUSE return 30 if counts . count(1) == 5 and c...
Generala - Dice Game
5f70c55c40b1c90032847588
[ "Games", "Algorithms" ]
https://www.codewars.com/kata/5f70c55c40b1c90032847588
6 kyu
# Leaderboard climbers In this kata you will be given a leaderboard of unique names for example: ```python ['John', 'Brian', 'Jim', 'Dave', 'Fred'] ``` ```haskell [ "John" , "Brian" , "Jim" , "Dave" , "Fred" ] ``` ```rust [ "John", "Brian", "Jim", "Dave", "Fred" ] ``` Then you will be given a list of str...
reference
def leaderboard_sort(leaderboard, changes): for change in changes: name, delta = change . split() idx = leaderboard . index(name) leaderboard . insert(idx - int(delta), leaderboard . pop(idx)) return leaderboard
Leaderboard climbers
5f6d120d40b1c900327b7e22
[ "Lists", "Fundamentals" ]
https://www.codewars.com/kata/5f6d120d40b1c900327b7e22
6 kyu
### History You are a great investigator. You are spending Christmas holidays with your family when you receive a series of postcards. At first glance the text on the postcards doesn't make sense (why send random quotes?), but after a closer look you notice something strange. *Maybe there is a hidden message!* ...
games
import re class Investigator: def __init__(self): self . decoded = [] def postcard(self, s): self . decoded . append( '' . join(re . findall(r'(?<=\w)[A-Z]| (?= )', s))) def hidden_message(self): return '' . join(self . decoded)
Investigator's holidays and hidden messages
5fe382d3e01a94000d54916a
[ "Strings", "Puzzles" ]
https://www.codewars.com/kata/5fe382d3e01a94000d54916a
6 kyu
Complete the function which accepts a string and return an array of character(s) that have the most spaces to their right and left. **Notes:** * the string can have leading/trailing spaces - you **should not** count them * the strings contain only unique characters from `a` to `z` * the order of characters in the r...
algorithms
import regex def loneliest(s): ss = regex . findall(r'(?<!\s)\s*\S\s*', s . strip(), overlapped=True) max_len = max(map(len, ss)) return [s . strip() for s in ss if len(s) == max_len]
Loneliest character
5f885fa9f130ea00207c7dc8
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/5f885fa9f130ea00207c7dc8
6 kyu
Let there be `k` different types of weather, where we denote each type of weather by a positive integer. For example, sunny = 0, rainy = 1, ..., cloudy = k. ### Task Find the probability of having weather `j` in `n` days from now given weather `i` today and conditional on some daily weather transition probabilities, ...
algorithms
import numpy as np ''' Parameters: - days (n) number of days for prediction, an integer - weather_today (i), an integer - final_whether (j) we want to predict in n days, an integer - P = [[p_11, ..., p_1k], [p_21, ..., p_2k], ..., [p_k1, ..., p_kk]], tranistion matrix, where p_xy is probab...
Weather prediction
602d1d769a1edc000cf59e4c
[ "Probability", "Algorithms", "Data Science" ]
https://www.codewars.com/kata/602d1d769a1edc000cf59e4c
6 kyu
This Kata is about spotting cyclic permutations represented in two-line notation. ### Introduction - A **permutation** of a set is a rearrangement of its elements. It is often the permutations of the set `(1, 2,...,n)` that are considered for studying permutations. - One way to represent a permutation is **two-line ...
reference
def is_cyclic(p): links = dict(zip(* p)) m = next(iter(links)) while m in links: m = links . pop(m) return not links
Cyclic Permutation Spotting
5f9d63c2ac08cb00338510f7
[ "Fundamentals", "Recursion" ]
https://www.codewars.com/kata/5f9d63c2ac08cb00338510f7
6 kyu
# Task You get a list of non-zero integers A, its length is always even and 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`. # Examples ```python # One of the possible solutions: W = [-10, -1...
reference
def weigh_the_list(a): return [w for i in range(0, len(a), 2) for w in [a[i + 1], - a[i]]]
Weigh The List #1
5fad2310ff1ef6003291a951
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5fad2310ff1ef6003291a951
6 kyu
_Yet another easy kata!_ ##### If you are newbie on CodeWars then I suggest you to go through [this](https://github.com/codewars/codewars.com/wiki/Troubleshooting-your-solution). # Background: _this kata is sort of educational too so, it you don't want to learn go away!_ \ CPU scheduling is a process which allows...
reference
def fcfs(lst): t, CT, TAT, WRT, dTP = (0,) * 5 for at, bt in sorted(lst): if t < at: dTP, t = dTP - (at - t), at ct = t + bt CT += ct WRT += t - at TAT += ct - at t += bt return tuple(round(v / len(lst), 2) for v in (CT, TAT, WRT, dTP + t))
Operating System Scheduling #1 : FCFS scheduling
5f0ea61fd997db00327e6c25
[ "Fundamentals" ]
https://www.codewars.com/kata/5f0ea61fd997db00327e6c25
6 kyu
**Introduction** Consider the first 16 terms of the series below: `11,32,53,94,135,176,217,298,379,460,541,622,703,784,865,1026...` which is generated by this sequence: `11,21,21,41,41,41,41,81,81,81,81,81,81,81,81,161...`. Each term `u` of the sequence is obtained by finding the: `(last power of 2) * 10 + 1` if ...
algorithms
from itertools import count def squared_digits_series(n): s = n for p in count(): p = 2 * * p x = min(p, n) s += 10 * p * x n -= x if n < 1: return s
Sequence of squared digits
5f8584916ddaa300013e1592
[ "Algorithms", "Mathematics", "Logic" ]
https://www.codewars.com/kata/5f8584916ddaa300013e1592
6 kyu
In this kata, you have an integer array which was ordered by ascending except one number. For Example: [1,2,3,4,17,5,6,7,8] For Example: [19,27,33,34,112,578,116,170,800] You need to figure out the first breaker. Breaker is the item, when removed from sequence, sequence becomes ordered by ascending. ...
reference
INF = float('inf') def order_breaker(lst): return next(b for a, b, c in zip([- INF] + lst, lst, lst[1:] + [INF]) if a <= c and (a > b or b > c))
Find the Order Breaker
5fc2a4b9bb2de30012c49609
[ "Fundamentals" ]
https://www.codewars.com/kata/5fc2a4b9bb2de30012c49609
6 kyu
<h2>Description</h2> Bob really likes to write his casual notes using a basic text editor.<br> He often uses tables to organize his informations but building them takes some time.<br> Would you help him to automatize the process ?<br> (No? Then keep an eye on your data 👀) <br><br> For example he would like the followi...
reference
def build_table(lst, style): if not lst: return '' align = {'left': '<', 'mid': '^', 'right': '>'}[style . align] pad = style . sep_hi * style . off_min sizes = [max(map(len, r)) for r in zip(* lst)] fullsize = sum(sizes) + style . off_min * 2 * len(sizes) + \ (len(sizes) - 1)...
Table Builder
5ff369c8ee41be0021770fee
[ "Algorithms", "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/5ff369c8ee41be0021770fee
6 kyu
## The task ~~~if:python,javascript, Consider a sequence, which is formed of re-sorted series of natural numbers. The terms of sequence are sorted by `steps to reach 1 (in Collatz iterations)` (ascending) and then by `value` (ascending). You are asked to write a generator, that yields the terms of the sequence in orde...
algorithms
def collatz(): seq = {1} while True: yield from sorted(seq) seq = {2 * x for x in seq} | {~ - x / / 3 for x in seq if x % 6 == 4} - {1}
Yet another Collatz kata
5fbfa1f738c33e00082025e0
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5fbfa1f738c33e00082025e0
6 kyu
# Make Chocolates Halloween is around the corner and we have to distribute chocolates. We need to assemble a parcel of `goal` grams of chocolates. The `goal` can be assumed to be always a positive integer value. - There are small chocolates (2 grams each) and big chocolates (5 grams each) - To reach the goal, th...
reference
def make_chocolates(s, b, n): bigs = min(n / / 5, b) n -= 5 * bigs if n & 1 and bigs: n += 5 smalls = min(s, n / / 2) return - 1 if n - 2 * smalls else smalls
Pack Some Chocolates
5f5daf1a209a64001183af9b
[ "Fundamentals" ]
https://www.codewars.com/kata/5f5daf1a209a64001183af9b
6 kyu
# Story You want to play a spinning wheel with your friend. Unfortunately, you have used all of your money to buy things that are more useful than a spinning wheel. So you have to create the rule and the spinning wheel yourself. # Task Your spinning wheel consists of sections which could be either __"Win"__ or __"Not W...
games
def spinning_wheel(wheel): n, k = len(wheel), wheel . count('W') return 100 * n / / (2 * n - k) if k else 0
Probability #1 : The Infinite Spinning Wheel
605d58ab7f229d001bac446e
[ "Mathematics", "Games", "Puzzles", "Probability" ]
https://www.codewars.com/kata/605d58ab7f229d001bac446e
6 kyu
Your job is to change the given string `s` using a non-negative integer `n`. Each bit in `n` will specify whether or not to swap the case for each alphabetic character in `s`: if the bit is `1`, swap the case; if its `0`, leave it as is. When you finish with the last bit of `n`, start again with the first bit. You sh...
reference
from itertools import cycle def swap(s, n): b = cycle(bin(n)[2:]) return "" . join(c . swapcase() if c . isalpha() and next(b) == '1' else c for c in s)
Swap Case Using N
5f3afc40b24f090028233490
[ "Fundamentals" ]
https://www.codewars.com/kata/5f3afc40b24f090028233490
6 kyu
#### Problem `b` boys and `g` girls went to the cinema and bought tickets for consecutive seats in the same row. Write a function that will tell you how to sit down for boys and girls, so that at least one girl sits next to each boy, and at least one boy sits next to each girl. ![picture](https://github.com/LarisaOvc...
reference
def cinema(x, y): if 2 * x >= y and 2 * y >= x: return "BGB" * (x - y) + "GBG" * (y - x) + "BG" * (min(x, y) - abs(x - y))
A Cinema
603301b3ef32ea001c3395d0
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/603301b3ef32ea001c3395d0
6 kyu
What date corresponds to the `n`<sup>th</sup> day of the year? The answer depends on whether the year is a leap year or not. Write a function that will help you determine the date if you know the number of the day in the year, as well as whether the year is a leap year or not. The function accepts the day number a...
reference
from datetime import * def get_day(days, is_leap): return (date(2019 + is_leap, 1, 1) + timedelta(days - 1)). strftime("%B, %-d")
Determine the date by the day number
602afedfd4a64d0008eb4e6e
[ "Fundamentals", "Date Time", "Algorithms" ]
https://www.codewars.com/kata/602afedfd4a64d0008eb4e6e
6 kyu
# Context In Dungeons and Dragons, a tabletop roleplaying game, movement is limited in combat. Characters can only move a set amount of distance per turn, meaning the distance you travel is very important. In the 5th edition of the rulebook, the board is commonly organized into a grid, but for ease of counting, moveme...
algorithms
def calc_distance(path): return 5 * sum( max(abs(a - b) for a, b in zip(p1, p2)) for p1, p2 in zip(path, path[1:]))
D&D: Non-Euclidian Movement
60ca2ce44875c5004cda5c74
[ "Algorithms", "Data Structures" ]
https://www.codewars.com/kata/60ca2ce44875c5004cda5c74
6 kyu
Would you believe me if I told you these particular tuples are special? (1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31) (2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31) (4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31) (8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31)...
games
def guess_number(answers): return int('' . join(map(str, reversed(answers))), 2) def answers_sequence(n): return list(map(int, reversed(f" { n :0 5 b } ")))
Impress your friends with Brown's Criterion!
604693a112b42a0016828d03
[ "Mathematics", "Logic", "Puzzles" ]
https://www.codewars.com/kata/604693a112b42a0016828d03
6 kyu
# Goal Print the Top Of Book of an orderbook # Introduction The state of each stock on a stock market is kept in a data structure called an orderbook. The orderbook consists of two sides, the "Buy Side", which represents offers to buy a stock, and the "Sell Side", which represents offers to sell a stock. The Buy Side...
algorithms
from collections import defaultdict def print_tob(feed): memo = {} for order in feed: if order[0] == 'c': del memo[order[1]] else: memo[order[2]] = (order[1], order[3], order[4]) res = defaultdict(lambda: defaultdict(int)) for side, quantity, price in memo . values...
Manage an Orderbook
5f3e7df1e0be5a00018a008c
[ "Algorithms" ]
https://www.codewars.com/kata/5f3e7df1e0be5a00018a008c
6 kyu
#### The following task has two parts. First you must figure out the principle behind the following encoding of natural numbers. The table below displays the encoding of the numbers from 0 to 11. **Number** -------> **Code** * `0 -------> '.'` * `1 -------> '()'` * `2 -------> '(())'` * `3 -------> '(.())'` * `4 -...
games
def puzzle(i): ps = set() def sp(i, p=2): if i == 1: return '' d = ps . add(p) or 0 while i % p == 0: d, i = d + 1, i / / p while any(p % q == 0 for q in ps): p += 1 return puzzle(d) + sp(i, p) return f'( { sp ( i )} )' if i else '.'
The Dots and Parentheses
5fe26f4fc09ce8002224e95d
[ "Algorithms", "Puzzles", "Strings" ]
https://www.codewars.com/kata/5fe26f4fc09ce8002224e95d
5 kyu
<h1>Task</h1> For given <strong style="color: red;">n</strong> (>0) points on the arc AB , and <strong style="color: green;">m</strong> (m>0) points on the diametr BA ,<br> write a function <strong>combinations(n , m)</strong> which returns a tuple of 2 numbers (or const array in JavaScript case) representing: <br> a)...
reference
from math import comb def combinations(n, m): return ( sum(comb(m + 2, i) * comb(n, 3 - i) for i in range(3)), sum(comb(m + 2, i) * comb(n, 4 - i) for i in range(3)), )
Combinations on semicircle
5f0f14348ff9dc0035690f34
[ "Combinatorics", "Fundamentals" ]
https://www.codewars.com/kata/5f0f14348ff9dc0035690f34
6 kyu
# Squared Spiral #1 Given the sequence of positive integers (0,1,2,3,4...), find out the coordinates (x,y) of a number on a square spiral, like the drawings bellow. ### Numbers ... ← 013 ← 012 ↑ ↑ ↑ ...
algorithms
def squared_spiral(n): b = round(n * * .5) e = (b / / 2 + b % 2 - max(0, b * * 2 - n), - (b / / 2) + max(0, n - b * * 2)) return e if b % 2 else (- e[0], - e[1])
Squared Spiral #1
60a38f4df61065004fd7b4a7
[ "Geometry", "Performance", "Algorithms" ]
https://www.codewars.com/kata/60a38f4df61065004fd7b4a7
6 kyu
You need to write a function that takes array of ```n``` colors and converts them to a linear gradient for example gradient from ```[r1, g1, b1]``` with position ```p1``` to ```[r2, g2, b2]``` with position ```p2``` in order to get the color of the gradient from ```p1``` to ```p2```, you need to find three functions...
algorithms
from itertools import groupby def create_gradient(colors): col_grad = sorted(colors, key=lambda x: x[1]) col_grad = [[* g][- 1] for k, g in groupby(col_grad, key=lambda x: x[1])] def lin_grad(pos): if not col_grad: return [0, 0, 0] ind = next((k for k, x in enumerate(col_grad) ...
Linear Color Gradient
607218fd3d84d3003685d78c
[ "Algorithms" ]
https://www.codewars.com/kata/607218fd3d84d3003685d78c
6 kyu
*Challenge taken from the [code.golf](https://code.golf/12-days-of-christmas) site* Return the lyrics of the song [The Twelve Days of Christmas](https://en.wikipedia.org/wiki/The_Twelve_Days_of_Christmas_(song)): ``` On the First day of Christmas My true love sent to me A partridge in a pear tree. On the Second day ...
games
A = """Twelve drummers drumming, Eleven pipers piping, Ten lords a-leaping, Nine ladies dancing, Eight maids a-milking, Seven swans a-swimming, Six geese a-laying, Five gold rings, Four calling birds, Three French hens, Two turtle doves, and A partridge in a pear tree.""" . split("\n") B = "First,...
[Code Golf] The Twelve Days of Christmas
6001a06c6aad37000873b48f
[ "Restricted", "Puzzles" ]
https://www.codewars.com/kata/6001a06c6aad37000873b48f
6 kyu
Reverse Number is a number which is the same when reversed. For example, the first 20 Reverse Numbers are: ``` 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101 ``` ```if:php In PHP, the parameter `$n` will be passed to the function `find_reverse_number` as a string, and the result should be retu...
algorithms
def find_reverse_number(n): """ Return the nth number in sequence of reversible numbers. For reversible numbers, a pattern emerges when compared to n: if we subtract a number made of a sequence of the digit 9 (i.e. 9, 99, 999, our magic number) from n, the result forms the left half of the nth r...
Find the nth Reverse Number (Extreme)
600c18ec9f033b0008d55eec
[ "Algorithms" ]
https://www.codewars.com/kata/600c18ec9f033b0008d55eec
4 kyu
Reverse Number is a number which is the same when reversed. For Example; 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101 => First 20 Reverse Numbers **TASK:** - You need to return the nth reverse number. (Assume that reverse numbers start from 0 as shown in the example...
algorithms
from itertools import count memo = [] def palgen(): yield 0 for digits in count(1): first = 10 * * ((digits - 1) / / 2) for s in map(str, range(first, 10 * first)): yield int(s + s[- (digits % 2) - 1:: - 1]) def gen_memo(): global memo for n in palgen(): memo . appen...
Find the nth Reverse Number
600bfda8a4982600271d6069
[ "Algorithms" ]
https://www.codewars.com/kata/600bfda8a4982600271d6069
6 kyu
## Problem All integers can be uniquely expressed as a sum of powers of 3 using each power of 3 **at most once**. For example: ```python 17 = (-1) + 0 + (-9) + 27 = (-1 * 3^0) + ( 0 * 3^1) + (-1 * 3^2) + (1 * 3^3) -8 = 1 + 0 + (-9) = ( 1 * 3^0) + ( 0 * 3^1) + (-1 * 3^2) 25 = 1 + (-3) + 0 + 27 = (...
reference
def as_sum_of_powers_of_3(n): if not n: return '0' r = '' while n != 0: k = n % 3 r += '0+-' [k] if k == 2: k = - 1 n = (n - k) / / 3 return r
Expressing Integers as Sum of Powers of Three
6012457c0aa675001d4d560b
[ "Fundamentals" ]
https://www.codewars.com/kata/6012457c0aa675001d4d560b
6 kyu
Ryomen Sukuna has entered your body, and he will only leave if you can solve this problem. Given an integer `n`, how many integers between `1` and `n` (inclusive) are unrepresentable as `$a^b$`, where `$a$` and `$b$` are integers not less than 2? Example: if `n` equals 10 then output must be 7, as 4 is representab...
reference
def sukuna(n): all_numbers, square = set(), int(n * * .5) + 1 for i in range(2, square): for j in range(2, square): if i * * j <= n: all_numbers . add(i * * j) else: break return n - len(all_numbers)
Ryomen Sukuna
607a8f270f09ea003a38369c
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/607a8f270f09ea003a38369c
6 kyu
# Convert Lambda To Def in this kata, you will be given a string with a lambda function in it. Your task is to convert that lambda function to a def function, with the exact same variables, the exact same name, and the exact same function it does. The function, like a normal `def` function should be returned on a sep...
reference
def convert_lambda_to_def(s): sheet = 'def {}({}):\n return{}' s = s . replace(' = lambda ', ':') name, arg, ret = s . split(':', 2) return sheet . format(name, arg, ret)
Convert Lambda To Def
605d25f4f24c030033da9afb
[ "Fundamentals", "Strings", "Regular Expressions" ]
https://www.codewars.com/kata/605d25f4f24c030033da9afb
6 kyu
## Task You are looking for teammates for an oncoming intellectual game in which you will have to answer some questions. It is known that each question belongs to one of the `n` categories. A team is called perfect if for each category there is at least one team member who knows it perfectly. You don't know any cate...
algorithms
from itertools import combinations def perfect_team_of_minimal_size(n, candidates): for j in range(1, len(candidates) + 1): if any(len(set(sum(i, []))) >= n for i in combinations(candidates, j)): return j + 1 return - 1
Simple Fun #243: Perfect Team Of MinimalSize
590a924c7dfc1a238d000047
[ "Algorithms" ]
https://www.codewars.com/kata/590a924c7dfc1a238d000047
6 kyu
# Description Your task is to create a class `Function`, that will be provided with 2 arguments - `f` & `df` - representing a function and its derivative. You should be able to do function algebra with this class, i.e. they can be added, subtracted, multiplied, divided and composed to give another `Function` object wi...
reference
class Function: def __init__(self, f, df): self . f = f self . df = df def __add__(self, other): def f(x): return self . f(x) + other . f(x) def df(x): return self . df(x) + other . df(x) return Function(f, df) def __sub__(self, other): def f(x): return self . f(x) - other...
Function Algebra
605f4035f38ca800072b6d06
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/605f4035f38ca800072b6d06
5 kyu
<h1><u>Gangs</u></h1> <p>Your math teacher is proposing a game with divisors, so that you can understand it better. The teacher gives you a <u>list of divisors</u> and a number <u>k</u>. You should find all the gangs in the range 1 to k.</p> <h4><u>What is a gang?</u></h4> <p>The numbers, which have the same subset of...
reference
def gangs(divisors, k): return len({tuple(y for y in divisors if x % y == 0) for x in range(1, k + 1)})
Gangs
60490a215465720017ab58fa
[ "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/60490a215465720017ab58fa
6 kyu
### Task Given three sides `a`, `b` and `c`, determine if a triangle can be built out of them. ### Code limit Your code can be up to `40` characters long. ### Note Degenerate triangles are not valid in this kata.
games
triangle = lambda * a: 2 * max(a) < sum(a)
[Code Golf] A Triangle?
60d20fe1820f1b004188ceed
[ "Puzzles", "Restricted" ]
https://www.codewars.com/kata/60d20fe1820f1b004188ceed
7 kyu
You have a function that takes an integer `n` and returns a list of length `n` of function objects that take an integer `x` and return `x` multiplied by the index of that object in this list(remember that in python the indexes of elements start from 0): ```python [f_0, f_1, ... f_n] ``` ``` f_0 returns x * 0, f_1 retur...
bug_fixes
def create_multiplications(l): return [lambda x, i=i: i * x for i in range(l)]
Bugs with late binding closure
60b775debec5c40055657733
[ "Debugging" ]
https://www.codewars.com/kata/60b775debec5c40055657733
6 kyu
## Task A list S will be given. You need to generate a list T from it by following the given process: 1) Remove the first and last element from the list S and add them to the list T. 2) Reverse the list S 3) Repeat the process until list S gets emptied. The above process results in the depletion of the list S. Your...
reference
from collections import deque def arrange(s): q = deque(s) return [q . pop() if 0 < i % 4 < 3 else q . popleft() for i in range(len(s))]
Back and forth then Reverse!
60cc93db4ab0ae0026761232
[ "Algorithms", "Performance", "Arrays" ]
https://www.codewars.com/kata/60cc93db4ab0ae0026761232
6 kyu
## How does an abacus work? An abacus is a mechanical tool for counting and performing simple mathematical operations. It consists of vertical poles with beads, where the position of the beads indicates the value stored on the abacus. The abacus in the image below, for example, is storing the number `1703`. <svg view...
reference
def create_abacus(n): n, res = map(int, str(n). zfill(9)), [] for d in n: a, b = divmod(d, 5) res . append(list("**-*****")) res[- 1][not a] = res[- 1][b + 3] = " " return "\n" . join(map("" . join, zip(* res))) def read_abacus(abacus): m, n = map("" . join, zip(* abacus . spli...
Representing Numbers on an Abacus
60d7a52b57c9d50055b1a1f7
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/60d7a52b57c9d50055b1a1f7
6 kyu
![a truth table](https://storage.googleapis.com/dycr-web/image/topic/logic-gate/xor-xnor/xor-table.png "XOR truth table") You are given a Boolean function (i.e. a function that takes boolean parameters and returns a boolean). You have to return a string representing the function's truth table. ~~~if:c In C, you will...
algorithms
def truth_table(f): vars = f . __code__ . co_varnames name = n if (n := f . __code__ . co_name) != "<lambda>" else "f" lines = [ f" { ' ' . join ( vars )} \t\t { name } ( { ',' . join ( vars )} )\n\n"] for i in range(0, 2 * * len(vars)): arg_values = tuple([int(x) for x in f" { i : 0...
Boolean function truth table
5e67ce1b32b02d0028148094
[ "Binary", "Algorithms" ]
https://www.codewars.com/kata/5e67ce1b32b02d0028148094
6 kyu
<h1 align="center">Subsequence Sums</h1> <hr> <h2> Task </h2> Given a sequence of integers named `arr`, find the number of continuous subsequences (sublist or subarray) in `arr` that sum up to `s`. A continuous subsequence can be defined as a sequence inbetween a start index and stop index (inclusive) of the sequence....
algorithms
from collections import defaultdict from itertools import accumulate def subsequence_sums(arr, s): res, memo = 0, defaultdict(int) for x in accumulate(arr, initial=0): res += memo[x - s] memo[x] += 1 return res
Subsequence Sums
60df63c6ce1e7b0023d4af5c
[ "Dynamic Programming", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/60df63c6ce1e7b0023d4af5c
5 kyu
### Task Consider a series of functions `$S_m(n)$` where: `$S_0(n) = 1$`<br> `$S_{m+1}(n) = \displaystyle\sum^n_{k=1}S_m(k)$` Write a function `s` which takes two integer arguments `m` and `n` and returns the value defined by `$S_m(n)$`. #### Inputs `0 <= m <= 100`<br> `1 <= n <= 10**100`
algorithms
from math import comb def S(m, n): return comb(m + n - 1, m)
Nth Order Summation
60d5b5cd507957000d08e673
[ "Mathematics", "Performance" ]
https://www.codewars.com/kata/60d5b5cd507957000d08e673
6 kyu
Your task is to find the last non-zero digit of `$n!$` (factorial). ``$n! = 1 \times 2 \times 3 \times \dots \times n$`` Example: If `$n = 12$`, your function should return `$6$` since `$12 != 479001\bold{6}00$` ### Input ```if:python,ruby,elixir Non-negative integer n Range: 0 - 2.5E6 ``` ```if:cpp,nasm,java...
algorithms
last_digit = l = lambda n, d = (1, 1, 2, 6, 4, 2, 2, 4, 2, 8): n < 10 and d[n] or ((6 - n / / 10 % 10 % 2 * 2) * l(n / / 5) * d[n % 10]) % 10
Last non-zero digit of factorial
5f79b90c5acfd3003364a337
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5f79b90c5acfd3003364a337
6 kyu
### Delta Generators In mathematics, the symbols `Δ` and `d` are often used to denote the difference between two values. Similarly, differentiation takes the ratio of changes (ie. `dy/dx`) for a linear relationship. This method can be applied multiple times to create multiple 'levels' of rates of change. (A common exa...
reference
def delta(iter_, n): iter_ = iter(iter_) if n == 1 else delta(iter_, n - 1) prev = next(iter_) for v in iter_: yield v - prev prev = v
Delta Generators
6040b781e50db7000ab35125
[ "Iterators", "Recursion" ]
https://www.codewars.com/kata/6040b781e50db7000ab35125
6 kyu
## Some but not all ### Description Your task is to create a function that given a sequence and a predicate, returns `True` if only some (but not all) the elements in the sequence are `True` after applying the predicate ### Examples ``` some('abcdefg&%$', str.isalpha) >>> True some('&%$=', str.isalpha) >>> False ...
reference
def some_but_not_all(seq, pred): return any(map(pred, seq)) and not all(map(pred, seq))
Some (but not all)
60dda5a66c4cf90026256b75
[ "Lists", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/60dda5a66c4cf90026256b75
7 kyu
Given a string, output the encoded version of that string. # Example: # ## Input: ## ```python,js 'When nobody is around, the trees gossip about the people who have walked under them.' ``` First, the input is normalized; Any character other than alphabetic characters should be removed from the text and the message is...
reference
import math def cipher_text(plain_text): text = "" . join(c . lower() for c in plain_text if c . isalpha()) s = math . sqrt(len(text)) a = math . floor(s) b = math . ceil(s) if a * b < len(text): a = b return " " . join(text[i:: b]. ljust(a, " ") for i in range(b))
Rectangle letter juggling
60d6f2653cbec40007c92755
[ "Strings", "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/60d6f2653cbec40007c92755
6 kyu
# Closure Counter - Define the function **counter** that returns a function that returns an increasing value. - The first value should be 1. - You're going to have to use closures. #### Example: > - const newCounter = counter(); > - newCounter() // 1 > - newCounter() // 2 ## Closure: > A closure is the combinati...
reference
def counter(): count = 0 def function(): nonlocal count count += 1 return count return function
Closure Counter
60edafd71dad1800563cf933
[ "Fundamentals" ]
https://www.codewars.com/kata/60edafd71dad1800563cf933
7 kyu
Given a balanced string with brackets like: "AA(XX((YY))(U))" find the substrings that are enclosed in the <strong>greatest depth</strong>.<br> <strong>Example:</strong><br> <strong>String</strong>:&ensp; A &ensp; A &ensp; <font color="green">(</font> &ensp; X &ensp; X &ensp; <font color="orange">(</font> &ensp; <fon...
algorithms
def strings_in_max_depth(s): start, deepest, lvl, out = 0, 0, 0, [s] for i, c in enumerate(s): if c == ')': if lvl == deepest: out . append(s[start: i]) lvl -= 1 elif c == '(': lvl += 1 start = i + 1 if lvl > deepest: out, deepest = [], lvl return out
Maximum Depth of Nested Brackets
60e4dfc1dc28e70049e2cb9d
[ "Strings", "Performance", "Algorithms" ]
https://www.codewars.com/kata/60e4dfc1dc28e70049e2cb9d
6 kyu
Let's define two functions: ```javascript S(N) — sum of all positive numbers not more than N S(N) = 1 + 2 + 3 + ... + N Z(N) — sum of all S(i), where 1 <= i <= N Z(N) = S(1) + S(2) + S(3) + ... + S(N) ``` You will be given an integer `N` as input; your task is to return the value of `S(Z(N))`. For example, let `N =...
reference
def sum_of_sums(n): def S(n): return (n * (n + 1)) / / 2 def Z(n): return (n * (n + 1) * (n + 2)) / / 6 return S(Z(n))
Sum the nums, sum the sums and sum the nums up to that sum
60d2325592157c0019ee78ed
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/60d2325592157c0019ee78ed
6 kyu
<h1 align="center"> Maximum Middle </h1> <h2> Task </h2> You will be given a sequence of integers represented by the array or list, `arr`, and the minimum length, `min_length` of a continuous subsequence (or a substring just applied to a list/array/sequence.) Then, return the maximum possible middle term of all possi...
reference
def maximum_median(arr, s): s / /= 2 return max(arr[s: - s or len(arr)])
Maximum Middle
60e238105b0327001434dfd8
[ "Fundamentals" ]
https://www.codewars.com/kata/60e238105b0327001434dfd8
7 kyu
# Corner Fill You receive a two dimensional array of size `n x n` and you want to fill in the square in one stroke while starting from `0:0` and ending on `n-1:0`. If `n = 3` then: ```rb [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] ``` Starting from left to right and then top to bottom we can grab the first corner! We ...
reference
def corner_fill(square): sq = square . copy() result = [] while True: try: result . extend(sq . pop(0)) result . extend(row . pop(- 1) for row in sq) result . extend([row . pop(- 1) for row in sq][:: - 1]) result . extend(sq . pop(0)[:: - 1]) except IndexError: break ...
Corner Fill
60b7d7c82358010006c0cda5
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/60b7d7c82358010006c0cda5
6 kyu
# Pig (dice game) Watch [this Numberphile video](https://www.youtube.com/watch?v=ULhRLGzoXQ0) for an introduction. The goal of Pig is to reach a total score of, say, 100, accumulated over multiple rounds by rolling a six-sided die. The players take turns in playing and, in each round, a player rolls the die as many t...
reference
from functools import lru_cache @ lru_cache(None) def stop_at(sides, target, curr_score=0): return curr_score if curr_score >= target else \ sum(stop_at(sides, target, curr_score + i) for i in range(2, sides + 1)) / sides
Pig Game
60b05d49639df900237ac463
[ "Fundamentals" ]
https://www.codewars.com/kata/60b05d49639df900237ac463
5 kyu
Your goal is to make a stack based programming language with the following functions/tokens: - `start` - Marks the start of the program. - `end` - Marks the end of the program, and returns the top element in the stack. - `push x` - Pushes the integer `x` into the stack. - `add` - Adds together the top two elements on...
games
def start(fn): return fn([]) def end(a): return a . pop() def push(a): return (lambda n: (lambda fn: fn(a + [n]))) def add(a): return (lambda fn: fn(a + [a . pop() + a . pop()])) def sub(a): return (lambda fn: fn(a + [a . pop() - a . pop()])) def mul(a): return (lambda fn: fn(a + [a . pop() * a...
A Bubbly Programming Language
5f7a715f6c1f810017c3eb07
[ "Puzzles" ]
https://www.codewars.com/kata/5f7a715f6c1f810017c3eb07
5 kyu
In Python, `==` tests for equality and `is` tests for identity. Two strings that are equal may also be identical, but this is not guaranteed, but rather an implementation detail. Given a computed expression, ensure that it is identical to the corresponding equal string literal by completing the `make_identical` functio...
reference
from sys import intern as make_identical
When we are equal, we are identical
60c47b07f24d000019f722a2
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/60c47b07f24d000019f722a2
7 kyu
# Background Your friend has come up with a way to represent any number using binary, but the number of bits can be infinite to represent even the smallest of numbers! He thinks it will be hard to break since just one number can be represented in so many different (and long) ways: `'000000000000000000000000' == 0` `...
games
def decode_bits(s): return s[1:: 2]. count('1') - s[:: 2]. count('1')
Infinite Length Binary Code
60c8bfa19547e80045184000
[ "Binary", "Puzzles", "Fundamentals" ]
https://www.codewars.com/kata/60c8bfa19547e80045184000
6 kyu