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
For this kata you will have to forget how to add two numbers. It can be best explained using the following meme: [![Dayane Rivas adding up a sum while competing in the Guatemalan television show "Combate" in May 2016](https://i.ibb.co/Y01rMJR/caf.png)](https://knowyourmeme.com/memes/girl-at-whiteboard-adding) In sim...
algorithms
def add(a, b): s = "" while a + b: a, p = divmod(a, 10) b, q = divmod(b, 10) s = str(p + q) + s return int(s or '0')
16+18=214
5effa412233ac3002a9e471d
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/5effa412233ac3002a9e471d
7 kyu
In cryptanalysis, words patterns can be a useful tool in cracking simple ciphers. A word pattern is a description of the patterns of letters occurring in a word, where each letter is given an integer code in order of appearance. So the first letter is given the code 0, and second is then assigned 1 if it is different ...
reference
def word_pattern(word): ret, box, i = [], {}, 0 for e in word . lower(): if e not in box: box[e] = str(i) i += 1 ret . append(box[e]) return '.' . join(ret)
Cryptanalysis Word Patterns
5f3142b3a28d9b002ef58f5e
[ "Fundamentals" ]
https://www.codewars.com/kata/5f3142b3a28d9b002ef58f5e
7 kyu
You probably know that some characters written on a piece of paper, after turning this sheet 180 degrees, can be read, although sometimes in a different way. So, uppercase letters "H", "I", "N", "O", "S", "X", "Z" after rotation are not changed, the letter "M" becomes a "W", and Vice versa, the letter "W" becomes a "M...
reference
def shifter(st): return sum(all(elem in "HIMNOSWXZ" for elem in x) for x in set(st . split()))
Shifter words
603b2bb1c7646d000f900083
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/603b2bb1c7646d000f900083
7 kyu
[FRACTRAN](https://esolangs.org/wiki/Fractran) is a Turing-complete esoteric programming language invented by John Conway. In Fractran, a program consists of a finite list of positive fractions. The input to a program is a positive integer `$n$`. The program is run by updating the integer `$n$` as follows: * For t...
algorithms
from fractions import Fraction as F def fractran(code, n): fs = [F(f) for f in code . split()] for _ in range(1000): try: n = next(f * n for f in fs if (f * n). denominator == 1) except StopIteration: break return n
Fractran Interpreter
5ebae674014091001729a9d7
[ "Interpreters", "Esoteric Languages" ]
https://www.codewars.com/kata/5ebae674014091001729a9d7
7 kyu
There are some stones on Bob's table in a row, and each of them can be red, green or blue, indicated by the characters `R`, `G`, and `B`. Help Bob find the minimum number of stones he needs to remove from the table so that the stones in each pair of adjacent stones have different colors. Examples: ``` "RGBRGBRGGB" ...
reference
def solution(s): st = [1 for i in range(1, len(s)) if s[i - 1] == s[i]] return sum(st)
Stones on the Table
5f70e4cce10f9e0001c8995a
[ "Fundamentals" ]
https://www.codewars.com/kata/5f70e4cce10f9e0001c8995a
7 kyu
Given a string as input, return a new string with each letter pushed to the right by its respective index in the alphabet. We all know that `A` is a slow and `Z` is a fast letter. This means that `Z` gets shifted to the right by 25 spaces, `A` doesn't get shifted at all, and `B` gets shifted by 1 space. You can assum...
algorithms
def speedify(s): lst = [' '] * (len(s) + 26) for i, c in enumerate(s): lst[i + ord(c) - 65] = c return '' . join(lst). rstrip()
The Speed of Letters
5fc7caa854783c002196f2cb
[ "Algorithms" ]
https://www.codewars.com/kata/5fc7caa854783c002196f2cb
7 kyu
We will call a natural number a "doubleton number" if it contains exactly two distinct digits. For example, `23, 35, 100, 12121` are doubleton numbers, and `123` and `9980` are not. For a given natural number `n` (from `1` to `1 000 000`), you need to find the next doubleton number. If `n` itself is a doubleton, retu...
reference
def doubleton(num): n = num + 1 while len(set(str(n))) != 2: n += 1 return n
Doubleton number
604287495a72ae00131685c7
[ "Sets", "Fundamentals" ]
https://www.codewars.com/kata/604287495a72ae00131685c7
7 kyu
Given a list of integers, find the positive difference between each consecutive pair of numbers, and put this into a new list of differences. Then, find the differences between consecutive pairs in this new list, and repeat until the list has a length of `1`. Then, return the single value. The list will only contain i...
algorithms
def differences(lst): if len(lst) < 2: return lst[0] if lst else 0 return differences([abs(b - a) for a, b in zip(lst, lst[1:])])
Consecutive Differences
5ff22b6e833a9300180bb953
[ "Algorithms" ]
https://www.codewars.com/kata/5ff22b6e833a9300180bb953
7 kyu
Red Knight is chasing two pawns. Which pawn will be caught, and where? #### Input / Output Input will be two integers: - `N` / `n` (Ruby) vertical position of Red Knight (`0` or `1`). - `P` / `p` (Ruby) horizontal position of two pawns (between `2` and `1000000`). Output has to be a _tuple_ (python, haskell, Rust, ...
reference
def red_knight(N, P): return ('White' if P % 2 == N else 'Black', P * 2)
Red Knight
5fc4349ddb878a0017838d0f
[ "Puzzles", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/5fc4349ddb878a0017838d0f
7 kyu
A laboratory is testing how atoms react in ionic state during nuclear fusion. They introduce different elements with Hydrogen in high temperature and pressurized chamber. Due to unknown reason the chamber lost its power and the elements in it started precipitating</br> Given the number of atoms of Carbon [C],Hydrogen[H...
reference
# Make sure you follow the order of reaction # output should be H2O,CO2,CH4 def burner(c, h, o): water = co2 = methane = 0 while h > 1 and o > 0: water += 1 h -= 2 o -= 1 while c > 0 and o > 1: co2 += 1 c -= 1 o -= 2 while c > 0 and h > 3: methane += 1 c -= 1 h -= 4 ...
⚠️Fusion Chamber Shutdown⚠️
5fde1ea66ba4060008ea5bd9
[ "Fundamentals" ]
https://www.codewars.com/kata/5fde1ea66ba4060008ea5bd9
7 kyu
# Right in the Center _This is inspired by one of Nick Parlante's exercises on the [CodingBat](https://codingbat.com/java) online code practice tool._ Given a sequence of characters, does `"abc"` appear in the CENTER of the sequence? The sequence of characters could contain more than one `"abc"`. To define CENTER, ...
reference
def is_in_middle(s): while len(s) > 4: s = s[1: - 1] return 'abc' in s
Right in the Centre
5f5da7a415fbdc0001ae3c69
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5f5da7a415fbdc0001ae3c69
7 kyu
Your friend has recently started using Codewars to learn more advanced coding. They have just created their first kata, and they want to write a proper description for it, using codeblocks, images and hyperlinks. However, they are struggling to understand how to use Markdown formatting properly, so they decide to as...
reference
MODELS = { 'link': '[{txt}]({uL})', 'img': '![{txt}]({uL})', 'code': "```{uL}\n{txt}\n```", } def generate_markdowns(mkd, txt, url_or_language): return MODELS[mkd]. format(txt=txt, uL=url_or_language)
Generating Markdowns
5f656199132bf60027275739
[ "Fundamentals" ]
https://www.codewars.com/kata/5f656199132bf60027275739
7 kyu
If you've completed this kata already and want a bigger challenge, here's the [3D version](https://www.codewars.com/kata/5f849ab530b05d00145b9495/) Bob is bored during his physics lessons so he's built himself a toy box to help pass the time. The box is special because it has the ability to change gravity. There are...
games
def flip(d, a): return sorted(a, reverse=d == 'L')
Gravity Flip
5f70c883e10f9e0001c89673
[ "Puzzles", "Arrays" ]
https://www.codewars.com/kata/5f70c883e10f9e0001c89673
8 kyu
## Introduction `float`s have limited precision and are unable to exactly represent some values. Rounding errors accumulate with repeated computation, and numbers expected to be equal often differ slightly. As a result, it is common advice to not use an exact equality comparison (`==`) with floats. ```python >>> a, ...
bug_fixes
def approx_equals(a, b): return abs(a - b) < 0.001
Floating point comparison
5f9f43328a6bff002fa29eb8
[ "Fundamentals", "Mathematics", "Debugging" ]
https://www.codewars.com/kata/5f9f43328a6bff002fa29eb8
8 kyu
Bob has a ladder. He wants to climb this ladder, but being a precocious child, he wonders in exactly how many ways he could climb this `n` size ladder using jumps of up to distance `k`. Consider this example... n = 5 k = 3 Here, Bob has a ladder of length `5`, and with each jump, he can ascend up to `3` step...
reference
from collections import deque def count_ways(n, k): s, d = 1, deque([0] * k) for i in range(n): d . append(s) s = 2 * s - d . popleft() return s - d . pop()
Bob's Jump
5eea52f43ed68e00016701f3
[ "Performance", "Fundamentals" ]
https://www.codewars.com/kata/5eea52f43ed68e00016701f3
null
## Your Task Complete the function to convert an integer into a string of the Turkish name. * input will always be an integer 0-99; * output should always be lower case. ## Background Forming the Turkish names for the numbers 0-99 is very straightforward: * units (0-9) and tens (10, 20, 30, etc.) each have their ow...
reference
UNITS = ' bir iki üç dört beş altı yedi sekiz dokuz' . split(' ') TENS = ' on yirmi otuz kırk elli altmış yetmiş seksen doksan' . split(' ') def get_turkish_number(n): return f' { TENS [ n / / 10 ] } { UNITS [ n % 10 ] } ' . strip() or 'sıfır'
Turkish Numbers, 0-99
5ebd53ea50d0680031190b96
[ "Fundamentals" ]
https://www.codewars.com/kata/5ebd53ea50d0680031190b96
7 kyu
## Task Create a function that given a sequence of strings, groups the elements that can be obtained by rotating others, ignoring upper or lower cases. In the event that an element appears more than once in the input sequence, only one of them will be taken into account for the result, discarding the rest. #...
games
def group_cities(seq): result = [] sort_result = [] seq = list(dict . fromkeys(seq)) # removing duplicates for e, i in enumerate(seq): sort_result = [j for j in seq if len(j) == len( i) and j . lower() in 2 * (i . lower())] if not sorted(sort_result) in result: result . appe...
rotate the letters of each element
5e98712b7de14f0026ef1cc1
[ "Lists", "Strings", "Sorting" ]
https://www.codewars.com/kata/5e98712b7de14f0026ef1cc1
6 kyu
Let us take a string composed of decimal digits: `"10111213"`. We want to code this string as a string of `0` and `1` and after that be able to decode it. To code we decompose the given string in its decimal digits (in the above example: `1 0 1 1 1 2 1 3`) and we will code each digit. #### Coding process to code a nu...
reference
def code(s): return '' . join(f' { "0" * ( d . bit_length () - 1 )} 1 { d : b } ' for d in map(int, s)) def decode(s): it, n, out = iter(s), 1, [] for c in it: if c == '0': n += 1 else: out . append(int('' . join(next(it) for _ in range(n)), 2)) n = 1 return '' . join...
Binaries
5d98b6b38b0f6c001a461198
[ "Fundamentals" ]
https://www.codewars.com/kata/5d98b6b38b0f6c001a461198
6 kyu
A floating-point number can be represented as `mantissa * radix ^ exponent` (^ is raising radix to power exponent). In this kata we will be given a positive floating-point number `aNumber` and we want to decompose it into a positive integer `mantissa` composed of a given number of digits (called `digitsNumber`) and of ...
reference
def mant_exp(a_number, digits_number): exp = 0 m = a_number num = 10 * * digits_number if m < num: # negative exponent while m * 10 < num: m *= 10 exp -= 1 else: while m >= num: m /= 10 exp += 1 return str(int(m)) + 'P' + str(exp)
A floating-point system
5df754981f177f0032259090
[ "Fundamentals" ]
https://www.codewars.com/kata/5df754981f177f0032259090
6 kyu
### Description Find the sum of all numbers with the same digits (permutations) as the input number, **including duplicates**. However, due to the fact that this is a performance edition kata, the input can go up to `10**10000`. That's a number with 10001 digits (at most)! Be sure to use efficient algorithms and good ...
reference
from math import factorial as fact def sum_arrangements(n): s = str(n) perms = fact(len(s) - 1) coefAll = int('1' * len(s)) return coefAll * perms * sum(map(int, s))
Sum of all numbers with the same digits (performance edition)
5eb9a92898f59000184c8e34
[ "Performance", "Permutations", "Fundamentals" ]
https://www.codewars.com/kata/5eb9a92898f59000184c8e34
6 kyu
In this kata your task is to differentiate a mathematical expression given as a string in prefix notation. The result should be the derivative of the expression returned in prefix notation. To simplify things we will use a simple list format made up of parentesis and spaces. - The expression format is (func arg1) or...
algorithms
def parse_expr(s): s = s[1: - 1] if s[0] == '(' else s if s . isdigit(): return ('num', int(s)) elif ' ' not in s: return ('var', s) depth = 0 first_space = s . index(' ') op = s[: first_space] for i, c in enumerate(s[first_space + 1:]): if c == '(': de...
Symbolic differentiation of prefix expressions
584daf7215ac503d5a0001ae
[ "Algorithms" ]
https://www.codewars.com/kata/584daf7215ac503d5a0001ae
2 kyu
You will be given an array of strings. The words in the array should mesh together where one or more letters at the end of one word will have the same letters (in the same order) as the next word in the array. But, there are times when all the words won't mesh. **Examples of meshed words:** "apply" and "plywood" ...
reference
import re def word_mesh(arr): common = re . findall(r'(.+) (?=\1)', ' ' . join(arr)) return '' . join(common) if len(common) + 1 == len(arr) else 'failed to mesh'
Word Mesh
5c1ae703ba76f438530000a2
[ "Regular Expressions", "Arrays", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5c1ae703ba76f438530000a2
6 kyu
Given an array of integers and an integer `m`, return the sum of the product of its subsequences of length `m`. Ex1: ```python a = [1, 2, 3] m = 2 ``` ```javascript a = [1, 2, 3] m = 2 ``` ```haskell xs = [1, 2, 3] m = 2 ``` ```cobol xs = [1, 2, 3] m = 2 ``` ```go a := []int{1, 2, 3} m := 2 ``` the subse...
reference
def product_sum(xs, m): ss = [1] + [0] * m for x in xs: for i in range(m, 0, - 1): ss[i] += ss[i - 1] * x return ss[m] % (10 * * 9 + 7)
Subsequence Product Sum
5d653190d94b3b0021ec8f2b
[ "Combinatorics", "Performance", "Dynamic Programming", "Fundamentals" ]
https://www.codewars.com/kata/5d653190d94b3b0021ec8f2b
5 kyu
# Autoformat code level 2 You have received a code file, it looks like that it has been written by different people with different code editors. There is an unwanted mix of spaces `" "` and tabs `"\t"` where there should only be spaces. ## Task: The function must correct errors in the indentation of each line of tex...
reference
import re def autoformat(s): return re . sub(r'^[ \t]+', indenter, s, flags=re . M) def indenter(m, s=0): for c in m[0]: s += c == ' ' or 4 - s % 4 n, r = divmod(s, 4) return ' ' * (n + (r > 1)) * 4
Computer problem series #7: Indentation mix
5db017dd3affec001f3775b1
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/5db017dd3affec001f3775b1
6 kyu
You're in the casino, playing Roulette, going for the "1-18" bets only and desperate to beat the house and so you want to test how effective the [Martingale strategy](https://en.wikipedia.org/wiki/Martingale_(betting_system)) is. You will be given a starting cash balance and an array of binary digits to represent a w...
games
def martingale(bank, outcomes): stake = 100 for i in outcomes: if i == 0: bank -= stake stake *= 2 else: bank += stake stake = 100 return bank
Mr Martingale
5eb34624fec7d10016de426e
[ "Games", "Puzzles" ]
https://www.codewars.com/kata/5eb34624fec7d10016de426e
7 kyu
Adding tip to a restaurant bill in a graceful way can be tricky, thats why you need make a function for it. The function will receive the restaurant bill (always a positive number) as an argument. You need to 1) **add at least 15%** in tip, 2) round that number up to an *elegant* value and 3) return it. What is an *e...
reference
from math import ceil, log10 def graceful_tipping(bill): bill *= 1.15 if bill < 10: return ceil(bill) e = int(log10(bill)) unit = (10 * * e) / 2 return ceil(bill / unit) * unit
Graceful Tipping
5eb27d81077a7400171c6820
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5eb27d81077a7400171c6820
7 kyu
This kata provides you with a list of parent-child pairs `family_list`, and from this family description you'll need to find the relationship between two members(what is the relation of latter with former) which is given as `target_pair`. For example, the family list may be given as: ```python [('Enid', 'Susan'), ('S...
algorithms
def relations(family_list, target_pair): parents = {} for parent, child in family_list: parents[child] = parent a, b = target_pair ap = parents . get(a) app = parents . get(ap) bp = parents . get(b) bpp = parents . get(bp) if b == ap: return 'Mother' if b == app:...
Family Relations
5eaf798e739e39001218a2f4
[ "Trees", "Algorithms", "Data Structures" ]
https://www.codewars.com/kata/5eaf798e739e39001218a2f4
7 kyu
## **Task** Four mirrors are placed in a way that they form a rectangle with corners at coordinates `(0, 0)`, `(max_x, 0)`, `(0, max_y)`, and `(max_x, max_y)`. A light ray enters this rectangle through a hole at the position `(0, 0)` and moves at an angle of 45 degrees relative to the axes. Each time it hits one of th...
algorithms
def reflections(n, m): x = y = 0 dx = dy = 1 while 1: x += dx y += dy if x == y == 0 or x == n and y == m: return 1 if 0 in (x, y) and (x == n or y == m): return 0 if x in (0, n): dx *= - 1 if y in (0, m): dy *= - 1
Reflecting Light
5eaf88f92b679f001423cc66
[ "Geometry", "Algorithms" ]
https://www.codewars.com/kata/5eaf88f92b679f001423cc66
7 kyu
This is the subsequent Kata of [this one](https://www.codewars.com/kata/597ccf7613d879c4cb00000f). In this Kata you should convert the representation of "type"s, from Kotlin to Java, and **you don't have to know Kotlin or Java in advance** :D ```if:haskell If you successfully parsed the input, return `Right result`, ...
reference
import re NAME = r'[_a-zA-Z]\w*' TOKENIZER = re . compile(fr'->|(?:in |out )(?= * { NAME } )| { NAME } |.') CONVERTER = {'*': '?', 'in ': '? super ', 'out ': '? extends ', 'Int': 'Integer', 'Unit': 'Void'} class InvalidExpr (Exception): ...
Type Transpiler
59a6949d398b5d6aec000007
[ "Algorithms", "Strings" ]
https://www.codewars.com/kata/59a6949d398b5d6aec000007
3 kyu
Stacey is a big [AD&D](https://en.wikipedia.org/wiki/Dungeons_%26_Dragons) games nerd. Moreover, she's a munchkin. Not a [cat breed](https://en.wikipedia.org/wiki/Munchkin_cat), but a person who likes to get maximum efficiency of their character. As you might know, many aspects of such games are modelled by rolling di...
algorithms
from math import factorial as fac def comb(n, k): return fac(n) / (fac(k) * fac(n - k)) def roll_dice(n, m, x): return 1 - sum((- 1) * * k * comb(n, k) * comb(x - 1 - k * m, x - n - 1 - k * m) / m * * n for k in range(n + 1) if x - n - 1 >= m * k)
Dice rolls threshold
55d18ceefdc5aba4290000e5
[ "Probability", "Combinatorics", "Algorithms" ]
https://www.codewars.com/kata/55d18ceefdc5aba4290000e5
4 kyu
# The folly of Mr Pong While Mrs Pong is away visiting her sister, **Mr Pong** has foolishly set up a ping pong table in his lounge room, and invites his neighbour **Mr Ping** over for a friendly ping pong session. When Mr Ping hits the ping pong ball, the ping pong ball goes `ping`. When Mr Pong hits the ping pong ...
algorithms
def ping_pong(sounds: str) - > str: p, c, f = dict . fromkeys(('ping', 'pong'), 0), None, None for x in sounds . split('-'): if c and x not in p: f = c if c and x in p: p[c] += 1 c = [None, x][x in p] if len(set(p . values())) == 1: p . pop(f) return max(p . items(), ke...
Ping Pong
5ea39ab1d8425e0029fcd035
[ "Algorithms" ]
https://www.codewars.com/kata/5ea39ab1d8425e0029fcd035
6 kyu
In lambda calculus, the only primitive are lambdas. No numbers, no strings, and of course no booleans. Everything is reduced to anonymous functions. Booleans are defined thusly ( this definition is `Preloaded` for you ) : ```lambdacalc True = \ true _false . true False = \ _true false . false ``` ```haskell type Boo...
algorithms
n = false(false) o = true(true) t = false a = false d = true(false) r = false(true) x = None
Church Booleans - Prefix is Overrated
5ea91813b4702500282042c3
[ "Puzzles", "Algorithms" ]
https://www.codewars.com/kata/5ea91813b4702500282042c3
6 kyu
# One is the loneliest number ## Task The range of vision of a digit is its own value. `1` can see one digit to the left and one digit to the right,` 2` can see two digits, and so on. Thus, the loneliness of a digit `N` is the sum of the digits which it can see. Given a non-negative integer, your funtion must deter...
games
def loneliest(n): a = list(map(int, str(n))) b = [(sum(a[max(0, i - x): i + x + 1]) - x, x) for i, x in enumerate(a)] return (min(b)[0], 1) in b
One is the loneliest number
5dfa33aacec189000f25e9a9
[ "Lists", "Puzzles" ]
https://www.codewars.com/kata/5dfa33aacec189000f25e9a9
6 kyu
In this kata your task is to create a hamiltonian cycle on a grid: a closed path which visits every single square in the grid exactly once. Finding hamiltonian cycles is in general a NP-complete problem; however, in the case of a grid, the problem is <strong>not</strong>, and you can find a much simpler solution! Inte...
games
def find_cycle(a, b): if (a % 2 and b % 2) or 1 in {a, b}: return None else: r, c = (a, b) if a % 2 == 0 else (b, a) res = [(0, y) for y in range(c)] res . extend([(x, c - 1) for x in range(1, r)]) for k, x in enumerate(range(r - 1, 0, - 1)): res . extend([(x, y if k % 2 else c...
Hamiltonian cycle: create one !
5ea6f5d99fe5a2001e14ba13
[ "Puzzles", "Graph Theory" ]
https://www.codewars.com/kata/5ea6f5d99fe5a2001e14ba13
6 kyu
# Max From Common DataFrames ## Input parameters Two `pandas.DataFrame` objects ## Task Your function must return a new `pandas.DataFrame` with the same data and columns from the first parameter. For common columns in both inputs you must return the greater value of each cell for that column. You must not modify...
reference
import pandas as pd def max_common(df_a, df_b): return pd . concat([df_a, df_b]). filter(items=df_a . columns). groupby(level=0). max()
Pandas Series 102: Max From Common DataFrames
5ea2a798f9632c0032659a75
[ "Data Frames", "Fundamentals", "Data Science" ]
https://www.codewars.com/kata/5ea2a798f9632c0032659a75
6 kyu
# Rename Columns ## Input parameters 1. `pandas.DataFrame` object 2. sequence ## Task Your function must return a new `pandas.DataFrame` object with same data than the original input but now its column names are the elements of the sequence. You must not modify the original input. The number of columns of the inpu...
reference
import pandas as pd def rename_columns(df, names): return pd . DataFrame(data=df . values, columns=names)
Pandas Series 101: Rename Columns
5e60cdcd01712200335bd676
[ "Strings", "Data Frames", "Fundamentals", "Data Science" ]
https://www.codewars.com/kata/5e60cdcd01712200335bd676
7 kyu
## Task: Given a circle and an external point, you have to find the tangents from point to the circle. ------ ## Background: One of the easiest methods in Analytic Geometry for finding the tangent lines from an external point is using the polar line. In the image we have below, we may see the method: ![Imgur](ht...
reference
import math def dist(x, y): return (x * * 2 + y * * 2) * * .5 def tang_from_point(circle, point): ((cx, cy), r), (px, py) = circle, point a, b = math . asin(r / dist(py - cy, px - cx) ), math . atan2(py - cy, px - cx) return [[round(m, 4), round(py - m * px, 4)] for m in sorted((m...
Tangent Lines to a Circle from an External Point
5602c713f75452a7c500005c
[ "Fundamentals", "Mathematics", "Geometry" ]
https://www.codewars.com/kata/5602c713f75452a7c500005c
6 kyu
We have a certain number of lattice points of coordinates (x, y), (both integer values). A random laser beam crosses the lattice points field. We are interested in finding the maximum number of lattice points that may be encountered by a single laser beam, and the number of different laser beams that cross that maxim...
reference
from fractions import Fraction from collections import defaultdict from itertools import combinations from math import inf def max_encount_points(lst): d = defaultdict(int) for (i, j), (x, y) in combinations(lst, 2): slope = Fraction(y - j, (x - i)) if x - i else inf ord0 = j - slope * i if x - i else...
Maximum Possible Amount of Lattice Points That May Be Encountered By a Single Laser Beam.
56ccc33b29aab18ca4001c64
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic", "Geometry" ]
https://www.codewars.com/kata/56ccc33b29aab18ca4001c64
6 kyu
You are given: - an array of integers, ```arr ```, all of them positive. - an integer ```k, 2 <= k <= 4 ```, (amount of digits) - an integer ```s, 6 <= s <= 24 ```, sum value of k contiguous digits. You have to search the maximum or minimum number obtained as a result of concatenating the numbers of the array in...
reference
from itertools import permutations def concat_max_min(arr, k, s): num = [] for i in range(1, len(arr) + 1): for x in permutations(arr, i): m = '' . join(map(str, x)) if len(m) >= k and all(sum(map(int, m[j: j + k])) <= s for j in range(len(m) - k + 1)): num . append(int(m)) retur...
Max & Min Numbers Concatenation with Constraints
57180ffc1c27346abd0011ee
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic", "Strings" ]
https://www.codewars.com/kata/57180ffc1c27346abd0011ee
5 kyu
A proper fraction: `n/d` has the property that `gcd(n,d)` equals to `1`, being gcd(n,d) **the greatest common divisor** of `n` and `d`. These kind of fractions receive also the name of **Irreducible Fractions**. If we generate all the proper fractions, with values less than one and positive, higher than zero, in dece...
reference
def f(d_max, n): """Calculate the nth element of d_max-th Farey sequence in descending order.""" a, b, c, d = 1, 1, d_max - 1, d_max for _ in range(n): if a == 0: break k = (d_max + b) / / d a, b, c, d = c, d, (k * c - a), (k * d - b) return f" { a } / { b } " if a else "-1"
Give me the Corresponding Proper Fraction!
5cb758d83e6dce00149bb5cd
[ "Performance", "Algorithms", "Mathematics", "Data Structures", "Strings", "Recursion" ]
https://www.codewars.com/kata/5cb758d83e6dce00149bb5cd
5 kyu
Write a class decorator `@remember` which makes the class remember its own objects, storing them in a dictionary with the creating arguments as keys. Also, you have to avoid creating a new member of the class with the same initial arguments as a previously remembered member. Additionally, if the (decorated) class...
reference
class MetaDict (type): def __getitem__(cls, item): return cls . members[item] def __iter__(cls): return (key for key in cls . members) def remember(cls): class Recall (cls): __metaclass__ = MetaDict members = {} def __new__(c, * args): key = args[0] if len(args) == 1 else args ...
Remember members decorator
571957959906af00f90012f3
[ "Decorator", "Singleton" ]
https://www.codewars.com/kata/571957959906af00f90012f3
4 kyu
Imagine if there were no order of operations. Instead, you would do the problem from left to right. For example, the equation `$a +b *c /d$` would become `$(((a+b)*c)//d)$` (`Math.floor(((a+b)*c)/d)` in JS). Return `None`/`null` (depending on your language) if the equation is `""`. ### Task: Given an equation with a...
algorithms
def no_order(equation): equation = equation . replace(' ', '') equation = equation . replace('+', ')+') equation = equation . replace('-', ')-') equation = equation . replace('*', ')*') equation = equation . replace('/', ')//') equation = equation . replace('%', ')%') equation = equat...
No Order of Operations
5e9df3a0a758c80033cefca1
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5e9df3a0a758c80033cefca1
6 kyu
We want to create an object with methods for various HTML elements: `div`, `p`, `span` and `h1` for the sake of this Kata. These methods will wrap the passed-in string in the tag associated with each. ```javascript Format.div("foo"); // returns "<div>foo</div>" Format.p("bar"); // returns "<p>bar</p>" Format.span("fi...
games
id_ = lambda * cnts: '' . join(cnts) class Tag: def __init__(self, f=id_): self . func = f def __call__(self, * contents): return self . func(* contents) def __getattr__(self, tag): return Tag( lambda * cnts: self(f'< { tag } > { "" . join ( cnts ) } </ { tag } >')) Format = Tag() ...
field chained HTML formatting
5e98a87ce8255200011ea60f
[ "Puzzles" ]
https://www.codewars.com/kata/5e98a87ce8255200011ea60f
5 kyu
### Background In classical cryptography, the Hill cipher is a polygraphic substitution cipher based on linear algebra. It was invented by Lester S. Hill in 1929. ### Task This cipher involves a text key which has to be turned into a matrix and text which needs to be encoded. The text key can be of any perfect squ...
reference
import numpy as np def encrypt(text, key): # Declare string variable to store the answer ans = '' # Covert all the alphabets to upper case and clean everything else clean_text = '' . join([i . upper() for i in text if i . isalpha()]) # Add Z to the cleaned text if the length of it is odd clean...
Hill Cipher: Encryption
5e958a9bbb01ec000f3c75d8
[ "Cryptography", "Matrix", "Security", "Fundamentals" ]
https://www.codewars.com/kata/5e958a9bbb01ec000f3c75d8
6 kyu
As you may know, once some people pass their teens, they jokingly only celebrate their 20th or 21st birthday, forever. With some maths skills, that's totally possible - you only need to select the correct number base! For example, if they turn 32, that's exactly 20 - in base 16... Already 39? That's just 21, in base 1...
reference
def womens_age(n): return f" { n } ? That's just { 20 + n % 2 } , in base { n / / 2 } !"
Happy Birthday, Darling!
5e96332d18ac870032eb735f
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5e96332d18ac870032eb735f
7 kyu
Rotate a 2D infinite array by 1 / 8<sup>th</sup> of a full turn, clockwise ### Example ```haskell rotate :: [[a]] -> [[a]] rotate [ "1234.." , "abc.." , "AB.." , "0.." , .. ] -> [ "1" , "a2" , "Ab3" , "0Bc4" , .. ] ``` ```python # Generators r...
algorithms
def rotate(seq): s = [] while True: s . append(next(seq)) yield iter([* map(next, s)][:: - 1])
Rotate 1 / 8th ( Infinity version )
5e921a2550beae0025322e79
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5e921a2550beae0025322e79
6 kyu
You are given a table, in which every key is a stringified number, and each corresponding value is an array of characters, e.g. ```javascript { "1": ["A", "B", "C"], "2": ["A", "B", "D", "A"], } ``` Create a function that returns a table with the same keys, but each character should appear only once among the v...
reference
def remove_duplicate_ids(obj): out, seen = {}, {} for i in sorted(obj . keys(), key=int, reverse=True): uniques = [] for v in obj[i]: if v not in seen: uniques . append(v) seen[v] = 1 out[i] = uniques return out
Duplicates. Duplicates Everywhere.
5e8dd197c122f6001a8637ca
[ "Arrays", "Sets", "Sorting", "Fundamentals" ]
https://www.codewars.com/kata/5e8dd197c122f6001a8637ca
6 kyu
<center><h1>DefaultList</h1></center> The collections module has defaultdict, which gives you a default value for trying to get the value of a key which does not exist in the dictionary instead of raising an error. Why not do this for a list? Your job is to create a class (or a function which returns an object) ca...
reference
class DefaultList (list): def __init__(self, it, default): super(). __init__(it) self . default = default def __getitem__(self, i): try: return super(). __getitem__(i) except IndexError: return self . default
DefaultList
5e882048999e6c0023412908
[ "Fundamentals" ]
https://www.codewars.com/kata/5e882048999e6c0023412908
6 kyu
# Task: Your function should return a valid regular expression. This is a pattern which is normally used to match parts of a string. In this case will be used to check if all the characters given in the input appear in a string. ## Input Non empty string of unique alphabet characters upper and lower case. ##...
reference
def regex_contains_all(st): return '' . join(f'(?=.* { x } )' for x in set(st))
regex pattern to check if string has all characters
5e4eb72bb95d28002dbbecde
[ "Regular Expressions", "Fundamentals", "Strings" ]
https://www.codewars.com/kata/5e4eb72bb95d28002dbbecde
6 kyu
## **Task** You are given a positive integer (`n`), and your task is to find the largest number **less than** `n`, which can be written in the form `a**b`, where `a` can be any non-negative integer and `b` is an integer greater than or equal to `2`. Try not to make the code time out :) The input range is from `1` to ...
algorithms
def largest_power(n): print(n) if n <= 4: if n == 1: return (0, - 1) return (1, - 1) # num_of_occurances freq = 0 x = [] largest = 0 j = 0 while 2 * * largest < n: largest += 1 largest -= 1 for i in range(2, largest + 1): while j * * i < n: ...
Largest Value of a Power Less Than a Number
5e860c16c7826f002dc60ebb
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5e860c16c7826f002dc60ebb
6 kyu
**DESCRIPTION:** Your strict math teacher is teaching you about right triangles, and the Pythagorean Theorem: `$a^2 + b^2 = c^2$` whereas `$a$` and `$b$` are the legs of the right triangle and `$c$` is the hypotenuse of the right triangle. On the test however, the question asks: **What are the possible integer lengt...
reference
def side_len(x, y): return [z for z in range(abs(x - y) + 1, x + y) if z * z not in (abs(x * x - y * y), x * x + y * y)]
Possible side lengths of a triangle excluding right triangles.
5e81303e7bf0410025e01031
[ "Fundamentals" ]
https://www.codewars.com/kata/5e81303e7bf0410025e01031
7 kyu
<style> .header { padding: 5px 5%; border-left: 5px solid #e9ed28; color: #ffcc66 !important; background-image: linear-gradient(to right, #222, rgb(0,0,0,0)); } </style> <h2 class="header">Overview</h2> <p>The task is simple - given a 2D array (list), generate an HTML table representing the data fr...
reference
def to_table(data, header=False, withIdx=False): head = f'<thead> { getLine ( data [ 0 ], withIdx , "th" ) } </thead>' * header body = f'<tbody> { "" . join ( getLine ( d , withIdx , n = i ) for i , d in enumerate ( data [ header :], 1 )) } </tbody>' return f'<table> { head }{ body } </table>' def g...
Array to HTML table
5e7e4b7cd889f7001728fd4a
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5e7e4b7cd889f7001728fd4a
6 kyu
In Scala, an underscore may be used to create a partially applied version of an infix operator using placeholder syntax. For example, `(_ * 3)` is a function that multiplies its input by 3. With a bit of manipulation, this idea can be extended to work on any arbitrary expression. Create an value/object named `x` that ...
algorithms
# -*- coding: utf-8 -*- import operator class Placeholder: def __init__(self, op=None, left=None, right=None): self . op = op self . left = left self . right = right def calc(self, args): if self . op: x, args = self . left . calc(args) if isinstance( self . left, Place...
Arithmetic Expression Placeholders
5e7bc286a758770033b56a5a
[ "Algorithms" ]
https://www.codewars.com/kata/5e7bc286a758770033b56a5a
5 kyu
<center><h1 style="font-size: 30px;">HTML Element Generator</h1></center> <p>In this kata, you will be creating a python function that will take arguments and turn them into an HTML element.</p> <h3>An HTML tag has three parts:</h3> <ol> <li>The opening tag, which consists of a tag name and potentially attributes, all ...
reference
def html(tag, * contents, * * attr): openTag = tag + \ '' . join( f' { "class" if k == "cls" else k } =" { v } "' for k, v in attr . items()) return '\n' . join(f'< { openTag } > { c } </ { tag } >' for c in contents) or f'< { openTag } />'
HTML Element Generator
5e7837d0262211001ecf04d7
[ "Fundamentals" ]
https://www.codewars.com/kata/5e7837d0262211001ecf04d7
6 kyu
You have a path of `n` tiles in your garden that you'd like to paint, and four different colors to do so. 'Thing is... You don't want any two adjacent tiles to be of the same color and you'd like that it'd cost you the minimum possible amount of money. 'Second thing is... due to differences in the texture and matter...
algorithms
def paint_tiles(costs): t = [0] * 4 for cs in costs: t = [c + min(t[j] for j in range(4) if j != i) for i, c in enumerate(cs)] return min(t)
Paint Tiles
5e297e9f63f1db003317cbac
[ "Dynamic Programming", "Algorithms" ]
https://www.codewars.com/kata/5e297e9f63f1db003317cbac
6 kyu
You get a list of nodes. Return the sorted list of nodes without any duplicates. See example test cases for expected inputs and outputs. ( Node data structure is inspired by `Cytoscape.js JSON`) ## Restriction ``` Your code length should not be longer than 85 characters. ```
reference
def remove_duplicate(A): return [* map(eval, sorted(set(map(str, A))))]
[ Code Golf ] Remove duplicated nodes
5c237d7c1ea8b34b32000244
[ "Restricted", "Fundamentals" ]
https://www.codewars.com/kata/5c237d7c1ea8b34b32000244
6 kyu
You are given 2 numbers is `n` and `k`. You need to find the number of integers between 1 and n (inclusive) that contains exactly `k` non-zero digit. Example1 ` almost_everywhere_zero(100, 1) return 19` by following condition we have 19 numbers that have k = 1 digits( not count zero ) ` [1,2,3,4,5,6,7,8,9,10,20,30...
algorithms
from scipy . special import comb def almost_everywhere_zero(n, k): if k == 0: return 1 first, * rest = str(n) l = len(rest) return 9 * * k * comb(l, k, exact=True) + \ (int(first) - 1) * 9 * * (k - 1) * comb(l, k - 1, exact=True) + \ almost_everywhere_zero(int("" . jo...
Almost Everywhere Zero
5e64cc85f45989000f61526c
[ "Algorithms", "Logic", "Mathematics" ]
https://www.codewars.com/kata/5e64cc85f45989000f61526c
4 kyu
In my school, a grand musical is performed every 4 years. This means that every student who comes to this school will get to see a musical performed exactly once in their 4-year stay. This is not always the case in other schools though. For a given duration of time, an interval after which a musical is performed, and ...
reference
def no_musical(classS, classE, showFreq, classT): nYears, deltaY = classE - classS, showFreq - classT if not showFreq: return nYears + 1 if deltaY < 1: return 0 n, r = divmod(nYears, showFreq) return deltaY * n + min(r, deltaY)
No musical :(
5e65916b4696e500134987e1
[ "Mathematics", "Logic", "Fundamentals" ]
https://www.codewars.com/kata/5e65916b4696e500134987e1
7 kyu
<style> table, th, td { border: 1px solid black; } </style> <h2>Introduction (skippable)</h2> Let's suppose you got a cake... : <strike>I eat it and the kata ends.</strike> <br> <br> Consider it to weigh `3 hg`, with the <b>smallest possible</b> slice to weigh `1 hg`.<br> In <b>how many ways</b> can you serve the <b...
algorithms
def odd_even_compositions(Q): return not Q or (2 - (1 & Q)) * 3 * * (~ - Q >> 1)
Odd-Even Compositions
5e614d3ffa2602002922a5ad
[ "Algorithms", "Performance", "Mathematics" ]
https://www.codewars.com/kata/5e614d3ffa2602002922a5ad
5 kyu
A *Vampire number* is a positive integer `z` with a factorization `x * y = z` such that - `x` and `y` have the same number of digits and - the multiset of digits of `z` is equal to the multiset of digits of `x` and `y`. - Additionally, to avoid trivialities, `x` and `y` may not both end with `0`. In this case, `x` an...
games
def is_vampire(x, y): return sorted(f" { x }{ y } ") == sorted( f" { x * y } ") and x % 10 + y % 10 > 0 vampires = sorted({x * y for p in (1, 2) for x in range(10 * * p, 10 * * (p + 1)) for y in range(x, 10 * * (p + 1)) if is_vampire(x, y)}) def VampireNumber(k): return vampires[k - 1]
Vampire numbers less than 1 000 000
558d5c71c68d1e86b000010f
[ "Puzzles" ]
https://www.codewars.com/kata/558d5c71c68d1e86b000010f
7 kyu
Consider the following equation of a surface `S`: `z*z*z = x*x * y*y`. Take a cross section of `S` by a plane `P: z = k` where `k` is a positive integer `(k > 0)`. Call this cross section `C(k)`. #### Task Find the *number* of points of `C(k)` whose coordinates are positive integers. #### Examples If we call `c...
reference
def c(k): from math import sqrt root = int(sqrt(k)) if (root * root != k): return 0 i = 2 num = k * root result = 1 while (num > 1): div_num_nb = 0 while (num % i == 0): num / /= i div_num_nb += 1 result *= div_num_nb + 1 i += 1 return result
Sections
5da1df6d8b0f6c0026e6d58d
[ "Fundamentals" ]
https://www.codewars.com/kata/5da1df6d8b0f6c0026e6d58d
5 kyu
# An introduction to propositional logic Logic and proof theory are fields that study the formalization of logical statements and the structure of valid proofs. One of the most common ways to represent logical reasonings is with **propositional logic**. A propositional formula is no more than what you normally use in...
algorithms
from itertools import compress, product, chain from functools import partial def check(f, s): if f . is_literal(): return f in s elif f . is_and(): return all(check(e, s) for e in f . args) elif f . is_or(): return any(check(e, s) for e in f . args) elif f . is_not()...
Propositional SAT Problem
5e5fbcc5fa2602003316f7b5
[ "Logic", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5e5fbcc5fa2602003316f7b5
5 kyu
<style> .cod {background:rgba(250, 250, 250, 0.05); padding: 10px; border-radius:20px;} .cod:hover {background: rgba(250, 250, 250, 0.067); transition: all 1.0s} </style> <h1>The n-Bonacci Ratio</h1> <div class="cod">The Fibonacci sequence is the sequence that starts with 0, 1 that increases by the previous two terms a...
reference
from math import sqrt def n_bonacci_ratio(n): return (n + sqrt(n * * 2 + 4)) / 2
n-Bonacci Ratio
5e60cc55d8e2eb000fe57a1c
[ "Mathematics", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/5e60cc55d8e2eb000fe57a1c
7 kyu
**The Rub** You need to make a function that takes an object as an argument, and returns a very similar object but with a special property. The returned object should allow a user to access values by providing only the beginning of the key for the value they want. For example if the given object has a key `idNumber`, ...
games
def partial_keys(d): class Dct (dict): def __getitem__(self, pk): k = min((k for k in self if k . startswith(pk)), default=None) return k if k is None else super(). __getitem__(k) return Dct(d)
Partial Keys
5e602796017122002e5bc2ed
[ "Regular Expressions" ]
https://www.codewars.com/kata/5e602796017122002e5bc2ed
6 kyu
Oh no! Someone left the server at your local car dealership too close to a blender and now all of their data is scrambled. It is your job to unscramble the data and put it into an easy to read dictionary. Unscramble the list you are given and return the values in a dictionary such as the following: ``` dictionary = {...
reference
def id_(k): return lambda v: (k, v) CONFIG = { bool: id_('new'), int: id_('year'), tuple: lambda t: ('model', ' ' . join(t)), str: id_('make'), } def make_model_year(lst): return dict(CONFIG[type(data)](data) for data in lst)
Data Type Scramble
5e5acfe31b1c240012717a78
[ "Parsing", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5e5acfe31b1c240012717a78
7 kyu
The conveyor can move parts in four directions: right(r), left(l), up(u) and down(d), wrapping around the border of the grid. There is also one element that is the output of the conveyor(f). The conveyor is represented by a rectangular list of strings, as shown below: ```python ["rdfrd", "uluul"] ``` During the step...
reference
def path_counter(con): out = [[- 1] * len(con[0]) for i in range(len(con))] f = 0, 0 for y in range(len(con)): for x in range(len(con[0])): if con[y][x] == 'f': f = y, x break out[f[0]][f[1]] = 0 dirs = {(0, 1): 'l', (0, - 1): 'r', (1, 0): 'u', (- 1, 0): 'd'} stack = ...
Elementary conveyor
5e417587e35dfb0036bd5d02
[ "Performance", "Fundamentals" ]
https://www.codewars.com/kata/5e417587e35dfb0036bd5d02
4 kyu
You are given a line from a movie subtitle file as a string.\ The line consists of time interval when the text is shown: ```start(hh:mm:ss,ms) --> stop(hh:mm:ss,ms)``` and the text itself, for example: ```01:09:02,684 --> 01:09:03,601 Run Forrest, run!``` Your task is to write a function ```subs_offset_apply``` ...
reference
def subs_offset_apply(subs, offset): def parse(time): hours, minutes, seconds, milliseconds = map( int, time . replace(',', ':'). split(':')) return ((hours * 60 + minutes) * 60 + seconds) * 1000 + milliseconds def render(time, min=parse('00:00:00,000'), max=parse('99:59:59,999')): if ...
Apply offset to subtitles
5e454bf176551c002ee36486
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5e454bf176551c002ee36486
6 kyu
Binary with 0 and 1 is good, but binary with only 0 is even better! Originally, this is a concept designed by Chuck Norris to send so called unary messages. Can you write a program that can send and receive this messages? <h2><span style="color:LightSeaGreen">Rules</span></h2> <ul> <li>The input message consists o...
reference
from re import compile REGEX1 = compile(r"0+|1+"). findall REGEX2 = compile(r"(0+) (0+)"). findall binary = "{:07b}" . format def send(s): temp = '' . join(binary(ord(c)) for c in s) return ' ' . join("0 " + '0' * len(x) if x[0] == '1' else "00 " + x for x in REGEX1(temp)) def receive(s): ...
Unary Messages
5e5ccbda30e9d0001ec77bb6
[ "Fundamentals" ]
https://www.codewars.com/kata/5e5ccbda30e9d0001ec77bb6
6 kyu
Your task is to write a function `calculate`, which accepts a string with a mathematical exprssion written in [prefix Polish notation](https://en.wikipedia.org/wiki/Polish_notation) and evaluates it. This means that all operations are placed before their operands. For example, the expression `3 + 5` is written in Polis...
reference
from operator import add, sub, mul, truediv def calculate(expression): stack = [] ops = {'+': add, '-': sub, '*': mul, '/': truediv} for a in reversed(expression . split()): stack . append(ops[a](stack . pop(), stack . pop()) if a in ops else float(a)) return stack . po...
Evaluating prefix Polish notation
5e5b7f55c2e8ae0016f42339
[ "Parsing", "Mathematics", "Algorithms", "Lists", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5e5b7f55c2e8ae0016f42339
6 kyu
You have been presented with a cipher, your goal is to re-create the cipher with little information. Use the examples provided to see if you can find a solution to how this cipher is made. You will be given no hints, only the handful of phrases that have already been deciphered for you. Your only hint: Spaces are lef...
games
def cipher(p): return '' . join(chr((ord(j) + i % 3 + (i - 1) / / 3 - 97) % 26 + 97) if j != ' ' and i != 0 else j for i, j in enumerate(p))
Rectangle Cipher Puzzle
5e539724dd38d0002992eaad
[ "Puzzles", "Ciphers", "Algorithms" ]
https://www.codewars.com/kata/5e539724dd38d0002992eaad
6 kyu
# Cellular Automata A cellular automata is a regular grid of cells, each with a state from a finite number of them (such as ON (1) and OFF (0)) and with a defined neighbourhood (which cells are considered adjacent to each cell). The automata is then given a initial state (a state for each of its cells) and rules to ch...
algorithms
def get_mask(xs): '''Convert iterable of 1s and 0s to a binary number''' d = 0 for x in xs: d = (d << 1) | x return d def automata(rules, initial, generations): automata = initial[:] # m: width of neighbourhood on either side m, n = len(rules[0]) / / 2, len(automata) # used to li...
1 Dimensional cellular automata
5e52946a698ef0003252b526
[ "Algorithms", "Cellular Automata" ]
https://www.codewars.com/kata/5e52946a698ef0003252b526
6 kyu
Here's a way to construct a list containing every positive rational number: Build a binary tree where each node is a rational and the root is `1/1`, with the following rules for creating the nodes below: * The value of the left-hand node below `a/b` is `a/a+b` * The value of the right-hand node below `a/b` is `a+b/b` ...
reference
def rat_at(n): a, b = 0, 1 for bit in f" { n + 1 : b } ": if bit == '1': a += b else: b += a return a, b def index_of(a, b): n, mask = 0, 1 while a != b: n += mask * (a > b) mask *= 2 a, b = (a, b - a) if b > a else (a - b, b) return n + mask - 1
List of all rationals - going further
5e529a6fb95d280032d04389
[ "Mathematics", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/5e529a6fb95d280032d04389
7 kyu
Here's a way to construct a list containing every positive rational number: Build a binary tree where each node is a rational and the root is `1/1`, with the following rules for creating the nodes below: * The value of the left-hand node below `a/b` is `a/a+b` * The value of the right-hand node below `a/b` is `a+b/b` ...
reference
def all_rationals(): yield (1, 1) for a, b in all_rationals(): yield from [(a, a + b), (a + b, b)]
List of all Rationals
5e4e8f5a72d9550032953717
[ "Mathematics", "Lists", "Fundamentals" ]
https://www.codewars.com/kata/5e4e8f5a72d9550032953717
7 kyu
Let an array or a list `arr = [x(1), x(2), x(3), x(4), ..., x(i), x(i+1), ..., x(m), x(m+1)]` where all `x(i)` are positive integers. The length `lg` of this array will be a positive multiple of 4. Let `P = (x(1) ** 2 + x(2) ** 2) * (x(3) ** 2 + x(4) ** 2) * ... * (x(m) ** 2 + x(m+1) ** 2)`, `x ** y` means x ra...
reference
def solve(arr): a, b, c, d = arr[0: 4] # print(a, b, c, d) # print(arr[4:]) first4 = [abs(a * c - b * d), (a * d + b * c)] if len(arr) == 4: return first4 return solve(first4 + arr[4:])
Operations on sequences
5e4bb05b698ef0001e3344bc
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/5e4bb05b698ef0001e3344bc
5 kyu
# Types and classes Nowadays, types and classes are no foreign concepts for any programmer, as they tend to be present on most programming languages in one form or another. The thing is that functional languages tipically see types in a different way that imperative ones. The distinctive factor is that they can operat...
algorithms
def bindable(a, b, bindings): if a == b or (a, b) in bindings: return True elif a . is_sum(): return all(bindable(x, b, bindings) for x in a . subtypes) elif b . is_sum(): return any(bindable(a, x, bindings) for x in b . subtypes) if a . is_product() and b . is_product(): asub, b...
Binding of Algebraic Data Types
5e4cf596dc3099002a30cbb1
[ "Functional Programming", "Algorithms" ]
https://www.codewars.com/kata/5e4cf596dc3099002a30cbb1
6 kyu
### Task: Decoding The task of this kata is to take an exponential-Golomb encoded binary string and return the array of decoded integers it represents. ### Encoding An exponential-Golomb code is a way of representing an integer using bit patterns. To encode any non-negative integer `x` using the exponential-Golomb c...
algorithms
def decoder(sequence): i = 0 out = [] while i < len(sequence): j = sequence . index('1', i) i = 2 * j + 1 - i out . append(int(sequence[j: i], 2) - 1) return out
Exponential-Golomb Decoder
5e4d8a53b499e20016b018a0
[ "Algorithms" ]
https://www.codewars.com/kata/5e4d8a53b499e20016b018a0
6 kyu
Given a non-negative number, return the next bigger polydivisible number, 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`, and so on. There are finitely many polydivisible numbers.
algorithms
d, polydivisible, arr = 1, [], list(range(1, 10)) while arr: d += 1 polydivisible . extend(arr) arr = [n for x in arr for n in range(- (- x * 10 / / d) * d, (x + 1) * 10, d)] def next_num(n): from bisect import bisect idx = bisect(polydivisible, n) if idx < len(polydivi...
Next polydivisible number
5e4a1a43698ef0002d2a1f73
[ "Algorithms" ]
https://www.codewars.com/kata/5e4a1a43698ef0002d2a1f73
6 kyu
# Welcome to Squareville! The king of these lands invited you to solve a problem that has been going on for ages now. Every citizen is assigned a square chunk of ground to cultivate their famous watermelons, but the distribution is becoming more and more tedious as the city grows in size. Every chunk is composed of n...
games
w = (s (q, s (q, r,)))
Real World Applications of Sqrton
5e498a51dc30990025221647
[ "Functional Programming", "Restricted", "Puzzles" ]
https://www.codewars.com/kata/5e498a51dc30990025221647
5 kyu
A grammar is a set of rules that let us define a language. These are called **production rules** and can be derived into many different tools. One of them is **String Rewriting Systems** (also called Semi-Thue Systems or Markov Algorithms). Ignoring technical details, they are a set of rules that substitute ocurrences ...
algorithms
def word_problem(rules: List[Tuple[str, str]], from_str: str, to_str: str, applications: int) - > bool: def rec(s, n): return s == to_str or n and any(s[i:]. startswith(x) and rec( s[: i] + y + s[i + len(x):], n - 1) for i in range(len(s)) for x, y in rules) return rec(from_str, applications)
Semi-Thue Systems - The Word Problem [Part 1]
5e453b6476551c0029e275db
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5e453b6476551c0029e275db
6 kyu
Most of this problem is by the original author of [the harder kata](https://www.codewars.com/kata/556206664efbe6376700005c), I just made it simpler. I read a book recently, titled "Things to Make and Do in the Fourth Dimension" by comedian and mathematician Matt Parker ( [Youtube](https://www.youtube.com/user/standupm...
algorithms
def polydivisible(x): for i in range(1, len(str(x)) + 1): if int(str(x)[: i]) % i != 0: return False return True
Polydivisible Numbers
5e4217e476126b000170489b
[ "Algorithms" ]
https://www.codewars.com/kata/5e4217e476126b000170489b
7 kyu
# How many urinals are free? In men's public toilets with urinals, there is this unwritten rule that you leave at least one urinal free between you and the next person peeing. For example if there are 3 urinals and one person is already peeing in the left one, you will choose the urinal on the right and not the one in...
reference
def get_free_urinals(urinals): return - 1 if '11' in urinals else sum(((len(l) - 1) / / 2 for l in f'0 { urinals } 0' . split('1')))
How many urinals are free?
5e2733f0e7432a000fb5ecc4
[ "Fundamentals" ]
https://www.codewars.com/kata/5e2733f0e7432a000fb5ecc4
7 kyu
You need to write a code that will return product ID from string representing URL for that product's page in your online shop. All URLs are formatted similarly, first there is a domain `exampleshop.com`, then we have name of a product separated by dashes(`-`), then we have letter `p` indicating start of product ID, th...
reference
def get_product_id(url): return url . split('-')[- 2]
Product ID from URL
5e2c7639b5d728001489d910
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5e2c7639b5d728001489d910
7 kyu
## Mighty Heroes Alyosha Popovich (Russian folk hero) stroke his sharp sword and cut the head of Zmey Gorynych (big Serpent with several heads)! He looked - and lo! - in its place immediately new heads appeared, exactly `n`. He stroke again, and where the second head was, `2*n` heads appeared! The third time it was `...
reference
from math import factorial def count_of_heads(heads, n, k): return sum(factorial(i) * n for i in range(1, k + 1)) + (heads - k)
Mighty Hero
5e2aec959bce5c001f090c4d
[ "Fundamentals", "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/5e2aec959bce5c001f090c4d
6 kyu
Given a board of `NxN`, distributed with tiles labeled `0` to `N² - 1`(inclusive): A solved grid will have the tiles in order of label, left to right, top to bottom. Return `true` if the board state is currently solved, and `false` if the board state is unsolved. Input will always be a square 2d array. For example...
games
def is_solved(board): curr = 0 for r in board: for c in r: if c != curr: return False curr += 1 return True
Sliding Puzzle Verification
5e28b3ff0acfbb001f348ccc
[ "Games" ]
https://www.codewars.com/kata/5e28b3ff0acfbb001f348ccc
7 kyu
⚠️ The world is in quarantine! There is a new pandemia that struggles mankind. Each continent is isolated from each other but infected people have spread before the warning. ⚠️ 🗺️ You would be given a map of the world in a type of string: string s = "01000000X000X011X0X" '0' : uninfected '1' : infected...
games
def infected(s): lands = s . split('X') total = sum(map(len, lands)) infected = sum(len(x) for x in lands if '1' in x) return infected * 100 / (total or 1)
Pandemia 🌡️
5e2596a9ad937f002e510435
[ "Strings", "Puzzles" ]
https://www.codewars.com/kata/5e2596a9ad937f002e510435
7 kyu
Ask a mathematician: "What proportion of natural numbers contain at least one digit `9` somewhere in their decimal representation?" You might get the answer "Almost all of them", or "100%". Clearly though, not all whole numbers contain a `9`. In this kata we ask the question: "How many `Integer`s in the range `[0..n...
games
from re import sub def nines(n): return n - int(sub(r'9.*$', lambda m: '8' * len(m[0]), str(n)), 9)
How many nines?
5e18743cd3346f003228b604
[ "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/5e18743cd3346f003228b604
6 kyu
You work in the best consumer electronics corporation, and your boss wants to find out which three products generate the most revenue. Given 3 lists of the same length like these: * products: `["Computer", "Cell Phones", "Vacuum Cleaner"]` * amounts: `[3, 24, 8]` * prices: `[199, 299, 399]` return the three product ...
reference
def top3(* args): return [item[0] for item in sorted(zip(* args), key=lambda x: x[1] * x[2], reverse=True)[: 3]]
Most sales
5e16ffb7297fe00001114824
[ "Fundamentals" ]
https://www.codewars.com/kata/5e16ffb7297fe00001114824
7 kyu
_Note: There is a harder version ([Sports League Table Ranking (with Head-to-head)](https://www.codewars.com/kata/5e0e17220d5bc9002dc4e9c4)) of this._ # Description You organize a sports league in a [round-robin-system](https://en.wikipedia.org/wiki/Round-robin_tournament). Each team meets all other teams. In your lea...
algorithms
from typing import List class GameTable: def __init__(self, number_of_teams, games): self . teams = self . __create_teams(number_of_teams) self . matches = self . __read_matches(games) self . ranks = [1] * number_of_teams def __create_teams(self, number_of_teams): teams = [] for ...
Sports League Table Ranking
5e0baea9d772160032022e8c
[ "Fundamentals", "Algorithms", "Arrays", "Sorting" ]
https://www.codewars.com/kata/5e0baea9d772160032022e8c
5 kyu
You are given three piles of casino chips: white, green and black chips: * the first pile contains only white chips * the second pile contains only green chips * the third pile contains only black chips Each day you take exactly two chips of different colors and head to the casino. You can choose any color, but you a...
reference
def solve(xs): x, y, z = sorted(xs) return min(x + y, (x + y + z) / / 2)
Casino chips
5e0b72d2d772160011133654
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5e0b72d2d772160011133654
6 kyu
At the casino you are presented with a wide array of games to play. You are there for fun, but you want to be economical about it by playing the game that maximises your profits (minimises your losses, let's be real). To do this, you will pick the game with the highest expected value (EV). If you are unfamiliar with t...
reference
def find_best_game(games): return max(games, key=lambda g: sum(p * v for p, v in g . outcomes)). name
Picking the best casino game
5dfd129673aa2c002591f65d
[ "Probability", "Mathematics", "Fundamentals", "Data Science", "Statistics" ]
https://www.codewars.com/kata/5dfd129673aa2c002591f65d
7 kyu
In this kata, you will be given a string of text and valid parentheses, such as `"h(el)lo"`. You must return the string, with only the text inside parentheses reversed, so `"h(el)lo"` becomes `"h(le)lo"`. However, if said parenthesized text contains parenthesized text itself, then that too must reversed back, so it fac...
reference
def reverse_in_parentheses(s): stack = [] for i in s: stack . append(i) if i == ')': opening = len(stack) - stack[:: - 1]. index('(') - 1 stack . append('' . join( [i[:: - 1]. translate(str . maketrans('()', ')(')) for i in stack[opening:][:: - 1]])) del stack[opening: - 1]...
Reverse Inside Parentheses (Inside Parentheses)
5e07b5c55654a900230f0229
[ "Strings", "Fundamentals", "Recursion", "Parsing" ]
https://www.codewars.com/kata/5e07b5c55654a900230f0229
5 kyu
Consider a sequence, which is formed by the following rule: next term is taken as the smallest possible non-negative integer, which is not yet in the sequence, so that no 3 terms of sequence form an arithmetic progression. ## Example `f(0) = 0` -- smallest non-negative `f(1) = 1` -- smallest non-negative, which is ...
algorithms
def sequence(n): return int(format(n, 'b'), 3)
No arithmetic progressions
5e0607115654a900140b3ce3
[ "Algorithms" ]
https://www.codewars.com/kata/5e0607115654a900140b3ce3
6 kyu
Given two integers `a` and `x`, return the minimum non-negative number to **add to** / **subtract from** `a` to make it a multiple of `x`. ```prolog minimum(9, 8, Result) % Result = 1 % 9-1 = 8 which is a multiple of 4 ``` ```javascript minimum(10, 6) //= 2 10+2 = 12 which is a multiple of 6 ``` ```python minimu...
reference
def minimum(a, x): return min(a % x, - a % x)
Minimum to multiple
5e030f77cec18900322c535d
[ "Fundamentals" ]
https://www.codewars.com/kata/5e030f77cec18900322c535d
7 kyu
A parity bit, or check bit, is a bit added to a string of bits to ensure that the total number of 1-bits in the string is even or odd. Parity bits are used as the simplest form of error detecting code. You have two parameters, one being the wanted parity (always 'even' or 'odd'), and the other being the binary represe...
reference
def check_parity(parity, bin_str): return [0, 1][bin_str . count("1") % 2 == (parity == "even")]
Calculate Parity bit!
5df261342964c80028345a0a
[ "Fundamentals" ]
https://www.codewars.com/kata/5df261342964c80028345a0a
7 kyu
You've decided to try to create a test framework that allows for easy testing of [Pathfinder Ability Score](https://www.d20pfsrd.com/basics-ability-scores/ability-scores/) arrays, and their validity, using 25 points. You will write a function that takes an array of 6 scores (integers) and will return a boolean if they...
algorithms
def pathfinder_scores(scores): pathpoints = {'7': - 4, '8': - 2, '9': - 1, '10': 0, '11': 1, '12': 2, '13': 3, '14': 5, '15': 7, '16': 10, '17': 13, '18': 17} points = [] for x in scores: if str(x) in pathpoints: points . append(pathpoints . get(str(x))) elif str(x) not ...
Pathfinder Ability Scores Calculator
5df0041acec189002d06101f
[ "Algorithms" ]
https://www.codewars.com/kata/5df0041acec189002d06101f
7 kyu
I'm afraid you're in a rather unfortunate situation. You've injured your leg, and are unable to walk, and a number of zombies are shuffling towards you, intent on eating your brains. Luckily, you're a crack shot, and have your trusty rifle to hand. The zombies start at `range` metres, and move at `0.5` metres per seco...
reference
def zombie_shootout(z, r, a): s = min(r * 2, a) return f"You shot all { z } zombies." if s >= z else f"You shot { s } zombies before being eaten: { 'overwhelmed' if s == 2 * r else 'ran out of ammo' } ."
Will you survive the zombie onslaught?
5deeb1cc0d5bc9000f70aa74
[ "Games", "Fundamentals" ]
https://www.codewars.com/kata/5deeb1cc0d5bc9000f70aa74
7 kyu
In this Kata, you will be given a string and your task is to return the most valuable character. The value of a character is the difference between the index of its last occurrence and the index of its first occurrence. Return the character that has the highest value. If there is a tie, return the alphabetically lowest...
reference
def solve(st): return min(set(st), key=lambda c: (st . index(c) - st . rindex(c), c))
Most valuable character
5dd5128f16eced000e4c42ba
[ "Fundamentals" ]
https://www.codewars.com/kata/5dd5128f16eced000e4c42ba
7 kyu
Given the sum and gcd of two numbers, return those two numbers in ascending order. If the numbers do not exist, return `-1`, (or `NULL` in C, `tuple (-1,-1)` in C#, `pair (-1,-1)` in C++,`None` in Rust, `array {-1,-1} ` in Java and Golang). ``` For example: Given sum = 12 and gcd = 4... solve(12,4) = [4,8]. The two ...
reference
def solve(s, g): return - 1 if s % g else (g, s - g)
GCD sum
5dd259444228280032b1ed2a
[ "Fundamentals" ]
https://www.codewars.com/kata/5dd259444228280032b1ed2a
7 kyu
# Fun fact Tetris was the first video game played in outer space In 1993, Russian cosmonaut Aleksandr A. Serebrov spent 196 days on the Mir space station with a very special distraction: a gray Game Boy loaded with Tetris. During that time the game orbited the Earth 3,000 times and became the first video game played i...
reference
class Game (): def __init__(self, arr): self . comands = arr self . score = 0 self . step = None self . fild = [- 1] * 9 self . over = lambda x: max(x) >= 29 def __break__(self): while - 1 not in self . fild: self . score += 1 self . fild = [e - 1 for e in self . fild...
Tetris Series #2 — Primitive Gameplay
5db8a241b8d7260011746407
[ "Fundamentals", "Games", "Algorithms", "Arrays", "Logic" ]
https://www.codewars.com/kata/5db8a241b8d7260011746407
6 kyu
In this kata, you need to make a (simplified) LZ78 encoder and decoder. [LZ78](https://en.wikipedia.org/wiki/LZ77_and_LZ78#LZ78) is a dictionary-based compression method created in 1978. You will find a detailed explanation about how it works below. The input parameter will always be a non-empty string of upper case ...
algorithms
import re def encoder(s): d, out, it = {}, [], iter(s) for c in it: i, k = 0, c while k in d: i, c = d[k], next(it, '') if not c: break k += c d[k] = len(d) + 1 out . append(f' { i }{ c } ') return '' . join(out) def decoder(s): d = [''] f...
LZ78 compression
5db42a943c3c65001dcedb1a
[ "Algorithms" ]
https://www.codewars.com/kata/5db42a943c3c65001dcedb1a
5 kyu