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
## Rummy In Rummy game, players must make melds of three or more cards from a hand of seven cards. There are two types of melds: * ___Sets:___ groups of three or more cards of the same face value for example `4♠ 4♥ 4♣`. * ___Runs:___ three or more sequential cards of the same suit such as `A♠ 2♠ 3♠`. We'll play an al...
algorithms
class Hand: ORDER = 'A23456789TJQK' PTS = {f: i for i, f in enumerate(ORDER, 1)} def __init__(self, hand): self . h = hand[:] self . score = float('inf') self . discard = None self . study() def get_hand(self): return self . h[:] def get_score(self): return self . score ...
Rummy: Find Lowest Scoring Hand
5b75aa794eb8801bd0000033
[ "Games", "Algorithms" ]
https://www.codewars.com/kata/5b75aa794eb8801bd0000033
3 kyu
# Task Mr.Right always tell the truth, Mr.Wrong always tell the lies. Some people are queuing to buy movie tickets, and one of them is Mr.Wrong. Everyone else is Mr.Right. Please judge who is Mr.Wrong according to their conversation. [[**Input**]] A string array: `conversation` They always talking about `I'm in .....
algorithms
from collections import deque, defaultdict from functools import cache def parse(s): name, rest = s . split(":") lst = rest . split(" ") if lst[- 1] == "position.": return (name, int("" . join(c for c in lst[- 2] if c . isdigit()))) elif lst[0] == "There": if lst[- 2] == "of": ...
Mr. Right & Mr. Wrong #2: Who is Mr.Wrong?
57a2e0dbe298a7fa4800003c
[ "Games", "Algorithms" ]
https://www.codewars.com/kata/57a2e0dbe298a7fa4800003c
2 kyu
## Preface This is the crazy hard version of the [Prime Ant - Performance Version](https://www.codewars.com/kata/prime-ant-performance-version/) kata. If you did not complete it yet, you should begin there. ## Description, task and examples Everything is exactly the same as in the previous version (see above). You s...
algorithms
LIMIT = 10 * * 7 / / 2 minimal_prime_factors = list(range(LIMIT + 1)) minimal_prime_factors[4:: 2] = (LIMIT / / 2 - 1) * [2] for i in range(3, int((LIMIT + 1) * * .5) + 1, 2): if minimal_prime_factors[i] == i: for j in range(i * i, LIMIT + 1, i): if minimal_prime_factors[j] == j: minimal_prime_fa...
Prime Ant - Crazy Version
5a54e01d80eba8014c000344
[ "Performance", "Memoization", "Algorithms" ]
https://www.codewars.com/kata/5a54e01d80eba8014c000344
3 kyu
Given a base between `2` and `62` ( inclusive ), and a non-negative number in that base, return the next bigger polydivisible number in that base, or an empty value like `null` or `Nothing`. A number is polydivisible if its first digit is cleanly divisible by `1`, its first two digits by `2`, its first three by `3`, a...
algorithms
from string import digits as d, ascii_uppercase as u, ascii_lowercase as l def next_num(b, n, s=d + u + l): digits = {d: i for i, d in enumerate(s[: b])} nxt, n = False, [s[0]] + list(n) inc, ptr, x = False, 1, 0 while 0 <= ptr < len(n): p = ptr + (ptr == 0 or n[0] > s[0]) inc |= ptr ...
Next polydivisible number in any base
5e4de3b05d0b5f0022501d5b
[ "Algorithms" ]
https://www.codewars.com/kata/5e4de3b05d0b5f0022501d5b
4 kyu
This kata concerns stochastic processes which often have to be repeated many times. We want to be able to randomly sample a long list of weighted outcomes quickly. For instance, with weights `[3, 1, 0, 1, 5]`, it's expected that index `4` occur 50% of the time, on average, and that index `2`, with no weight, never occ...
algorithms
from fractions import Fraction def make_table(weights): # Normalize probabilities n, den = len(weights), sum(weights) prob = [Fraction(w, den) * n for w in weights] # Initialize groups small, large = [], [] for i in range(len(prob)): (small if prob[i] < 1 else large). append(i)...
Random sampling in constant time
604a1de6d117a400159239e5
[ "Algorithms" ]
https://www.codewars.com/kata/604a1de6d117a400159239e5
5 kyu
# Task John won the championship of a TV show. He can get some bonuses. He needs to play a game to determine the amount of his bonus. Here are `n` rows and `m` columns of cards were placed on the ground. A non-negative number is written on each card. The rules of the game are: - Player starts from the top-left con...
algorithms
def calc(gamemap): nr, nc = len(gamemap), len(gamemap[0]) def _i(ra, rb): return ra * nr + rb vs, ws = [0] * nr * * 2, [0] * nr * * 2 for s in range(nr + nc - 1): for ra in range(max(0, s - nc + 1), min(s + 1, nr)): for rb in range(ra, min(s + 1, nr)): ws[_i(ra, rb)] = ( ...
Kata 2019: Bonus Game II
5c2ef8c3a305ad00139112b7
[ "Algorithms", "Dynamic Programming", "Performance" ]
https://www.codewars.com/kata/5c2ef8c3a305ad00139112b7
5 kyu
# Basic golf rules You find yourself in a rectangular golf field like this one (ignore the borders): ``` +----------+ | ** ***| | ***| |****## | | ** | |* F| +----------+ ``` In these fields you can find empty spaces, bushes (`*`), walls (`#`) and a flag (`F`). You start from a position with...
algorithms
golf = a = lambda f, i, j, h, b = 0: all([i + 1, len(f) > i, j + 1, len(f[0]) > j, h + 1]) and (g := f[i][j]) != '#' and (g == 'F' or any((a(f, c / / 3 + i - 1, c % 3 + j - 1, h - (b != c), c) for c in [1, 3, 5, 7] if b == c or '*' != g)))
Golf [Code Golf]
5e91c0f2b89d48002eee828b
[ "Restricted", "Algorithms" ]
https://www.codewars.com/kata/5e91c0f2b89d48002eee828b
4 kyu
## Background ### Adjacency matrix An adjacency matrix is a way of representing the connections between nodes in a graph. For example, the graph 0 -- 1 / \ 2 - 3 can be represented as ```math \begin{bmatrix} 0 & 1 & 0 & 0\\ 1 & 0 & 1 & 1\\ 0 & 1 & 0 & 1\\ 0 & 1 & 1 & 0 \end{bmatrix} ```...
algorithms
def maximum_clique(adjacency): """Maximum clique algorithm by Carraghan and Pardalos""" if not adjacency: return set() graph = {} for a, row in enumerate(adjacency): for b, connected in enumerate(row): if connected: graph . setdefault(a, set()). add(b) if not graph: ...
Maximum clique
55064222d54715566800043d
[ "Algorithms" ]
https://www.codewars.com/kata/55064222d54715566800043d
4 kyu
Given a height map as a 2D array of integers, return the volume of liquid that it could contain. For example: heightmap: 8 8 8 8 6 6 6 6 8 0 0 8 6 0 0 6 8 0 0 8 6 0 0 6 8 8 8 8 6 6 6 0 filled: 8 8 8 8 6 6 6 6 8 8 8 8 6 6 6 6 8 8 8 8 6 6 6 6 8 8 8 8 6 6 6 0 ...
algorithms
from heapq import heapify, heappop, heappush def volume(heightmap): N, M = len(heightmap), len(heightmap[0]) if N < 3 or M < 3: return 0 heap, seen = [], [[0] * M for _ in range(N)] for x in range(N): for y in range(M): if not x * y or x + 1 == N or y + 1 == M: heap . appe...
Fluid Volume of a Heightmap
5b98dfa088d44a8b000001c1
[ "Algorithms" ]
https://www.codewars.com/kata/5b98dfa088d44a8b000001c1
3 kyu
<img src="https://i.imgur.com/ta6gv1i.png?1" /> --- # Hint This Kata is an extension of the earlier ones in this series. Completing those first will make this task easier. # Background My TV remote control has arrow buttons and an `OK` button. I can use these to move a "cursor" on a logical screen keyboard to ty...
algorithms
H, W = 6, 8 KEYBOARD = ["abcde123fghij456klmno789pqrst.@0uvwxyz_/\u000e ", "ABCDE123FGHIJ456KLMNO789PQRST.@0UVWXYZ_/\u000e ", "^~?!'\"()-:;+&%*=<>€£$¥¤\\[]{},.@§#¿¡\u000e\u000e\u000e_/\u000e "] MAP = [{c: (i / / W, i % W) for i, c in enumerate(KEYBOARD[x])} for x in range(len(KEYBOARD))] ...
TV Remote (symbols)
5b3077019212cbf803000057
[ "Algorithms" ]
https://www.codewars.com/kata/5b3077019212cbf803000057
5 kyu
This kata is similar to [All Balanced Parentheses](https://www.codewars.com/kata/5426d7a2c2c7784365000783). That kata asks for a list of strings representing all of the ways you can balance `n` pairs of parentheses. Imagine that list being sorted alphabetically (where `'(' < ')'`). In this kata we are interested in the...
reference
from math import factorial dyck = [factorial(2 * i) / / (factorial(i) * factorial(i + 1)) for i in range(201)] def dyck_triangle(n): arr = [[0 for j in range(2 * n + 1)] for i in range(n + 1)] for i in range(n + 1): arr[i][2 * n - i] = 1 for i in range(n + 1): arr[0][2 * (n - i)] = dyck[i...
Balanced parentheses string
60790e04cc9178003077db43
[ "Algorithms", "Dynamic Programming" ]
https://www.codewars.com/kata/60790e04cc9178003077db43
4 kyu
It is a kata to practice knapsack problem. https://en.wikipedia.org/wiki/Knapsack_problem You get a list of items and an integer for the limit of total weights `(w_limit)`. Each item is represented by `(weight, value)` Return the list of maximum total value with the sorted lists of all lists of values that are also s...
algorithms
def knapsack(items, w_limit): dpt = {0: [[0, [[]]] for _ in range(w_limit + 1)]} for i in range(len(items)): dpt[i + 1] = [] for j in range(w_limit + 1): if items[i][0] > j or dpt[i][j - items[i][0]][0] + items[i][1] < dpt[i][j][0]: dpt[i + 1]. append(dpt[i][j]) elif dpt[i][j - items[...
Knapsack problem - the max value with the lists of elements
5c2256acb26767ff56000047
[ "Algorithms" ]
https://www.codewars.com/kata/5c2256acb26767ff56000047
4 kyu
## Play game Series #8: Three Dots ### Welcome In this kata, we'll playing with three dots. ### Task You are given a `gamemap`, like this: ``` +------------+ |RGY | +,-,| --> The boundary of game map | | * --> The obstacle | ** | R,G,Y --> Three Dots with different color(red,green,ye...
games
from heapq import * import re MOVES = ((0, 1), (0, - 1), (1, 0), (- 1, 0)) BACK = {dxy: c for dxy, c in zip(MOVES, '→←↓↑')} def three_dots(game_map): class Dot: __slots__ = 'rgy h dist' . split() def __init__(self, dct, chars='rgy', d=None): self . rgy = r, g, y = tuple(map(dct . __getit...
Three Dots--Play game Series #8
59a67e34485a4d1ccb0000ae
[ "Puzzles", "Games", "Game Solvers" ]
https://www.codewars.com/kata/59a67e34485a4d1ccb0000ae
2 kyu
A right truncatable prime is a prime with the property that, if you remove the rightmost digit, the result will be prime, and you can repeat this until the number is one digit (by definition, one-digit primes are right-truncatable). An example of this in base 10 is 37397: the number itself is a prime, as is 3739, 373,...
algorithms
def get_right_truncatable_primes(base): primes, bag = [], list(filter(fast_is_prime, range(2, base))) while bag: leaf, n = True, bag . pop(0) for x in range(base * n, base * (n + 1)): if fast_is_prime(x): leaf = False bag . append(x) if leaf: primes . append(n) return p...
Right truncatable primes in a given base
5f3db6f4c6197b00151ceae8
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5f3db6f4c6197b00151ceae8
4 kyu
__Pick Until Match__ is a pure game of chance featuring several meters with associated point values. A single player picks and removes hidden items until one of the meters tops off, at which point that meter awards and the game ends. This form of entertainment is sometimes seen with bonus rounds on gambling machines, a...
algorithms
from math import factorial, comb, gcd from collections import Counter from functools import reduce def partition(n, xs): if not xs: return 0 if n else 1 h, * t = xs return sum(comb(h, k) * partition(n - k, t) for k in range(min(h, n + 1))) def count(x, xs): n = x + sum(xs) re...
Pick Until Match
604064f13daac00013a8ef2a
[ "Algorithms", "Probability", "Combinatorics" ]
https://www.codewars.com/kata/604064f13daac00013a8ef2a
4 kyu
## Theory Binary relation is a system which encodes relationship between elements of 2 sets of elements. If a pair `(x, y)` is present in a binary relation, it means that the element `x` from the first set is related to the element `y` from the second set. One of the spheres where binary relations are used is decisio...
algorithms
def find_vertices(adj): opt, todo = set(), {* range(len(adj))} while todo: new = {x for x in todo if not any(adj[y][x] for y in todo)} todo -= new todo -= {x for y in new for x in todo if adj[y][x]} opt |= new return sorted(opt)
Binary relation optimization
603928e6277a4e002bb33d5a
[ "Algorithms", "Graph Theory" ]
https://www.codewars.com/kata/603928e6277a4e002bb33d5a
5 kyu
## Task For every Lambda calculus<sup>[wiki](https://en.wikipedia.org/wiki/Lambda_calculus)</sup> combinator, infinitely many equivalent SKI calculus<sup>[wiki](https://en.wikipedia.org/wiki/SKI_combinator_calculus)</sup> combinators exist. Define a function that accepts a Lambda calculus combinator, as a string, an...
reference
def parse_term(s, start=0): terms = [] i = start while i < len(s): c = s[i] i += 1 if c == '(': term, end = parse_term(s, i) terms . append(term) i = end elif c == 'λ': fn, end = parse_fn(s, i) terms . append(fn) i = end elif c == ')': break ...
Abstraction elimination
601c6f43bee795000d950ed1
[ "Fundamentals" ]
https://www.codewars.com/kata/601c6f43bee795000d950ed1
3 kyu
## Background An old rich man buried many diamonds in a large family farm. He passed a secret map to his son. The map is divided into many small square parcels. The number of diamonds in each parcel is marked on the map. Now the son wants to sell off some land parcels. The buyer knows about the diamonds and wishes to g...
games
def count_diamonds(a, q): n = len(a) m = len(a[0]) if q == 0: return [[[i, j], [i, j]] for i in range(n) for j in range(m) if a[i][j] == 0] ans = [] size = n * m for u in range(n): s = [0] * (m) for d in range(u, n): l = 0 cur = 0 for r in range(m): s...
Counting diamonds
5ff0fc329e7d0f0010004c03
[ "Algorithms", "Puzzles" ]
https://www.codewars.com/kata/5ff0fc329e7d0f0010004c03
4 kyu
## Task Write a function which accepts a string consisting only of `'A'`, `'B'`, `'X'` and `'Y'`, and returns the maximum possible number of pairwise connections that can be made. ### Rules 1. You can connect `A` with `B` or `B` with `A` or `X` with `Y` or `Y` with `X`. 1. Each letter can participate in such connect...
games
def match(s, conns=dict(zip('ABXY', 'BAYX'))): dp = [[0]] for j, c in enumerate(s): dp . append([ max([dp[j][i]] + [ dp[k][i] + 1 + dp[j][k + 1] for k in range(i, j) if s[k] == conns[s[j]] ]) for i in range(j + 1)] + [0]) return dp[- 1][0]
Connect Letters
58f5f479bc60c6898d00009e
[ "Algorithms", "Dynamic Programming", "Puzzles" ]
https://www.codewars.com/kata/58f5f479bc60c6898d00009e
4 kyu
### If you like more challenges, here is [a harder verion of this Kata.](https://www.codewars.com/kata/5f70eac4a27e7a002eccf941) --- # Four Color Theorem In mathematics, the four color theorem, or the four color map theorem, states that, given any separation of a plane into contiguous regions, producing a figure call...
algorithms
from itertools import product def color(testmap): m = {r: i for i, r in enumerate(set(testmap . replace('\n', '')))} g = testmap . strip(). split('\n') h, w = len(g), len(g[0]) adj = set() for y, x in product(range(h), range(w)): if y + 1 < h and g[y][x] != g[y + 1][x]: adj ....
Four Color Theorem (Easy Version)
5f88a18855c6c100283b3773
[ "Algorithms", "Graph Theory" ]
https://www.codewars.com/kata/5f88a18855c6c100283b3773
4 kyu
## Removing Internal Vertices A two dimensional mesh can be defined by a list of triangles. These triangles are references (by index) to vertices; positions in 2D space. Here is such a mesh: <center> <img src="https://docs.google.com/uc?id=1Pm2XmPzVIaJ_3RNalIbttr2mn2khswE4"> </center> ## Task For this task, you wil...
algorithms
from typing import List, Tuple, Set from collections import defaultdict def remove_internal(triangles: List[Tuple[int, int, int]]) - > Set[int]: table = defaultdict(int) for i, j, k in triangles: table[(min(i, j), max(i, j))] += 1 table[(min(k, j), max(k, j))] += 1 table[(min(i, k), max(i, k))] +=...
Removing Internal Vertices
5da06d425ec4c4001df69c49
[ "Geometry", "Algorithms" ]
https://www.codewars.com/kata/5da06d425ec4c4001df69c49
5 kyu
## TL;DR ~~~if-not:haskell Given a number of vertices `N` and a list of weighted directed edges in a directed acyclic graph (each edge is written as `[start, end, weight]` where `start < end`), compute the weight of the shortest path from vertex `0` to vertex `N - 1`. If there is no such path, return `-1`. ~~~ ~~~if:...
algorithms
def shortest(n, edges): m = [0] + [float('inf')] * (n - 1) for start, end, weight in sorted(edges): if m[start] == float('inf'): continue m[end] = min(m[start] + weight, m[end]) return - 1 if m[- 1] == float('inf') else m[- 1]
Dynamic Programming #1: Shortest Path in a Weighted DAG
5a2c343e8f27f2636c0000c9
[ "Dynamic Programming", "Algorithms", "Graph Theory" ]
https://www.codewars.com/kata/5a2c343e8f27f2636c0000c9
5 kyu
David wants to travel, but he doesn't like long routes. He wants to decide where he will go, can you tell him the shortest routes to all the cities? Clarifications: - David can go from a city to another crossing more cities - Cities will be represented with numbers - David's city is always the number 0 - If there ...
algorithms
# Doesn't work because of paths with 0 weight from scipy . sparse import csr_matrix from scipy . sparse . csgraph import shortest_path def shortest_routes(n, routes): graph = [[0] * n for _ in range(n)] for i, j, x in routes: graph[i][j] = x return list(enumerate(shortest_path(csgraph=csr...
The Shortest Routes
5f60407d1d026a00235d047d
[ "Graphs" ]
https://www.codewars.com/kata/5f60407d1d026a00235d047d
null
The Dynamic Connectivity Problem Given a set of of N objects, is there a path connecting the two objects? Implement an class that implements the following API: * Takes n as input, initializing a data-structure with N objects (0...N-1) * Implements a Union command that adds a connection between point p and poin...
algorithms
# 10 times faster than naive class DynamicConnectivity (object): def __init__(self, n): self . items = {i: {i} for i in range(n)} def union(self, p, q): if self . items[p] is not self . items[q]: for x in self . items[q]: self . items[p]. add(x) self . items[x] = self . items[p] ...
Dynamic Connectivity
58936eb3d160ee775d000018
[ "Algorithms" ]
https://www.codewars.com/kata/58936eb3d160ee775d000018
4 kyu
# The Kata Your task is to transform an input nested list into an hypercube list, which is a special kind of nested list where each level must have the very same size, This Kata is an exercise on recursion and algorithms. You will need to visualize many aspects of this question to be able to solve it efficiently, as su...
algorithms
from itertools import zip_longest def normalize(lst, growing=0): def seeker(lst, d=1): yield len(lst), d for elt in lst: if isinstance(elt, list): yield from seeker(elt, d + 1) def grower(lst, d=1): return [grower(o if isinstance(o, list) else [o] * size, d + 1) ...
Hypercube Lists
5aa859ad4a6b3408920002be
[ "Algorithms", "Lists", "Recursion" ]
https://www.codewars.com/kata/5aa859ad4a6b3408920002be
4 kyu
<style> pre.handle{ height: 2em; width: 4em; margin: auto; margin-bottom: 0 !important; background: none !important; border-radius: 0.5em 0.5em 0 0; border-top: 5px solid saddlebrown; border-left: 5px solid saddlebrown; border-right: 5px solid saddlebrown;...
algorithms
from itertools import chain def fit_bag(H, W, items): def deploy(item): X, Y = len(item), len(item[0]) v = (set(chain . from_iterable(item)) - {0}). pop() deltas = [(x, y) for x, r in enumerate(item) for y, n in enumerate(r) if n] return (len(deltas), X * Y, max(X, Y), min(X, Y), X, Y, d...
I hate business trips
5e9c8a54ae2b040018f68dd9
[ "Algorithms" ]
https://www.codewars.com/kata/5e9c8a54ae2b040018f68dd9
4 kyu
# Overview The goal here is to solve a puzzle (the "pieces of paper" kind of puzzle). You will receive different pieces of that puzzle as input, and you will have to find in what order you have to rearrange them so that the "picture" of the puzzle is complete. <br> ## Puzzle pieces All the pieces of the puzzle will...
games
def puzzle_solver(pieces, w, h): memo, D, result = {}, {None: (None, None)}, [[None] * w for _ in range(h)] for (a, b), (c, d), id in pieces: memo[(a, b, c)] = id D[id] = (c, d) for i in range(h): for j in range(w): a, b = D[result[i - 1][j]] _, c = D[result[i][j - 1]] r...
Solving a puzzle by matching four corners
5ef2bc554a7606002a366006
[ "Games", "Performance", "Puzzles" ]
https://www.codewars.com/kata/5ef2bc554a7606002a366006
4 kyu
Your task is to create a change machine. The machine accepts a single coins or notes, and returns change in 20p and 10p coins. The machine will try to avoid returning its exact input, but will otherwise return as few coins as possible. For example, a 50p piece should become two 20p pieces and one 10p piece, but a 20p ...
reference
def change_me(money): match money: case "£5": return " " . join(["20p"] * 25) case "£2": return " " . join(["20p"] * 10) case "£1": return " " . join(["20p"] * 5) case "50p": return "20p 20p 10p" case "20p": return "10p 10p" case _: return money
Simple Change Machine
57238766214e4b04b8000011
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/57238766214e4b04b8000011
8 kyu
The eight queens puzzle is the problem of placing eight chess queens on an 8×8 chessboard so that no two queens threaten each other. Thus, a solution requires that no two queens share the same row, column or diagonal. The eight queens puzzle is an example of the more general N queens problem of placing N non-attacking ...
algorithms
from random import choice def no_solution(n, fix): # checks whether it is a no solution case. return True if n == 2 or n == 3 or n == 4 and fix in [(0, 0), (0, 3), (3, 0), (3, 3), (1, 1), (1, 2), (2, 1), (2, 2)] or n == 6 and fix in [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (0, 5), (1, 4), (2, 3), (3,...
N queens problem (with one mandatory queen position) - challenge version
5985ea20695be6079e000003
[ "Algorithms", "Mathematics", "Performance" ]
https://www.codewars.com/kata/5985ea20695be6079e000003
1 kyu
The snake cube is a puzzle consisting of `27` small wooden cubes connected by an elastic string. The challenge is the twist the string of cubes into a complete `3 x 3 x 3` cube. Some of the small cubes are threaded straight through the centre. Others are threaded at a right-angle - this allows the solver to change di...
games
from itertools import product def solve(config): def get_angles(a, b, c): return (b, c, a), (- b, - c, - a), (c, a, b), (- c, - a, - b) def dfs(pos, d, iC): out . append(pos) cube . remove(pos) if not cube: return True to_check = get_angles(* d) if config[iC] else ...
Snake Cube Solver
5df653efc6ba5100191e602f
[ "Recursion", "Geometry", "Puzzles", "Algorithms", "Game Solvers", "Graph Theory" ]
https://www.codewars.com/kata/5df653efc6ba5100191e602f
4 kyu
Removed due to copyright infringement. <!--- ### Task An `amazon` (also known as a queen+knight compound) is an imaginary chess piece that can move like a `queen` or a `knight` (or, equivalently, like a `rook`, `bishop`, or `knight`). The diagram below shows all squares which the amazon attacks from e4 (circles repr...
games
from itertools import count # Natural directions of moves for king or queen (one step) ALL_MOVES = [(1, 1), (0, 1), (1, 0), (- 1, 0), (0, - 1), (- 1, 1), (1, - 1), (- 1, - 1)] AMA_MOVES = [(1, 2), (2, 1), (- 1, 2), (2, - 1), (1, - 2), (- 2, 1), (- 1, - 2), (- 2, - 1)] # Knight moves for amazo...
Chess Fun #8: Amazon Checkmate
5897f30d948beb78580000b2
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/5897f30d948beb78580000b2
4 kyu
<a href="https://preview.mailerlite.com/d5g0h3/1389145903520025821/l1w0/" target="_blank"><img src="https://i.imgur.com/ta6gv1i.png?1" title="source: imgur.com"></a> <a href="https://en.wikipedia.org/wiki/Laura_Bassi">Laura Bassi</a> was the first female professor at a European university. Despite her immense intell...
algorithms
def advice(agents, n): frontier = {(x, y) for x, y in agents if 0 <= x < n and 0 <= y < n} bag = {(x, y) for x in range(n) for y in range(n)} if frontier == bag: return [] while frontier and bag > frontier: bag -= frontier frontier = {pos for x, y in frontier for pos in ( ...
Find the safest places in town
5dd82b7cd3d6c100109cb4ed
[ "Algorithms" ]
https://www.codewars.com/kata/5dd82b7cd3d6c100109cb4ed
5 kyu
You're stuck in a maze and have to escape. However, the maze is blocked by various doors and you'll need the correct key to get through a door. --- ## Basic instructions You are given a grid as the input and you have to return the positions to go through to escape. To escape, you have to collect every key and then ...
algorithms
from collections import deque from itertools import chain, product def escape(grid): nr, nc = len(grid), len(grid[0]) open = {x for x in chain . from_iterable( grid) if x != '#' and not x . isupper()} all_keys = {x . upper() for x in chain . from_iterable(grid) if x . islo...
Escape!
5dc49700c6f56800271424a5
[ "Algorithms" ]
https://www.codewars.com/kata/5dc49700c6f56800271424a5
3 kyu
A "graph" consists of "nodes", also known as "vertices". Nodes may or may not be connected with one another. In our definition below the node "A0" is connected with the node "A3", but "A0" is not connected with "A1". The connecting line between two nodes is called an edge. If the edges between the nodes are undirecte...
reference
from collections import deque class Graph (): def __init__(self, vertices_num): self . v = vertices_num def adjmat_2_graph(self, adjm): d = {f'A { i } ': [] for i in range(self . v)} for i, j in enumerate(adjm): for k, l in enumerate(j): if l: d[f'A { i } ']. append((f...
Undirected weighted graph
5aaea7a25084d71006000082
[ "Fundamentals", "Lists", "Matrix", "Graph Theory" ]
https://www.codewars.com/kata/5aaea7a25084d71006000082
4 kyu
## Minimal Cost Binary Search Trees The description that follows presumes that you have completed [Binary Search Trees](http://www.codewars.com/kata/binary-search-trees). Before starting on this kata, fill in the code for `Tree`'s `__eq__`, `__ne__`, and `__str__` methods as described and verified by that kata. Imagi...
reference
import math from functools import cache class Tree (object): def __init__(self, root, left=None, right=None): assert root and type(root) == Node if left: assert type(left) == Tree and left . root < root if right: assert type(right) == Tree and root < right . root self . left = left...
Minimal Cost Binary Search Trees
571a7c0cf24bdf99a8000df5
[ "Algorithms", "Binary Search Trees", "Fundamentals" ]
https://www.codewars.com/kata/571a7c0cf24bdf99a8000df5
3 kyu
Ever heard about Dijkstra's shallowest path algorithm? Me neither. But I can imagine what it would be. You're hiking in the wilderness of Northern Canada and you must cross a large river. You have a map of one of the safer places to cross the river showing the depths of the water on a rectangular grid. When crossing t...
algorithms
from heapq import * MOVES = tuple((dx, dy) for dx in range(- 1, 2) for dy in range(- 1, 2) if dx or dy) def shallowest_path(river): lX, lY = len(river), len(river[0]) pathDct = {} cost = [[(float('inf'), float('inf'))] * lY for _ in range(lX)] for x in range(lX): cost...
Shallowest path across the river
585cec2471677ee42c000296
[ "Algorithms", "Graph Theory" ]
https://www.codewars.com/kata/585cec2471677ee42c000296
4 kyu
<!--Area of House from Path of Mouse--> <img src='https://i.imgur.com/IVdNZe1.png'/><br/> <sup style='color:#ccc'><i>Above: An overhead view of the house in one of the tests. The green outline indicates the path taken by K</i></sup> <p>A mouse named K has found a new home on Ash Tree Lane. K wants to know the size of t...
algorithms
def add_point(ori, dis, c): lastPoint = c[- 1] if ori == "N": c . append((lastPoint[0], lastPoint[1] + dis)) elif ori == "S": c . append((lastPoint[0], lastPoint[1] - dis)) elif ori == "E": c . append((lastPoint[0] + dis, lastPoint[1])) else: c . append((lastPoint[0] - dis, ...
Area of House from Path of Mouse
5d2f93da71baf7000fe9f096
[ "Strings", "Puzzles", "Algorithms" ]
https://www.codewars.com/kata/5d2f93da71baf7000fe9f096
4 kyu
<img src="https://i.imgur.com/ta6gv1i.png?1" title="weekly coding challenge" /> x 3 *I bet you won't ever catch a Lift (a.k.a. elevator) again without thinking of this Kata !* <hr> # Synopsis A multi-floor building has a Lift in it. People are queued on different floors waiting for the Lift. Some people want to ...
algorithms
class Dinglemouse (object): def __init__(self, queues, capacity): self . inLift, self . moves = [], [0] self . peopleOnFloorsLists = [list(floor) for floor in queues] self . stage, self . moving = - 1, 1 self . capacity = capacity def theLift(self): while self . areStillPeopleToBe...
The Lift
58905bfa1decb981da00009e
[ "Algorithms", "Queues", "Data Structures" ]
https://www.codewars.com/kata/58905bfa1decb981da00009e
3 kyu
# Overview: The idea of this kata is to create two classes, `Molecule` and `Atom`, that will allow you, using a set of methods, to build numerical equivalents of organic compounds and to restitute some of their simplest properties (molecular weight and raw formula, for instance). You will need to implement some Except...
reference
from collections import Counter from functools import wraps class InvalidBond (Exception): pass class UnlockedMolecule (Exception ): pass class LockedMolecule (Exception ): pass class EmptyMolecule (Exception ): pass class Atom (object): __slo...
Full Metal Chemist #1: build me...
5a27ca7ab6cfd70f9300007a
[ "Object-oriented Programming", "Fundamentals" ]
https://www.codewars.com/kata/5a27ca7ab6cfd70f9300007a
2 kyu
# Disclaimer If you're not yet familiar with the puzzle called Nonogram, I suggest you to solve [5x5 Nonogram Solver](https://www.codewars.com/kata/5x5-nonogram-solver/python) first. # Task Complete the function `solve(clues)` that solves 15-by-15 Nonogram puzzles. Your algorithm has to be clever enough to solve al...
games
from itertools import groupby from collections import defaultdict POS, B = defaultdict(set), 15 f = "{:0>" + str(B) + "b}" for n in range(1 << B): s = f . format(n) POS[tuple(sum(1 for _ in g) for k, g in groupby(s) if k == '1')]. add(tuple(map(int, s))) def solve(clues): clues ...
15x15 Nonogram Solver
5a5072a6145c46568800004d
[ "Puzzles", "Games", "Performance", "Game Solvers" ]
https://www.codewars.com/kata/5a5072a6145c46568800004d
2 kyu
## Description You are the Navigator on a pirate ship which has just collected a big haul from a raid on an island, but now you need to get home! Your captain has given you an intended course for your passage from the island - but the Royal Navy is on patrol! you need to tell your captain whether you will be able to m...
games
def check_course(sea): def canPassAround(c, isBottom): for dy in range(- 1, 2): y = c + dy if 0 <= y <= mY: turned, actualX = divmod(y, mX) if isBottom ^ turned % 2: actualX = mX - actualX boat, navy = (ship, y), (actualX, c) dist = sum((a - b) * * 2 for a, b in zip(bo...
Escape with your booty!
5b0560ef4e44b721850000e8
[ "Puzzles", "Games", "Matrix", "Simulation" ]
https://www.codewars.com/kata/5b0560ef4e44b721850000e8
5 kyu
Given two times in hours, minutes, and seconds (ie '15:04:24'), add or subtract them. This is a 24 hour clock. Output should be two digits for all numbers: hours, minutes, seconds (ie '04:02:09'). ``` timeMath('01:24:31', '+', '02:16:05') === '03:40:36' timeMath('01:24:31', '-', '02:31:41') === '22:52:50' ```
algorithms
from functools import reduce def f(s): return reduce(lambda a, b: a * 60 + int(b), s . split(":"), 0) def time_math(time1, op, time2): t1, t2 = f(time1), f(time2) n = t1 + t2 if op == '+' else t1 - t2 hr, mn, sc = n / / 3600 % 24, n / / 60 % 60, n % 60 return "%02d:%02d:%02d" % (hr, mn, ...
Time Math
5aceae374d9fd1266f0000f0
[ "Date Time", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5aceae374d9fd1266f0000f0
6 kyu
<!--Gerrymander Solver--> <img src="https://i.imgur.com/8UQHI9E.jpg"> <p><span style='color:#8df'><b><a href='https://en.wikipedia.org/wiki/Gerrymandering' style='color:#9f9;text-decoration:none'>gerrymander</a></b></span> — <i>noun.</i> the dividing of a state, county, etc., into election districts so as to give one p...
algorithms
def moves(p): if p < 25 and p % 5 != 4: yield p + 1 if p >= 5: yield p - 5 if p >= 0 and p % 5 != 0: yield p - 1 if p < 20: yield p + 5 def gerrymander(s): so = [1 if c == 'O' else 0 for c in s if c != '\n'] mp = [0] * 25 def dfs(pp, p0, k, ko, n, no): ...
Gerrymander Solver
5a70285ab17101627a000024
[ "Puzzles", "Logic", "Algorithms" ]
https://www.codewars.com/kata/5a70285ab17101627a000024
2 kyu
<!--Four Pass Transport--> <p>The eccentric candy-maker, Billy Bonka, is building a new candy factory to produce his new 4-flavor sugar pops. The candy is made by placing a piece of candy base onto a conveyer belt which transports the candy through four separate processing stations in sequential order. Each station add...
algorithms
from itertools import permutations, starmap from heapq import * INF = float("inf") MOVES = (((0, 1), (- 1, 0), (0, - 1), (1, 0)), # Turn anticlockwise ((1, 0), (0, - 1), (- 1, 0), (0, 1))) # Turn clockwise def four_pass(stations): print(stations) def dfs(pOrder, paths, n=0): if n == 3...
Four Pass Transport
5aaa1aa8fd577723a3000049
[ "Puzzles", "Games", "Logic", "Algorithms" ]
https://www.codewars.com/kata/5aaa1aa8fd577723a3000049
1 kyu
<!--Alphametics Solver--> <p><span style='color:#8df'><a href='https://en.wikipedia.org/wiki/Verbal_arithmetic' style='color:#9f9;text-decoration:none'>Alphametics</a></span> is a type of cryptarithm in which a set of words is written down in the form of a long addition sum or some other mathematical problem. The objec...
algorithms
from itertools import permutations def alphametics(puzzle, base=10, alphabet='0123456789'): def invalidate(digits, mapping, letter, n): if letter in firsts and n == 0: return True if letter in mapping: return mapping[letter] != n elif n not in digits: return True ...
Alphametics Solver
5b5fe164b88263ad3d00250b
[ "Puzzles", "Performance", "Cryptography", "Algorithms" ]
https://www.codewars.com/kata/5b5fe164b88263ad3d00250b
3 kyu
We need a system that can learn facts about family relationships, check their consistency and answer queries about them. # The task ~~~if:javascript Create a class `Family` with the following methods. All arguments are strings: names of persons. Upon the first use of a name, that name is added to the family. * `male...
algorithms
from copy import deepcopy class Person: def __init__(self, name="", gender=None): self . name = name self . gender = gender self . parents = [] self . children = [] class Family: def __init__(self): self . members = {} def male(self, name): if name not in self ...
We are Family
5b602842146a2862d9000085
[ "Algorithms", "Graph Theory" ]
https://www.codewars.com/kata/5b602842146a2862d9000085
4 kyu
# Task Given an array of roots of a polynomial equation, you should reconstruct this equation. ___ ## Output details: * If the power equals `1`, omit it: `x = 0` instead of `x^1 = 0` * If the power equals `0`, omit the `x`: `x - 2 = 0` instead of `x - 2x^0 = 0` * There should be no 2 signs in a row: `x - 1 = 0` ins...
reference
import re def polynomialize(roots): def deploy(roots): r = - roots[0] if len(roots) == 1: return [r, 1] sub = deploy(roots[1:]) + [0] return [c * r + sub[i - 1] for i, c in enumerate(sub)] coefs = deploy(roots) poly = ' + ' . join(["{}x^{}" . format(c, i) ...
Constructing polynomials
5b2d5be2dddf0be5b00000c4
[ "Mathematics", "Performance", "Fundamentals" ]
https://www.codewars.com/kata/5b2d5be2dddf0be5b00000c4
5 kyu
<img src="https://i.imgur.com/ta6gv1i.png?1" /> --- <span style="font-weight:bold;font-size:1.5em;color:red">*Blaine is a pain, and that is the truth</span>&nbsp;- Jake Chambers* # <span style='color:orange'>Background</span> Blaine likes to deliberately crash toy trains! ## <span style='color:orange'>*Trains*</s...
reference
import re train_crash = lambda * args: BlaimHim(* args). crash() class BlaimHim (object): MOVES = {'/': ([[(0, - 1, '-'), (1, - 1, '/'), (1, 0, '|')], # up-right => down-left: (dx, dy, expected char) [(- 1, 0, '|'), (- 1, 1, '/'), (0, 1, '-')]], # down-left => up-right la...
Blaine is a pain
59b47ff18bcb77a4d1000076
[ "Fundamentals" ]
https://www.codewars.com/kata/59b47ff18bcb77a4d1000076
2 kyu
*You should be familiar with the "Find the shortest path" problem. But what if moving to a neighboring coordinate counted not as* `1` *step but as* `N` *steps? * ___ **INSTRUCTIONS** Your task is to find the path through the *field* which has the lowest *cost* to go through. As input you will receive: 1) a `...
algorithms
from heapq import * MOVES = [(1, 0), (0, 1), (0, - 1), (- 1, 0)] BACK = {(1, 0): "down", (0, 1): "right", (0, - 1): "left", (- 1, 0): "up"} DEFAULT = (float("inf"), 0, 0) def cheapest_path(t, start, finish): # heapq structure: (total cost, isEnd, position tuple) lX, lY =...
Find the cheapest path
5abeaf0fee5c575ff20000e4
[ "Algorithms", "Performance" ]
https://www.codewars.com/kata/5abeaf0fee5c575ff20000e4
3 kyu
Your task is to solve <font size="+1">N x M Systems of Linear Equations (LS)</font> and to determine the <b>complete solution space</b>.<br>&nbsp;<br>Normally an endless amount of solutions exist, not only one or none like for N x N. You have to handle <b>N</b> unkowns and <b>M</b> equations (<b>N>=1</b>, <b>M>=1</b>) ...
algorithms
from fractions import Fraction import re def gauss(matrix): n, m = len(matrix), len(matrix[0]) - 1 refs = [- 1] * m r = 0 for c in range(m): k = next((i for i in range(r, n) if matrix[i][c] != 0), - 1) if k < 0: continue refs[c] = r row = matrix[k] if r != k: ...
Linear equations N x M, complete solution space, fraction representation
56464cf3f982b2e10d000015
[ "Algorithms", "Linear Algebra", "Algebra", "Mathematics" ]
https://www.codewars.com/kata/56464cf3f982b2e10d000015
2 kyu
You are given a ASCII diagram, comprised of minus signs `-`, plus signs `+`, vertical bars `|` and whitespaces ` `. Your task is to write a function which breaks the diagram in the minimal pieces it is made of. For example, if the input for your function is this diagram: ``` +------------+ | | | ...
algorithms
from typing import List, Tuple import random class FrameCoordinate: def __init__(self, x: int, y: int, adjacency_ops: List[Tuple[int, int]] = [(1, 0), (0, 1), (- 1, 0), (0, - 1)]) - > None: self . x = x self . y = y self . adjacency_ops = adjacency_ops self . cur_op = 0 def __str__(s...
Break the pieces
527fde8d24b9309d9b000c4e
[ "Algorithms" ]
https://www.codewars.com/kata/527fde8d24b9309d9b000c4e
2 kyu
Task ======= Given a string representing a quadratic equation, return its roots in either order. 1. The coefficients and constants are [Gaussian Integers](https://en.wikipedia.org/wiki/Gaussian_integer) 2. You might need to rearrange and / or simplify the equation by collecting terms and expanding brackets ___ __E...
games
import re def complex_quadratics(eq): eq = re.sub(r'(i|\d|\))(x)', lambda g: g.group(1) + '*' + g.group(2), eq) eq = re.sub(r'(\d|\))(i)', lambda g: g.group(1) + '*' + g.group(2), eq) eq = re.sub(r'(^|\D)(i)', lambda g: g.group(1) + '1' + g.group(2), eq) eq = eq.replace('i', 'j').replace('^', '**') ...
Complex Quadratics
66291436acf94b67ea835b0f
[ "Regular Expressions", "Mathematics", "Strings", "Algebra" ]
https://www.codewars.com/kata/66291436acf94b67ea835b0f
5 kyu
You are in charge of a squad of robots in a row. At some time, an order to fire is given to the first of these robots, and your goal is to make sure all of the robots will fire simultaneously. To do that you will have to manage the communication between them, but they are very limited. The robots are basically cells o...
games
INITIAL_STATE = 'L' TRIGGER_STATE = 'G' FIRING_STATE = 'F' rules = { 'A': 'ABCBAF, GCCGC,A A , CC C,ALG ,F G ', 'B': 'BBL G ,ABCBG ,A LLL,C BGCG,GBLB , ', 'C': ' B BBB, CGCG,ABCBC , B BBB,AGCGC , ', 'L': 'LLLCGC,LLLLLL,LLLGAG,LLLACA, LLLLL, L ', 'G': ' GG B , GGGBG, GGAAA, GGFBF,GGG ...
Firing squad synchronisation
61aba5e564cd720008ed3bf3
[ "Cellular Automata", "Puzzles" ]
https://www.codewars.com/kata/61aba5e564cd720008ed3bf3
5 kyu
In this challenge, you have to create two functions to convert an emoji string to the "emojicode" format, and back. **Emoji strings** consist solely of Unicode emojis, and each of the emojis can be represented with a single Unicode code point. There is no combining characters, variant selectors, joiners, direction mod...
reference
def to_emojicode(emojis): return ' '.join(''.join(d + '️⃣' for d in str(ord(c))) for c in emojis) def to_emojis(emojicode): return ''.join(chr(int(ds.encode('ascii', 'ignore'))) for ds in emojicode.split())
Emojicode
66279e3bcb95174d2f9cf050
[ "Strings", "Unicode" ]
https://www.codewars.com/kata/66279e3bcb95174d2f9cf050
6 kyu
# Background Congratulations! Your next best-selling novel is finally finished. You cut/paste text fragments from your various notes to build the final manuscript. But you sure are a terrible typist! Often you press the "paste" key multiple times by mistake. You'd better fix those errors before sending it off to the...
reference
import re def fix_cut_paste(x): return re.sub("([^~]*(?<![~])[~](.*?[~])??(?![~])[^~]*)\\1+".replace("~", "A-Za-z"), r'\\1', x)
Cut/Paste errors
5d6ef1abd6dca5002e723923
[ "Fundamentals" ]
https://www.codewars.com/kata/5d6ef1abd6dca5002e723923
5 kyu
# Overview In this Kata you will be looking at the runs scored by a team in an innings of a game of cricket. <img src="https://i.imgur.com/OBJ6zAQ.png" title="cricket" /> # Rules The rules of <a href="https://en.wikipedia.org/wiki/Cricket">cricket</a> are much too complex to describe here. Some basic things that y...
algorithms
def score_card(balls, batsmen): scores = [0 for _ in range(len(batsmen))] b1, b2, nextIn, tot = 1, 0, 2, 0 # b1,b2 = indexes of the batsmen in the field # b1: side 1, b2: side 2 (reversed when declared because swapped righ...
Cricket Scores
5a5ed3d1e626c5140f00000e
[ "Algorithms" ]
https://www.codewars.com/kata/5a5ed3d1e626c5140f00000e
5 kyu
You're an elevator. People on each floor get on you in the order they are queued as long as you're stopped on their floor. Your doors are one-person wide. No one can board you when someone else is departing or vice versa. You must **stop** at each floor you pass that you can drop off and/or pick up passengers. Conve...
games
def order(level, queue): cargo = [] visited_floors = [] capacity = 5 direction = None cmp = lambda a, b: (a > b) - (a < b) # Each loop is a stop counting the starting level. # Note, we don't mark the first stop if there's no one to pick up. while cargo or queue: # Drop off ...
Elevator Action!
654cdf611d68c91228af27f1
[ "Algorithms", "Performance" ]
https://www.codewars.com/kata/654cdf611d68c91228af27f1
4 kyu
Zeckendorf's Theorem<sup>[[wiki]](https://en.wikipedia.org/wiki/Zeckendorf%27s_theorem)</sup> states that every positive integer can be represented uniquely as the sum of one or more distinct Fibonacci numbers in such a way that the sum does not include any two consecutive Fibonacci numbers. This representation can be ...
algorithms
def negative_fibonacci_representation(n): fibs = [1, -1] sums, res = fibs[:], [] while abs(sums[n < 0]) < abs(n): x = fibs[-2] - fibs[-1] sums[x < 0] += x fibs.append(x) while fibs: x = fibs.pop() sums[x < 0] -= x if abs(sums[n < 0]) < abs(n): ...
NegaFibonacci representation
5c880b6fc249640012f74cd5
[ "Number Theory", "Puzzles", "Algorithms" ]
https://www.codewars.com/kata/5c880b6fc249640012f74cd5
5 kyu
<!-- Blobservation 2: Merge Inert Blobs --> <h2 style='color:#f88'>Overview</h2> <p>You have an <code>m</code> x <code>n</code> rectangular matrix (grid) where each index is occupied by a blob.<br/> Each blob is given a positive integer value; let's say it represents its mass.<br/> Each blob is immobile on its own, but...
algorithms
class Blobservation: @staticmethod def _move(L): tmp, res = [L[0]], [] for x in L[1:]: if x == 0: continue if tmp[-1] < x: tmp.append(x) else: res.append(sum(tmp)) tmp = [x] res.append(sum...
Blobservation 2: Merge Inert Blobs
5f8fb3c06c8f520032c1e091
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5f8fb3c06c8f520032c1e091
5 kyu
# <span style='color:orange'>Background</span> It is the middle of the night. You are jet-lagged from your long cartesian plane trip, and find yourself in a rental car office in an unfamiliar city. You have no idea how to get to your hotel. Oh, and it's raining. Could you be any more miserable? But the friendly...
reference
import re N,S,E,W = "NORTH", "SOUTH", "EAST", "WEST" DIRS = {N: (0,1), S:(0,-1), E: (1,0), W:(-1,0)} TURNS = {"LEFT": { DIRS[N]: DIRS[W], DIRS[S]: DIRS[E], DIRS[E]: DIRS[N], DIRS[W]: DIRS[S]}, "RIGHT": { DIRS[N]: DIRS[E], DIRS[S]: DIRS[W], DIRS[E]: DIRS[S], DIRS[W]: DIRS[N]} } PATTERN = re.com...
Sat Nav directions
5a9b4d104a6b341b42000070
[ "Fundamentals" ]
https://www.codewars.com/kata/5a9b4d104a6b341b42000070
5 kyu
<center> <div style="float:left;width:45%;" > <svg width="301" height="201"> <rect x="0" y="0" width="301" height="201" style="fill:rgb(64,64,64); stroke-width:0" /> <rect x="75" y="75" width="150" height="25" style="fill:rgb(192,192,192); stroke-width:0" /> <rect x="75" y="100" width="50" height="25" style="f...
algorithms
# Asuuming border printout start top-left, finish top row, then go down # So my thinking is: sort all elements based on y decending, and x accending orders. # Output will initially be a matrix of (' ', '+', '-', '|'). ' ' is padded to the # front of each row to line up with the left-most element. Plan to start to fill ...
Draw the borders I - Simple ascii border
5ffcbacca79621000dbe7238
[ "Geometry", "Strings", "ASCII Art", "Algorithms" ]
https://www.codewars.com/kata/5ffcbacca79621000dbe7238
5 kyu
**See Also** * [Traffic Lights - one car](https://www.codewars.com/kata/5d0ae91acac0a50232e8a547) * [Traffic Lights - multiple cars](.) --- # 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
class Car: l = None def __init__(self, pos): self.pos = pos def forward(self, lights, cars): move = True for light in lights: if light.pos == self.pos + 1: if light.state != "G": move = False for car in cars: ...
Traffic Lights - multiple cars
5d230e119dd9860028167fa5
[ "Algorithms" ]
https://www.codewars.com/kata/5d230e119dd9860028167fa5
5 kyu
<b>You are to write a function to transpose a <a href="https://en.wikipedia.org/wiki/Tablature#Guitar_tablature" target="_blank">guitar tab</a> up or down a number of semitones.</b> The <i>amount</i> to transpose is a number, positive or negative. The <i>tab</i> is given as an array, with six elements for each guitar s...
algorithms
from itertools import groupby import re class OutOfFrets(Exception): pass def convert(k,grp,amount): def convertOrRaise(m): v = int(m.group()) + amount if not (0 <= v < 23): raise OutOfFrets() return str(v) lst = list(map(''.join, zip(*grp))) if isinstance(k,str): re...
Transposing Guitar Tabs
5ac62974348c2203a90000c0
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5ac62974348c2203a90000c0
5 kyu
![Gameplay screencap](https://i.imgur.com/mYgmiOz.jpg) <p><a href="https://en.wikipedia.org/wiki/Papers%2C_Please" style='color:#9f9;text-decoration:none'><b>Papers, Please</b></a> is an indie video game where the player takes on a the role of a border crossing immigration officer in the fictional dystopian Eastern Bl...
reference
from itertools import combinations from collections import defaultdict from datetime import date import re EXPIRE_DT = date(1982,11,22) NATION = 'Arstotzka'.lower() COUNTRIES = set(map(str.lower, ('Arstotzka', 'Antegria', 'Impor', 'Kolechia', 'Obristan', 'Republia', 'United Federation'))...
Papers, Please
59d582cafbdd0b7ef90000a0
[ "Object-oriented Programming", "Games", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/59d582cafbdd0b7ef90000a0
3 kyu
# QR-Code Message Encoding ## Information This kata will only focus on the message encoding, not on error correction or the 2d representation. A message for a QR-Code can be encoded in 5 different modes: - Byte Mode - Alphanumeric Mode - Numeric Mode - (ECI Mode) - (Kanji Mode) To simplify this kata, we will only us...
reference
CHAR_SET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:" ALPHA = {c:i for i,c in enumerate(CHAR_SET)} NUMS_SET = set('0123456789') def qr_encode(s): n = 3 if set(s) <= NUMS_SET else 2 if all(map(ALPHA.__contains__,s)) else 1 func = (_byte, _alnum, _num)[n-1] msg = ''.join( func(s[i:i+n]) for i in...
QR-Code Message Encoding
605da8dc463d940023f2022e
[ "Fundamentals" ]
https://www.codewars.com/kata/605da8dc463d940023f2022e
5 kyu
## <span style="color:#0ae">Task</span> <svg width="426" height="201"> <rect x="0" y="0" width="426" height="201" style="fill:rgb(48,48,48); stroke-width:0" /> <rect x="50" y="50" width="100" height="25" style="fill:rgb(96,96,96); stroke-width:0" /> <rect x="50" y="125" width="100" height="25" style="fill:rgb(96...
algorithms
borders = { (1,0,0,0): '┐', (0,1,0,0): '┘', (0,0,1,0): '┌', (0,0,0,1): '└', (0,1,1,1): '┐', (1,0,1,1): '┘', (1,1,0,1): '┌', (1,1,1,0): '└', (1,1,0,0): '│', (0,0,1,1): '│', (1,0,1,0): '─', (0,1,0,1): '─', (1,0,0,1): '┼', (0,1,1,0): '┼', (0,0,0,0): ' ', (1,1,1,1): ' ', } def draw_borders(shape): x0 ...
Draw the borders II - Fast and furious
5ff11422d118f10008d988ea
[ "Strings", "Performance", "ASCII Art", "Algorithms" ]
https://www.codewars.com/kata/5ff11422d118f10008d988ea
5 kyu
Cluster analysis - Unweighted pair-group average Clustering is a task of grouping a set of objects in such a way that the objects in the same class are similar to each other and the objects in different classes are distinct. Cluster analysis is employed in many fields such as machine learning, pattern recognition, ima...
algorithms
from itertools import combinations from math import hypot def cluster(points, n): def distGrp(a,b): return sum(hypot(*(z2-z1 for z1,z2 in zip(aa,bb))) for aa in a for bb in b )/ (len(a)*len(b)) g = {(p,) for p in points} while len(g) > n: a,b = min(combinations(g,2), key=lambda pair: dist...
Simple cluster analysis
5a99d851fd5777f746000066
[ "Algorithms" ]
https://www.codewars.com/kata/5a99d851fd5777f746000066
5 kyu
# You Bought the Farm! Well, actually you just inherited the farm, after your grandfather bought the farm in darker and more figurative sense. The point is, you now have a farm, and you've decided to abandon your life as a programmer in the city and become a farmer instead. It's a small farm with only a single field....
algorithms
import numpy as np import scipy.optimize as spo def fit_biggest_circle(coords): coords = np.reshape(coords, (4, 2))[::-1] best_p, best_r = None, np.NINF for i in range(4): ps = np.roll(coords, i, axis=0) *p, r = circle_with_tangents(ps) if best_r < r <= distance(ps[3], ps[0], np.arr...
Buying the Farm : Irrigation
5af4855c68e6449fbf00015c
[ "Geometry", "Algorithms" ]
https://www.codewars.com/kata/5af4855c68e6449fbf00015c
5 kyu
## Conway's Game of Life ... is a 2d cellular automaton where each cell has 8 neighboors and one of two states: alive or dead.<br> After a generation passes each cell either **stays alive**, **dies** or **is born** according to the following rules:<br> * if a living cell has 2 or 3 neighboors it stays alive * if a dea...
algorithms
def find_predecessor(p): H = len(p)+2 W = len(p[0])+2 Q = [[[] for i in range(W)] for j in range(H)] for i in range(H): for j in range(W): Q[min(H-1,i+1)][min(W-1,j+1)]+=[(i,j)] def valid(i,j,a): for i,j in Q[i][j]: c = p[i-1][j-1] if 0<i<H-1 and 0<j<W-...
Game of Life in Reverse
5ea6a8502186ab001427809e
[ "Algorithms", "Cellular Automata" ]
https://www.codewars.com/kata/5ea6a8502186ab001427809e
1 kyu
_Molecules are beautiful things. Especially organic ones..._ <br> <hr> # Overview This time, you will be provided the name of a molecule as a string, and you'll have to convert it to the corresponding raw formula (as a dictionary/mapping). ### Input: ``` "5-methylhexan-2-ol" OH CH3 | | ...
games
from collections import UserDict from enum import Flag, auto import re class TokenType(Flag): POS_MULT, MULT, RAD = auto(), auto(), auto() LS, RS, SPACE, E = auto(), auto(), auto(), auto() AN, EN, YN, YL = auto(), auto(), auto(), auto() CYCLO, BENZEN, PHEN = auto(), auto(), auto() FLUORO, CHLORO...
Full Metal Chemist #2: parse me...
5a529cced8e145207e000010
[ "Regular Expressions", "Puzzles" ]
https://www.codewars.com/kata/5a529cced8e145207e000010
1 kyu
## Task This kata is about the <a href="https://en.wikipedia.org/wiki/Travelling_salesman_problem" target="_blank">travelling salesman problem</a>. You have to visit every city once and return to the starting point. You get an adjacency matrix, which shows the distances between the cities. The total cost of path is d...
algorithms
import numpy as np def sort_and_return_args(input_list): # Enumerate the input list to get index-value pairs enum_list = list(enumerate(input_list)) # Use sorted with a custom key function to sort based on values sorted_enum_list = sorted(enum_list, key=lambda x: x[1]) # Extract the indic...
Approximate Solution of Travelling Salesman Problem
601b1d0c7de207001c81980b
[ "Dynamic Programming", "Algorithms" ]
https://www.codewars.com/kata/601b1d0c7de207001c81980b
5 kyu
Given a 2D array and a number of generations, compute n timesteps of [Conway's Game of Life](http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life). The rules of the game are: 1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation. 2. Any live cell with more than three live neighbou...
games
def get_neighbours(x, y): return {(x + i, y + j) for i in range(- 1, 2) for j in range(- 1, 2)} def get_generation(cells, generations): if not cells: return cells xm, ym, xM, yM = 0, 0, len(cells[0]) - 1, len(cells) - 1 cells = {(x, y) for y, l in enumerate(cells) for x, c in enumera...
Conway's Game of Life - Unlimited Edition
52423db9add6f6fc39000354
[ "Games", "Arrays", "Puzzles", "Cellular Automata" ]
https://www.codewars.com/kata/52423db9add6f6fc39000354
4 kyu
Perform the secret knock() to enter...
games
knock(knock)()()
Secret knock
525f00ec798bc53e8e00004c
[ "Puzzles" ]
https://www.codewars.com/kata/525f00ec798bc53e8e00004c
5 kyu
```if-not:ruby Create a function, that accepts an arbitrary number of arrays and returns a single array generated by alternately appending elements from the passed in arguments. If one of them is shorter than the others, the result should be padded with empty elements. ``` ```if:ruby Create a function, that accepts an ...
algorithms
from itertools import chain, zip_longest def interleave(* args): return list(chain . from_iterable(zip_longest(* args)))
Interleaving Arrays
523d2e964680d1f749000135
[ "Algorithms", "Arrays" ]
https://www.codewars.com/kata/523d2e964680d1f749000135
5 kyu
A string is considered to be in title case if each word in the string is either (a) capitalised (that is, only the first letter of the word is in upper case) or (b) considered to be an exception and put entirely into lower case unless it is the first word, which is always capitalised. Write a function that will conver...
reference
def title_case(title, minor_words=''): title = title . capitalize(). split() minor_words = minor_words . lower(). split() return ' ' . join([word if word in minor_words else word . capitalize() for word in title])
Title Case
5202ef17a402dd033c000009
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5202ef17a402dd033c000009
6 kyu
For this exercise you will create a global flatten method. The method takes in any number of arguments and flattens them into a single array. If any of the arguments passed in are an array then the individual objects within the array will be flattened so that they exist at the same level as the other arguments. Any nes...
algorithms
def flatten(* a): r = [] for x in a: if isinstance(x, list): r . extend(flatten(* x)) else: r . append(x) return r
flatten()
513fa1d75e4297ba38000003
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/513fa1d75e4297ba38000003
5 kyu
### Tongues Gandalf's writings have long been available for study, but no one has yet figured out what language they are written in. Recently, due to programming work by a hacker known only by the code name ROT13, it has been discovered that Gandalf used nothing but a simple letter substitution scheme, and further, th...
algorithms
def tongues(code): import string gandalf = string . maketrans( 'aiyeoubkxznhdcwgpvjqtsrlmfAIYEOUBKXZNHDCWGPVJQTSRLMF', 'eouaiypvjqtsrlmfbkxznhdcwgEOUAIYPVJQTSRLMFBKXZNHDCWG') return string . translate(code, gandalf)
Tongues
52763db7cffbc6fe8c0007f8
[ "Strings", "Ciphers", "Algorithms" ]
https://www.codewars.com/kata/52763db7cffbc6fe8c0007f8
5 kyu
#### Complete the method so that it does the following: - Removes any duplicate query string parameters from the url (the first occurence should be kept) - Removes any query string parameters specified within the 2nd argument (optional array) #### Examples: ```javascript stripUrlParams('www.codewars.com?a=1&b=2&a=2...
algorithms
import urlparse import urllib def strip_url_params(url, strip=None): if not strip: strip = [] parse = urlparse . urlparse(url) query = urlparse . parse_qs(parse . query) query = {k: v[0] for k, v in query . iteritems() if k not in strip} query = urllib . urlencode(query) ...
Strip Url Params
51646de80fd67f442c000013
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/51646de80fd67f442c000013
6 kyu
The businesspeople among you will know that it's often not easy to find an appointment. In this kata we want to find such an appointment automatically. You will be given the calendars of our businessperson and a duration for the meeting. Your task is to find the earliest time, when every businessperson is free for at l...
algorithms
def get_start_time(schedules, duration): free_minutes = [True] * 60 * 24 for schedule in schedules: for meeting in schedule: for i in range(to_minute(meeting[0]), to_minute(meeting[1])): free_minutes[i] = False for time, available in enumerate(free_minutes): if 540 <= time <= 1140 - d...
Finding an appointment
525f277c7103571f47000147
[ "Date Time", "Algorithms" ]
https://www.codewars.com/kata/525f277c7103571f47000147
5 kyu
In this kata you should simply determine, whether a given year is a leap year or not. In case you don't know the rules, here they are: * Years divisible by 4 are leap years, * but years divisible by 100 are **not** leap years, * but years divisible by 400 are leap years. Tested years are in range `1600 ≤ year ≤ 4000`...
algorithms
def is_leap_year(year): return (year % 100 and not year % 4) or not year % 400 isLeapYear = is_leap_year
Leap Years
526c7363236867513f0005ca
[ "Date Time", "Algorithms" ]
https://www.codewars.com/kata/526c7363236867513f0005ca
7 kyu
Pete likes to bake some cakes. He has some recipes and ingredients. Unfortunately he is not good in maths. Can you help him to find out, how many cakes he could bake considering his recipes? ~~~if-not:factor,cpp,rust Write a function `cakes()`, which takes the recipe (object) and the available ingredients (also an obj...
algorithms
def cakes(recipe, available): return min(available . get(k, 0) / recipe[k] for k in recipe)
Pete, the baker
525c65e51bf619685c000059
[ "Algorithms" ]
https://www.codewars.com/kata/525c65e51bf619685c000059
5 kyu
Write a class that, when given a string, will return an **uppercase** string with each letter shifted forward in the alphabet by however many spots the cipher was initialized to. For example: ```javascript var c = new CaesarCipher(5); // creates a CipherHelper with a shift of five c.encode('Codewars'); // returns 'HT...
algorithms
class CaesarCipher (object): def __init__(self, shift): self . s = shift pass def encode(self, str): return '' . join(chr((ord(i) + self . s - ord('A')) % 26 + ord('A')) if i . isalpha() else i for i in str . upper()) def decode(self, str): return '' . join(chr((ord(i) - self . s ...
Caesar Cipher Helper
526d42b6526963598d0004db
[ "Ciphers", "Object-oriented Programming", "Strings", "Algorithms" ]
https://www.codewars.com/kata/526d42b6526963598d0004db
5 kyu
Write a function that when given a number >= 0, returns an Array of ascending length subarrays. ``` pyramid(0) => [ ] pyramid(1) => [ [1] ] pyramid(2) => [ [1], [1, 1] ] pyramid(3) => [ [1], [1, 1], [1, 1, 1] ] ``` **Note:** the subarrays should be filled with `1`s ```if:c Subarrays should not overlap; this will be ...
algorithms
def pyramid(n): return [[1] * x for x in range(1, n + 1)]
Pyramid Array
515f51d438015969f7000013
[ "Algorithms" ]
https://www.codewars.com/kata/515f51d438015969f7000013
6 kyu
A format for expressing an ordered list of integers is to use a comma separated list of either * individual integers * or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. The range includes all integers in the interval including both endpoints. It is not ...
algorithms
def solution(args): out = [] beg = end = args[0] for n in args[1:] + [""]: if n != end + 1: if end == beg: out . append(str(beg)) elif end == beg + 1: out . extend([str(beg), str(end)]) else: out . append(str(beg) + "-" + str(end)) beg = n end = n retur...
Range Extraction
51ba717bb08c1cd60f00002f
[ "Algorithms" ]
https://www.codewars.com/kata/51ba717bb08c1cd60f00002f
4 kyu
Pete is now mixing the cake mixture. He has the recipe, containing the required ingredients for one cake. He also might have added some of the ingredients already, but something is missing. Can you help him to find out, what he has to add to the mixture? Requirements: * Pete only wants to bake whole cakes. And ingred...
algorithms
from math import ceil def get_missing_ingredients(recipe, added): piece = max( ceil(v / recipe[k]) if k in recipe else 1 for k, v in added . items()) return {k: v * piece - added . get(k, 0) for k, v in recipe . items() if (v * piece) > added . get(k, 0)}
Pete, the baker (part 2)
5267e5827526ea15d8000708
[ "Algorithms" ]
https://www.codewars.com/kata/5267e5827526ea15d8000708
6 kyu
Complete the solution so that it returns true if it contains any duplicate argument values. Any number of arguments may be passed into the function. The array values passed in will only be strings or numbers. The only valid return values are `true` and `false`. Examples: solution(1, 2, 3) --> false ...
algorithms
def solution(* args): return len(args) != len(set(args))
Duplicate Arguments
520d9c27e9940532eb00018e
[ "Algorithms" ]
https://www.codewars.com/kata/520d9c27e9940532eb00018e
6 kyu
Write a function that accepts two square matrices (`N x N` two dimensional arrays), and return the sum of the two. Both matrices being passed into the function will be of size `N x N` (square), containing only integers. How to sum two matrices: Take each cell `[n][m]` from the first matrix, and add it with the same `...
algorithms
import numpy as np def matrix_addition(a, b): return (np . mat(a) + np . mat(b)). tolist()
Matrix Addition
526233aefd4764272800036f
[ "Matrix", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/526233aefd4764272800036f
6 kyu
Sort the given **array of strings** in alphabetical order, case **insensitive**. For example: ``` ["Hello", "there", "I'm", "fine"] --> ["fine", "Hello", "I'm", "there"] ["C", "d", "a", "B"]) --> ["a", "B", "C", "d"] ```
reference
def sortme(words): return sorted(words, key=str . lower)
Sort Arrays (Ignoring Case)
51f41fe7e8f176e70d0002b9
[ "Arrays", "Sorting" ]
https://www.codewars.com/kata/51f41fe7e8f176e70d0002b9
6 kyu
You've just recently been hired to calculate scores for a Dart Board game! Scoring specifications: * 0 points - radius above 10 * 5 points - radius between 5 and 10 inclusive * 10 points - radius less than 5 **If all radii are less than 5, award 100 BONUS POINTS!** Write a function that accepts an array of radii (...
algorithms
def score_throws(radiuses): score = 0 for r in radiuses: if r < 5: score += 10 elif 5 <= r <= 10: score += 5 if radiuses and max(radiuses) < 5: score += 100 return score
Throwing Darts
525dfedb5b62f6954d000006
[ "Algorithms" ]
https://www.codewars.com/kata/525dfedb5b62f6954d000006
6 kyu
Have a look at the following numbers. ``` n | score ---+------- 1 | 50 2 | 150 3 | 300 4 | 500 5 | 750 ``` Can you find a pattern in it? If so, then write a function `getScore(n)`/`get_score(n)`/`GetScore(n)` which returns the score for any positive number `n`. ___Note___ Real test cases consists of 100 ...
games
def get_score(n): return n * (n + 1) * 25
Sequences and Series
5254bd1357d59fbbe90001ec
[ "Mathematics", "Algorithms", "Puzzles" ]
https://www.codewars.com/kata/5254bd1357d59fbbe90001ec
6 kyu
Write a simple parser that will parse and run Deadfish. Deadfish has 4 commands, each 1 character long: * `i` increments the value (initially `0`) * `d` decrements the value * `s` squares the value * `o` outputs the value into the return array Invalid characters should be ignored. ```javascript parse("iiisdoso") =...
algorithms
def parse(data): value = 0 res = [] for c in data: if c == "i": value += 1 elif c == "d": value -= 1 elif c == "s": value *= value elif c == "o": res . append(value) return res
Make the Deadfish Swim
51e0007c1f9378fa810002a9
[ "Parsing", "Algorithms" ]
https://www.codewars.com/kata/51e0007c1f9378fa810002a9
6 kyu
Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_'). Examples: ``` * 'abc' => ['ab', 'c_'] * 'abcdef' => ['ab', 'cd', 'ef'] ```
algorithms
def solution(s): result = [] if len(s) % 2: s += '_' for i in range(0, len(s), 2): result . append(s[i: i + 2]) return result
Split Strings
515de9ae9dcfc28eb6000001
[ "Regular Expressions", "Strings", "Algorithms" ]
https://www.codewars.com/kata/515de9ae9dcfc28eb6000001
6 kyu
Inspired from real-world [Brainf\*\*k](http://en.wikipedia.org/wiki/Brainfuck), we want to create an interpreter of that language which will support the following instructions: * `>` increment the data pointer (to point to the next cell to the right). * `<` decrement the data pointer (to point to the next cell to the ...
algorithms
from collections import defaultdict def brain_luck(code, input): p, i = 0, 0 output = [] input = iter(input) data = defaultdict(int) while i < len(code): c = code[i] if c == '+': data[p] = (data[p] + 1) % 256 elif c == '-': data[p] = (data[p] - 1) % 256 ...
My smallest code interpreter (aka Brainf**k)
526156943dfe7ce06200063e
[ "Interpreters", "Algorithms" ]
https://www.codewars.com/kata/526156943dfe7ce06200063e
5 kyu
Write an algorithm that will identify valid IPv4 addresses in dot-decimal format. IPs should be considered valid if they consist of four octets, with values between `0` and `255`, inclusive. #### Valid inputs examples: ``` Examples of valid inputs: 1.2.3.4 123.45.67.89 ``` #### Invalid input examples: ``` 1.2.3 1.2....
algorithms
import socket def is_valid_IP(addr): try: socket . inet_pton(socket . AF_INET, addr) return True except socket . error: return False
IP Validation
515decfd9dcfc23bb6000006
[ "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/515decfd9dcfc23bb6000006
6 kyu
Write a function that takes in a string of one or more words, and returns the same string, but with all words that have five or more letters reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present. Examples: ...
algorithms
def spin_words(sentence): # Your code goes here return " " . join([x[:: - 1] if len(x) >= 5 else x for x in sentence . split(" ")])
Stop gninnipS My sdroW!
5264d2b162488dc400000001
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/5264d2b162488dc400000001
6 kyu
In mathematics, Pascal's triangle is a triangular array of the binomial coefficients expressed with formula ```math \lparen {n \atop k} \rparen = \frac {n!} {k!(n-k)!} ``` where `n` denotes a row of the triangle, and `k` is a position of a term in the row. ![Pascal's Triangle](http://upload.wikimedia.org/wikipedia/c...
algorithms
def pascals_triangle(n): if n == 1: return [1] prev = pascals_triangle(n - 1) return prev + [1 if i == 0 or i == n - 1 else prev[- i] + prev[- (i + 1)] for i in range(n)]
Pascal's Triangle
5226eb40316b56c8d500030f
[ "Arrays", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5226eb40316b56c8d500030f
6 kyu
Have you heard of the game "electrons around the cores"? I'm not allowed to give you the complete rules of the game, just so much: - the game is played with 4 to 6 ___dice___, so you get an array of 4 to 6 numbers, each 1-6 - the name of the game is important - you have to return the correct number five times in a row...
games
def electrons_around_the_cores(dice): return dice . count(5) * 4 + dice . count(3) * 2
Game - Electrons around the cores
52210226578afb73bd0000f1
[ "Reverse Engineering", "Games", "Puzzles", "Riddles" ]
https://www.codewars.com/kata/52210226578afb73bd0000f1
5 kyu
How can you tell an extrovert from an introvert at NSA? Va gur ryringbef, gur rkgebireg ybbxf ng gur BGURE thl'f fubrf. I found this joke on USENET, but the punchline is scrambled. Maybe you can decipher it? According to Wikipedia, [ROT13](http://en.wikipedia.org/wiki/ROT13) is frequently used to obfuscate jokes o...
algorithms
def rot13(message): def decode(c): if 'a' <= c <= 'z': base = 'a' elif 'A' <= c <= 'Z': base = 'A' else: return c return chr((ord(c) - ord(base) + 13) % 26 + ord(base)) return "" . join(decode(c) for c in message)
ROT13
52223df9e8f98c7aa7000062
[ "Strings", "Ciphers", "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/52223df9e8f98c7aa7000062
5 kyu
The marketing team is spending way too much time typing in hashtags. Let's help them with our own Hashtag Generator! Here's the deal: - It must start with a hashtag (`#`). - All words must have their first letter capitalized. - If the final result is longer than 140 chars it must return `false`. - If the input or ...
algorithms
def generate_hashtag(s): output = "#" for word in s . split(): output += word . capitalize() return False if (len(s) == 0 or len(output) > 140) else output
The Hashtag Generator
52449b062fb80683ec000024
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/52449b062fb80683ec000024
5 kyu
Triangular numbers are so called because of the equilateral triangular shape that they occupy when laid out as dots. i.e. ``` 1st (1) 2nd (3) 3rd (6) * ** *** * ** * ``` You need to return the nth triangular number. You should return 0 for out of range valu...
algorithms
def triangular(n): return n * (n + 1) / / 2 if n > 0 else 0
Triangular Treasure
525e5a1cb735154b320002c8
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/525e5a1cb735154b320002c8
7 kyu