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
## Background Starting with the closed interval `$[0,1]$`, the Cantor ternary set is constructed by iteratively applying the operation "remove the middle thirds", by which we mean removing the open interval `$(\frac{2a + b}{3}, \frac{a + 2b}{3})$` from each remaining closed interval `$[a,b]$`. If `$C_n$` denotes the re...
algorithms
def is_in_cantor(num, den, n): if num < 0 or num > den: return False for i in range(n): num *= 3 if num > den and num < den * 2: return False num %= den return True
The Cantor ternary set
60b744478e8d62003d327e6a
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/60b744478e8d62003d327e6a
6 kyu
Returns the commom directory path for specified array of full filenames. ``` @param {array} pathes @return {string} ``` Examples: ``` ['/web/images/image1.png', '/web/images/image2.png'] => '/web/images/' ['/web/assets/style.css', '/web/scripts/app.js', 'home/setting.conf'] => '' ['/web/assets/style.css',...
games
def get_common_directory_path(pathes): res = '' for cs in zip(* pathes): if len(set(cs)) == 1: res += cs[0] else: break arr = res . split('/')[: - 1] if not arr: return '' return '/' . join(arr) + '/'
Common directory path
597f334f1fe82a950500004b
[ "Strings", "Puzzles" ]
https://www.codewars.com/kata/597f334f1fe82a950500004b
6 kyu
Regular Tic-Tac-Toe is boring. That's why in this Kata you will be playing Tic-Tac-Toe in **3D** using a 4 x 4 x 4 matrix! <img src="https://i.imgur.com/NlG3wai.png" title="source: imgur.com" /> # Kata Task Play the game. Work out who wins. Return a string * `O wins after <n> moves` * `X wins after <n> moves` * ...
reference
WINS = [(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11), (12, 13, 14, 15), (16, 17, 18, 19), (20, 21, 22, 23), (24, 25, 26, 27), (28, 29, 30, 31), (32, 33, 34, 35), (36, 37, 38, 39), (40, 41, 42, 43), (44, 45, 46, 47), (48, 49, 50, 51), (52, 53, 54, 55), (56, 57, 58, 59), (60, 61, 62, 63), ...
Tic-Tac-Toe (3D)
5aa67541373c2e69a20000c9
[ "Fundamentals" ]
https://www.codewars.com/kata/5aa67541373c2e69a20000c9
5 kyu
# VIN Checker In this Kata you should write a function to validate VINs, Vehicle Identification Numbers. Valid VINs are exactly 17 characters long, its composed of capital letters (except "I","O" and "Q") and digits. The 9th character is a MODULUS 11 check digit. Here is how it works: ## 1. Letters are converted to n...
algorithms
TRANS = str . maketrans("A B C D E F G H I J K L M N O P Q R S T U V W X Y Z", "1 2 3 4 5 6 7 8 1 2 3 4 5 7 9 2 3 4 5 6 7 8 9") WEIGHTS = [8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2] def check_vin(vin): try: return len(vin) == 17 and vin[8] == "0123456789X" [sum(int(c) *...
VIN Checker
60a54750138eac0031eb98e1
[ "Strings", "Logic", "Algorithms" ]
https://www.codewars.com/kata/60a54750138eac0031eb98e1
6 kyu
### Description Consider some _subject_, who has some initial _momentum_ and is travelling through an array (_powerups_). _momentum_ is an integer that represents the "distance" the _subject_ can travel through the array. Each index travelled requires one unit of _momentum_. (The _subject_ starts outside of the array...
reference
from itertools import accumulate def survivors(ms, pss): return [i for i, (m, pss) in enumerate(zip(ms, pss)) if all(m > 0 for m in accumulate(pss, lambda m, p: m - 1 + p, initial=m))]
Survivors Ep.4
60a516d70759d1000d532029
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/60a516d70759d1000d532029
6 kyu
Given a list of strings (of letters and spaces), and a list of numbers: Considering the list of strings as a 2D character array, the idea is to remove from each column, starting from bottom, as many letters as indicated in the list of numbers. Then return the remaining letters in any order as a string. * If there are...
reference
def last_survivors(arr, nums): return '' . join(map(shrink, zip(* arr), nums)) def shrink(col, n): return '' . join(col). replace(' ', '')[: - n or len(col)]
Last Survivors Ep.3
60a2d7f50eee95000d34f414
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/60a2d7f50eee95000d34f414
6 kyu
Given a number, find the permutation with the smallest absolute value (no leading zeros). ```python -20 => -20 -32 => -23 0 => 0 10 => 10 29394 => 23499 ``` The input will always be an integer.
reference
def min_permutation(n): f = n < 0 s = "" . join(sorted(str(abs(n)))) n = s . count("0") s = s . replace("0", "") return int(s[: 1] + "0" * n + s[1:]) * (- 1 if f else 1)
Smallest Permutation
5fefee21b64cc2000dbfa875
[ "Fundamentals" ]
https://www.codewars.com/kata/5fefee21b64cc2000dbfa875
6 kyu
You are given a string of letters and an array of numbers. The numbers indicate positions of letters that must be removed, in order, starting from the beginning of the array. After each removal the size of the string decreases (there is no empty space). Return the only letter left. Example: ~~~if-not:java ``` ...
reference
def last_survivor(letters, coords): for x in coords: letters = letters[0: x] + letters[x + 1:] return letters
Last Survivor
609eee71109f860006c377d1
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/609eee71109f860006c377d1
7 kyu
Substitute two equal letters by the next letter of the alphabet (two letters convert to one): "aa" => "b", "bb" => "c", .. "zz" => "a". The equal letters do _not_ have to be adjacent. Repeat this operation until there are no possible substitutions left. Return a string. Example: let str = "zzzab" ...
reference
from re import sub def last_survivors(s): while len(set(s)) != len(s): s = sub(r'(.)(.*)\1', lambda x: chr((ord(x . group(1)) - 96) % 26 + 97) + x . group(2), s) return s
Last Survivors Ep.2
60a1aac7d5a5fc0046c89651
[ "Fundamentals", "Arrays", "Regular Expressions" ]
https://www.codewars.com/kata/60a1aac7d5a5fc0046c89651
6 kyu
### Overview Many people know that Apple uses the letter "i" in almost all of its devices to emphasize its personality. And so John, a programmer at Apple, was given the task of making a program that would add that letter to every word. Let's help him do it, too. ### Task: Your task is to make a function that takes ...
reference
vowel = set("aeiouAEIOU"). __contains__ def i(word): if not word or word[0]. islower() or word[0] == 'I' or 2 * sum(map(vowel, word)) >= len(word): return "Invalid word" return 'i' + word
I'm everywhere!
6097a9f20d32c2000d0bdb98
[ "Fundamentals" ]
https://www.codewars.com/kata/6097a9f20d32c2000d0bdb98
7 kyu
Your job is to create a class called `Song`. A new `Song` will take two parameters, `title` and `artist`. ```javascript const mountMoose = new Song('Mount Moose', 'The Snazzy Moose'); mountMoose.title => 'Mount Moose' mountMoose.artist => 'The Snazzy Moose' ``` ```python mount_moose = Song('Mount Moose', 'The Snazzy...
reference
class Song: def __init__(self, title, artist): self . title = title self . artist = artist self . _seen = set() def how_many(self, people): tmp = set(map(str . lower, people)) res = len(tmp - self . _seen) self . _seen . update(tmp) return res
What a "Classy" Song
6089c7992df556001253ba7d
[ "Fundamentals", "Object-oriented Programming" ]
https://www.codewars.com/kata/6089c7992df556001253ba7d
7 kyu
### Overview Have you ever wondered how a user interface handles key presses? So today you have the opportunity to create it. ### Task: The keyboard handler is a function which receives three parameters as input: 1. **Key** - the entered character on the keyboard. 2. **isCaps** (or **is_caps**) - boolean variable r...
algorithms
def handler(key, isCaps=False, isShift=False): if not isinstance(key, str) or len(key) != 1 or key . isupper(): return 'KeyError' num = "1234567890-=[];'\/.,`" unNum = '!@#$%^&*()_+{}:"|?><~' if key . isalpha() and (isCaps != isShift): return key . upper() if not key . isalpha() and...
Keyboard handler
609d17f9838b2c0036b10e89
[ "Algorithms", "Logic" ]
https://www.codewars.com/kata/609d17f9838b2c0036b10e89
7 kyu
In Lambda Calculus, lists can be represented as their right fold. A right fold <sup>[wiki](https://en.wikipedia.org/wiki/Fold_(higher-order_function))</sup> takes a combining function and an initial value, and returns a single combined value for the whole list, eg.: ``` < x y z > = λ c n . c x (c y (c z n)) ``` ~~~if...
algorithms
def cons(a): return lambda b: lambda c: lambda d: c(a)(b(c)(d)) def snoc(a): return lambda b: lambda c: lambda d: b(c)(c(a)(d)) def map(a): return lambda b: lambda c: lambda d: b( lambda e: lambda f: c(a(e))(f))(d) def filter(a): return lambda b: lambda c: lambda d: b( lambda e: lambda f: a(e)(...
Lambda Calculus: Lists as folds I
5fb44fbd98799a0021dca93a
[ "Algorithms" ]
https://www.codewars.com/kata/5fb44fbd98799a0021dca93a
5 kyu
This is my republished first kata(with issues fixed!), hope you guys will enjoy it! For input, you will be given a string in the form `"(mx+n)(px+q)"` where the character `x` can be any single lowercase alphabet from a-z, while `m`, `n`, `p` and `q` are integers(can be negative). ## Task * Return a string in the f...
reference
import re def quadratic_builder(expression): # replace -x with -1x in the expression expression = re . sub("-([a-z])", r"-1\1", expression) # extract constants and variable name m, x, n, p, _, q = re . findall(""" \( # opening bracket (-?\d*) # constant (m) (\D) # variable (x) ([+-]\d*) # con...
Build a quadratic equation
60a9148187cfaf002562ceb8
[ "Mathematics", "Strings", "Algebra", "Fundamentals" ]
https://www.codewars.com/kata/60a9148187cfaf002562ceb8
5 kyu
Re-write the initial function below so that it is `31` characters or less: ```python def f(iterable, integer): length = len(iterable) if length > integer: return length else: return 0 ``` This simple function takes an input iterable and an integer. If the length of the iterable is larger t...
games
def f(a, b): return (0, z: = len(a))[z > b]
[Code Golf] Optional Walrus?
60a82776de1604000e29eb50
[ "Restricted", "Puzzles" ]
https://www.codewars.com/kata/60a82776de1604000e29eb50
6 kyu
### Task: You need to write a function ```grid``` that returns an alphabetical grid of size NxN, where a = 0, b = 1, c = 2.... ### Examples: grid(4) ``` a b c d b c d e c d e f d e f g ``` grid(10) ``` a b c d e f g h i j b c d e f g h i j k c d e f g h i j k l d e f g h i j k l m e f g h i j k l m n f g h i j k l m...
algorithms
def grid(N): if N < 0: return None abc = 'abcdefghijklmnopqrstuvwxyz' * 8 val = [] for i in range(N): arr = list(abc[i: N + i]) out = ' ' . join(arr) val . append(out) return '\n' . join(val)
Alphabetical Grid
60a94f1443f8730025d1744b
[ "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/60a94f1443f8730025d1744b
7 kyu
Your music theory class just gave you a homework where you have to find the keys for a bunch of melodies. You decided to be lazy and create a key detection program to do the work for you. Each melody in this assignment is supposed to be strictly derived from a major scale. There are twelve major scales each of which ...
reference
from itertools import accumulate import re DEFAULT = 'No' NOTES = 'C C# D D# E F F# G G# A A# B' . split() MAJOR_SCHEME = (0, 2, 2, 1, 2, 2, 2, 1) SPLITTER = re . compile('|' . join( sorted(NOTES, key=len, reverse=True)) + '|.') CHORDS_DCT = {frozenset(NOTES[(i + delta) % 12] for delta in accumulate(MAJOR_...
Music Fun #1 - Major Scale
5c1b25bc85042749e9000043
[ "Algorithms", "Strings", "Parsing", "Logic", "Fundamentals" ]
https://www.codewars.com/kata/5c1b25bc85042749e9000043
6 kyu
Implement a function which creates a **[radix tree](https://en.wikipedia.org/wiki/Radix_tree)** ( a space-optimized trie \[prefix tree\] ) * in which each node that is the only child is merged with its parent ( unless a word from the input ends there ) * from a given list of words * using dictionaries ( aka hash ta...
algorithms
from itertools import groupby from operator import itemgetter from os . path import commonprefix first = itemgetter(0) def radix_tree(* words): words = [w for w in words if w] result = {} for key, grp in groupby(sorted(words), key=first): lst = list(grp) prefix = commonprefix(lst) ...
Radix Tree
5c9d62cbf1613a001af5b067
[ "Data Structures", "Algorithms" ]
https://www.codewars.com/kata/5c9d62cbf1613a001af5b067
6 kyu
# Markdown 101: Code Format Corrector ## Description We are writing the document `README.md` for our [github](https://github.com/) but we have forgotten to format correctly the code. According to this [documentation](https://guides.github.com/features/mastering-markdown/) and this [cheat sheet](https://github.com/ad...
reference
def markdown_code_corrector(s): out, inBlk, cont = [], 0, 0 for l in s . split('\n'): isCode = l . startswith(('&', '>>>')) if not inBlk and isCode or inBlk and not isCode and not cont: out . append("```") out . append(l) inBlk = isCode or inBlk and cont cont = l . endswith('\\')...
Markdown 101: Code Format Corrector
5e9ed1864f12ec003281e761
[ "Strings", "Lists", "Fundamentals" ]
https://www.codewars.com/kata/5e9ed1864f12ec003281e761
6 kyu
### Task Write a function that receives a non-negative integer `n ( n >= 0 )` and returns the next higher multiple of five of that number, obtained by concatenating the ***shortest possible*** binary string to the end of this number's binary representation. ### Examples ```python 1. next_multiple_of_five(8) ``` ```...
algorithms
PROVIDERS = ( lambda n: n * 2 or 5, lambda n: n * 4 + 1, lambda n: n * 2 + 1, lambda n: n * 4 + 3, lambda n: n * 8 + 3, ) def next_multiple_of_five(n): return PROVIDERS[n % 5](n)
Next multiple of 5
604f8591bf2f020007e5d23d
[ "Algorithms", "Logic", "Performance" ]
https://www.codewars.com/kata/604f8591bf2f020007e5d23d
6 kyu
Your goal in this kata is to implement an algorithm, which increases `number` in the way explained below, and returns the result. Input data: `number, iterations, step`. Stage 1: We get the: `number:143726`, `iterations: 16`, `step:3` And make increment operations in a special way Position: We start from `1` posi...
algorithms
def increment(number, iterations, spacer): step = len(str(number)) - 1 for i in range(iterations): step = (step - spacer) % len(str(number)) number = number + 10 * * (step) return number
Increment with iterations
5ecc16daa200d2000165c5b1
[ "Algorithms" ]
https://www.codewars.com/kata/5ecc16daa200d2000165c5b1
6 kyu
A group of horses just ran past Farmer Thomas, and he would like to figure out how many horses were there. However, Farmer Thomas has a bad eye sight, and cannot really see the horses that are now distant. He did remember the sound of their galloping though, and he wants your help in figuring out how many horses (and t...
algorithms
def count_horses(sound_str): res = [] lst = list(sound_str) while set(lst) != {'0'}: for j in range(len(lst)): if lst[j] != '0': res . append(j + 1) for k in range(j, len(lst), j + 1): lst[k] = str(int(lst[k]) - 1) break return res
Counting Horses
5f799eb13e8a260015f58944
[ "Algorithms" ]
https://www.codewars.com/kata/5f799eb13e8a260015f58944
6 kyu
### Checkerboard Resolution In this kata we will be counting the the black squares on a special checkerboard. It is special because it has a `resolution` which determines how the black and white squares are laid out. The `resolution` refers to the dimensions of squares of a single colour. See below for an example wit...
algorithms
def count_checkerboard(w, h, r): nW, rW = divmod(w, r) nH, rH = divmod(h, r) rect = nW * nH / / 2 * r * * 2 # full rectangle # right vertical strip (except corner) rStrip = (nH + nW % 2) / / 2 * r * rW # bottom horizontal strip (except corner) bStrip = (nW + nH % 2) / / 2 * r * rH ...
Checkerboard Resolution
60576b180aef19001bce494d
[ "Performance", "Algorithms", "Matrix" ]
https://www.codewars.com/kata/60576b180aef19001bce494d
6 kyu
Given a natural number n, we want to know in how many ways we may express these numbers as product of other numbers. For example the number ```python 18 = 2 x 9 = 3 x 6 = 2 x 3 x 3 # (we do not consider the product 18 x 1), (3 ways) ``` See this example a bit more complicated, ```python 60 = 2 x 30 = 3 x 20 = 4 x ...
reference
def prod_int_part(n, min_=2): total, fac = 0, [] for d in range(min_, int(n * * .5) + 1): if not n % d: count, sub = prod_int_part(n / / d, d) total += count + 1 if not count: sub = [n / / d] if not fac: fac = [d] + sub return [total, fac]
Product Partitions I
56135a61f8b29814340000cd
[ "Fundamentals", "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/56135a61f8b29814340000cd
6 kyu
<b>Unicode Transformation Format – 8-bit</b> </br>As the name suggests <a href="https://en.wikipedia.org/wiki/UTF-8">UTF-8</a> was designed to encode data in a stream of bytes. It works by splitting the bits up in multiples of eight. This is achieved by inserting headers to mark in how many bytes the bits were split. ...
algorithms
from textwrap import wrap def to_utf8_binary(string): return '' . join(format(x, 'b'). rjust(8, '0') for x in bytearray(string, 'utf-8')) def from_utf8_binary(bitstring): return bytearray([int(t, 2) for t in wrap(bitstring, 8)]). decode()
Utf-8: Binary Encoding
5f5fffc4f6b3390029a6b277
[ "Unicode", "Strings", "Algorithms" ]
https://www.codewars.com/kata/5f5fffc4f6b3390029a6b277
6 kyu
It's about time your hacking skills paid off! You've come across proprietary code for a slot machine (see below), and as it turns out, the program uses a pseudorandom number generator that isn't very random. Now you've realized the potential to win big! Your session starts with a bankroll of `36.00` dollars. You will ...
games
def session(play): play . __globals__['threshold'] = 0
Rob the one-armed bandit
601ae2a5f6d6bb0012947f27
[ "Puzzles", "Algorithms", "Cryptography" ]
https://www.codewars.com/kata/601ae2a5f6d6bb0012947f27
6 kyu
**set!** is a card game where you compete with other players, to find out who can find a _set_ of cards first. Your task is to write a function that checks if a collection of three input cards qualifies as a set. ### The cards Every card has one, two or three symbols in it. A symbol has three distinct features: - ...
algorithms
def is_valid_set(* props): return all(len(set(x)) != 2 for x in props)
Is it a Set?
5fddfbe6a65636001cc4fcd2
[ "Games", "Logic", "Algorithms" ]
https://www.codewars.com/kata/5fddfbe6a65636001cc4fcd2
6 kyu
A [Leyland number](https://en.wikipedia.org/wiki/Leyland_number) is a number of the form `$x^y + y^x$` where `$x$` and `$y$` are integers greater than 1. The first few such numbers are: * `$8 = 2^2 + 2^2$` * `$17 = 2^3 + 3^2$` * `$32 = 2^4 + 4^2$` * `$54 = 3^3 + 3^3$` Return all Leyland numbers up to 10<sup>12</sup>...
games
r = range(2, 40) def f(): return sorted({x * * y + y * * x for x in r for y in r})[: 121]
[Code Golf] Leyland Numbers
6021ab77b00bf1000dd276d3
[ "Restricted", "Puzzles" ]
https://www.codewars.com/kata/6021ab77b00bf1000dd276d3
6 kyu
# Task You are given string <code>s</code>. For example: ```python s = "aebecda" ``` Your task is to shuffle and divide this line into the lowest number of palindromes so that the <b>length</b> of the <b>smallest</b> palindrome in the chosen division is the <b>largest</b> amongst all the smallest palindromes across al...
algorithms
from collections import Counter def lowest(s): if not s: return 0 cnt = Counter(s) pairs, seeds = map(sum, zip(* (divmod(n, 2) for n in cnt . values()))) return len(s) if not seeds else pairs / / seeds * 2 + 1
Divide into palindromes
5f8219c1ae0eb800291c50c1
[ "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/5f8219c1ae0eb800291c50c1
6 kyu
Have you heard about <b>Megamind</b>? <b>Megamind</b> and <b>Metro Man</b> are two aliens who came to earth. <b>Megamind</b> wanted to destroy the earth, while <b>Metro Man</b> wanted to stop him and protect mankind. After a lot of fighting, <b>Megamind</b> finally threw <b>Metro Man</b> up into the sky. <b>Metro Man</...
reference
from math import ceil def mega_mind(hp, dps, shots, regen): if dps * shots >= hp: return ceil(hp / dps) if dps * shots <= regen: return - 1 number_of_regenerations = ceil((hp - dps * shots) / (dps * shots - regen)) return ceil((hp + regen * number_of_regenerations) / dps)
Megamind
5baf21542d15ec9453000147
[ "Fundamentals", "Games" ]
https://www.codewars.com/kata/5baf21542d15ec9453000147
6 kyu
# Scenario With **_Cereal crops_** like wheat or rice, before we can eat the grain kernel, we need to remove that inedible hull, or *to separate the wheat from the chaff*. ___ # Task **_Given_** a *sequence of n integers* , **_separate_** *the negative numbers (chaff) from positive ones (wheat).* ![!alt](https://i...
reference
def wheat_from_chaff(values): i, j = 0, len(values) - 1 while True: while i < j and values[i] < 0: i += 1 while i < j and values[j] > 0: j -= 1 if i >= j: return values values[i], values[j] = values[j], values[i]
Separate The Wheat From The Chaff
5bdcd20478d24e664d00002c
[ "Fundamentals", "Arrays", "Performance" ]
https://www.codewars.com/kata/5bdcd20478d24e664d00002c
6 kyu
Convert the 8-bit grayscale input image (2D-list) into an ASCII-representation. ``` _____/\\\\\\\\\________/\\\\\\\\\\\__________/\\\\\\\\\__/\\\\\\\\\\\__/\\\\\\\\\\\_ ___/\\\\\\\\\\\\\____/\\\/////////\\\_____/\\\////////__\/////\\\///__\/////\\\///__ __/\\\/////////\\\__\//\\\______\///____/\\\/__...
algorithms
def image2ascii(image): return '\n' . join('' . join(glyphs[(v * 8) / / 255] for v in r) for r in image)
Grayscale ASCII-art
5c22954a58251f1fdc000008
[ "ASCII Art", "Algorithms" ]
https://www.codewars.com/kata/5c22954a58251f1fdc000008
6 kyu
This kata is a slightly harder version of [Gravity Flip](https://www.codewars.com/kata/5f70c883e10f9e0001c89673). It is recommended to do that first. Bob is bored in his physics lessons yet again, and this time, he's brought a more complex gravity-changing box with him. It's 3D, with small cubes arranged in a matrix o...
games
import numpy as np dir = { 'L': lambda a: np . sort(a)[:, :: - 1], 'R': lambda a: np . sort(a), 'U': lambda a: np . sort(a, axis=0)[:: - 1, :], 'D': lambda a: np . sort(a, axis=0) } def flip(d, a): return dir[d](np . array(a)). tolist()
Gravity Flip (3D version)
5f849ab530b05d00145b9495
[ "Puzzles", "Arrays" ]
https://www.codewars.com/kata/5f849ab530b05d00145b9495
6 kyu
Remove the parentheses = In this kata you are given a string for example: ```python "example(unwanted thing)example" ``` Your task is to remove everything inside the parentheses as well as the parentheses themselves. The example above would return: ```python "exampleexample" ``` ## Notes * Other than parentheses o...
reference
def remove_parentheses(s): lvl, out = 0, [] for c in s: lvl += c == '(' if not lvl: out . append(c) lvl -= c == ')' return '' . join(out)
Remove the parentheses
5f7c38eb54307c002a2b8cc8
[ "Strings", "Algorithms", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/5f7c38eb54307c002a2b8cc8
6 kyu
Given time in 24-hour format, convert it to words. ``` For example: 13:00 = one o'clock 13:09 = nine minutes past one 13:15 = quarter past one 13:29 = twenty nine minutes past one 13:30 = half past one 13:31 = twenty nine minutes to two 13:45 = quarter to two 00:48 = twelve minutes to one 00:08 = eight minutes p...
reference
def solve(time): def number(n): if n > 20: return "twenty {}" . format(number(n - 20)) return [ None, "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", ...
Read the time
5c2b4182ac111c05cf388858
[ "Fundamentals" ]
https://www.codewars.com/kata/5c2b4182ac111c05cf388858
6 kyu
## Description As the title already told you, you have to parse a IPv6 hex string in a weird way. For each block in the string you have to parse its characters as if they were separate hexadecimal values, add them up, and join the results into a string. Here's an example of an IPv6 string: `1B1D:AF01:3847:F8C4:20E9:0...
algorithms
def parse_IPv6(iPv6): return '' . join(str(sum(int(c, 16) for c in s)) for s in iPv6 . split(iPv6[4]))
Weird IPv6 hex string parsing
5f5bc8a04e485f002d85b303
[ "Parsing", "Algorithms" ]
https://www.codewars.com/kata/5f5bc8a04e485f002d85b303
6 kyu
# Story Those pesky rats have returned and this time they have taken over the Town Square. The <a href="https://en.wikipedia.org/wiki/Pied_Piper_of_Hamelin">Pied Piper</a> has been enlisted again to play his magical tune and coax all the rats towards him. But some of the rats are deaf and are going the wrong way! #...
reference
from math import hypot DIRS = {'←': (0, - 1), '↑': (- 1, 0), '→': (0, 1), '↓': (1, 0), '↖': (- 1, - 1), '↗': (- 1, 1), '↘': (1, 1), '↙': (1, - 1)} def count_deaf_rats(town): pipper = next((x, y) for x, r in enumerate(town) for y, c in enumerate(r) if c == 'P') return sum(isDe...
The Deaf Rats of Hamelin (2D)
5c1448e08a2d87eda400005f
[ "Fundamentals" ]
https://www.codewars.com/kata/5c1448e08a2d87eda400005f
6 kyu
### Lazy Decorator Function You have decided to play a prank on your programmer friend. You want to make his code "Lazy". And not in the good way. You want his functions to only run normally every _nth_ run, otherwise doing nothing. To do this, you are going to write a function decorator `@lazy(n)` where `n` is the ...
reference
def lazy(n): step = - 1 def inner(func): def wrapper(* args, * * kwargs): nonlocal step step += 1 if n > 0 and step % n: return None elif n < 0 and not (step + 1) % n: return None else: return func(* args, * * kwargs) return wrapper return inner
A different kind of 'Lazy' function.
601d457ce00e9a002ccb7403
[ "Decorator" ]
https://www.codewars.com/kata/601d457ce00e9a002ccb7403
6 kyu
# Unpack delicious sausages! A food delivery truck carrying boxes of delicious sausages has arrived and it's your job to unpack them and put them in the store's display counter. The truck is filled with boxes of goods. Among the goods, there are various types of sausages. Straight sausages ```I```, curvy sausages ```...
reference
def unpack_sausages(truck): display = "" counter = 0 for box in truck: for pack in box: if pack[0] == "[" and pack[- 1] == "]": contents = pack[1: - 1] if len(contents) == 4 and len(set(contents)) == 1: counter += 1 if counter % 5: display += contents return " " . ...
Unpack delicious sausages!
5fa6d9e9454977000fb0c1f8
[ "Data Structures", "Fundamentals" ]
https://www.codewars.com/kata/5fa6d9e9454977000fb0c1f8
6 kyu
<!-- Hexagon Beam Max Sum --> <p>In this kata, your task is to find the maximum sum of any straight "beam" on a hexagonal grid, where its cell values are determined by a finite integer sequence <code>seq</code>.<br/><br/> In this context, a beam is a linear sequence of cells in any of the 3 pairs of opposing sides of a...
algorithms
from itertools import cycle, chain def max_hexagon_beam(n, seq): h = 2 * n - 1 seq = cycle(seq) sums = [[0] * h for _ in range(3)] # [horz, diagUp, diagDown] for r in range(h): for c, v in zip(range(n + r if r < n else h + n - 1 - r), seq): idxs = (r, c + max(0, r - n + 1), c + max(0...
Hexagon Beam Max Sum
5ecc1d68c6029000017d8aaf
[ "Puzzles", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5ecc1d68c6029000017d8aaf
6 kyu
## Task Let's say we have a positive integer, `$n$`. You have to find the smallest possible positive integer that when multiplied by `$n$`, becomes a perfect power of integer `$k$`. A perfect power of `$k$` is any positive integer that can be represented as `$a^k$`. For example if `$k = 2$`, then `$36$` is a perfect p...
algorithms
def mul_power(n, k): a = 1 for p in range(2, int(n * * .5) + 1): if not n % p: m = 0 while not n % p: n / /= p m += 1 a *= p * * (- m % k) if n > 1: a *= n * * (k - 1) return a
Multiply by a number, so it becomes a perfect power
5ee98cf315741d00104499e5
[ "Mathematics", "Algebra", "Algorithms" ]
https://www.codewars.com/kata/5ee98cf315741d00104499e5
6 kyu
[IEEE 754](https://en.wikipedia.org/wiki/IEEE_754) is a standard for representing floating-point numbers (i.e. numbers that can have a fractional part and emulate real numbers). Its use is currently ubiquitous in both software (programming languages implementations) and hardware (Floating Point Units ([FPU](https://en...
reference
from struct import pack s = "{:08b}" . format def float_to_IEEE_754(f: float) - > str: binary = '' . join(map(s, pack('!d', f))) return ' ' . join((binary[0], binary[1: 12], binary[12:]))
IEEE 754 floating point numbers
5efcaedf95d7110017896ced
[ "Binary", "Fundamentals" ]
https://www.codewars.com/kata/5efcaedf95d7110017896ced
6 kyu
<img src="https://upload.wikimedia.org/wikipedia/commons/a/a9/IEEE_754_Double_Floating_Point_Format.svg" style="background-color:white" alt="The IEEE 754 double-precision encoding scheme" title = "The IEEE 754 double-precision encoding scheme"> ___ The following table describes the different types of [IEEE 754](http...
reference
import struct class FloatType (NoValue): POSITIVE_DENORMALIZED = auto() NEGATIVE_DENORMALIZED = auto() POSITIVE_NORMALIZED = auto() NEGATIVE_NORMALIZED = auto() POSITIVE_INFINITY = auto() NEGATIVE_INFINITY = auto() POSITIVE_ZERO = auto() NEGATI...
Classify a floating point number
5f1ab7bd5af35f000f4ff875
[ "Binary", "Fundamentals" ]
https://www.codewars.com/kata/5f1ab7bd5af35f000f4ff875
6 kyu
## Text printing like <span style="color:#6899D3">Portal 2</span> end credits Now you finished this brilliant game and wanna create some simillar that you saw after. ### Task: Create function, <span style="color: #D6F870">that take song text</span> and then return <span style="color: #D6F870">symbols step by step o...
algorithms
def lyrics_print(lyrics): return [lyric[: i] + [f" { w [: j + 1 ]} _"] for lyric in lyrics for i, w in enumerate(lyric) for j in range(len(w))]
Portal 2: End credits song. Text printing.
608673cf4b69590030fee8d6
[ "Algorithms" ]
https://www.codewars.com/kata/608673cf4b69590030fee8d6
6 kyu
You're a buyer/seller and your buisness is at stake... You ___need___ to make profit... Or at least, you need to lose the least amount of money! Knowing a list of prices for buy/sell operations, you need to pick two of them. Buy/sell market is evolving across time and the list represent this evolution. First, you nee...
algorithms
def max_profit(prices): m = best = float('-inf') for v in reversed(prices): m, best = max(m, best - v), max(best, v) return m
Best Stock Profit in Single Sale
58f174ed7e9b1f32b40000ec
[ "Algorithms" ]
https://www.codewars.com/kata/58f174ed7e9b1f32b40000ec
6 kyu
<b>Task</b> Given the following arguments and examples, could you figure out my operator? ``` a: integer (0 <= a) -> left operand n: integer (0 <= n <= 4) -> Somehow used by my operator, but I can't remember exactly how, sorry! b: integer (0 <= b) -> right operand * for this kata: all values will be ...
games
from functools import reduce def operator(a, n, b): if n == 0: return 1 + b if n == 1: return a + b if n == 2: return a * b if n == 3: return a * * b return reduce(lambda x, _: a * * x, [1] * (b + 1))
Guess Operator
60512be8bbc51a000a83d767
[ "Algorithms", "Puzzles", "Mathematics" ]
https://www.codewars.com/kata/60512be8bbc51a000a83d767
6 kyu
# Task You are a lifelong fan of your local football club, and proud to say you rarely miss a game. Even though you're a superfan, you still hate boring games. Luckily, boring games often end in a draw, at which point the winner is determined by a penalty shoot-out, which brings some excitement to the viewing experienc...
games
def penaltyShots(shots, score): sa, sb = score return (abs(sa - sb) <= 1) + (sa == sb) if shots >= 5 else max(6 - shots - abs(sa - sb), 0)
Simple Fun #229: Penalty Shots
59073712f98c4718b5000022
[ "Puzzles" ]
https://www.codewars.com/kata/59073712f98c4718b5000022
6 kyu
# Penguin Olympics: Swimming Race Disaster The situation... - The fastest penguins in the world have just swum for the ultimate prize in professional penguin swimming. - The cameras that were capturing the race stopped recording half way through. - The athletes, and the fans are in disarray waiting for the results. ...
games
def score(line): try: pos = line . index('p') except ValueError: pos = line . index('P') left = line[pos + 1: - 1] return len(left) + left . count('~') def calculate_winners(snapshot, penguins): res = sorted((score(line), name) for line, name in zip(snapshot ....
Penguin Olympics: Swimming Race Disaster
6022c97dac16b0001c0e7ccc
[ "Puzzles" ]
https://www.codewars.com/kata/6022c97dac16b0001c0e7ccc
6 kyu
In this Kata you will be given an array (or another language-appropriate collection) representing contestant ranks. You must eliminate contestant in series of rounds comparing consecutive pairs of ranks and store all initial and intermediate results in an array. During one round, the lowest rank of a pair is eliminate...
reference
def tourney(lst): out = [lst] while len(lst) > 1: lst = [lst[- 1]] * (len(lst) % 2) + [* map(max, lst[:: 2], lst[1:: 2])] out . append(lst) return out
Elimination Tournament
5f631ed489e0e101a70c70a0
[ "Arrays", "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/5f631ed489e0e101a70c70a0
6 kyu
The Evil King of Numbers wants to conquer all space in the Digital World. For that reason, His Evilness declared war on Letters, which actually stay in the Alphabet Fragmentation. You were nominated the Great Arbiter and must provide results of battles to the technology God 3 in 1, Llib Setag-Kram Grebrekcuz-Nole Ksum....
reference
def battle_codes(chars, nums): if not chars or not nums: return 'Peace' chars = [ord(c) - 96 for c in chars] nums = [* map(int, nums[:: - 1])] while chars and nums: c, n = chars[- 1], nums[- 1] chars[- 1], nums[- 1] = c - n, n - c if len(chars) > 1: chars[- 2] -= n ...
The Great Digital Conflict
605150ba96ff8c000b6e3df8
[ "Fundamentals" ]
https://www.codewars.com/kata/605150ba96ff8c000b6e3df8
6 kyu
*You don't need python knowledge to complete this kata* You've waited weeks for this moment. Finally an NSA agent has opened the malware you planted on their system. Now you can execute code remotly. It looks like you're on a Linux machine. Your goal is to root the box and return the content of root.txt You don't hav...
games
import crypt def runShell(boxNr): print(boxNr) if boxNr == 1: # return "cd /root; cat root.txt" return 'CodeWars{7594357083475890320019dsfsdjfl32423hjkasd9834haksdSKJAHD32423khdf}' elif boxNr == 2: hash = crypt . crypt('a', '$1$root') cmds = ['cd /etc', 'ls -l', ...
Hack the NSA
5f0795c6e45bc600247ab794
[ "Puzzles" ]
https://www.codewars.com/kata/5f0795c6e45bc600247ab794
5 kyu
Given is a md5 hash of a five digits long PIN. It is given as string. Md5 is a function to hash your password: "password123" ===> "482c811da5d5b4bc6d497ffa98491e38" Why is this useful? Hash functions like md5 can create a hash from string in a short time and it is impossible to find out the password, if you only got t...
algorithms
import hashlib def crack(hash): for i in range(100000): if hashlib . md5(str(i). zfill(5). encode()). hexdigest() == hash: return str(i). zfill(5)
Crack the PIN
5efae11e2d12df00331f91a6
[ "Algorithms", "Cryptography" ]
https://www.codewars.com/kata/5efae11e2d12df00331f91a6
6 kyu
*Translations appreciated* ## Background information The Hamming Code is used to correct errors, so-called bit flips, in data transmissions. Later in the description follows a detailed explanation of how it works. <br> In this Kata we will implement the Hamming Code with bit length 3; this has some advantages and dis...
algorithms
def encode(stg): return "" . join(digit * 3 for char in stg for digit in f" { ord ( char ):0 8 b } ") def decode(binary): reduced = (get_digit(triplet) for triplet in chunks(binary, 3)) return "" . join(get_char(byte) for byte in chunks("" . join(reduced), 8)) def chunks(seq, size): re...
Error correction #1 - Hamming Code
5ef9ca8b76be6d001d5e1c3e
[ "Algorithms", "Bits" ]
https://www.codewars.com/kata/5ef9ca8b76be6d001d5e1c3e
6 kyu
Consider the following well known rules: - To determine if a number is divisible by 37, we take numbers in groups of three digits from the right and check if the sum of these groups is divisible by 37. Example: 4567901119 is divisible by 37 because 37 * 123456787 = 4567901119. Now: 4 + 567 + 901 + 119 = 1591 = 37 * 43...
reference
import math def divisors(p): a = [1] for i in range(2, int(math . sqrt(p)) + 1): if p % i == 0: a . extend([i, p / / i]) a . extend([p]) return list(set(a)) def solve(p): for d in sorted(divisors(p - 1)): if pow(10, d, p) == 1: return '{}-sum' . format(d) brea...
Divisible by primes
5cfe4465ac68b86026b09c77
[ "Fundamentals" ]
https://www.codewars.com/kata/5cfe4465ac68b86026b09c77
6 kyu
## Task Given a string, add the fewest number of characters possible from the front or back to make it a palindrome. ## Example For the input `cdcab`, the output should be `bacdcab` ## Input/Output Input is a string consisting of lowercase latin letters with length 3 <= str.length <= 10 The output is a palindrome...
algorithms
def build_palindrome(s): for n in range(len(s), - 1, - 1): if s[: n] == s[: n][:: - 1]: return s[n:][:: - 1] + s if s[- n:] == s[- n:][:: - 1]: return s + s[: - n][:: - 1]
Palindrome Builder
58efb6ef0849132bf000008f
[ "Algorithms" ]
https://www.codewars.com/kata/58efb6ef0849132bf000008f
6 kyu
### Story In the fictional country of Bugliem, you can ask for a custom licence plate on your car, provided that it meets the followoing criteria: * it's 2-8 characters long * it contains only letters `A-Z`, numbers `0-9`, and dashes `-` * letters and numbers are separated by a dash * it doesn't start or end with a da...
algorithms
import re def licence_plate(s): plate = '-' . join(re . findall(r'[A-Z]+|\d+', s . upper()))[: 8]. rstrip('-') return plate if len(plate) > 1 and not plate . isdigit() else 'not possible'
Custom Licence Plate
5bc64f48eba26e79df000031
[ "Algorithms" ]
https://www.codewars.com/kata/5bc64f48eba26e79df000031
6 kyu
# Introduction A new casino has come to Las Vegas, but this casino does not want to have human staff, but they want to implement a series of computer systems that automate the process. After looking for references and recommendations, the administrative team has decided to hire you to develop these systems. Your assi...
algorithms
def score(hand): score = sum(int(c) if c . isdigit() else 11 if c == "A" else 10 for c in hand) aces = hand . count("A") for _ in range(aces): if score > 21: score -= 10 return "BJ" if score == 21 and len(hand) == 2 else score if score <= 21 else 0 def winners(playe...
Card Games: Black Jack
5bebcbf2832c3acc870000f6
[ "Games", "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/5bebcbf2832c3acc870000f6
6 kyu
## Task You will receive a string consisting of lowercase letters, uppercase letters and digits as input. Your task is to return this string as blocks separated by dashes (`"-"`). The elements of a block should be sorted with respect to the hierarchy listed below, and each block cannot contain multiple instances of th...
reference
from collections import Counter def blocks(s): def sort(c): return (c . isdigit(), c . isupper(), c) answer, counter = [], Counter(s) while counter: block = '' . join(sorted(counter, key=sort)) answer . append(block) counter = counter - Counter(block) return '-' . join(answer)
Return String As Sorted Blocks
5e0f6a3a2964c800238ca87d
[ "Strings", "Algorithms", "Sorting" ]
https://www.codewars.com/kata/5e0f6a3a2964c800238ca87d
6 kyu
In this kata, you have an input string and you should check whether it is a valid message. To decide that, you need to split the string by the numbers, and then compare the numbers with the number of characters in the following substring. For example `"3hey5hello2hi"` should be split into `3, hey, 5, hello, 2, hi` and...
algorithms
import re def is_a_valid_message(message): return all(n and int(n) == len(s) for n, s in re . findall("(\d*)(\D*)", message)[: - 1])
Message Validator
5fc7d2d2682ff3000e1a3fbc
[ "Algorithms" ]
https://www.codewars.com/kata/5fc7d2d2682ff3000e1a3fbc
6 kyu
<h2>Introduction</h2> Let’s assume that when you register a car you are assigned two numbers: 1. Customer ID – number between `0` and `17558423` inclusively. It is assigned to car buyers in the following order: the first customer receives an ID of `0`, the second customer receives an ID of `1`, the third - `2`, and s...
algorithms
def find_the_number_plate(customer_id): q, r = divmod(customer_id, 999) q, a = divmod(q, 26) c, b = divmod(q, 26) return f" { chr ( a + 97 )}{ chr ( b + 97 )}{ chr ( c + 97 )}{ r + 1 :0 3 d } "
Car Number Plate Calculator
5f25f475420f1b002412bb1f
[ "Algorithms", "Logic", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5f25f475420f1b002412bb1f
6 kyu
Two moving objects A and B are moving accross the same orbit (those can be anything: two planets, two satellites, two spaceships,two flying saucers, or spiderman with batman if you prefer). If the two objects start to move from the same point and the orbit is circular, write a function that gives the time the two objec...
reference
def meeting_time(Ta, Tb, r): if Ta == 0: return "{:.2f}" . format(abs(Tb)) elif Tb == 0: return "{:.2f}" . format(abs(Ta)) else: return "{:.2f}" . format(abs(Ta * Tb / (Tb - Ta)))
Basic physics problem - Space -Kinematics
58dc420210d162048a000085
[ "Fundamentals", "Physics", "Algorithms" ]
https://www.codewars.com/kata/58dc420210d162048a000085
6 kyu
You are given a certain array of positive and negative integers which elements occur only once (all of them different from 0), a certain number known as target, ```t, t ≠ 0```, and a number ```k, k > 0.``` You should find the amount of combinations, which numbers are not contiguous elements of the given array and whic...
reference
def find_comb_noncontig(arr, t, k): comb_sum = [] for r, x in enumerate(arr, - 1): comb_sum . append([x] + [x + y for l in range(r) for y in comb_sum[l]]) return sum(t - k <= z <= t + k for row in comb_sum for z in row)
Find Amount of Certain Combinations than its Sum of Elements Are Within a Given Range
5713338968e0cf779b00096e
[ "Fundamentals", "Mathematics", "Data Structures", "Algorithms", "Logic" ]
https://www.codewars.com/kata/5713338968e0cf779b00096e
6 kyu
A binary operation `op` is called associative if `op(a, op(b, c)) = op(op(a, b), c)` for example: `(1 + 2) + 8 = 1 + (2 + 8)` `(A * B) * C = A * (B * C)` where `A, B, C` are matrices with sizes `N x M, M x K, K x L` ## Task Inputs: - `arr` - array of objects with type `T` and size `n` (1..100 000) - `op` - assoc...
algorithms
def compute_ranges(arr, op, rs): """ Efficient and easy segment trees http://codeforces.com/blog/entry/18051 """ def f(a, b): if a is None: return b if b is None: return a return op(a, b) def query(l, r): resL = resR = None l += n r += n...
Associative Operation on Range
608cc9666513cc00192a67a9
[ "Performance", "Algorithms" ]
https://www.codewars.com/kata/608cc9666513cc00192a67a9
4 kyu
Same as https://www.codewars.com/kata/605e61435c2b250040deccf2, but code golf. ### Task You've been given an analogue clock, but rather than the standard 12 hours it can display any number of hours. Given an hour return the time to the second during which the minute and hour hands on an analogue clock would be align...
reference
# 78 :D def time_hands_cross(a, b): return f" { a } :%02d:%02d" % divmod(a % b * 3600 / / ~ - b, 60) * (a != ~ - b)
Clock hands cross [Code Golf]
6004cb552b8bc80017fe26b1
[ "Restricted", "Fundamentals" ]
https://www.codewars.com/kata/6004cb552b8bc80017fe26b1
6 kyu
# Scraping Wikipedia Links From Wikipedia Articles You will create a function that accepts the url of a Wikipedia article as an argument. This function will return a dictionary of keys as titles of articles (given by the title attribute of anchor tags), and values as URLs of articles. The dictionary will only conta...
reference
import re import bs4 import requests HOST = 'https://en.wikipedia.org' EXCLUDING_NAMESPACES = re . compile(f"^/wiki/(?!\w+:)") def wikiscraping(url): body = bs4 . BeautifulSoup(requests . get( url). text). find('div', id='bodyContent') links = body . find_all('a', href=EXCLUDING_NAMESPACES) ...
Web Scraping: Find Every Link to Another Wikipedia Article in a Wikipedia Article
5ecb44975864da0012572d5c
[ "Web Scraping", "Fundamentals" ]
https://www.codewars.com/kata/5ecb44975864da0012572d5c
6 kyu
Credits go to the fantastic Numberphile YouTube channel for the inspiration behind this kata - the specific video for it can be found here: https://www.youtube.com/watch?v=tP-Ipsat90c&t=545s Your challenge in this Kata is to code a function ```check_sequence``` that checks a sequence of coin flip results for specific ...
algorithms
def check_sequence(seq, L, N): return sum(1 for r in seq . replace('HT', 'H T'). replace('TH', 'T H'). split() if len(r) == L) == N
Streaky Patterns in Coin Flips
5c1ac4f002c59c725900003f
[ "Strings", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/5c1ac4f002c59c725900003f
7 kyu
<h1>Task</h1> <p>You get a Boolean expression and the values of its variables as input. Your task is to calculate this Boolean expression with a given set of variable values.</p> <h1>Details</h1> <ul> <li>The input expression consists of variables represented by uppercase letters A-F and operations "&" (logical AND) a...
reference
calculate = eval
Boolean Trilogy #2: Calculate Boolean Expression (Easy)
5f8070c834659f00325b5313
[ "Fundamentals" ]
https://www.codewars.com/kata/5f8070c834659f00325b5313
7 kyu
You will be given a string with sets of characters, (i.e. words), seperated by between one and four spaces (inclusive). Looking at the first letter of each word (case insensitive-`"A"` and `"a"` should be treated the same), you need to determine whether it falls into the positive/first half of the alphabet (`"a"`-`"m"...
reference
def connotation(s): lst = s . upper(). split() return sum('A' <= w[0] <= 'M' for w in lst) >= len(lst) / 2
Negative Connotation
5ef0456fcd067000321baffa
[ "Fundamentals" ]
https://www.codewars.com/kata/5ef0456fcd067000321baffa
7 kyu
# Task In Python 3.5 a new module called [typing](https://docs.python.org/3/library/typing.html) was introduced which provides type hints. In this kata you will need to implement `to_type_hint` which needs to return (a best match of) such a type hint for some input. # Examples ### Numeric Types (int, float, complex...
algorithms
from collections import deque from typing import * def f(t): return Union[tuple(to_type_hint(x) for x in t)] d = { list: List, set: Set, deque: Deque, frozenset: FrozenSet } def to_type_hint(t): v = t . __class__ if t is None: return if v is tuple: w = tuple...
Hint a Type
5ed7625f548425001205e290
[ "Recursion", "Algorithms" ]
https://www.codewars.com/kata/5ed7625f548425001205e290
6 kyu
## Problem Complete the function that takes an odd integer (`0 < n < 1000000`) which is the difference between two consecutive perfect squares, and return these squares as a string in the format `"bigger-smaller"` ## Examples ``` 9 --> "25-16" 5 --> "9-4" 7 --> "16-9" ```
algorithms
def find_squares(n): m = (n - 1) / / 2 return f' {( m + 1 ) * * 2 } - { m * * 2 } '
Find the Squares
60908bc1d5811f0025474291
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/60908bc1d5811f0025474291
7 kyu
The date is March 24, 2437 and the the Earth has been nearly completely destroyed by the actions of its inhabitants. Our last hope in this disaster lies in a shabby time machine built from old toasters and used microwave parts. The World Time Agency requires you to travel back in time to prevent disaster. You are o...
algorithms
import datetime def days(date, month, year): x = datetime . datetime(year, month, date) y = datetime . datetime(2437, 3, 24) delta = y - x t = delta . days if year < 1752 or (year == 1752 and month < 9) or (year == 1752 and month == 9 and date < 14): t -= 11 if year < 1752: ...
Secret Agent Time Travel Calculations
5c1556f37f0627f75b0000d5
[ "Date Time", "Algorithms" ]
https://www.codewars.com/kata/5c1556f37f0627f75b0000d5
5 kyu
Your task is to write a function which counts the number of squares contained in an ASCII art picture. The input pictures contain rectangles---some of them squares---drawn with the characters `-`, `|`, and `+`, where `-` and `|` are used to represent horizontal and vertical sides, and `+` is used to represent corners ...
games
import re def count_squares(lines): h, w = len(lines), max(map(len, lines)) grid = "\t" . join(line . ljust(w) for line in lines) return sum( len(re . findall(r"(?=\+[-+]{%d}\+.{%d}(?:[|+].{%d}[|+].{%d}){%d}\+[-+]{%d}\+)" % (i, w + 1 - i - 2, i, w + 1 - i - 2, i,...
Counting ASCII Art Squares
5bf71b94e50d1b00590000fe
[ "Geometry", "Algorithms", "Puzzles" ]
https://www.codewars.com/kata/5bf71b94e50d1b00590000fe
6 kyu
<!--Transforming Maze Solver--> The objective of this kata will be to guide a ball through an `m` x `n` rectangular maze. This maze is special in that: - all the cells rotate `90` degrees clockwise, in unison, at each interval - each cell can have anywhere from `0` to `4` walls <p>Your goal is to write a function that...
games
from itertools import count def getRevStep(step): return ((step << 2) + (step >> 2)) & 15 CONFIG = ((8, - 1, 0, 'N'), (4, 0, - 1, 'W'), (2, 1, 0, 'S'), (1, 0, 1, 'E')) SWARM = [tuple((step, getRevStep(step), dx, dy, dir) for step, dx, dy, dir in CONFIG if not step & n) for n in range(16)] def ...
Transforming Maze Solver
5b86a6d7a4dcc13cd900000b
[ "Algorithms", "Arrays", "Performance", "Puzzles" ]
https://www.codewars.com/kata/5b86a6d7a4dcc13cd900000b
2 kyu
# Generate All Possible Matches Your mission is to list all possible match flows with scores up to k (k is a parameter). Meaning the first to reach k points wins the match. For examples, Table Tennis (Ping-pong) is a game with 11-point system (up to 11). In this kata your mission is to write a function getting a pos...
reference
def generate_all_possible_matches(n=1): def rec(a, b, p): p . append(f' { a } : { b } ') if n == a or n == b: yield p[:] else: yield from rec(a + 1, b, p) yield from rec(a, b + 1, p) p . pop() return list(rec(0, 0, []))
Generate All Possible Matches
605721e922624800435689e8
[ "Recursion", "Fundamentals" ]
https://www.codewars.com/kata/605721e922624800435689e8
6 kyu
_That's terrible! Some evil korrigans have abducted you during your sleep and threw you into a maze of thorns in the scrubland D: But have no worry, as long as you're asleep your mind is floating freely in the sky above your body._ > **Seeing the whole maze from above in your sleep, can you remember the list of movem...
reference
from collections import deque from numpy import cross, dot MOVES = ((1, 0), (- 1, 0), (0, 1), (0, - 1)) DIRS = ('v', '^', '>', '<') def escape(maze): start = x, y = next((x, y) for x, row in enumerate(maze) for y, c in enumerate(row) if c not in '# ') X, Y, dir = len(maze), ...
Escape the maze
5877027d885d4f6144000404
[ "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/5877027d885d4f6144000404
4 kyu
If you're old enough, you might remember buying your first mobile phone, one of the old ones with no touchscreen, and sending your first text message with excitement in your eyes. Maybe you still have one lying in a drawer somewhere. Let's try to remember the good old days and what it was like to send text messages wi...
algorithms
HOLDERS = '12345678910*#' TOME = {c: n * str(i) for i, seq in enumerate(' /.,?!/abc/def/ghi/jkl/mno/pqrs/tuv/wxyz' . split('/')) for n, c in enumerate(seq, 1)} TOME . update({c: c + '-' for c in HOLDERS}) TOME . update({c: n * '*' for n, c in enumerate("'-+=", 1)}) def send_message(s): isUp, out =...
Texting with an old-school mobile phone
5ca24526b534ce0018a137b5
[ "Fundamentals", "Strings", "Algorithms" ]
https://www.codewars.com/kata/5ca24526b534ce0018a137b5
6 kyu
Let's say we have a number, `num`. Find the number of values of `n` such that: there exists `n` consecutive **positive** values that sum up to `num`. A positive number is `> 0`. `n` can also be 1. ```python #Examples num = 1 #1 return 1 num = 15 #15, (7, 8), (4, 5, 6), (1, 2, 3, 4, 5) return 4 num = 48 #48, (15, 16,...
algorithms
def consecutive_sum(num): upper_limit = 1 while True: if upper_limit * (upper_limit + 1) / / 2 > num: break upper_limit += 1 return sum([1 if i % 2 and not num % i else 1 if not i % 2 and num % i == i / / 2 else 0 for i in range(1, upper_limit)])
Consecutive Sum
5f120a13e63b6a0016f1c9d5
[ "Mathematics" ]
https://www.codewars.com/kata/5f120a13e63b6a0016f1c9d5
null
In this Kata your task is to check the possibility to solve the 'Knight's tour problem' for the desk of the current size. A knight's tour is a sequence of moves of a knight on a chessboard such that the knight visits every square exactly once. If the knight ends on a square that is one knight's move away from the begi...
algorithms
def check(n, m): return n * m >= 20 or f" { min ( n , m )}{ max ( n , m )} " == "34"
Knight's tour problem on (N x M) desk
5fc836f5a167260008dfad7f
[ "Algorithms" ]
https://www.codewars.com/kata/5fc836f5a167260008dfad7f
7 kyu
It's been a tough week at work and you are stuggling to get out of bed in the morning. While waiting at the bus stop you realise that if you could time your arrival to the nearest minute you could get valuable extra minutes in bed. There is a bus that goes to your office every 15 minute, the first bus is at `06:00`, ...
reference
def bus_timer(current_time): h, m = map(int, current_time . split(":")) current_time = 60 * h + m if current_time >= 1436 or current_time <= 355: return (355 - current_time) % 1440 else: return (10 - current_time) % 15
Bus Timer
5736378e3f3dfd5a820000cb
[ "Parsing", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5736378e3f3dfd5a820000cb
7 kyu
### Task Return the length of the given month in the given year. ```if:python,ruby Your code can be maximum `90` characters long. ``` --- ### My other katas If you enjoyed this kata then please try [my other katas](https://www.codewars.com/users/anter69/authored)! :-) #### *Translations are welcome!*
games
from calendar import _monthlen as last_day
[Code Golf] Length of Month
5fc4e46867a010002b4b5f70
[ "Restricted", "Date Time", "Puzzles" ]
https://www.codewars.com/kata/5fc4e46867a010002b4b5f70
7 kyu
Write a function which maps a function over the lists in a list: ```ruby def grid_map inp,&block # applies the &block to all nested elements ``` ```haskell gridMap :: (a -> b) -> [[a]] -> [[b]] ``` ```python def grid_map(inp, op) # which performs op(element) for all elements of inp ``` ```javascript function grid...
reference
def grid_map(lst, op): return [[* map(op, x)] for x in lst]
Map over a list of lists
606b43f4adea6e00425dff42
[ "Fundamentals", "Lists" ]
https://www.codewars.com/kata/606b43f4adea6e00425dff42
7 kyu
## Task In this kata you will be given a list consisting of unique elements except for one thing that appears twice. Your task is to output a list of everything inbetween both occurrences of this element in the list. ## Examples: ```python [0, 1, 2, 3, 4, 5, 6, 1, 7, 8] => [2, 3, 4, 5, 6] ['None', 'Hello', 'Example...
reference
def duplicate_sandwich(arr): start, end = [i for i, x in enumerate(arr) if arr . count(x) > 1] return arr[start + 1: end]
Duplicate sandwich
5f8a15c06dbd530016be0c19
[ "Lists", "Fundamentals" ]
https://www.codewars.com/kata/5f8a15c06dbd530016be0c19
7 kyu
# Description There is a narrow hallway in which people can go right and left only. When two people meet in the hallway, by tradition they must salute each other. People move at the same speed left and right. Your task is to write a function that, given a string representation of people moving in the hallway, will co...
reference
def count_salutes(hallway: str) - > int: right = 0 salutes = 0 for p in hallway: if p == '>': right += 1 if p == '<': salutes += 2 * right return salutes
Count salutes
605ae9e1d2be8a0023b494ed
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/605ae9e1d2be8a0023b494ed
7 kyu
Given: a sequence of different type of values (number, string, boolean). You should return an object with a separate properties for each of types presented in input. Each property should contain an array of corresponding values. - keep order of values like in input array - if type is not presented in input, no corresp...
reference
def separate_types(seq): result = {} for element in seq: if type(element) not in result: result[type(element)] = [element] else: result[type(element)]. append(element) return result
Separate basic types
60113ded99cef9000e309be3
[ "Fundamentals" ]
https://www.codewars.com/kata/60113ded99cef9000e309be3
7 kyu
You are given an n by n ( square ) grid of characters, for example: ```python [['m', 'y', 'e'], ['x', 'a', 'm'], ['p', 'l', 'e']] ``` You are also given a list of integers as input, for example: ```python [1, 3, 5, 8] ``` You have to find the characters in these indexes of the grid if you think of the indexes a...
reference
def grid_index(grid, indexes): flat = sum(grid, []) return "" . join(flat[i - 1] for i in indexes)
Grid index
5f5802bf4c2cc4001a6f859e
[ "Lists", "Fundamentals" ]
https://www.codewars.com/kata/5f5802bf4c2cc4001a6f859e
7 kyu
## Theory In Boolean algebra, any Boolean function takes the value 0 or 1 (True or False) and depends on Boolean variables, which also have two values 0 and 1. Any Boolean function can be placed in canonical disjunctive normal form (CDNF). CDNF is a conjunction of minterms - expressions that are true only on a single ...
algorithms
def cdnf(truth_table): return ' + ' . join(f'( { buildRow ( r [: - 1 ]) } )' for r in truth_table if r[- 1]) def buildRow(r): return ' * ' . join(f' { "~" * ( not b ) } x { i } ' for i, b in enumerate(r, 1))
Boolean Trilogy #1: CDNF
5f76c4779164bf001d52c141
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5f76c4779164bf001d52c141
7 kyu
My PC got infected by a strange virus. It only infects my text files and replaces random letters by `*`, `li*e th*s` `(like this)`. Fortunately, I discovered that the virus hides my censored letters inside root directory. It will be very tedious to recover all these files manually, so your goal is to implement `uncen...
games
def uncensor(infected, discovered): return infected . replace('*', '{}'). format(* discovered)
Ce*s*r*d Strings
5ff6060ed14f4100106d8e6f
[ "Puzzles", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5ff6060ed14f4100106d8e6f
7 kyu
### Task Given an array of numbers and an index, return either the index of the smallest number that is larger than the element at the given index, or `-1` if there is no such index ( or, where applicable, `Nothing` or a similarly empty value ). ### Notes Multiple correct answers may be possible. In this case, retur...
algorithms
def least_larger(a, i): b = [x for x in a if x > a[i]] return a . index(min(b)) if b else - 1
Least Larger
5f8341f6d030dc002a69d7e4
[ "Algorithms", "Arrays" ]
https://www.codewars.com/kata/5f8341f6d030dc002a69d7e4
7 kyu
# Four Seven ```if:python Simple kata, simple rules: your function should accept the inputs `4` and `7`. If `4` is entered, the function should return `7`. If `7` is entered, the function should return `4`. Anything else entered as input should return a false-y value such as `False`, `0`, `[]`, `""`. There's only o...
games
def solution(n): return {4: 7, 7: 4}. get(n)
Four/Seven
5ff50f64c0afc50008861bf0
[ "Puzzles" ]
https://www.codewars.com/kata/5ff50f64c0afc50008861bf0
7 kyu
Given the integer `n` return odd numbers as they are, but subtract 1 from even numbers. **Note:** ~~~if:python,ruby Your solution should be 36 or less characters long. ~~~ ~~~if:javascript Your solution should be 22 or less characters long. ~~~ ### Examples ``` Input = 2 Output = 1 Input = 13 Output = 13 Input ...
algorithms
def always_odd(n): return n - (n % 2 == 0)
[Code Golf] Return Odd No Matter What
5f882dcc272e7a00287743f5
[ "Fundamentals", "Restricted", "Algorithms" ]
https://www.codewars.com/kata/5f882dcc272e7a00287743f5
7 kyu
You are given a list of unique integers `arr`, and two integers `a` and `b`. Your task is to find out whether or not `a` and `b` appear consecutively in `arr`, and return a boolean value (`True` if `a` and `b` are consecutive, `False` otherwise). It is guaranteed that `a` and `b` are both present in `arr`. ~~~if:lam...
reference
def consecutive(A, a, b): return abs(A . index(a) - A . index(b)) == 1
Consecutive items
5f6d533e1475f30001e47514
[ "Fundamentals" ]
https://www.codewars.com/kata/5f6d533e1475f30001e47514
7 kyu
## Task Implement a function that takes an unsigned 32 bit integer as input and sorts its bytes in descending order, returning the resulting (unsigned 32 bit) integer. An alternative way to state the problem is as follows: The number given as input is made up of four bytes. Reorder these bytes so that the resulting (...
reference
def sort_bytes(number): return int . from_bytes(sorted(number . to_bytes(4, 'little')), 'little')
Sort the Bytes
6076d4edc7bf5d0041b31dcf
[ "Algorithms", "Fundamentals", "Sorting" ]
https://www.codewars.com/kata/6076d4edc7bf5d0041b31dcf
7 kyu
The <b><i>status</b></i> of each element of an array of integers can be determined by its position in the array and the value of the other elements in the array. The status of an element <i><b>E</b></i> in an array of size <i><b>N</b></i> is determined by adding the position <i><b>P</b></i>, 0 <= <i><b>P</b></i> ...
algorithms
def status(nums): cnts = {n: len(nums) - i for i, n in enumerate(sorted(nums, reverse=True), 1)} def itemStatus(it): return it[0] + cnts[it[1]] return [v for _, v in sorted(enumerate(nums), key=itemStatus)]
Status Arrays
601c18c1d92283000ec86f2b
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/601c18c1d92283000ec86f2b
7 kyu
# Task You have a list of integers. The task is to return the maximum sum of the elements located between two negative elements. No negative element should be present in the sum. If there is no such sum: `-1` for Python, C++, JavaScript, Java, CoffeeScript and COBOL, `Nothing` for Haskell, `None` for Rust. ## Example ...
algorithms
from itertools import dropwhile def max_sum_between_two_negatives(arr): top = c = - 1 for v in dropwhile((0). __le__, arr): if v < 0: top, c = max(top, c), 0 else: c += v return top
Max sum between two negatives
6066ae080168ff0032c4107a
[ "Algorithms" ]
https://www.codewars.com/kata/6066ae080168ff0032c4107a
7 kyu
All clocks can have their times changed, so when a clock is going too fast or slow, the time can be changed to be correct again. Bob has a 24-hour clock (so `2:00 PM` will be `14:00` instead), on which there are two buttons -- the `H` button and the `M` button, which increase the hour and minute, respectively, by one. ...
reference
def set_clock(time, buttons): h, m = map(int, time . split(':')) h += buttons . count('H') m += buttons . count('M') return f' { h % 24 or 24 } : { m % 60 :0 2 } '
Set the Clock
5fbfc2c0dce9ec000de691e3
[ "Puzzles", "Fundamentals" ]
https://www.codewars.com/kata/5fbfc2c0dce9ec000de691e3
7 kyu
## Task Your task is to write a function called ```valid_spacing()``` or ```validSpacing()``` which checks if a string has valid spacing. The function should return either ```true``` or ```false``` (or the corresponding value in each language). For this kata, the definition of valid spacing is one space between wor...
reference
def valid_spacing(s): return s == ' ' . join(s . split())
Valid Spacing
5f77d62851f6bc0033616bd8
[ "Fundamentals" ]
https://www.codewars.com/kata/5f77d62851f6bc0033616bd8
7 kyu
# Tap Code Translation [Tap code](https://en.wikipedia.org/wiki/Tap_code) is a way to communicate using a series of taps and pauses for each letter. In this kata, we will use dots `.` for the taps and whitespaces for the pauses. The number of taps needed for each letter matches its coordinates in the following polybi...
algorithms
def tap_code_translation(text): dots = {'a': '. .', 'b': '. ..', 'c': '. ...', 'd': '. ....', 'e': '. .....', 'f': '.. .', 'g': '.. ..', 'h': '.. ...', 'i': '.. ....', 'j': '.. .....', 'k': '. ...', 'l': '... .', 'm': '... ..', 'n': '... ...', 'o': '... ....', 'p': '... .....', 'q': '.... .', 'r': '.....
Tap Code Translation
605f5d33f38ca800322cb18f
[ "Algorithms", "Strings", "Cryptography", "Security" ]
https://www.codewars.com/kata/605f5d33f38ca800322cb18f
7 kyu
In a certain kingdom, strange mathematics is taught at school. Its main difference from ordinary mathematics is that the numbers in it are not ordered in ascending order, but lexicographically, as in a dictionary (first by the first digit, then, if the first digit is equal, by the second, and so on). In addition, we do...
reference
def strange_math(n, k): return sorted(range(n + 1), key=str). index(k)
Strange mathematics
604517d65b464d000d51381f
[ "Sorting", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/604517d65b464d000d51381f
7 kyu
Uh oh, Someone at the office has dropped all these sequences on the floor and forgotten to label them with their correct bases. We have to fix this before the boss gets back or we're all going to be fired! This is what your years of coding have been leading up to, now is your time to shine! ## Task You will have t...
games
def base_finder(seq): return len(set('' . join(seq)))
Bases Everywhere
5f47e79e18330d001a195b55
[ "Puzzles" ]
https://www.codewars.com/kata/5f47e79e18330d001a195b55
7 kyu
<h1>Hit the target</h1> given a matrix <code>n x n</code> (2-7), determine if the arrow is directed to the target (x). <br> There will be only 1 arrow '>' and 1 target 'x'<br> An empty spot will be denoted by a space " ", the target with a cross "x", and the scope ">" <h2>Examples:</h2> given matrix 4x4: <br> <code>[...
reference
def solution(mtrx): for row in mtrx: if ">" in row and "x" in row: return row . index(">") < row . index("x") return False
Game Hit the target
5ffc226ce1666a002bf023d2
[ "Games", "Matrix", "Arrays", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5ffc226ce1666a002bf023d2
7 kyu