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
<link href="https://fonts.googleapis.com/css?family=Comfortaa&effect=canvas-print" rel="stylesheet"> <style> .task { background: #fff; color: #333; padding: 25px; box-sizing: border-box; font-family: Comfortaa, sans-serif !important; position: relative; } .task code, .task_code { display: inline-block; ...
algorithms
from math import floor, log def count_sixes(n): return floor((n - n % 2) * log(2, 10))
Devil's Sequence
582110dc2fd420bf7f00117b
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/582110dc2fd420bf7f00117b
5 kyu
Looking at consecutive powers of `2`, starting with `2^1`: `2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, ...` Note that out of all the digits `0-9`, the last one ever to appear is `7`. It only shows up for the first time in the number `32768 (= 2^15)`. So let us define LAST DIGIT TO APPE...
reference
def digits(x): return set(str(x)) def LDTA(n): if digits(n) == digits(n * n): return None seen = [] x = n while len(seen) < 10: for d in str(x): if d not in seen: seen . append(d) x *= n return int(seen[- 1])
Last Digit to Appear in Sequence of Powers
5ccfcfad7306d900269da53f
[ "Fundamentals" ]
https://www.codewars.com/kata/5ccfcfad7306d900269da53f
7 kyu
A stem-and-leaf plot groups data points that have the same leading digit, resembling a histogram. For example, for the input `[11, 35, 14, 9, 39, 23, 35]`, it might look something like this: ``` stem | leaf ----------- 0 | 9 1 | 1 4 2 | 3 3 | 5 5 9 ``` Some important things to notice: * Any single-digi...
reference
from collections import defaultdict def stem_and_leaf(a): d = defaultdict(list) for x in a: d[x / / 10]. append(x % 10) return {x: sorted(y) for x, y in d . items()}
Stem-and-leaf plot
5cc80fbe701f0d001136e5eb
[ "Fundamentals", "Lists" ]
https://www.codewars.com/kata/5cc80fbe701f0d001136e5eb
7 kyu
## Number pyramid Number pyramid is a recursive structure where each next row is constructed by adding adjacent values of the current row. For example: ``` Row 1 [1 2 3 4] Row 2 [3 5 7] Row 3 [8 12] Row 4 [20] ``` ___ ## Task Given the first row of the number...
algorithms
from operator import mul def reduce_pyramid(base): return sum(map(mul, base, comb_n(len(base) - 1))) def comb_n(n): c = 1 for k in range(0, n + 1): yield c c = c * (n - k) / / (k + 1)
Reducing a pyramid
5cc2cd9628b4200020880248
[ "Algorithms", "Performance" ]
https://www.codewars.com/kata/5cc2cd9628b4200020880248
6 kyu
If this challenge is too easy for you, check out: https://www.codewars.com/kata/5cc89c182777b00001b3e6a2 ___ Upside-Down Pyramid Addition is the process of taking a list of numbers and consecutively adding them together until you reach one number. When given the numbers `2, 1, 1` the following process occurs: ``` ...
algorithms
def reverse(lst): ret = [] while lst: ret . append(lst[- 1]) lst = [a - b for a, b in zip(lst, lst[1:])] return ret[:: - 1]
Upside-Down Pyramid Addition...REVERSED!
5cc1e284ece231001ccf7014
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5cc1e284ece231001ccf7014
6 kyu
Hey, Path Finder, where are you? ## Path Finder Series: - [#1: can you reach the exit?](https://www.codewars.com/kata/5765870e190b1472ec0022a2) - [#2: shortest path](https://www.codewars.com/kata/57658bfa28ed87ecfa00058a) - [#3: the Alpinist](https://www.codewars.com/kata/576986639772456f6f00030c) - [#4: where are you...
games
import re class Me (object): def __init__(self): self . x, self . y, self . dx, self . dy = 0, 0, - 1, 0 def move(self, n): self . x += n * self . dx; self . y += n * self . dy def back(self): self . dx *= - 1; self . dy *= - 1 def turn(self, d): self . dx, self . dy = (self . dy * (- 1) * * (d...
Path Finder #4: where are you?
5a0573c446d8435b8e00009f
[ "Puzzles" ]
https://www.codewars.com/kata/5a0573c446d8435b8e00009f
4 kyu
We define the function `f1(n,k)`, as the least multiple of `n` that has all its digits less than `k`. We define the function `f2(n,k)`, as the least multiple of `n` that has all the digits that are less than `k`, and no others. Each digit may occur more than once in both values of `f1(n,k)` and `f2(n,k)`. The possi...
reference
from itertools import count def f1(n, k): return next(n * m for m in count(1) if all(int(d) < k for d in str(n * m))) def f2(n, k): s = set(map(str, range(0, k))) return next(n * m for m in count(1) if set(str(n * m)) == s) def find_f1_eq_f2(n, k): return next(m for m in count(n +...
Forgiving Numbers
5cb99d1a1e00460024827738
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/5cb99d1a1e00460024827738
7 kyu
Alan is going to watch the Blood Moon (lunar eclipse) tonight for the first time in his life. But his mother, who is a history teacher, thinks the Blood Moon comes with an evil intent. The ancient Inca people interpreted the deep red coloring as a jaguar attacking and eating the moon. But who believes in Inca myths the...
algorithms
def blood_moon(r): """ if AC = r = CD then AD = r * root2 then AE = r * root 2 / 2 = EF then AF = r then area AEFH is pi r^2/ 8 area triangle AEF is bh/2 = 1/2r^2 / 2 = r^2 / 4 therefore area AFH = pir^2 / 8 - r^2 / 4 or pir^2 - 2r^2 all over 8 area AFG is pi (r/2)^2 / 2 which is ...
Blood Moon
5cba04533e6dce000eaf6126
[ "Mathematics", "Geometry", "Algorithms" ]
https://www.codewars.com/kata/5cba04533e6dce000eaf6126
7 kyu
## A Discovery One fine day while tenaciously turning the soil of his fields, Farmer Arepo found a square stone tablet with letters carved into it... he knew such artifacts may '_show a message in four directions_', so he wisely kept it. As he continued to toil in his work with his favourite rotary plough, he found mo...
algorithms
def is_sator_square(tablet): A = {'' . join(lst) for lst in tablet} B = {'' . join(lst)[:: - 1] for lst in tablet} C = {'' . join(lst) for lst in zip(* tablet)} D = {'' . join(lst)[:: - 1] for lst in zip(* tablet)} return A == B == C == D
Is Sator Square?
5cb7baa989b1c50014a53333
[ "Arrays", "Data Structures", "Algorithms" ]
https://www.codewars.com/kata/5cb7baa989b1c50014a53333
7 kyu
A pair of numbers has a unique LCM but a single number can be the LCM of more than one possible pairs. For example `12` is the LCM of `(1, 12), (2, 12), (3,4)` etc. For a given positive integer N, the number of different integer pairs with LCM is equal to N can be called the LCM cardinality of that number N. In this ka...
reference
from itertools import combinations from math import gcd def lcm_cardinality(n): return 1 + sum(1 for a, b in combinations(divisors(n), 2) if lcm(a, b) == n) def divisors(n): d = {1, n} for k in range(2, int(n * * 0.5) + 1): if n % k == 0: d . add(k) d . add(n / / k) retur...
LCM Cardinality
5c45bef3b6adcb0001d3cc5f
[ "Fundamentals" ]
https://www.codewars.com/kata/5c45bef3b6adcb0001d3cc5f
6 kyu
Your website is divided vertically in sections, and each can be of different size (height). You need to establish the section index (starting at `0`) you are at, given the `scrollY` and `sizes` of all sections. Sections start with `0`, so if first section is `200` high, it takes `0-199` "pixels" and second starts a...
algorithms
def get_section_id(scroll, sizes): c = 0 for idx, s in enumerate(sizes): c += s if scroll < c: return idx return - 1
Which section did you scroll to?
5cb05eee03c3ff002153d4ef
[ "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/5cb05eee03c3ff002153d4ef
7 kyu
A programmer that loves creating algorithms for security is doing a previous investigation of a special set of primes. Specially, he has to define ranges of values and to have the total number of the required primes. These primes should fulfill the following requirements: * The primes should have at least 3 digits. ...
reference
def special_primes(n): cat = [[] for _ in range(3)] for x in range(101, n + 1, 2): dig = list(map(int, str(x))) sum_, set_ = sum(dig), set(dig) if not sum_ % 3 or len(set_) != len(dig): continue if 0 in set_ or dig[0] * dig[- 1] == 45: continue if all(sum_ % k * * 2 ...
Special Subsets of Primes
55d5f4aae676c3da53000024
[ "Fundamentals", "Algorithms", "Mathematics", "Data Structures" ]
https://www.codewars.com/kata/55d5f4aae676c3da53000024
6 kyu
Consider a pyramid made up of blocks. Each layer of the pyramid is a rectangle of blocks, and the dimensions of these rectangles increment as you descend the pyramid. So, if a layer is a `3x6` rectangle of blocks, then the next layer will be a `4x7` rectangle of blocks. A `1x10` layer will be on top of a `2x11` layer o...
algorithms
def num_blocks(w, l, h): return w * l * h + (w + l) * (h - 1) * h / / 2 + (h - 1) * h * (2 * h - 1) / / 6 """ For those who wonder: first layer being of size w*l, the total number of blocks, SB, is: SB = w*l + (w+1)*(l+1) + (w+2)*(l+2) + ... + (w+h-1)*(l+h-1) So: SB = " Sum from i=0 to h-1 of (w+i)*(l+i...
Blocks in an Irregular Pyramid
5ca6c0a2783dec001da025ee
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5ca6c0a2783dec001da025ee
6 kyu
A few years ago, <b>Aaron</b> left his old school and registered at another due to security reasons. Now he wishes to find <b>Jane</b>, one of his schoolmates and good friends. There are `n` schools numbered from 1 to `n`. One can travel between each pair of schools by buying a ticket. The ticket between schools `i` a...
reference
def find_jane(n): return (n - 1) / / 2
Minimum Ticket Cost
5bdc1558ab6bc57f47000b8e
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/5bdc1558ab6bc57f47000b8e
7 kyu
Removed due to copyright infringement. <!--- Fibsieve had a fantabulous (yes, it's an actual word) birthday party this year. He had so many gifts that he was actually thinking of not having a party next year. Among these gifts there was an `N x N` glass chessboard that had a light in each of its cells. When the boar...
algorithms
from math import ceil, sqrt def fantabulous_birthday(n): a = ceil(sqrt(n)) b = a * a - a + 1 c = a - abs(n - b) return [a, c] if (n < b) ^ (a % 2) == 0 else [c, a]
Fantabulous Birthday
5be83eb488c754f304000185
[ "Algorithms", "Fundamentals", "Mathematics", "Logic", "Numbers" ]
https://www.codewars.com/kata/5be83eb488c754f304000185
6 kyu
`{a, e, i, o, u, A, E, I, O, U}` Natural Language Understanding is the subdomain of Natural Language Processing where people used to design AI based applications have ability to understand the human languages. HashInclude Speech Processing team has a project named Virtual Assistant. For this project they appointed you...
algorithms
def vowel_recognition(input): vowels = set('aeiouAEIOU') s = t = 0 for c, e in enumerate(input, 1): if e in vowels: t += c s += t return s
Vowel Recognition
5bed96b9a68c19d394000b1d
[ "Algorithms", "Performance" ]
https://www.codewars.com/kata/5bed96b9a68c19d394000b1d
6 kyu
## My problem I'm currently applying/interviewing for jobs, and as graph problems are one of my weaker points, I'm working on leveling up on them. I noticed that Codewars didn't have a kata of the classic Clone Graph problem yet, so I thought I would fix that. :-) ## Your problem In this kata you need to clone a conne...
reference
def clone_graph(node): queue, mp = [node] if node else [], {} while queue: cur = queue . pop(0) mp[cur] = GraphNode(cur . val) for nd in cur . neighbors: if nd not in mp: queue . append(nd) for k in mp: mp[k]. neighbors = [mp[nd] for nd in k . neighbors] return mp ....
Clone Graph
5c9a6e225ae9822e70abc7c1
[ "Fundamentals", "Graph Theory" ]
https://www.codewars.com/kata/5c9a6e225ae9822e70abc7c1
6 kyu
# Task In the city, a bus named Fibonacci runs on the road every day. There are `n` stations on the route. The Bus runs from station<sub>1</sub> to station<sub>n</sub>. At the departure station(station<sub>1</sub>), `k` passengers get on the bus. At the second station(station<sub>2</sub>), a certain number of pass...
algorithms
def sim(k, n, p): r = [(k, k, 0), (k, p, p)] for i in range(n - 2): u, d = r[0][1] + r[1][1], r[1][1] r = [r[1], (r[1][0] + u - d, u, d)] return r[1][0] def calc(k, n, m, x): z, o = sim(k, n - 1, 0), sim(k, n - 1, 1) return sim(k, x, (m - z) / / (o - z))
Kata 2019: Fibonacci Bus
5c2c0c5e2f172f0fae21729f
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5c2c0c5e2f172f0fae21729f
6 kyu
*This kata is based on [Project Euler Problem #349](https://projecteuler.net/problem=349). You may want to start with solving [this kata](https://www.codewars.com/kata/langtons-ant) first.* ### Task [Langton's ant](https://en.wikipedia.org/wiki/Langton%27s_ant) moves on a regular grid of squares that are coloured ei...
algorithms
# precalculate results LIMIT = 11000 # > 9977 + 104 CACHE = [0] GRID = set() # empty grid x, y = 0, 0 # ant's position dx, dy = 1, 0 # direction for _ in range(LIMIT + 1): if (x, y) in GRID: # square is black GRID . remove((x, y)) dx, dy = - dy, dx else: # square is white GRID . add((x, y)) ...
Langton's Ant - Advanced Version
5c99553d5c67244b60cb5722
[ "Mathematics", "Performance", "Algorithms" ]
https://www.codewars.com/kata/5c99553d5c67244b60cb5722
5 kyu
A Magic Square contains the integers 1 to n<sup>2</sup>, arranged in an n by n array such that the columns, rows and both main diagonals add up to the same number.<br/>For doubly even positive integers (multiples of 4) the following method can be used to create a magic square.<br/> Fill an array with the numbers 1 to n...
games
def even_magic(n): return [[n * n - (y * n + x) if x % 4 == y % 4 or (x % 4 + y % 4) % 4 == 3 else y * n + x + 1 for x in range(n)] for y in range(n)]
Double Even Magic Square
570e0a6ce5c9a0a8c4000bbb
[ "Fundamentals", "Puzzles", "Arrays", "Mathematics" ]
https://www.codewars.com/kata/570e0a6ce5c9a0a8c4000bbb
6 kyu
*Based on this Numberphile video: https://www.youtube.com/watch?v=Wim9WJeDTHQ* --- Multiply all the digits of a nonnegative integer `n` by each other, repeating with the product until a single digit is obtained. The number of steps required is known as the **multiplicative persistence**. Create a function that calcu...
algorithms
def per(n): r = [] while n >= 10: p = 1 for i in str(n): p = p * int(i) r . append(p) n = p return r
Multiplicative Persistence... What's special about 277777788888899?
5c942f40bc4575001a3ea7ec
[ "Algorithms" ]
https://www.codewars.com/kata/5c942f40bc4575001a3ea7ec
7 kyu
Given a string `s` and a character `c`, return an array of integers representing the shortest distance from the current character in `s` to `c`. ### Notes * All letters will be lowercase. * If the string is empty, return an empty array. * If the character is not present, return an empty array. ## Examples ``` s = ...
algorithms
def shortest_to_char(s, c): if not s or not c: return [] indexes = [i for i, ch in enumerate(s) if ch == c] if not indexes: return [] return [min(abs(i - ic) for ic in indexes) for i in range(len(s))]
Shortest Distance to a Character
5c8bf3ec5048ca2c8e954bf3
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/5c8bf3ec5048ca2c8e954bf3
6 kyu
You have read the title: you must guess a sequence. It will have something to do with the number given. ## Example ``` x = 16 result = [1, 10, 11, 12, 13, 14, 15, 16, 2, 3, 4, 5, 6, 7, 8, 9] ``` Good luck!
algorithms
def sequence(x): return sorted(range(1, x + 1), key=str)
Guess the Sequence
5b45e4b3f41dd36bf9000090
[ "Puzzles", "Algorithms" ]
https://www.codewars.com/kata/5b45e4b3f41dd36bf9000090
7 kyu
*This kata is inspired by [Project Euler Problem #387](https://projecteuler.net/problem=387)* ### Description A [Harshad number](https://en.wikipedia.org/wiki/Harshad_number) (or Niven number) is a number that is divisible by the sum of its digits. A *right truncatable Harshad number* is any Harshad number that, when...
algorithms
def gen(n): if n >= 10 * * 16: return for i in range(10): x = 10 * n + i if x % sum(map(int, str(x))): continue yield x for y in gen(x): yield y L = sorted(x for n in range(1, 10) for x in gen(n)) from bisect import bisect_left as bl, bisect_right as br def r...
Right Truncatable Harshad numbers
5c824b7b9775761ada934500
[ "Mathematics", "Number Theory", "Algorithms" ]
https://www.codewars.com/kata/5c824b7b9775761ada934500
5 kyu
[Haikus](https://en.wikipedia.org/wiki/Haiku_in_English) are short poems in a three-line format, with 17 syllables arranged in a 5–7–5 pattern. Your task is to check if the supplied text is a haiku or not. #### About syllables [Syllables](https://en.wikipedia.org/wiki/Syllable) are the phonological building blocks o...
algorithms
import re PATTERN = re . compile(r'[aeyuio]+[^aeyuio ]*((?=e\b)e)?', flags=re . I) def is_haiku(text): return [5, 7, 5] == [check(s) for s in text . split("\n")] def check(s): return sum(1 for _ in PATTERN . finditer(s))
Haiku Checker
5c765a4f29e50e391e1414d4
[ "Algorithms" ]
https://www.codewars.com/kata/5c765a4f29e50e391e1414d4
5 kyu
### Description Lets imagine a yoga classroom as a Square 2D Array of Integers ```classroom```, with each integer representing a person, and the value representing their skill level. ``` classroom = [ [3,2,1,3], [1,3,2,1], [1,1,1,2], ] poses = [1,7,5,9,10,2...
algorithms
def yoga(classroom, poses): total_poses = 0 for pose in poses: for row in classroom: for person in row: if person + sum(row) >= pose: total_poses += 1 return total_poses
Yoga Class
5c79c07b4ba1e100097f4e1a
[ "Mathematics", "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/5c79c07b4ba1e100097f4e1a
7 kyu
Create a Regular Expression that matches a string with lowercase characters in alphabetical order, including any number of spaces. There can be NO whitespace between groups of the same letter. Leading and trailing whitespace is also allowed. An empty string should match. Your regex should match: ``` "" "abc" "aaabc "...
algorithms
REGEX = r'^ *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* *\Z'
RegEx Like a Boss #2: Alphabetical Order String
5c1a334516537ccd450000d8
[ "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/5c1a334516537ccd450000d8
7 kyu
Convert hex-encoded (https://en.wikipedia.org/wiki/Hexadecimal) string to base64 (https://en.wikipedia.org/wiki/Base64) Example: The string: 49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d Should produce: SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb...
algorithms
from base64 import b64encode def hex_to_base64(h: str) - > str: return b64encode(bytes . fromhex(h)). decode()
Hex to base64
5b360fcc9212cb0cf300001f
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/5b360fcc9212cb0cf300001f
6 kyu
### Description As hex values can include letters `A` through to `F`, certain English words can be spelled out, such as `CAFE`, `BEEF`, or `FACADE`. This vocabulary can be extended by using numbers to represent other letters, such as `5EAF00D`, or `DEC0DE5`. Given a string, your task is to return the decimal sum of al...
reference
def hex_word_sum(s): return sum(int(w, 16) for w in s . translate(str . maketrans('OS', '05')). split() if set(w) <= set('0123456789ABCDEF'))
Hex Word Sum
5c46ea433dd41b19af1ca3b3
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/5c46ea433dd41b19af1ca3b3
7 kyu
In some ranking people collects points. The challenge is sort by points and calulate position for every person. But remember if two or more persons have same number of points, they should have same position number and sorted by name (name is unique). For example: Input structure: ```javascript [ { name: "John", ...
algorithms
def ranking(a): a . sort(key=lambda x: (- x["points"], x["name"])) for i, x in enumerate(a): x["position"] = i + 1 if not i or x["points"] < a[i - 1]["points"] else a[i - 1]["position"] return a
Ranking position
5c784110bfe2ef660cb90369
[ "Algorithms" ]
https://www.codewars.com/kata/5c784110bfe2ef660cb90369
7 kyu
___ ### Background Moving average of a set of values and a window size is a series of local averages. ``` Example: Values: [1, 2, 3, 4, 5] Window size: 3 Moving average is calculated as: 1, 2, 3, 4, 5 | | ^^^^^^^ (1+2+3)/3 = 2 1, 2, 3, 4, 5 | | ^^^^^^^ (2+3+4)/3 = 3 1, 2, 3, ...
algorithms
def moving_average(a, n): if 0 < n <= len(a): return [sum(a[i: i + n]) / n for i in range(len(a) - n + 1)]
Moving Average
5c745b30f6216a301dc4dda5
[ "Algorithms", "Logic", "Mathematics", "Lists" ]
https://www.codewars.com/kata/5c745b30f6216a301dc4dda5
7 kyu
Given the current exchange rate between the USD and the EUR is 1.1363636 write a function that will accept the Curency type to be returned and a list of the amounts that need to be converted. Don't forget this is a currency so the result will need to be rounded to the second decimal. 'USD' Return format should be `'...
reference
def solution(to, lst): dolSym, eurSym, power = ('', '€', - 1) if to == 'EUR' else ('$', '', 1) return [f" { dolSym }{ v * 1.1363636 * * power :, .2 f }{ eurSym } " for v in lst]
Converting Currency II
5c744111cb0cdd3206f96665
[ "Lists", "Mathematics", "Fundamentals", "Algorithms", "Algebra", "Strings" ]
https://www.codewars.com/kata/5c744111cb0cdd3206f96665
7 kyu
## Description You've been working with a lot of different file types recently as your interests have broadened. But what file types are you using the most? With this question in mind we look at the following problem. Given a `List/Array` of Filenames (strings) `files` return a `List/Array of string(s)` containing t...
reference
from collections import Counter import re def solve(files): c = Counter(re . match('.*(\.[^.]+)$', fn). group(1) for fn in files) m = max(c . values(), default=0) return sorted(k for k in c if c[k] == m)
Which filetypes are you using the most?
5c7254fcaccda64d01907710
[ "Fundamentals", "Algorithms", "Strings", "Arrays" ]
https://www.codewars.com/kata/5c7254fcaccda64d01907710
6 kyu
# Echo Program Write an <code>echoProgram</code> function (or <code>echo_program</code> depend on language) that returns your solution source code as a string. ~~~if:javascript ### Note: `Function.prototype.toString` has been disabled. ~~~
games
def echo_program(): return open(__file__). read()
Echo
5c6dc504abcd1628cd174bea
[ "Puzzles", "Strings", "Games" ]
https://www.codewars.com/kata/5c6dc504abcd1628cd174bea
7 kyu
Koch curve is a simple geometric fractal. This fractal is constructed as follows: take a segment divided into three equal parts. Instead of the middle part, two identical segments are inserted, set at an angle of 60 degrees to each other. This process is repeated at each iteration: each segment is replaced by four. Y...
reference
def koch_curve(n): if not n: return [] deep = koch_curve(n - 1) return [* deep, 60, * deep, - 120, * deep, 60, * deep]
Koch curve
5c5abf56052d1c0001b22ce5
[ "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/5c5abf56052d1c0001b22ce5
7 kyu
You are given array of integers, your task will be to count all pairs in that array and return their count. **Notes:** * Array can be empty or contain only one value; in this case return `0` * If there are more pairs of a certain number, count each pair only once. E.g.: for `[0, 0, 0, 0]` the return value is `2` ...
reference
def duplicates(arr): return sum(arr . count(i) / / 2 for i in set(arr))
Find all pairs
5c55ad8c9d76d41a62b4ede3
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5c55ad8c9d76d41a62b4ede3
7 kyu
<h2> INTRODUCTION </h2> <p> The Club Doorman will give you a word. To enter the Club you need to provide the right number according to provided the word.</p> <p>Every given word has a doubled letter, like 'tt' in lettuce.</p> <p>To answer the right number you need to find the doubled letter's position of the given word...
reference
def pass_the_door_man(word): for i in word: if i * 2 in word: return (ord(i) - 96) * 3
Club Doorman
5c563cb78dac1951c2d60f01
[ "Fundamentals" ]
https://www.codewars.com/kata/5c563cb78dac1951c2d60f01
7 kyu
Mr. Square is going on a holiday. He wants to bring 2 of his favorite squares with him, so he put them in his rectangle suitcase. Write a function that, given the size of the squares and the suitcase, return whether the squares can fit inside the suitcase. ```Python fit_in(a,b,m,n) a,b are the sizes of the 2 squares m...
games
def fit_in(a, b, m, n): return max(a, b) <= min(m, n) and a + b <= max(m, n)
Suitcase packing
5c556845d7e0334c74698706
[ "Puzzles" ]
https://www.codewars.com/kata/5c556845d7e0334c74698706
7 kyu
There exist two zeroes: +0 (or just 0) and -0. Write a function that returns `true` if the input number is -0 and `false` otherwise (`True` and `False` for Python). In JavaScript / TypeScript / Coffeescript the input will be a number. In Python / Java / C / NASM / Haskell / the input will be a float.
reference
def is_negative_zero(n): return str(n) == '-0.0'
Is It Negative Zero (-0)?
5c5086287bc6600001c7589a
[ "Fundamentals" ]
https://www.codewars.com/kata/5c5086287bc6600001c7589a
7 kyu
## Description For this Kata you will be given an array of numbers and another number `n`. You have to find the **sum** of the `n` largest numbers of the array and the **product** of the `n` smallest numbers of the array, and compare the two. If the sum of the `n` largest numbers is higher, return `"sum"` If the p...
reference
from math import prod def sum_or_product(array, n): array . sort() n_sum = sum(array[- n:]) n_prod = prod(array[: n]) return "sum" if n_sum > n_prod else "product" if n_sum < n_prod else "same"
Larger Product or Sum
5c4cb8fc3cf185147a5bdd02
[ "Fundamentals", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5c4cb8fc3cf185147a5bdd02
7 kyu
Given 2 elevators (named "left" and "right") in a building with 3 floors (numbered `0` to `2`), write a function `elevator` accepting 3 arguments (in order): - `left` - The current floor of the left elevator - `right` - The current floor of the right elevator - `call` - The floor that called an elevator It should re...
algorithms
def elevator(left, right, call): return "left" if abs(call - left) < abs(call - right) else "right"
Closest elevator
5c374b346a5d0f77af500a5a
[ "Algorithms" ]
https://www.codewars.com/kata/5c374b346a5d0f77af500a5a
8 kyu
Write a function that returns the number of arguments it received. ``` args_count() --> 0 args_count('a') --> 1 args_count('a', 'b') --> 2 ``` ```if:python,ruby The function must work for keyword arguments too: ``` ```if:python ~~~ args_count(x=10, y=20, 'z') --> 3 ~~~ ``` ```if:ruby ~~~ args_count(x:10, y:20, 'z'...
reference
def args_count(* args, * * kwargs): return len(args) + len(kwargs)
How many arguments
5c44b0b200ce187106452139
[ "Fundamentals" ]
https://www.codewars.com/kata/5c44b0b200ce187106452139
7 kyu
The dominoes in a full set come in a couple of types. For each number of pips there is a double domino, ranging from double blank represented `[0, 0]` up to double six, sometimes nine, fifteen, or in general `[n, n]`. Then there are all combinations of different numbers. For instance, a standard set has a single domino...
games
def domino(n): for a in range(n + 1): for b in range(a): yield b yield a yield a yield 0 def domino_train(n): return list(domino(n))
Train of dominoes
5c356d3977bd7254d7191403
[ "Puzzles", "Graph Theory" ]
https://www.codewars.com/kata/5c356d3977bd7254d7191403
5 kyu
Return the `n`th term of the Recamán's sequence. ``` a(0) = 0; a(n-1) - n, if this value is positive and not yet in the sequence / a(n) < \ a(n-1) + n, otherwise ``` Input range: 0 – 30,000 ___ A video about Recamán's sequence by Numberphile: https://www.youtube.com/watch?v=FGC5TdIiT9U
algorithms
def recaman(n): series, last = {0}, 0 for i in range(1, n + 1): test = last - i last = last + i if test < 0 or test in series else test series . add(last) return last
Recaman Sequence
5c3f31c2460e9b4020780aa2
[ "Algorithms", "Performance" ]
https://www.codewars.com/kata/5c3f31c2460e9b4020780aa2
7 kyu
# Task John is an orchard worker. There are `n` piles of fruits waiting to be transported. Each pile of fruit has a corresponding weight. John's job is to combine the fruits into a pile and wait for the truck to take them away. Every time, John can combine any two piles(`may be adjacent piles, or not`), and the...
algorithms
from heapq import heappop, heappush def comb(fruits): total, heap = 0, sorted(fruits) while len(heap) > 1: cost = heappop(heap) + heappop(heap) heappush(heap, cost) total += cost return total
Kata 2019: Combine Fruits
5c2ab63b1debff404a46bd12
[ "Algorithms", "Performance" ]
https://www.codewars.com/kata/5c2ab63b1debff404a46bd12
6 kyu
## Task Given an array of strings, reverse them and their order in such way that their length stays the same as the length of the original inputs. ### Example: ``` Input: {"I", "like", "big", "butts", "and", "I", "cannot", "lie!"} Output: {"!", "eilt", "onn", "acIdn", "ast", "t", "ubgibe", "kilI"} ``` Good luck!
reference
def reverse(a): s = reversed('' . join(a)) return ['' . join(next(s) for _ in w) for w in a]
Ultimate Array Reverser
5c3433a4d828182e420f4197
[ "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/5c3433a4d828182e420f4197
7 kyu
Create a Regular Expression that matches a word consistent only of letter `x`. No other letters will be used. The word has to have prime numbers of letters. Matching with `re.match()` Should match: ``` xx xxx xxxxx xxxxxxx xxxxxxxxxxx xxxxxxxxxxxxx ``` Should NOT match ``` xxxx xxxxxx xxxxxxxx xxxxxxxxx xxxxxxxxx...
algorithms
REGEX = r'(?!(xx+)\1+$)xx+$'
RegEx Like a Boss #4 CodeGolf : Prime length
5c2cea87b0aea22f8181757c
[ "Regular Expressions", "Strings", "Restricted", "Algorithms" ]
https://www.codewars.com/kata/5c2cea87b0aea22f8181757c
5 kyu
# Task Numpy has a function [numpy.fmax](https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.fmax.html) which computes the element-wise maximum for two arrays. However, there are two problems with this: First, you don't want to get numpy just to use this function. Second, you want a *in-place* version o...
reference
def fmax(a, b): a[:] = map(max, a, b)
One Line Task: Element-wise Maximum
5c2dbc63bfc6ec0001d2fcf9
[ "Restricted", "Fundamentals" ]
https://www.codewars.com/kata/5c2dbc63bfc6ec0001d2fcf9
6 kyu
<h2>Introduction</h2> It's been more than 20 minutes since the negligent waiter has taken your order for the house special prime tofu steak with a side of chili fries. Out of boredom, you start fiddling around with the condiments tray. To be efficient, you want to be familiar with the choice of sauces and spices befo...
algorithms
from math import log2 def t(n): if n == 0: return 0 k = int(log2(n)) i = n - 2 * * k if i == 0: return (2 * * (2 * k + 1) + 1) / / 3 else: return t(2 * * k) + 2 * t(i) + t(i + 1) - 1 toothpick = t
Toothpick Sequence
5c258f3c48925d030200014b
[ "Algorithms", "Mathematics", "Recursion" ]
https://www.codewars.com/kata/5c258f3c48925d030200014b
6 kyu
Welcome to yet *another* kata on palindromes! Your job is to return a string with 2 requirements: 1 . The first half of the string should represent a proper function expression in your chosen language. 2 . The string should be a palindrome. Wait... that's too easy -- let's add one more requirement: Call...
algorithms
def palindromic_expression(): return "intni"
Palindromic Expression
5c11c3f757415b1735000338
[ "Algorithms" ]
https://www.codewars.com/kata/5c11c3f757415b1735000338
7 kyu
# Toggling Grid You are given a grid (2d array) of 0/1's. All 1's represents a solved puzzle. Your job is to come up with a sequence of toggle moves that will solve a scrambled grid. Solved: ``` [ [1, 1, 1], [1, 1, 1], [1, 1, 1] ] ``` "0" (first row) toggle: ``` [ [0, 0, 0], [1, 1, 1], [1, 1, 1] ] ``` then...
games
def findSolution(m): return [j for j, r in enumerate(m) if r[0] ^ m[0][0]] + [len(m) + i for i, b in enumerate(m[0]) if not b]
Solve the Grid! Binary Toggling Puzzle
5bfc9bf3b20606b065000052
[ "Binary", "Puzzles", "Arrays" ]
https://www.codewars.com/kata/5bfc9bf3b20606b065000052
5 kyu
In English, all words at the begining of a sentence should begin with a capital letter. You will be given a paragraph that does not use capital letters. Your job is to capitalise the first letter of the first word of each sentence. For example, input: `"hello. my name is inigo montoya. you killed my father. prepar...
reference
def fix(paragraph): return '. ' . join(s . capitalize() for s in paragraph . split('. '))
Sentences should start with capital letters.
5bf774a81505a7413400006a
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5bf774a81505a7413400006a
7 kyu
Your task is to write a regular expression that matches positive decimal integers divisible by 4. Negative numbers should be rejected, but leading zeroes are permitted. Random tests can consist of numbers, ascii letters, some puctuation and brackets. But no need to check for line breaks (\n) and non-ASCII chatracters,...
games
div_4 = '[048]$|\d*([02468][048]|[13579][26])$'
Regex for a decimal number divisible by 4
5bf6bd7a3efceeda4700011f
[ "Regular Expressions", "Puzzles" ]
https://www.codewars.com/kata/5bf6bd7a3efceeda4700011f
6 kyu
In this kata we have to calculate products and sums using the values of an array with an arbitrary number of non-zero integers (positive and/or negative). Each number in the array occurs once, i.e. they are all unique. You need to implement a function `eval_prod_sum(arr, num_fact, num_add, max_val)` that takes the fol...
reference
from itertools import combinations from math import comb, prod def eval_prod_sum(numbers: list, factor_count: int, addend_count: int, max_value: int) - > list or str: if not (all(isinstance(i, int) for i in numbers) and all(isinstance(i, int) and i > 0 for i in {factor_count, addend_count, max_value})...
A Combinatorial Way to Get Products and Sums of an Array
561f18d45df118e7c400000b
[ "Fundamentals", "Mathematics", "Data Structures", "Algorithms" ]
https://www.codewars.com/kata/561f18d45df118e7c400000b
6 kyu
Pythagoras(569-500 B.C.E.) discovered the relation ```a² + b² = c²``` for rectangle triangles,```a, b and c``` are the side values of these special triangles. A rectangle triangle has an angle of 90°. In the following animated image you can see a rectangle triangle with the side values of (a, b, c) = (3, 4, 5) The pink...
reference
from math import gcd def find_max_triple(c_max): triples = [(n * n - m * m, 2 * m * n, m * m + n * n) for n in range(2, int(c_max * * 0.5) + 1) for m in range(1 + n % 2, min(n, int((c_max - n * n) * * 0.5) + 1), 2) if gcd(m, n) == 1] largest = tuple(sorted(...
Primitive Pythagorean Triples
5622c008f0d21eb5ca000032
[ "Fundamentals", "Mathematics", "Algorithms", "Data Structures", "Algebra", "Geometry", "Memoization" ]
https://www.codewars.com/kata/5622c008f0d21eb5ca000032
5 kyu
A specialist of statistics was hired to do an investigation about the people's voting intention for a certain candidate for the next elections. Unfortunately, some of the interviewers, hired for the researches, are not honest and they want to modify the results because, some of them like the candidate too much, or oth...
reference
def avg(x): return sum(x) / len(x) def std(arr): mu = avg(arr) var = sum([(x - mu) * * 2 for x in arr]) / len(arr) return var * * 0.5 def filter_val(lst): len1 = len(lst) while True: mu = avg(lst) s = std(lst) ret = [x for x in lst if mu - 2.5 * s <= x <= mu + 2....
Filtering Values For an Election
574b448ed27783868600004c
[ "Mathematics", "Statistics", "Recursion", "Data Science" ]
https://www.codewars.com/kata/574b448ed27783868600004c
6 kyu
A chain of car rental locals made a statistical research for each local in a city. They measure the average of clients for every day. They used the Simpson model for probabilities: <a href="http://imgur.com/LQWj8kM"><img src="http://i.imgur.com/LQWj8kM.png?1" title="source: imgur.com" /></a> The number ```e``` is ``...
reference
from math import e, factorial def poi(l, x): return e * * - l * l * * x / factorial(x) def prob_simpson(l, x, op='='): if op == '=': return poi(l, x) if op == '>=': return sum(poi(l, e) for e in range(x + 1)) if op == '>': return sum(poi(l, e) for e in range(x)) ...
Car Rental Business Needs Statistics and Programming
570176b0d1acef5778000fbd
[ "Algorithms", "Mathematics", "Statistics", "Probability", "Data Science" ]
https://www.codewars.com/kata/570176b0d1acef5778000fbd
5 kyu
Some languages like Chinese, Japanese, and Thai do not have spaces between words. However, most natural languages processing tasks like part-of-speech tagging require texts that have segmented words. A simple and reasonably effective algorithm to segment a sentence into its component words is called "MaxMatch". ## Max...
algorithms
def max_match(s): result = [] while s: for size in range(len(s), 0, - 1): word = s[: size] if word in VALID_WORDS: break result . append(word) s = s[size:] return result
Word Segmentation: MaxMatch
5be350bcce5afad8020000d6
[ "Parsing", "Recursion", "Strings", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5be350bcce5afad8020000d6
6 kyu
An **Almost Isosceles Integer Triangle** is a triangle that all its side lengths are integers and also, two sides are almost equal, being their absolute difference `1` unit of length. We are interested in the generation of the almost isosceles triangles by the diophantine equation (length sides of triangles are posit...
reference
# A001921 + A001570, aka A011944 v = [0, 2] while v[- 1] < 1e180: v . append(14 * v[- 1] - v[- 2]) from bisect import bisect def find_closest_perim(p): i = bisect(v, p) return v [2 ] if i == 2 else min ([v [i ], v [i - 1 ]], key = lambda t : ( abs ( t - p ), - t ))
Almost Isosceles Integer Triangles With Their Angles With Asymptotic Tendency
5be4d000825f24623a0001e8
[ "Algorithms", "Performance", "Number Theory", "Recursion", "Geometry", "Fundamentals" ]
https://www.codewars.com/kata/5be4d000825f24623a0001e8
5 kyu
# Task You are given a positive integer `n`. We intend to make some ascending sequences according to the following rules: 1. Make a sequence of length 1: [ n ] 2. Or, insert a number to the left side of the sequence. But this number can not exceed half of the first number of the sequence. 3. Follow rule 2, cont...
algorithms
from functools import lru_cache @ lru_cache(maxsize=None) def make_sequences(n): return 1 + sum(map(make_sequences, range(1, n / / 2 + 1)))
Simple Fun #399: Make Ascending Sequences
5be0f1786279697939000157
[ "Fundamentals", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5be0f1786279697939000157
7 kyu
Ever wonder how many keystrokes any given string takes to type? No? Most normal people don't...but we're not normal! :D Program a ```num_key_strokes (string)``` function that takes a string and returns a count of the number of keystrokes that it took to type that string. For example, ```Hello, world!``` takes 15 key...
reference
def num_key_strokes(text): return sum([1 if i in "abcdefghijklmnopqrestuvwxyz1234567890-=`];[',.\/ " else 2 for i in text])
Keystroking
5be085e418bcfd260b000028
[ "Fundamentals" ]
https://www.codewars.com/kata/5be085e418bcfd260b000028
7 kyu
The first positive integer, `n`, with its value `4n² + 1`, being divisible by `5` and `13` is `4`. (condition 1) It can be demonstrated that we have infinite numbers that may satisfy the above condition. If we name **<i>a</i><sub><i>i</i></sub>**, the different terms of the sequence of numbers with this property, we ...
reference
def sierpinski(): x = s = 0 while 1: for a in 4, 9, 56, 61: s += x + a yield s x += 65 s = sierpinski() S = [next(s)] from bisect import bisect_left def find_closest_value(m): while S[- 1] < m: S . append(next(s)) i = bisect_left(S, m) return m...
Following Sierpinski's Footprints
5be0af91621daf08e1000185
[ "Algorithms", "Performance", "Number Theory", "Fundamentals" ]
https://www.codewars.com/kata/5be0af91621daf08e1000185
5 kyu
You are given two strings. In a single move, you can choose any of them, and delete the first (i.e. leftmost) character. For Example: * By applying a move to the string `"where"`, the result is the string `"here"`. * By applying a move to the string `"a"`, the result is an empty string `""`. Implement a function tha...
reference
def shift_left(a, b): r = len(a) + len(b) for i in range(- 1, - min(len(a), len(b)) - 1, - 1): if a[i] != b[i]: break r -= 2 return r
Shift Left
5bdc191306a8a678f6000187
[ "Fundamentals" ]
https://www.codewars.com/kata/5bdc191306a8a678f6000187
7 kyu
## Background Those of you who have used spreadsheets will know that rows are identified by numbers and columns are identified by letters. For example the top left square of a spreadsheet is identified as `A1`, and the start of the grid is labelled like so: A1 | B1 | C1 ---+----+--- A2 | B2 | C2 ---...
algorithms
class SpreadSheetHelper: from string import ascii_uppercase BASE26 = dict(zip(ascii_uppercase, range(len(ascii_uppercase)))) @ classmethod def convert_to_display(cls, internal): display = [] row, col = internal row += 1 while row: row -= 1 row, n = divmod(row, 26) ...
Spreadsheet Cell Name Conversions
5540b8b79bb322607b000021
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/5540b8b79bb322607b000021
5 kyu
You are given a sequence of a journey in London, UK. The sequence will contain bus **numbers** and TFL tube names as **strings** e.g. ```javascript ['Northern', 'Central', 243, 1, 'Victoria'] ``` ```java new Object[] {"Northern", "Central", 243, 1, "Victoria"} ``` ```haskell [ Tube "Northern", Tube "Central", Bus 243,...
reference
def london_city_hacker(journey): # your code here tube = 2.40 bus = 1.50 total_cost = 0.00 count = 0 for link in journey: if isinstance(link, str): total_cost += tube count = 0 else: if count == 0: total_cost += bus count += 1 else: count = 0 return '£{:.2...
London CityHacker
5bce125d3bb2adff0d000245
[ "Fundamentals" ]
https://www.codewars.com/kata/5bce125d3bb2adff0d000245
7 kyu
# Scenario *the rhythm of beautiful musical notes is drawing a Pendulum* **_Beautiful musical notes_** are the **_Numbers_** ___ # Task **_Given_** an *array/list [] of n integers* , **_Arrange_** *them in a way similar to the to-and-fro movement of a Pendulum* * **_The Smallest element_** of the list of integ...
reference
def pendulum(a): a = sorted(a) return a[:: 2][:: - 1] + a[1:: 2]
The Poet And The Pendulum
5bd776533a7e2720c40000e5
[ "Fundamentals", "Arrays", "Algorithms", "Performance" ]
https://www.codewars.com/kata/5bd776533a7e2720c40000e5
7 kyu
Given an array `[x1, x2, ..., xn]` determine whether it is possible to put `+` or `-` between the elements and get an expression equal to `sum`. Result is `boolean` ``` 2 <= n <= 22 0 <= xi <= 20 -10 <= sum <= 10 ``` ## Example `arr = [1, 3, 4, 6, 8]` `sum = -2` **1 + 3 - 4 + 6 - 8 = -2** Result is: `true` ## N...
algorithms
def is_possible(nums, goal): if not nums: return False sums = {nums[0]} for i in range(1, len(nums)): sums = {n + s for n in sums for s in (- nums[i], nums[i])} return goal in sums
Plus - minus - plus - plus - ... - Sum
5bc463f7797b00b661000118
[ "Algorithms" ]
https://www.codewars.com/kata/5bc463f7797b00b661000118
6 kyu
You've had a baby. Well done. Nice isn't it? Life destroying... but in a good way. Part of your new routine is lying awake at night worrying that you've either lost the baby... or that you have more than 1! Given a string of words (x), you need to calculate how many babies are in it. To count as a baby you must have...
reference
def baby_count(x): x = x . lower() return min(x . count('a'), x . count('b') / / 2, x . count('y')) or "Where's the baby?!"
The Baby Years I - Baby Counting
5bc9951026f1cdc77400011c
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/5bc9951026f1cdc77400011c
7 kyu
# Story OOP is a very useful paradigm which allows creating infinite amount of similar objects. On the contrary, "singleton pattern" limits it, so only 1 instance of a class can be created, and any future attempt to instantiate a new object returns the already existing one. But what if we want something in between? _...
reference
def limiter(limit, unique, lookup): def wrapper(class_): instances = {} lookups = {} def getinstance(* args, * * kwargs): new_obj = class_(* args, * * kwargs) if "FIRST" not in lookups: lookups["FIRST"] = new_obj id = getattr(new_obj, unique) if id in instances: r...
Limited number of instances
5bd36d5e03c3c4a37f0004f4
[ "Object-oriented Programming", "Metaprogramming" ]
https://www.codewars.com/kata/5bd36d5e03c3c4a37f0004f4
5 kyu
In this kata you will be given a random string of letters and tasked with returning them as a string of comma-separated sequences sorted alphabetically, with each sequence starting with an uppercase character followed by `n-1` lowercase characters, where `n` is the letter's alphabet position `1-26`. ## <span style="co...
reference
def alpha_seq(s): return "," . join((c * (ord(c) - 96)). capitalize() for c in sorted(s . lower()))
Alphabetical Sequence
5bd00c99dbc73908bb00057a
[ "Fundamentals", "Strings", "Arrays" ]
https://www.codewars.com/kata/5bd00c99dbc73908bb00057a
7 kyu
## Story As a part of your work on a project, you are supposed to implement a node-based calculator. Thinking that it is too much of a boring task, you decided to give it to a less experienced developer without telling the management. When he finished, you were astounded to see how poor and ugly his implementation is....
refactoring
import operator as o class v: def __init__(s, a, b): s . a, s . b = a, b def compute(s): return getattr(o, type(s). __name__)(s . a, s . b) class value (int): pass class add (v): pass class sub (v): pass class mul (v): pass class truediv (v): pa...
Refactor a node-based calculator (DRY)
5bcf52022f660cab19000300
[ "Refactoring", "Object-oriented Programming" ]
https://www.codewars.com/kata/5bcf52022f660cab19000300
5 kyu
### Story Your company migrated the last 20 years of it's *very important data* to a new platform, in multiple phases. However, something went wrong: some of the essential time-stamps were messed up! It looks like that some servers were set to use the `dd/mm/yyyy` date format, while others were using the `mm/dd/yyyy` ...
algorithms
def candidates(ymd): y, m, d = ymd . split('-') return {ymd, f' { y } - { d } - { m } '} def check_dates(records): result = [0, 0, 0] for start, end in records: xs = [(dt1, dt2) for dt1 in candidates(start) for dt2 in candidates(end) if dt1 <= dt2 and dt1[5: 7] <= '12' >= dt2[...
Data Analysis Following Migration
5bc5cfc9d38567e29600019d
[ "Date Time", "Algorithms", "Data Science" ]
https://www.codewars.com/kata/5bc5cfc9d38567e29600019d
6 kyu
# Task You are given a string `s`. It's a string consist of letters, numbers or symbols. Your task is to find the Longest substring consisting of unique characters in `s`, and return the length of it. # Note - `1 <= s.length <= 10^7` - `5` fixed testcases - `100` random testcases, testing for correctness of solu...
algorithms
def longest_substring(s: str) - > int: start, memo, res = 0, {}, 0 for i, c in enumerate(s): if c in memo and memo[c] >= start: start, res = memo[c] + 1, max(res, i - start) memo[c] = i return max(res, len(s) - start)
Simple Fun #396: Find the Longest Substring Consisting of Unique Characters
5bcd90808f9726d0f6000091
[ "Algorithms", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5bcd90808f9726d0f6000091
6 kyu
With one die of 6 sides we will have six different possible results:``` 1, 2, 3, 4, 5, 6``` . With 2 dice of six sides, we will have 36 different possible results: ``` (1,1),(1,2),(2,1),(1,3),(3,1),(1,4),(4,1),(1,5), (5,1), (1,6),(6,1),(2,2),(2,3),(3,2),(2,4),(4,2), (2,5),(5,2)(2,6),(6,2),(3,3),(3,4),(4,3),(3,5),(5,...
reference
import numpy as np def products(n, min_divisor, max_divisor): if n == 1: yield [] for divisor in range(min_divisor, max_divisor + 1): if n % divisor == 0: for product in products(n / / divisor, divisor, max_divisor): yield product + [divisor] def eq_dice(set): product = np...
Equivalent Dice
5b26047b9e40b9f4ec00002b
[ "Algorithms", "Performance", "Number Theory", "Recursion", "Fundamentals" ]
https://www.codewars.com/kata/5b26047b9e40b9f4ec00002b
5 kyu
In this kata we are going to mimic a software versioning system. ```if:javascript You have to implement a `vm` function returning an object. ``` ```if:factor You have to implement a `<version-manager>` constructor word, and some associated words. ``` ```if:rust You have to implement a `VersionManager` struct. ``` ```i...
algorithms
class VersionManager: def __init__(self, version=None): if not version: version = '0.0.1' self . __memory = [] try: arr = [* map(int, version . split('.')[: 3])] + [0, 0, 0] except: raise Exception("Error occured while parsing version!") del arr[3:] self . __versi...
Versions manager
5bc7bb444be9774f100000c3
[ "Algorithms", "Arrays", "Strings", "Object-oriented Programming" ]
https://www.codewars.com/kata/5bc7bb444be9774f100000c3
6 kyu
The leader of the village sends you to carry back exactly `c` litres from the mountain shrine holy water, but you can only bring back one of the 2 jars `a` or `b` (`a` and `b` are known values) in the shrine. You also have to do that in one travel... you can't risk going to the shrine and die trying to fill one of the ...
algorithms
from math import gcd def can_measure(a, b, c): return not (a < c > b or c % gcd(a, b))
3 litres and 5 litres
5bc8c9db40ecc7f792002308
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5bc8c9db40ecc7f792002308
7 kyu
Baby is getting his frst tooth. This means more sleepless nights, but with the fun of feeling round his gums and trying to guess which will be first out! Probably best have a sweepstake with your friends - because you have the best chance of knowing. You can feel the gums and see where the raised bits are - most rais...
reference
def first_tooth(lst): gums = lst[: 1] + lst + lst[- 1:] diff = [gums[i + 1] * 2 - gums[i] - gums[i + 2] for i in range(len(lst))] m = max(diff) return diff . index(m) if diff . count(m) == 1 else - 1
The Baby Years III - First Tooth
5bcac5a01cbff756e900003e
[ "Fundamentals", "Strings", "Arrays" ]
https://www.codewars.com/kata/5bcac5a01cbff756e900003e
7 kyu
We have the array of string digits, ```arr = ["3", "7", "7", "7", "3", "3, "3", "7", "8", "8", "8"]```. The string digit with the least frequency is "8" occurring three times. We will pop the first element of the array three times (exactly the same value of the minimum frequency) and we get "377" ``` ["3", "7", "7", "...
algorithms
from collections import Counter from math import factorial as fact def proc_arrII(arr): c = Counter(arr) l = min(c . values()) p = len(c) * * l return [p] if len(c) < l else [p, p - fact(len(c)) / / fact(len(c) - l), int('' . join(sorted(c . keys(), reverse=True)[: l]))]
Generate Numbers From Digits #2
584e936ae82520a397000027
[ "Fundamentals", "Logic", "Strings", "Data Structures", "Algorithms", "Mathematics", "Number Theory", "Permutations" ]
https://www.codewars.com/kata/584e936ae82520a397000027
5 kyu
There is no single treatment that works for every phobia, but some people cure it by being gradually exposed to the phobic situation or object. In this kata we will try curing arachnophobia by drawing primitive spiders. Our spiders will have legs, body, eyes and a mouth. Here are some examples: ``` /\((OOwOO))/\ /╲(...
reference
def draw_spider(leg_size, body_size, mouth, eye): lleg = ['', '^', '/\\', '/╲', '╱╲'][leg_size] rleg = ['', '^', '/\\', '╱\\', '╱╲'][leg_size] lbody = '(' * body_size rbody = ')' * body_size eye *= 2 * * (body_size - 1) return f' { lleg }{ lbody }{ eye }{ mouth }{ eye }{ rbody }{ rleg } ' ...
Curing Arachnophobia
5bc73331797b005d18000255
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5bc73331797b005d18000255
7 kyu
# Task **Your task** is to implement function `printNumber` (`print_number` in C/C++ and Python `Kata.printNumber` in Java) that returns string that represents given number in text format (see examples below). Arguments: - `number` — Number that we need to print (`num` in C/C++/Java) - `char` — Character for buildi...
reference
DIGITS = """ *************************************************************************** * * * **** ** **** **** ** ** ****** ** ****** **** **** * * ** ** *** ** ** ** ** ** ** ** ** ** ** ** ** ** ** * * ** ** * ** ** ** ** ** ***** **** ** **** ** ** * * ** ** ** ** ** ***** ** ** ** ** **** **** * * *...
Print number with character
5bc5c0f8eba26e792400012a
[ "Fundamentals" ]
https://www.codewars.com/kata/5bc5c0f8eba26e792400012a
6 kyu
# Silent Import As part of your spy training, You were taught to be as stealthy as possible while carrying out missions. This time, you have to silently import modules from a without getting caught. Most of your peers are skeptical if you will be able to do this. But, you are the [G.O.A.T](https://www.urbandictionary.c...
games
def silent_thief(module_name): return globals()['_' '_builtins_' '_']['_' '_imp' 'ort_' '_'](module_name)
Silent Import
5bc5c064eba26ef6ed000158
[ "Puzzles", "Language Features", "Restricted" ]
https://www.codewars.com/kata/5bc5c064eba26ef6ed000158
6 kyu
## Task You are given three non negative integers `a`, `b` and `n`, and making an infinite sequence just like fibonacci sequence, use the following rules: - step 1: use `ab` as the initial sequence. - step 2: calculate the sum of the last two digits of the sequence, and append it to the end of sequence. - repeat step...
games
def find(a, b, n): strng = str(a) + str(b) # there are 10 and 4 long loops if (n > 20): n = n % 20 + 20 while len(strng) <= n: next_ch = int(strng[- 1]) + int(strng[- 2]) strng = strng + str(next_ch) return int(strng[n])
Simple Fun #395: Fibonacci digit sequence
5bc555bb62a4cec849000047
[ "Puzzles", "Fundamentals" ]
https://www.codewars.com/kata/5bc555bb62a4cec849000047
6 kyu
John has invited some friends. His list is: ``` s = "Fred:Corwill;Wilfred:Corwill;Barney:Tornbull;Betty:Tornbull;Bjon:Tornbull;Raphael:Corwill;Alfred:Corwill"; ``` Could you make a program that - makes this string uppercase - gives it sorted in alphabetical order by last name. When the last names are the same, sort...
reference
def meeting(s): return '' . join(sorted('({1}, {0})' . format(* (x . split(':'))) for x in s . upper(). split(';')))
Meeting
59df2f8f08c6cec835000012
[ "Fundamentals" ]
https://www.codewars.com/kata/59df2f8f08c6cec835000012
6 kyu
A rook is a piece used in the game of chess which is played on a board of square grids. A rook can only move vertically or horizontally from its current position and two rooks attack each other if one is on the path of the other. In the following figure, the dark squares represent the reachable locations for rook R<sub...
reference
from math import factorial, comb def rooks(n, k): return factorial(k) * comb(n, k) * * 2
Rooks
5bc2c8e230031558900000b5
[ "Algorithms", "Mathematics", "Fundamentals", "Combinatorics" ]
https://www.codewars.com/kata/5bc2c8e230031558900000b5
6 kyu
We need a function that may receive a list of an unknown amount of points in the same plane, having each of them, cartesian coordinates of the form (x, y) and may find the biggest triangle (the one with the largest area) formed by all of the possible combinations of groups of three points of that given list. Of course...
reference
from itertools import combinations def find_biggTriang(listPoints): def area(a, b, c): return 0.5 * abs(b[0] * c[1] - b[1] * c[0] - a[0] * c[1] + a[1] * c[0] + a[0] * b[1] - a[1] * b[0]) triangls = [[[a, b, c], area(a, b, c)] for a, b, c in combin...
Find the Biggest Triangle
55f0a7d8c44c6f1438000013
[ "Data Structures", "Algorithms", "Mathematics", "Searching", "Sorting", "Fundamentals" ]
https://www.codewars.com/kata/55f0a7d8c44c6f1438000013
6 kyu
The conic curves may be obtained doing different sections of a cone and we may obtain the three principal groups: ellipse, hyperbola and parabola. <a href="http://imgur.com/4NdOkgf"><img src="http://i.imgur.com/4NdOkgf.png?2" title="source: imgur.com" /></a> The circle is a special case of ellipses. In mathematics a...
reference
def det(matrix: list) - > int: if len(matrix) == 1: return matrix[0][0] return sum((- 1) * * i * matrix[0][i] * det([row[: i] + row[i + 1:] for row in matrix[1:]]) for i in range(len(matrix))) def classify_conic(A: int, B: int, C: int, D: int, E: int, F: int) - > str: M = det([[2 * A, B, D], [B...
Conic Classification
56546460730f15790b000075
[ "Fundamentals", "Logic", "Data Structures", "Mathematics", "Geometry", "Linear Algebra" ]
https://www.codewars.com/kata/56546460730f15790b000075
6 kyu
You will be given two strings `a` and `b` consisting of lower case letters, but `a` will have at most one asterix character. The asterix (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase letters. No other character of string `a` can be replaced. If it is possible to replace the asterix i...
reference
from fnmatch import fnmatch def solve(a, b): return fnmatch(b, a)
Simple string matching
5bc052f93f43de7054000188
[ "Fundamentals" ]
https://www.codewars.com/kata/5bc052f93f43de7054000188
7 kyu
Given an integer `n`, find two integers `a` and `b` such that: ```Pearl A) a >= 0 and b >= 0 B) a + b = n C) DigitSum(a) + Digitsum(b) is maximum of all possibilities. ``` You will return the digitSum(a) + digitsum(b). ``` For example: solve(29) = 11. If we take 15 + 14 = 29 and digitSum = 1 + 5 + 1 + 4 = 11. There...
reference
def solve(n): if n < 10: return n a = int((len(str(n)) - 1) * '9') b = n - a return sum([int(i) for i in (list(str(a)) + list(str(b)))])
Simple sum of pairs
5bc027fccd4ec86c840000b7
[ "Fundamentals", "Performance" ]
https://www.codewars.com/kata/5bc027fccd4ec86c840000b7
6 kyu
We have an integer array with unique elements and we want to do the permutations that have an element fixed, in other words, these permutations should have a certain element at the same position than the original. These permutations will be called: **permutations with one fixed point**. Let's see an example with an a...
reference
def fixed_points_perms(n, k): if k > n: return 0 if k == n: return 1 if k == 0: def subf(n): return 1 if n == 0 else n * subf(n - 1) + (- 1) * * n return subf(n) return fixed_points_perms(n - 1, k - 1) * n / / k
Shuffle It Up II
5bbecf840441ca6d6a000126
[ "Algorithms", "Performance", "Number Theory", "Recursion", "Fundamentals" ]
https://www.codewars.com/kata/5bbecf840441ca6d6a000126
6 kyu
This kata is an extension of "Combinations in a Set Using Boxes":https://www.codewars.com/kata/5b5f7f7607a266914200007c The goal for this kata is to get all the possible combinations (or distributions) (with no empty boxes) of a certain number of balls, but now, **with different amount of boxes.** In the previous kata...
reference
MAX_BALL = 2 + 1800 DP, lst = [None], [0, 1] for _ in range(MAX_BALL): DP . append([sum(lst), * max((v, i) for i, v in enumerate(lst))]) lst . append(0) lst = [v * i + lst[i - 1] for i, v in enumerate(lst)] combs_non_empty_boxesII = DP . __getitem__
Combinations in a Set Using Boxes II
5b61e9306d0db7d097000632
[ "Performance", "Algorithms", "Mathematics", "Machine Learning", "Combinatorics", "Number Theory" ]
https://www.codewars.com/kata/5b61e9306d0db7d097000632
5 kyu
You have a set of four (4) balls labeled with different numbers: ball_1 (1), ball_2 (2), ball_3 (3) and ball(4) and we have 3 equal boxes for distribute them. The possible combinations of the balls, without having empty boxes, are: ``` (1) (2) (3)(4) ______ ______ _______ ```...
reference
# Stirling numbers of second kind # http://mathworld.wolfram.com/StirlingNumberoftheSecondKind.html # S(n,k)=1/(k!)sum_(i=0)^k(-1)^i(k; i)(k-i)^n from math import factorial as fact def combs_non_empty_boxes(n, k): if k < 0 or k > n: return 'It cannot be possible!' return sum([1, - 1][i % 2] * (k - i) ...
Combinations in a Set Using Boxes
5b5f7f7607a266914200007c
[ "Performance", "Algorithms", "Mathematics", "Machine Learning", "Combinatorics", "Number Theory", "Memoization" ]
https://www.codewars.com/kata/5b5f7f7607a266914200007c
5 kyu
Cheesy Cheeseman just got a new monitor! He is happy with it, but he just discovered that his old desktop wallpaper no longer fits. He wants to find a new wallpaper, but does not know which size wallpaper he should be looking for, and alas, he just threw out the new monitor's box. Luckily he remembers the width and the...
reference
def find_screen_height(width, ratio): a, b = map(int, ratio . split(":")) return f" { width } x { int ( width / a * b )} "
Find Screen Size
5bbd279c8f8bbd5ee500000f
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/5bbd279c8f8bbd5ee500000f
7 kyu
<img src="https://i.imgur.com/ta6gv1i.png?1" title="weekly coding challenge" /> # Background I have stacked some cannon balls in a triangle-based pyramid. Like this, <img src="https://i.imgur.com/ut4ejG1.png" title="cannon balls triangle base" /> # Kata Task Given the number of `layers` of my stack, what is the ...
reference
def stack_height_3d(layers): return 1 + (layers - 1) * (2 / 3) * * 0.5 if layers else 0
Stacked Balls - 3D (triangle base)
5bbad1082ce5333f8b000006
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5bbad1082ce5333f8b000006
7 kyu
Alice, Samantha, and Patricia are relaxing on the porch, when Alice suddenly says: _"I'm thinking of two numbers, both greater than or equal to 2. I shall tell Samantha the sum of the two numbers and Patricia the product of the two numbers."_ She takes Samantha aside and whispers in her ear the sum so that Patricia c...
games
def is_prime(n): return n == 2 or n % 2 != 0 and all(n % k != 0 for k in xrange(3, root(n) + 1, 2)) def root(p): return int(p * * 0.5) def statement1(s): return not (s % 2 == 0 or is_prime(s - 2)) def statement2(p): return sum(statement1(i + p / i) for i in xrange(2, root(p) + 1...
Bridge Puzzle
56f6380a690784f96e00045d
[ "Recursion", "Puzzles" ]
https://www.codewars.com/kata/56f6380a690784f96e00045d
4 kyu
# Background I have stacked some cannon balls in a square pyramid. Like this, <img src="https://i.imgur.com/6d5Kpva.png" title="cannon balls" /> # Kata Task Given the number of `layers` of my stack, what is the total height? Return the height as multiple of the ball diameter. ## Example The image above shows a ...
reference
def stack_height_3d(layers): return layers and 1 + (layers - 1) / 2 * * 0.5
Stacked Balls - 3D (square base)
5bb493932ce53339dc0000c2
[ "Fundamentals" ]
https://www.codewars.com/kata/5bb493932ce53339dc0000c2
7 kyu
![Image of sliding puzzle](https://i.imgur.com/AUVWFOn.png) A [sliding puzzle](https://en.wikipedia.org/wiki/Sliding_puzzle) is a combination puzzle that challenges a player to slide (frequently flat) pieces along certain routes (usually on a board) to establish a certain end-configuration. Your goal for this kata is...
algorithms
from itertools import chain, combinations, accumulate from heapq import heappush, heappop def slide_puzzle(arr): def moveTargetTo(iX, i0, grid, target=None, lowLim=None): """ iX: index in the grid of the position to work on i0: blank index grid: current grid stat...
Sliding Puzzle Solver
5a20eeccee1aae3cbc000090
[ "Puzzles", "Genetic Algorithms", "Game Solvers", "Algorithms" ]
https://www.codewars.com/kata/5a20eeccee1aae3cbc000090
1 kyu
We want to obtain number ```π``` (```π = 3,1415926535897932384626433832795```) with an approximate fraction having a relative error of 1% ``` rel_error = (π - fraction_value) / π * 100 = ± 1 absolute_error = |± 1 / 100 * π| = 0.031416 ``` Try to get the used algorithm to obtain the approximate fraction, observing th...
reference
import math def approx_fraction(target: float, rel_err_pct: float, eps: float = 1e-10) - > list[str, int] | str: if math . isclose(round(target), target, rel_tol=eps): return f'There is no need to have a fraction for { round ( target )} ' if target < 0: a, b = approx_fraction(- target, rel_err_pct) ...
Approximate Fractions
56797325703d8b34a4000014
[ "Fundamentals", "Mathematics", "Strings" ]
https://www.codewars.com/kata/56797325703d8b34a4000014
6 kyu
# A History Lesson The <a href=https://en.wikipedia.org/wiki/Pony_Express>Pony Express</a> was a mail service operating in the US in 1859-60. <img src="https://i.imgur.com/oEqUjpP.png" title="Pony Express" /> It reduced the time for messages to travel between the Atlantic and Pacific coasts to about 10 days, befor...
algorithms
def riders(stations, lost): stations = stations[: lost - 1] + stations[lost - 2:] rider, dist = 1, 0 for i, d in enumerate(stations): rider += (dist + d > 100) + (i == lost - 2) dist = dist * (dist + d <= 100 and i != lost - 2) + d return rider
The Pony Express (missing rider)
5b204d1d9212cb6ef3000111
[ "Algorithms" ]
https://www.codewars.com/kata/5b204d1d9212cb6ef3000111
6 kyu
Count how often sign changes in array. ### result number from `0` to ... . Empty array returns `0` ### example ```javascript const arr = [1, -3, -4, 0, 5]; /* | elem | count | |------|-------| | 1 | 0 | | -3 | 1 | | -4 | 1 | | 0 | 2 | | 5 | 2 | */ catchSignChange(arr) == 2; ``` ~...
reference
def catch_sign_change(lst): count = 0 for i in range(1, len(lst)): if lst[i] < 0 and lst[i - 1] >= 0: count += 1 if lst[i] >= 0 and lst[i - 1] < 0: count += 1 return count
Plus - minus - plus - plus - ... - Count
5bbb8887484fcd36fb0020ca
[ "Fundamentals" ]
https://www.codewars.com/kata/5bbb8887484fcd36fb0020ca
7 kyu
## Description "John, come here, we have to talk about the order form. Although I was drunk yesterday, today is not fully awake, but why do they look so strange?" ``` [ {"tire":1,"steeringWheel":2,"totalPrice":31.56}, {"tire":5,"steeringWheel":1,"totalPrice":73.69} ] ``` "Oh, my boss, all of these are based on the lis...
games
def correct_order(orders): result = [] for o in orders: for t in range(5, 20): for s in range(t + 1, t + 4): if round((t + .98) * o["tire"] + (s + .79) * o["steeringWheel"], 2) == o["totalPrice"]: result . append({"tire": 4, "steeringWheel": 1, "totalPrice": round((t +...
T.T.T.47: The boss is always right
57be4f2e87e4483c800002ee
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/57be4f2e87e4483c800002ee
6 kyu