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
A [perfect power](https://en.wikipedia.org/wiki/Perfect_power) is a classification of positive integers: > In mathematics, a **perfect power** is a positive integer that can be expressed as an integer power of another positive integer. More formally, n is a perfect power if there exist natural numbers m > 1, and k > 1...
reference
def isPP(n): for i in range(2, n + 1): for j in range(2, n + 1): if i * * j > n: break elif i * * j == n: return [i, j] return None
What's a Perfect Power anyway?
54d4c8b08776e4ad92000835
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/54d4c8b08776e4ad92000835
5 kyu
The input is a string `str` of digits. Cut the string into chunks (a chunk here is a substring of the initial string) of size `sz` (ignore the last chunk if its size is less than `sz`). If the sum of a chunk's digits is divisible by `2`, reverse that chunk; otherwise rotate it to the left by one position. Put togethe...
reference
def func(s): result = sum(int(x) * * 3 for x in s) if result % 2 == 0: return s[:: - 1] else: return s[1:] + s[0] def revrot(s, sz): if not sz: return '' return '' . join(func('' . join(x)) for x in zip(* [iter(list(s))] * sz))
Reverse or rotate?
56b5afb4ed1f6d5fb0000991
[ "Algorithms", "Strings" ]
https://www.codewars.com/kata/56b5afb4ed1f6d5fb0000991
6 kyu
Write a function that accepts a string, and returns the same string with all even indexed characters in each word upper cased, and all odd indexed characters in each word lower cased. The indexing just explained is zero based, so the zero-ith index is even, therefore that character should be upper cased and you need to...
algorithms
def to_weird_case_word(string): return "" . join(c . upper() if i % 2 == 0 else c for i, c in enumerate(string . lower())) def to_weird_case(string): return " " . join(to_weird_case_word(str) for str in string . split())
WeIrD StRiNg CaSe
52b757663a95b11b3d00062d
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/52b757663a95b11b3d00062d
6 kyu
In this kata, you should calculate the type of triangle with three given sides ``a``, ``b`` and ``c`` (given in any order). If each angle is less than ``90°``, this triangle is ``acute`` and the function should return ``1``. If one angle is strictly ``90°``, this triangle is ``right`` and the function should return `...
algorithms
def triangle_type(a, b, c): x, y, z = sorted([a, b, c]) if z >= x + y: return 0 if z * z == x * x + y * y: return 2 return 1 if z * z < x * x + y * y else 3
Triangle type
53907ac3cd51b69f790006c5
[ "Geometry", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/53907ac3cd51b69f790006c5
6 kyu
There is a secret string which is unknown to you. Given a collection of random triplets from the string, recover the original string. A triplet here is defined as a sequence of three letters such that each letter occurs somewhere before the next in the given string. "whi" is a triplet for the string "whatisup". As a...
algorithms
def recoverSecret(triplets): r = list(set([i for l in triplets for i in l])) for l in triplets: fix(r, l[1], l[2]) fix(r, l[0], l[1]) return '' . join(r) def fix(l, a, b): """let l.index(a) < l.index(b)""" if l . index(a) > l . index(b): l . remove(a) l . insert(l . i...
Recover a secret string from random triplets
53f40dff5f9d31b813000774
[ "Algorithms" ]
https://www.codewars.com/kata/53f40dff5f9d31b813000774
4 kyu
We want to create a function that will add numbers together when called in succession. ```javascript add(1)(2); // == 3 ``` ```ruby add(1).(2); # equals 3 ``` ```python add(1)(2) # equals 3 ``` We also want to be able to continue to add numbers to our chain. ```javascript add(1)(2)(3); // == 6 add(1)(2)(3)(4); // ...
games
class add (int): def __call__(self, n): return add(self + n)
A Chain adding function
539a0e4d85e3425cb0000a88
[ "Mathematics", "Functional Programming", "Puzzles" ]
https://www.codewars.com/kata/539a0e4d85e3425cb0000a88
5 kyu
# Introduction <pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;"> Guess Who? is a two-player guessing game created by Ora and Theo Coster, also known as Theora Design, that was first manufactured by Milton Bradley in 1979. It was first ...
reference
class GuessWho (object): def __init__(self, character): self . char = character self . possibles = set(characters) self . attempt = 0 def guess(self, guess): self . attempt += 1 if guess == self . char: return [f"Correct! in { self . attempt } turns"] if guess in characters:...
Guess Who?
58b2c5de4cf8b90723000051
[ "Games", "Fundamentals" ]
https://www.codewars.com/kata/58b2c5de4cf8b90723000051
6 kyu
A squared string is a string of `n` lines, each substring being `n` characters long. We are given two n-squared strings. For example: `s1 = "abcd\nefgh\nijkl\nmnop"` `s2 = "qrst\nuvwx\nyz12\n3456"` Let us build a new string `strng` of size `(n + 1) x n` in the following way: - The first line of `strng` has the firs...
reference
def compose(s1, s2): s1 = s1 . split("\n") s2 = s2 . split("\n")[:: - 1] n = len(s1) out = [] for i in range(n): out . append(s1[i][: i + 1] + s2[i][:(n - i)]) return "\n" . join(out)
Composing squared strings
56f253dd75e340ff670002ac
[ "Fundamentals" ]
https://www.codewars.com/kata/56f253dd75e340ff670002ac
7 kyu
A number system with moduli is defined by a vector of k moduli, `[m1,m2, ···,mk]`. The moduli must be `pairwise co-prime`, which means that, for any pair of moduli, the only common factor is `1`. In such a system each number `n` is represented by a string `"-x1--x2-- ... --xk-"` of its residues, one for each modul...
reference
from math import gcd, prod from itertools import combinations def from_nb_2_str(n, modsys): if prod(modsys) < n or next((True for a, b in combinations(modsys, 2) if gcd(a, b) != 1), False): return "Not applicable" return '-' + '--' . join(str(n % m) for m in modsys) + '-'
Moduli number system
54db15b003e88a6a480000b9
[ "Fundamentals" ]
https://www.codewars.com/kata/54db15b003e88a6a480000b9
6 kyu
In the drawing below we have a part of the Pascal's triangle, horizontal lines are numbered from **zero** (top). We want to calculate the sum of the squares of the binomial coefficients on a given horizontal line with a function called `easyline` (or easyLine or easy-line). Can you write a program which calculate `ea...
reference
def easyline(n): return easyline(n - 1) * (4 * n - 2) / / n if n else 1
Easy Line
56e7d40129035aed6c000632
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/56e7d40129035aed6c000632
7 kyu
# RoboScript #2 - Implement the RS1 Specification ## Disclaimer The story presented in this Kata Series is purely fictional; any resemblance to actual programming languages, products, organisations or people should be treated as purely coincidental. ## About this Kata Series This Kata Series is based on a fictional...
algorithms
from collections import deque import re TOKENIZER = re . compile(r'(R+|F+|L+)(\d*)') def execute(code): pos, dirs = (0, 0), deque([(0, 1), (1, 0), (0, - 1), (- 1, 0)]) seens = {pos} for act, n in TOKENIZER . findall(code): s, r = act[0], int(n or '1') + len(act) - 1 if s == 'F': ...
RoboScript #2 - Implement the RS1 Specification
5870fa11aa0428da750000da
[ "Esoteric Languages", "Algorithms" ]
https://www.codewars.com/kata/5870fa11aa0428da750000da
5 kyu
# RoboScript #1 - Implement Syntax Highlighting ## Disclaimer The story presented in this Kata Series is purely fictional; any resemblance to actual programming languages, products, organisations or people should be treated as purely coincidental. ## About this Kata Series This Kata Series is based on a fictional s...
reference
import re def highlight(code): code = re . sub(r"(F+)", '<span style="color: pink">\g<1></span>', code) code = re . sub(r"(L+)", '<span style="color: red">\g<1></span>', code) code = re . sub(r"(R+)", '<span style="color: green">\g<1></span>', code) code = re . sub(r"(\d+)", '<span style="color...
RoboScript #1 - Implement Syntax Highlighting
58708934a44cfccca60000c4
[ "Fundamentals" ]
https://www.codewars.com/kata/58708934a44cfccca60000c4
6 kyu
Given u<sub>0</sub> = 1, u<sub>1</sub> = 2 and the relation 6u<sub>n</sub>u<sub>n+1</sub>-5u<sub>n</sub>u<sub>n+2</sub>+u<sub>n+1</sub>u<sub>n+2</sub> = 0</code> calculate u<sub>n</sub> for any integer n >= 0. #### Examples: Call `fcn` the function such as fcn(n) = u<sub>n</sub>. `fcn(17) -> 131072; fcn(21) -> 209715...
algorithms
def fcn(n): return 2 * * n
A disguised sequence (I)
563f0c54a22b9345bf000053
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/563f0c54a22b9345bf000053
6 kyu
Agent 47, you have a new task! Among citizens of the city X are hidden 2 dangerous criminal twins. Your task is to identify them and eliminate! Given an array of integers, your task is to find two same numbers and return one of them, for example in array ``[2, 3, 6, 34, 7, 8, 2]`` answer is ``2``. ```if-not:c If ther...
algorithms
def elimination(arr): for x in arr: if arr . count(x) == 2: return x
Find twins
5834315e06f227a6ac000099
[ "Algorithms" ]
https://www.codewars.com/kata/5834315e06f227a6ac000099
7 kyu
<a href="http://imgur.com/h75nn5H"><img src="http://i.imgur.com/h75nn5H.png?1" title="source: imgur.com" /></a> This kata was thaught to continue with the topic of ```Tracking Hits for Different Sum Values for Different Kinds of Dice``` see at:http://www.codewars.com/kata/56f852635d7c12fb610013d7 In that kata we show...
reference
from itertools import product from collections import Counter def most_prob_sum(dice, n): c = Counter(sum(p) for p in product( * [[i for i in range(1, 1 + {'tet': 4, 'cub': 6, 'oct': 8, 'nin': 9, 'ten': 10, 'dod': 12, 'ico': 20}[dice[: 3]])] for _ in range(n)])) mx = max(c . values()) retu...
Find the Most Probable Sum Value or Values, in Rolling N-dice of n Sides
56fb9da2fca8b9d7de00083f
[ "Algorithms", "Mathematics", "Statistics" ]
https://www.codewars.com/kata/56fb9da2fca8b9d7de00083f
5 kyu
<a href="http://imgur.com/zlXr2na"><img src="http://i.imgur.com/zlXr2na.jpg?1" title="source: imgur.com" /></a> Perhaps it would be convenient to solve first ```Probabilities for Sums in Rolling Cubic Dice``` see at: http://www.codewars.com/kata/probabilities-for-sums-in-rolling-cubic-dice Suppose that we roll dice t...
reference
def reg_sum_hits(dices, sides=6): d, s = sides * [1], sides - 1 for i in range(dices - 1): t = s * [0] + d + s * [0] d = [sum(t[i: i + sides]) for i in range(len(t) - s)] return [[i + dices, prob] for (i, prob) in enumerate(d)]
Tracking Hits for Different Sum Values for Different Kinds of Dice
56f852635d7c12fb610013d7
[ "Mathematics", "Statistics", "Probability", "Permutations", "Data Science" ]
https://www.codewars.com/kata/56f852635d7c12fb610013d7
5 kyu
<a href="http://imgur.com/E4b42Sm"><img src="http://i.imgur.com/E4b42Sm.jpg?1" title="source: imgur.com" /></a> When we throw 2 classical dice (values on each side from 1 to 6) we have 36 (6 * 6) different results. We want to know the probability of having the sum of the results equals to ```11```. For that result w...
reference
def rolldice_sum_prob(sum_, dice_amount): import itertools import collections sums = [sum(list(i)) for i in itertools . product( [1, 2, 3, 4, 5, 6], repeat=dice_amount)] count = collections . Counter(sums) prob = count[sum_] * 1.0 / (len(sums)) return prob
Probabilities for Sums in Rolling Cubic Dice
56f78a42f749ba513b00037f
[ "Mathematics", "Statistics", "Probability", "Logic" ]
https://www.codewars.com/kata/56f78a42f749ba513b00037f
5 kyu
Check if given chord is minor or major. ### Rules 1. Basic minor/major chord have three elements. 2. A chord is *minor* when the interval between first and second element = 3 and between second and third = 4 3. A chord is *major* when the interval between first and second element = 4 and between second and third = 3 ...
reference
from itertools import product NOTES = [['C'], ['C#', 'Db'], ['D'], ['D#', 'Eb'], ['E'], ['F'], [ 'F#', 'Gb'], ['G'], ['G#', 'Ab'], ['A'], ['A#', 'Bb'], ['B']] * 2 config = [('Major', 4), ('Minor', 3)] DCT_CHORDS = {c: mode for mode, offset in config for i in range(len(NOTES) / / 2) ...
#01 - Music theory - Minor/Major chords
57052ac958b58fbede001616
[ "Strings", "Data Structures", "Logic", "Fundamentals" ]
https://www.codewars.com/kata/57052ac958b58fbede001616
6 kyu
<img src="https://i.imgur.com/ta6gv1i.png?1" title="cw weekly challenge" /> Have you ever noticed that cows in a field are always facing in the same direction? Reference: http://bfy.tw/7fgf <hr> Well.... not quite always. One stubborn cow wants to be different from the rest of the herd - it's that damn *Wrong-Way ...
algorithms
SEARCH_COWES = {"cow", "woc"} def find_wrong_way_cow(field): for i, f in enumerate([field, list(zip(* field))]): length, strField = len(f[0]), '\n' . join('' . join(line) for line in f) for sCow in SEARCH_COWES: pos = strField . find(sCow) if pos != - 1 and pos == strField . rfind(sCow):...
The Wrong-Way Cow
57d7536d950d8474f6000a06
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/57d7536d950d8474f6000a06
5 kyu
The Arara are an isolated tribe found in the Amazon who count in pairs. For example one to eight is as follows: 1 = anane </br> 2 = adak </br> 3 = adak anane </br> 4 = adak adak </br> 5 = adak adak anane </br> 6 = adak adak adak</br> 7 = adak adak adak anane</br> 8 = adak adak adak adak </br> T...
games
def count_arara(n): return " " . join(['adak'] * (n / / 2) + ['anane'] * (n % 2))
Counting in the Amazon
55b95c76e08bd5eef100001e
[ "Puzzles", "Fundamentals" ]
https://www.codewars.com/kata/55b95c76e08bd5eef100001e
7 kyu
## Task Implement a function which receives a list of values `lst` and a function `fn` as its arguments, and returns a new list where the `i`-th element is the result of left-reducing the first `i+1` elements of `lst` using `fn`. Assuming `lst[:n]` syntax represents taking the first `n` elements of `lst`, the functio...
reference
from itertools import accumulate def running(lst, fn): return list(accumulate(lst, fn))
Running functions
58b42c98f4cdd62f45000c6e
[ "Lists", "Fundamentals" ]
https://www.codewars.com/kata/58b42c98f4cdd62f45000c6e
7 kyu
Data: an array of integers, a function f of two variables and an init value. `Example: a = [2, 4, 6, 8, 10, 20], f(x, y) = x + y; init = 0` Output: an array of integers, say r, such that `r = [r[0] = f(init, a[0]), r[1] = f(r[0], a[1]), r[2] = f(r[1], a[2]), ...]` With our example: `r = [2, 6, 12, 20, 30, 50]` ###...
reference
def gcdi(a, b): from fractions import gcd return abs(gcd(a, b)) def lcmu(a, b): from fractions import gcd return abs(a * b / / gcd(a, b)) def som(a, b): return a + b def maxi(a, b): return max(a, b) def mini(a, b): return min(a, b) def oper_array(fct, arr, ini...
Reducing by steps
56efab15740d301ab40002ee
[ "Mathematics", "Arrays", "Functional Programming", "Lists", "Data Structures" ]
https://www.codewars.com/kata/56efab15740d301ab40002ee
6 kyu
*There is a secret message in the first six sentences of this kata description. Have you ever felt like there was something more being said? Was it hard to figure out that unspoken meaning? Never again! Never will a secret go undiscovered. Find all duplicates from our message!* Your job is to write a function that wil...
algorithms
def find_secret_message(paragraph): s = set() ret = [] for w in (word . strip('.,:!?'). lower() for word in paragraph . split()): if w in s and not w in ret: ret . append(w) else: s . add(w) return ' ' . join(ret)
Secret Message
54808e45ab03a2c8330009fb
[ "Algorithms" ]
https://www.codewars.com/kata/54808e45ab03a2c8330009fb
6 kyu
## Objective Given a number `n` we will define its scORe to be `0 | 1 | 2 | 3 | ... | n`, where `|` is the [bitwise OR operator](https://en.wikipedia.org/wiki/Bitwise_operation#OR). Write a function that takes `n` and finds it's scORe. --------------------- | n | scORe n | |---------|-------- | | 0 ...
algorithms
def score(n): return 2 * * n . bit_length() - 1
Binary scORe
56cafdabc8cfcc3ad4000a2b
[ "Binary", "Algorithms" ]
https://www.codewars.com/kata/56cafdabc8cfcc3ad4000a2b
7 kyu
In this kata you need to write a function that will receive two strings (```n1``` and ```n2```), each representing an integer as a binary number. A third parameter will be provided (```o```) as a string representing one of the following operators: add, subtract, multiply. Your task is to write the calculate function s...
algorithms
def calculate(n1, n2, o): operators = { "add": (lambda x, y: x + y), "subtract": (lambda x, y: x - y), "multiply": (lambda x, y: x * y), } return "{:b}" . format(operators[o](int(n1, 2), int(n2, 2)))
Binary Calculator
546ba103f0cf8f7982000df4
[ "Binary", "Algorithms" ]
https://www.codewars.com/kata/546ba103f0cf8f7982000df4
7 kyu
Define n!! as n!! = 1 \* 3 \* 5 \* ... \* n if n is odd, n!! = 2 \* 4 \* 6 \* ... \* n if n is even. Hence 8!! = 2 \* 4 \* 6 \* 8 = 384, there is no zero at the end. 30!! has 3 zeros at the end. For a positive integer n, please count how many zeros are there at the end of n!!. Example: ``` 30!! = 2 * 4 * ...
games
def count_zeros_n_double_fact(n): if n % 2 != 0: return 0 k = 0 while n >= 10: k += n / / 10 n / /= 5 return k
Jungerstein's Math Training Room: 1. How many zeros are at the end of n!! ?
58cbfe2516341cce1e000001
[ "Puzzles", "Mathematics", "Number Theory", "Discrete Mathematics" ]
https://www.codewars.com/kata/58cbfe2516341cce1e000001
6 kyu
No Story No Description Only by Thinking and Testing Look at result of testcase, guess the code! ## Series: * [01: A and B?](https://www.codewars.com/kata/56d904db9963e9cf5000037d) * [02: Incomplete string](https://www.codewars.com/kata/56d9292cc11bcc3629000533) * [03: True or False](https://www.codewars.com/kata/...
games
def testit(a, b): return a | b
Thinking & Testing: A and B?
56d904db9963e9cf5000037d
[ "Puzzles" ]
https://www.codewars.com/kata/56d904db9963e9cf5000037d
7 kyu
Let us define two sums `v(n, p)` and `u(n, p)`: ```math v(n,p) = \sum_{k=0}^n (-1)^k \times p \times 4^{n-k} \times {2n - k \choose k} ``` ```math u(n,p) = \sum_{k=0}^n (-1)^k \times p \times 4^{n-k} \times {2n - k + 1 \choose k} ``` #### Task: - 1) Calculate `v(n, p)` and `u(n, p)` with two brute-force functions `v...
reference
''' from math import factorial def nCr(n, r): return factorial(n) / factorial(n-r) / factorial(r) def u1(n, p): return sum((-1)**k * p * 4 ** (n-k) * nCr(2*n-k+1, k) for k in range(n + 1)) def v1(n, p): return sum((-1)**k * p * 4 ** (n-k) * nCr(2*n-k, k) for k in range(n + 1)) ''' u1 = u_eff = lambda ...
Disguised sequences (II)
56fe17fcc25bf3e19a000292
[ "Puzzles", "Discrete Mathematics", "Mathematics" ]
https://www.codewars.com/kata/56fe17fcc25bf3e19a000292
6 kyu
Braking distance `d1` is the distance a vehicle will go from the point when it brakes to when it comes to a complete stop. It depends on the original speed `v` and on the coefficient of friction `mu` between the tires and the road surface. The braking distance is one of two principal components of the total stopping ...
reference
def dist(v, mu): # suppose reaction time is 1 v /= 3.6 return v + v * v / (2 * mu * 9.81) def speed(d, mu): # suppose reaction time is 1 b = - 2 * mu * 9.81 return round(3.6 * (b + (b * b - 4 * b * d) * * 0.5) / 2, 2)
Braking well
565c0fa6e3a7d39dee000125
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/565c0fa6e3a7d39dee000125
6 kyu
When working with color values it can sometimes be useful to extract the individual red, green, and blue (RGB) component values for a color. Implement a function that meets these requirements: + Accepts a case-insensitive hexadecimal color string as its parameter (ex. `"#FF9933"` or `"#ff9933"`) + Returns a Map<String...
algorithms
def hex_string_to_RGB(hex): return {'r': int(hex[1: 3], 16), 'g': int(hex[3: 5], 16), 'b': int(hex[5: 7], 16)}
Convert A Hex String To RGB
5282b48bb70058e4c4000fa7
[ "Parsing", "Strings", "Algorithms" ]
https://www.codewars.com/kata/5282b48bb70058e4c4000fa7
5 kyu
**Description:** We want to generate a function that computes the series starting from 0 and ending until the given number. Example: ---- **Input:** > 6 **Output:** > 0+1+2+3+4+5+6 = 21 **Input:** > -15 **Output:** > -15<0 **Input:** > 0 **Output:** > 0=0
reference
def show_sequence(n): if n == 0: return "0=0" elif n < 0: return str(n) + "<0" else: counter = sum(range(n + 1)) return '+' . join(map(str, range(n + 1))) + " = " + str(counter)
Sum of numbers from 0 to N
56e9e4f516bcaa8d4f001763
[ "Fundamentals" ]
https://www.codewars.com/kata/56e9e4f516bcaa8d4f001763
7 kyu
The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers: ```haskell maxSequence [-2, 1, -3, 4, -1, 2, 1, -5, 4] -- should be 6: [4, -1, 2, 1] ``` ```javascript maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4]) // should be 6: [4, -1, 2, 1] ``` ```pyth...
reference
def maxSequence(arr): max, curr = 0, 0 for x in arr: curr += x if curr < 0: curr = 0 if curr > max: max = curr return max
Maximum subarray sum
54521e9ec8e60bc4de000d6c
[ "Algorithms", "Lists", "Dynamic Programming", "Fundamentals", "Performance" ]
https://www.codewars.com/kata/54521e9ec8e60bc4de000d6c
5 kyu
*Don't be afraid, the description is rather long but - hopefully - it is in order that the process be well understood*. You are given a string `s` made up of substring `s(1), s(2), ..., s(n)` separated by whitespaces. Example: `"after be arrived two My so"` #### Task Return a string `t` having the following property:...
reference
def arrange(strng): words = strng . split() for i in range(len(words)): words[i: i + 2] = sorted(words[i: i + 2], key=len, reverse=i % 2) words[i] = words[i]. upper() if i % 2 else words[i]. lower() return ' ' . join(words)
up AND down
56cac350145912e68b0006f0
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/56cac350145912e68b0006f0
6 kyu
Congratulations! That Special Someone has given you their phone number. But WAIT, is it a valid number? Your task is to write a function that verifies whether a given string contains a valid British mobile (cell) phone number or not. If valid, return 'In with a chance'. If invalid, or if you're given an empty str...
algorithms
import re yes = "In with a chance" no = "Plenty more fish in the sea" def validate_number(string): return yes if re . match(r'^(\+44|0)7[\d]{9}$', re . sub('-', '', string)) else no
Is that a real phone number? (British version)
581a52d305fe7756720002eb
[ "Regular Expressions", "Strings", "Algorithms" ]
https://www.codewars.com/kata/581a52d305fe7756720002eb
7 kyu
** SHORT INTRO ** "Tombola" is an Italian raffle/bingo-like game, mostly played during Christmas holidays; you have a sheet with 15 numbers and win increasing prizes while you complete it. [Wikipedia link](https://en.wikipedia.org/wiki/Tombola_(raffle). ** SHEET SAMPLES ** <img src="http://i46.servimg.com/u/f46/13/7...
reference
from itertools import chain def checkCols(i, col, sortedCol): return (len(set(col)) != 0 # 1 to 3 numbers (cannot be more if shapeGridOK is True so need only to check not zero) and col == sortedCol # In increasing order # Values in ...
Tombola - validation
5898a751b2edc082f60005f4
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5898a751b2edc082f60005f4
6 kyu
The company you work for has just been awarded a contract to build a payment gateway. In order to help move things along, you have volunteered to create a function that will take a float and return the amount formatting in dollars and cents. `39.99 becomes $39.99` The rest of your team will make sure that the argumen...
algorithms
def format_money(amount): return '${:.2f}' . format(amount)
Dollars and Cents
55902c5eaa8069a5b4000083
[ "Functional Programming", "Strings", "Algorithms" ]
https://www.codewars.com/kata/55902c5eaa8069a5b4000083
8 kyu
Create a function `add(n)`/`Add(n)` which returns a function that always adds n to any number Note for Java: the return type and methods have not been provided to make it a bit more challenging. ```javascript var addOne = add(1); addOne(3); // 4 var addThree = add(3); addThree(3); // 6 ``` ```python add_one = add(1)...
reference
def add(n): return lambda x: x + n
Functional Addition
538835ae443aae6e03000547
[ "Functional Programming", "Fundamentals" ]
https://www.codewars.com/kata/538835ae443aae6e03000547
7 kyu
# Write Number in Expanded Form - Part 2 This is version 2 of my ['Write Number in Exanded Form' Kata](https://www.codewars.com/kata/write-number-in-expanded-form). You will be given a number and you will need to return it as a string in expanded form : ![expanded form illustration](https://cdn-skill.splashmath.com/...
reference
def expanded_form(num): integer_part, fractional_part = str(num). split('.') result = [str(int(num) * (10 * * i)) for i, num in enumerate(integer_part[:: - 1]) if num != '0'][:: - 1] result += [str(num) + '/' + str(10 * * (i + 1)) for i, num in enumerate(fractional_part) if num != '0'] return ' ...
Write Number in Expanded Form - Part 2
58cda88814e65627c5000045
[ "Mathematics", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/58cda88814e65627c5000045
6 kyu
# Write Number in Expanded Form You will be given a number and you will need to return it as a string in [Expanded Form](https://www.mathsisfun.com/definitions/expanded-notation.html). For example: ```haskell expandedForm 12 -- Should return '10 + 2' expandedForm 42 -- Should return '40 + 2' expandedForm 70304 ...
reference
def expanded_form(num): num = list(str(num)) return ' + ' . join(x + '0' * (len(num) - y - 1) for y, x in enumerate(num) if x != '0')
Write Number in Expanded Form
5842df8ccbd22792a4000245
[ "Strings", "Mathematics", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/5842df8ccbd22792a4000245
6 kyu
NOTE: It is recommended you complete [Introduction to Esolangs](https://www.codewars.com/kata/esolang-interpreters-number-1-introduction-to-esolangs-and-my-first-interpreter-ministringfuck/) or [MiniBitFlip](https://www.codewars.com/kata/esolang-minibitflip/) before solving this one. <h3>Task:</h3> Make an interpreter ...
reference
def interpreter(tape): memory, ptr, output = {0: 0}, 0, "" for command in tape: if command == ">": ptr += 1 elif command == "<": ptr -= 1 elif command == "!": memory[len(memory)] = 0 elif command == "*": output += chr(memory . get(ptr, 0) % 256) elif ptr in me...
Esolang: Ticker
5876e24130b45aaa0c00001d
[ "Interpreters", "Strings", "Arrays", "Esoteric Languages" ]
https://www.codewars.com/kata/5876e24130b45aaa0c00001d
5 kyu
Tired of those repetitive javascript challenges? Here's a unique hackish one that should keep you busy for a while ;) There's a mystery function which is already available for you to use. It's a simple function called `mystery`. It accepts a string as a parameter and outputs a string. The exercise depends on guessing ...
games
def solved(s): x = len(s) / / 2 return '' . join(sorted(s[: x] + s[x + (len(s) % 2):]))
Mystery function #1
531963f82dde6fc8c800048a
[ "Puzzles" ]
https://www.codewars.com/kata/531963f82dde6fc8c800048a
5 kyu
# Task You are given an array of integers `arr` that representing coordinates of obstacles situated on a straight line. Assume that you are jumping from the point with coordinate 0 to the right. You are allowed only to make jumps of the same length represented by some integer. Find the minimal length of the jump e...
games
def avoid_obstacles(arr): n = 2 while 1: if all([x % n for x in arr]): return n n += 1
Simple Fun #70: Avoid Obstacles
5894045b8a8a230d0c000077
[ "Puzzles" ]
https://www.codewars.com/kata/5894045b8a8a230d0c000077
6 kyu
We have the numbers with different colours with the sequence: [<span style="color:red">'red'</span>, <span style="color:#EEBB00">'yellow'</span>, <span style="color:DodgerBlue">'blue'</span>]. That sequence colours the numbers in the following way: <span style="color:red"> 1 </span> <span style="color:#EEBB00"> 2 </s...
reference
D, R = {}, [[], [], []] for i in range(10000): D[i] = D . get(i - 1, 0) + i R[D[i] % 3]. append(D[i]) def same_col_seq(val, k, col): r = ['blue', 'red', 'yellow']. index(col) return [e for e in R[r] if e > val][: k]
Working With Coloured Numbers
57f891255cae44b2e10000c5
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic", "Strings", "Recursion", "Dynamic Programming" ]
https://www.codewars.com/kata/57f891255cae44b2e10000c5
5 kyu
# Parse a linked list from a string ## Related Kata Although this Kata is not part of an official Series, you may want to complete [this Kata](https://www.codewars.com/kata/convert-a-linked-list-to-a-string) before attempting this one as these two Kata are deeply related. ## Preloaded Preloaded for you is a class, ...
algorithms
def linked_list_from_string(s): head = None for i in s . split('->')[- 2:: - 1]: head = Node(int(i), head) return head
Parse a linked list from a string
582c5382f000e535100001a7
[ "Linked Lists", "Recursion", "Algorithms" ]
https://www.codewars.com/kata/582c5382f000e535100001a7
6 kyu
Professor Chambouliard hast just discovered a new type of magnet material. He put particles of this material in a box made of small boxes arranged in K rows and N columns as a kind of **2D matrix** `K x N` where `K` and `N` are postive integers. He thinks that his calculations show that the force exerted by the partic...
algorithms
from scipy . special import zeta, zetac def doubles(maxk, maxn): return sum((zetac(2 * k) - zeta(2 * k, 2 + maxn)) / k for k in range(1, maxk + 1))
Magnet particules in boxes
56c04261c3fcf33f2d000534
[ "Mathematics", "Matrix", "Algorithms" ]
https://www.codewars.com/kata/56c04261c3fcf33f2d000534
4 kyu
Teemo is not really excited about the new year's eve, but he has to celebrate it with his friends anyway. <br> <br> He has a really big passion about programming and he wants to be productive till midnight. He wants to know how many minutes he has left to work on his new project.<br> He doesn't want to look on the cloc...
reference
from datetime import datetime, time, timedelta def minutes_to_midnight(d): next_day = datetime . combine(d + timedelta(days=1), time . min) remain = next_day - d minutes = round(remain . seconds / 60) return f' { minutes } minutes'
Minutes to Midnight
58528e9e22555d8d33000163
[ "Date Time", "Fundamentals" ]
https://www.codewars.com/kata/58528e9e22555d8d33000163
6 kyu
Little Annie is very excited for upcoming events. She wants to know how many days she has to wait for a specific event. Your job is to help her out. Task: Write a function which returns the number of days from today till the given date. The function will take a Date object as parameter. You have to round the amount ...
reference
from datetime import datetime as dt def count_days(d): days = round((d - dt . now()). total_seconds() / 86400) return ['Today is the day!', '%d days' % days, 'The day is in the past!'][(days > 0) - (days < 0)]
Count the days!
5837fd7d44ff282acd000157
[ "Date Time", "Fundamentals" ]
https://www.codewars.com/kata/5837fd7d44ff282acd000157
6 kyu
# Can Santa save Christmas? Oh no! Santa's little elves are sick this year. He has to distribute the presents on his own. But he has only 24 hours left. Can he do it? ## Your Task: You will get an array as input with time durations as string in the following format: `HH:MM:SS`. Each duration represents the time tak...
reference
def determine_time(arr): total = 0 for time in arr: h, m, s = map(int, time . split(":")) total += h * 60 * 60 + m * 60 + s return total <= 24 * 60 * 60
Can Santa save Christmas?
5857e8bb9948644aa1000246
[ "Date Time", "Fundamentals" ]
https://www.codewars.com/kata/5857e8bb9948644aa1000246
7 kyu
The student needs to get on a train that leaves from the station `D` kilometres away in `T` minutes. She can get a taxi that drives at `V1` km/h for the price of `R` €/km or she can walk at `V2` km/h for free. A correct solution will be a function that returns the minimum price she needs to pay the taxi driver or the...
games
def calculate_optimal_fare(d, t, taxi, r, walk): h = t / 60.0 if walk * h >= d: return "0.00" if taxi * h < d: return "Won't make it!" return "%.2f" % (r * taxi * (d - walk * h) / (taxi - walk))
Optimal Taxi Fare
52f51502053125863c0009d7
[ "Mathematics", "Algebra", "Puzzles" ]
https://www.codewars.com/kata/52f51502053125863c0009d7
6 kyu
# Task You are given a `moment` in time and space. What you must do is break it down into time and space, to determine if that moment is from the past, present or future. `Time` is the sum of characters that increase time (i.e. numbers in range `['1'..'9']`. `Space` in the number of characters which do not increa...
reference
def moment_of_time_in_space(moment): d = sum(int(c) if c in '123456789' else - 1 for c in moment) return [d < 0, d == 0, d > 0]
Simple Fun #193: Moment Of Time In Space
58c2158ec7df54a39d00015c
[ "Fundamentals" ]
https://www.codewars.com/kata/58c2158ec7df54a39d00015c
7 kyu
Given two numbers and an arithmetic operator (the name of it, as a string), return the result of the two numbers having that operator used on them. ```a``` and ```b``` will both be positive integers, and ```a``` will always be the first number in the operation, and ```b``` always the second. The four operators are ...
reference
def arithmetic(a, b, operator): return { 'add': a + b, 'subtract': a - b, 'multiply': a * b, 'divide': a / b, }[operator]
Make a function that does arithmetic!
583f158ea20cfcbeb400000a
[ "Fundamentals" ]
https://www.codewars.com/kata/583f158ea20cfcbeb400000a
7 kyu
Given: an array containing hashes of names Return: a string formatted as a list of names separated by commas except for the last two names, which should be separated by an ampersand. Example: ``` ruby list([ {name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'} ]) # returns 'Bart, Lisa & Maggie' list([ {name: 'Bart'}, {...
reference
def namelist(names): if len(names) > 1: return '{} & {}' . format(', ' . join(name['name'] for name in names[: - 1]), names[- 1]['name']) elif names: return names[0]['name'] else: return ''
Format a string of names like 'Bart, Lisa & Maggie'.
53368a47e38700bd8300030d
[ "Fundamentals", "Strings", "Data Types", "Formatting", "Algorithms", "Logic" ]
https://www.codewars.com/kata/53368a47e38700bd8300030d
6 kyu
The number six has this interesting property, and is the smallest number in having it (after the integer ```1``` that obviously fulfills this condition): Its cube, is divisible by the sum of its divisors. Let's see it: ``` 6 ^ 3 = 216 divisors of 6: 1, 2, 3, 6 sum of its divisors= 1 + 2 + 3 + 6 = 12 And 216 / 12 = 18 ...
algorithms
# The global variable holding the matching numbers. # It will increase in size as more numbers are found while the program is running continuously. NUMS = [6, 28, 30, 84, 102] 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) ...
Raise Me to The Third Power, Search My Divisors... .....Could You Believe that?
56060ba7b02b967eb1000013
[ "Algorithms", "Mathematics", "Memoization", "Dynamic Programming" ]
https://www.codewars.com/kata/56060ba7b02b967eb1000013
6 kyu
The number 45 is the first integer in having this interesting property: the sum of the number with its reversed is divisible by the difference between them(absolute Value). ``` 45 + 54 = 99 abs(45 - 54) = 9 99 is divisible by 9. ``` The first terms of this special sequence are : ``` n a(n) 1 45 2 54 3 495 4 594 `...
reference
MEMO = [] def sum_dif_rev(n): i = MEMO[- 1] if MEMO else 0 while len(MEMO) < n: i += 1 r = int(str(i)[:: - 1]) if i % 10 and r != i and (i + r) % abs(r - i) == 0: MEMO . append(i) return MEMO[n - 1]
Sum and Rest the Number with its Reversed and See What Happens
5603a9585480c94bd5000073
[ "Fundamentals", "Mathematics", "Algorithms", "Memoization", "Dynamic Programming" ]
https://www.codewars.com/kata/5603a9585480c94bd5000073
5 kyu
The number `12` is the first number in having six divisors, they are: `1, 2, 3, 4, 6 and 12.` Your challenge for this kata is to find the minimum number that has a certain number of divisors. For this purpose we have to create the function `find_min_num() or findMinNum() or similar in the other languages` that recei...
reference
# key - number of divisors: value - the smallest number with the given number of divisors. # 'nr' indicates the number that the search was performed to # When the program is running continuously, the dictionary grows with new values. CACHE = {'nr': 2, 2: 2} def divisors(n): d = {1, n} for k in range(2, int(n ...
Find the First Number in Having a Certain Number of Divisors I
5612ab201830eb000f0000c0
[ "Fundamentals", "Mathematics", "Data Structures", "Dynamic Programming", "Memoization" ]
https://www.codewars.com/kata/5612ab201830eb000f0000c0
6 kyu
You receive some random elements as a space-delimited string. Check if the elements are part of an ascending sequence of integers starting with 1, with an increment of 1 (e.g. 1, 2, 3, 4). Return: * `0` if the elements can form such a sequence, and no number is missing ("not broken", e.g. `"1 2 4 3"`) * `1` if there ...
reference
def find_missing_number(sequence): try: numbers = sorted([int(x) for x in sequence . split()]) for i in range(1, len(numbers) + 1): if i not in numbers: return i except ValueError: return 1 return 0
Broken sequence
5512e5662b34d88e44000060
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5512e5662b34d88e44000060
7 kyu
##Do you know how to write a recursive function? Let's test it! --- * Definition: Recursive function is a function that calls itself during its execution * ``` Classic factorial counting on Javascript function factorial(n) { return n <= 1 ? 1 : n * factorial(n-1) } ``` --- Your objective is to complete a recursiv...
reference
def reverse(str): return "" if not str else str[- 1] + reverse(str[: - 1])
Recursive reverse string
536a9f94021a76ef0f00052f
[ "Fundamentals", "Strings", "Data Types" ]
https://www.codewars.com/kata/536a9f94021a76ef0f00052f
7 kyu
We are interested in collecting the sets of six prime numbers, that having a starting prime p, the following values are also primes forming the sextuplet ```[p, p + 4, p + 6, p + 10, p + 12, p + 16]``` The first sextuplet that we find is ```[7, 11, 13, 17, 19, 23]``` The second one is ```[97, 101, 103, 107, 109, 113]...
reference
def find_primes_sextuplet(limit): for p in [7, 97, 16057, 19417, 43777, 1091257, 1615837, 1954357, 2822707, 2839927, 3243337, 3400207, 6005887]: if p * 6 + 48 > limit: return [p, p + 4, p + 6, p + 10, p + 12, p + 16]
Prime Sextuplets
57bf7fae3b3164dcac000352
[ "Algorithms", "Mathematics", "Sorting", "Data Structures", "Memoization" ]
https://www.codewars.com/kata/57bf7fae3b3164dcac000352
5 kyu
Your task is to generate the Fibonacci sequence to `n` places, with each alternating value as `"skip"`. For example: `"1 skip 2 skip 5 skip 13 skip 34"` Return the result as a string You can presume that `n` is always a positive integer between (and including) 1 and 64.
games
def skiponacci(n): fib = [1, 1][: n] for _ in range(n - 2): fib . append(sum(fib[- 2:])) return " " . join(str(n) if i % 2 else "skip" for i, n in enumerate(fib, 1))
The Skiponacci Sequence
580777ee2e14accd9f000165
[ "Puzzles", "Algorithms" ]
https://www.codewars.com/kata/580777ee2e14accd9f000165
7 kyu
# SpeedCode #2 - Array Madness ## Objective Given two **integer arrays** ```a, b```, both of ```length >= 1```, create a program that returns ```true``` if the **sum of the squares** of each element in ```a``` is **strictly greater than** the **sum of the cubes** of each element in ```b```. E.g. ```c array_madness(3...
games
def array_madness(a, b): return sum(x * * 2 for x in a) > sum(x * * 3 for x in b)
SpeedCode #2 - Array Madness
56ff6a70e1a63ccdfa0001b1
[ "Arrays", "Puzzles" ]
https://www.codewars.com/kata/56ff6a70e1a63ccdfa0001b1
8 kyu
# Task Timed Reading is an educational tool used in many schools to improve and advance reading skills. A young elementary student has just finished his very first timed reading exercise. Unfortunately he's not a very good reader yet, so whenever he encountered a word longer than maxLength, he simply skipped it and re...
games
import re def timed_reading(max_length, text): return sum(len(i) <= max_length for i in re . findall('\w+', text))
Simple Fun #40: Timed Reading
588817db5fb13af14a000020
[ "Puzzles" ]
https://www.codewars.com/kata/588817db5fb13af14a000020
7 kyu
Given a Sudoku data structure with size `NxN, N > 0 and √N == integer`, write a method to validate if it has been filled out correctly. The data structure is a multi-dimensional Array, i.e: ``` [ [7,8,4, 1,5,9, 3,2,6], [5,3,9, 6,7,2, 8,4,1], [6,1,2, 4,3,8, 7,5,9], [9,2,8, 7,1,5, 4,6,3], [3,5,7, ...
games
import math class Sudoku (object): def __init__(self, board): self . board = board def is_valid(self): if not isinstance(self . board, list): return False n = len(self . board) rootN = int(round(math . sqrt(n))) if rootN * rootN != n: return False def isValidRow(...
Validate Sudoku with size `NxN`
540afbe2dc9f615d5e000425
[ "Arrays", "Puzzles", "Algorithms", "Object-oriented Programming" ]
https://www.codewars.com/kata/540afbe2dc9f615d5e000425
4 kyu
There are no explanations. You have to create the code that gives the following results in Python, Ruby, and Haskell: ```javascript one_two_three(0) == [0, 0] one_two_three(1) == [1, 1] one_two_three(2) == [2, 11] one_two_three(3) == [3, 111] one_two_three(19) == [991, 1111111111111111111] ``` And it should give the f...
games
def one_two_three(n): x, y = divmod(n, 9) return [* map(int, ("9" * x + str(y) * (y > 0), "1" * n))] if n else [0] * 2
Begin your day with a challenge, but an easy one.
5873b2010565844b9100026d
[ "Puzzles" ]
https://www.codewars.com/kata/5873b2010565844b9100026d
6 kyu
# Task A rectangle with sides equal to even integers a and b is drawn on the Cartesian plane. Its center (the intersection point of its diagonals) coincides with the point (0, 0), but the sides of the rectangle are not parallel to the axes; instead, they are forming `45 degree` angles with the axes. How many points ...
games
def rectangle_rotation(a, b): a / /= 2 * * 0.5 b / /= 2 * * 0.5 r = (a + 1) * (b + 1) + a * b return r + r % 2 - 1
Simple Fun #27: Rectangle Rotation
5886e082a836a691340000c3
[ "Puzzles" ]
https://www.codewars.com/kata/5886e082a836a691340000c3
4 kyu
Write a function done_or_not/`DoneOrNot` passing a board (list[list_lines]) as parameter. If the board is valid return 'Finished!', otherwise return 'Try again!' Sudoku rules: Complete the Sudoku puzzle so that each and every row, column, and region contains the numbers one through nine only once. Rows: <img src="h...
games
import numpy as np def done_or_not(aboard): # board[i][j] board = np . array(aboard) rows = [board[i, :] for i in range(9)] cols = [board[:, j] for j in range(9)] sqrs = [board[i: i + 3, j: j + 3]. flatten() for i in [0, 3, 6] for j in [0, 3, 6]] for view in np . vstack((...
Did I Finish my Sudoku?
53db96041f1a7d32dc0004d2
[ "Mathematics", "Puzzles", "Games", "Game Solvers" ]
https://www.codewars.com/kata/53db96041f1a7d32dc0004d2
5 kyu
Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition. The binary number returned should be a string. **Examples:(Input1, Input2 --> Output (explanation)))** ``` 1, 1 --> "10" (1 + 1 = 2 in decimal or 10 in binary) 5, 9 --> "1110"...
reference
def add_binary(a, b): return bin(a + b)[2:]
Binary Addition
551f37452ff852b7bd000139
[ "Binary", "Fundamentals" ]
https://www.codewars.com/kata/551f37452ff852b7bd000139
7 kyu
I always thought that my old friend John was rather richer than he looked, but I never knew exactly how much money he actually had. One day (as I was plying him with questions) he said: * "Imagine I have between `m` and `n` Zloty..." (or did he say Quetzal? I can't remember!) * "If I were to buy **9** cars costing `c`...
reference
def howmuch(m, n): return [['M: %d' % i, 'B: %d' % (i / 7), 'C: %d' % (i / 9)] for i in range(min(m, n), max(m, n) + 1) if i % 7 == 2 and i % 9 == 1]
How Much?
55b4d87a3766d9873a0000d4
[ "Fundamentals" ]
https://www.codewars.com/kata/55b4d87a3766d9873a0000d4
6 kyu
---- Sum of Pairs ---- Given a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum. If there are two or more pairs with the required sum, the pair whose second element has the smallest index is the solution. ```python su...
reference
def sum_pairs(lst, s): cache = set() for i in lst: if s - i in cache: return [s - i, i] cache . add(i)
Sum of Pairs
54d81488b981293527000c8f
[ "Memoization", "Fundamentals", "Performance" ]
https://www.codewars.com/kata/54d81488b981293527000c8f
5 kyu
Check to see if a string has the same amount of 'x's and 'o's. The method must return a boolean and be case insensitive. The string can contain any char. Examples input/output: ``` XO("ooxx") => true XO("xooxx") => false XO("ooxXm") => true XO("zpzpzpp") => true // when no 'x' and 'o' is present should return true XO(...
reference
def xo(s): s = s . lower() return s . count('x') == s . count('o')
Exes and Ohs
55908aad6620c066bc00002a
[ "Fundamentals" ]
https://www.codewars.com/kata/55908aad6620c066bc00002a
7 kyu
# Task A little boy is studying arithmetics. He has just learned how to add two integers, written one below another, column by column. But he always forgets about the important part - carrying. Given two integers, find the result which the little boy will get. # Example For param1 = 456 and param2 = 1734, the out...
games
def addition_without_carrying(a, b): r = 0 m = 1 while a + b: r += (a + b) % 10 * m m *= 10 a / /= 10 b / /= 10 return r
Simple Fun #15: Addition without Carrying
588468f3b3d02cf67b0005cd
[ "Puzzles" ]
https://www.codewars.com/kata/588468f3b3d02cf67b0005cd
6 kyu
Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements. For example: ```cpp uniqueInOrder("AAAABBBCCDAABBB") == {'A', 'B', 'C', 'D', 'A', 'B'} uniqueInOrder("ABBCcAD...
reference
def unique_in_order(iterable): result = [] prev = None for char in iterable[0:]: if char != prev: result . append(char) prev = char return result
Unique In Order
54e6533c92449cc251001667
[ "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/54e6533c92449cc251001667
6 kyu
# Task A media access control address (MAC address) is a unique identifier assigned to network interfaces for communications on the physical network segment. The standard (IEEE 802) format for printing MAC-48 addresses in human-friendly form is six groups of two hexadecimal digits (0 to 9 or A to F), separated by hy...
games
import re def is_mac_48_address(address): return bool(re . match("^([0-9A-F]{2}[-]){5}([0-9A-F]{2})$", address . upper()))
Simple Fun #29: Is MAC48 Address?
5886faac54a7111c21000072
[ "Puzzles" ]
https://www.codewars.com/kata/5886faac54a7111c21000072
6 kyu
# MOD 256 without the MOD operator The MOD-operator % (aka mod/modulus/remainder): ``` Returns the remainder of a division operation. The sign of the result is the same as the sign of the first operand. (Different behavior in Python!) ``` The short unbelievable mad story for this kata:<br> I wrote a program and neede...
games
def mod256_without_mod(number): return number & 255
MOD 256 without the MOD operator
581e1d083a4820eb4f00004f
[ "Algorithms", "Fundamentals", "Logic", "Mathematics", "Restricted", "Puzzles" ]
https://www.codewars.com/kata/581e1d083a4820eb4f00004f
7 kyu
<font>You've been going to the gym for some time now and recently you started taking care of your nutrition as well. You want to gain some weight but who wants to bother counting calories every day. It said somewhere that protein is the foundation of building muscle, so let's try to calculate the total amount of calori...
games
import re PATTERN = re . compile(r'(\d+)g (\w+)') CALORIES_PER_100g = {typ: sum( m * cal for m, cal in zip(masses, [4, 4, 9])) for typ, masses in food . items()} def formatAns(n): return str(round(n, 2)) if n % 1 else str(int(n)) def bulk(arr): prots, cals = 0, 0 for plate in arr: for ma...
Bulk up!
5863f1c8b359c4dd4e000001
[ "Puzzles" ]
https://www.codewars.com/kata/5863f1c8b359c4dd4e000001
5 kyu
# Task You have a rectangular white board with some black cells. The black cells create a connected black figure, i.e. it is possible to get from any black cell to any other one through connected adjacent (sharing a common side) black cells. Find the perimeter of the black figure assuming that a single cell has unit...
games
import numpy as np from scipy import signal k = np . array([[0, - 1, 0], [- 1, 4, - 1], [0, - 1, 0]]) def polygon_perimeter(m): return signal . convolve2d(np . array(m, int), k, mode='same'). clip(0). sum()
Simple Fun #85: Polygon Perimeter
58953a5a41c97914d7000070
[ "Puzzles" ]
https://www.codewars.com/kata/58953a5a41c97914d7000070
6 kyu
A new task for you! * You have to create a method, that corrects a given time string. * There was a problem in addition, so many of the time strings are broken. * Time is formatted using the 24-hour clock, so from `00:00:00` to `23:59:59`. ## Examples ``` "09:10:01" -> "09:10:01" "11:70:10" -> "12:10:10" "19:99...
reference
def time_correct(t): if not t: return t try: h, m, s = map(int, t . split(':')) if s >= 60: s -= 60 m += 1 if m >= 60: m -= 60 h += 1 return '%02d:%02d:%02d' % (h % 24, m, s) except: pass
Correct the time-string
57873ab5e55533a2890000c7
[ "Parsing", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/57873ab5e55533a2890000c7
7 kyu
#### Task: Your job here is to implement a method, `approx_root` in Ruby/Python/Crystal and `approxRoot` in JavaScript/CoffeeScript, that takes one argument, `n`, and returns the approximate square root of that number, rounded to the nearest hundredth and computed in the following manner. 1. Start with `n = 213` (as ...
reference
def approx_root(n): base = int(n * * 0.5) return round(base + (n - base * * 2) / ((base + 1) * * 2 - base * * 2), 2)
Square Roots: Approximation
58475cce273e5560f40000fa
[ "Fundamentals" ]
https://www.codewars.com/kata/58475cce273e5560f40000fa
7 kyu
A natural number is called **k-prime** if it has exactly k prime factors, counted with multiplicity. A natural number is thus prime if and only if it is 1-prime. ``` Examples: k = 2 -> 4, 6, 9, 10, 14, 15, 21, 22, … k = 3 -> 8, 12, 18, 20, 27, 28, 30, … k = 5 -> 32, 48, 72, 80, 108, 112, … ``` #### Task: Given an inte...
reference
def primes(n): primefac = [] d = 2 while d * d <= n: while (n % d) == 0: primefac . append(d) n / /= d d += 1 if n > 1: primefac . append(n) return len(primefac) def consec_kprimes(k, arr): return sum(primes(arr[i]) == primes(arr[i + 1]) == k for i in range(...
Consecutive k-Primes
573182c405d14db0da00064e
[ "Fundamentals" ]
https://www.codewars.com/kata/573182c405d14db0da00064e
5 kyu
For this kata, you are given three points ```(x1,y1,z1)```, ```(x2,y2,z2)```, and ```(x3,y3,z3)``` that lie on a straight line in 3-dimensional space. You have to figure out which point lies in between the other two. Your function should return 1, 2, or 3 to indicate which point is the in-between one.
algorithms
def middle_point(x1, y1, z1, x2, y2, z2, x3, y3, z3): return sorted(((x1, y1, z1, 1), (x2, y2, z2, 2), (x3, y3, z3, 3)))[1][3]
Find the in-between point
58a672d6426bf38be4000057
[ "Fundamentals", "Geometry", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/58a672d6426bf38be4000057
6 kyu
#### Task: Your job here is to implement a function `factors`, which takes a number `n`, and outputs an array of arrays comprised of two parts, `sq` and `cb`. The part `sq` will contain all the numbers that, when squared, yield a number which is a factor of `n`, while the `cb` part will contain all the numbers that, w...
reference
def factors(n): sq = [a for a in range(2, n + 1) if not n % (a * * 2)] cb = [b for b in range(2, n + 1) if not n % (b * * 3)] return [sq, cb]
Square and Cubic Factors
582b0d73c190130d550000c6
[ "Fundamentals" ]
https://www.codewars.com/kata/582b0d73c190130d550000c6
7 kyu
### What is simplifying a square root? If you have a number, like 80, for example, you would start by finding the greatest perfect square divisible by 80. In this case, that's 16. Find the square root of 16, and multiply it by 80 / 16. Answer = 4 √5. ##### The above example: ```math \sqrt{80} = \sqrt{5\times 16} ...
reference
def simplify(n): for d in range(int(n * * .5), 0, - 1): if not n % d * * 2: break if d * d == n: return '%d' % d elif d == 1: return 'sqrt %d' % n else: return '%d sqrt %d' % (d, n / / d * * 2) def desimplify(s): x, _, y = s . partition('sqrt') ...
Square Roots: Simplify/Desimplify
5850e85c6e997bddd300005d
[ "Fundamentals" ]
https://www.codewars.com/kata/5850e85c6e997bddd300005d
6 kyu
Say hello! Write a function to greet a person. Function will take name as input and greet the person by saying hello. Return null/nil/None if input is empty string or null/nil/None. Example: ```javascript greet("Niks") === "hello Niks!"; greet("") === null; // Return null if input is empty string greet(null) === nu...
reference
def greet(name): return f"hello { name } !" if name else None
Say hello!
55955a48a4e9c1a77500005a
[ "Fundamentals" ]
https://www.codewars.com/kata/55955a48a4e9c1a77500005a
7 kyu
# Introduction <pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;"> Mastermind or Master Mind is a code-breaking game for two players. The modern game with pegs was invented in 1970 by Mordecai Meirowitz, an Israeli postmaster and telecom...
reference
def mastermind(game): colors = ["Red", "Blue", "Green", "Orange", "Purple", "Yellow"] a = random . sample(colors, 4) return game . check(a)
Mastermind
58a848258a6909dd35000003
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/58a848258a6909dd35000003
5 kyu
In mathematics, a [Diophantine equation](https://en.wikipedia.org/wiki/Diophantine_equation) is a polynomial equation, usually with two or more unknowns, such that only the integer solutions are sought or studied. In this kata we want to find all integers `x, y` (`x >= 0, y >= 0`) solutions of a diophantine equation o...
reference
import math def sol_equa(n): res = [] for i in range(1, int(math . sqrt(n)) + 1): if n % i == 0: j = n / / i if (i + j) % 2 == 0 and (j - i) % 4 == 0: x = (i + j) / / 2 y = (j - i) / / 4 res . append([x, y]) return res
Diophantine Equation
554f76dca89983cc400000bb
[ "Fundamentals", "Mathematics", "Algebra" ]
https://www.codewars.com/kata/554f76dca89983cc400000bb
5 kyu
The prime numbers are not regularly spaced. For example from `2` to `3` the gap is `1`. From `3` to `5` the gap is `2`. From `7` to `11` it is `4`. Between 2 and 50 we have the following pairs of 2-gaps primes: `3-5, 5-7, 11-13, 17-19, 29-31, 41-43` A prime gap of length n is a run of n-1 consecutive composite numbers...
reference
def gap(g, m, n): previous_prime = n for i in range(m, n + 1): if is_prime(i): if i - previous_prime == g: return [previous_prime, i] previous_prime = i return None def is_prime(n): for i in range(2, int(n * * .5 + 1)): if n % i == 0: return False return True ...
Gap in Primes
561e9c843a2ef5a40c0000a4
[ "Fundamentals" ]
https://www.codewars.com/kata/561e9c843a2ef5a40c0000a4
5 kyu
The prime numbers are not regularly spaced. For example from `2` to `3` the step is `1`. From `3` to `5` the step is `2`. From `7` to `11` it is `4`. Between 2 and 50 we have the following pairs of 2-steps primes: `3, 5 - 5, 7, - 11, 13, - 17, 19, - 29, 31, - 41, 43` We will write a function `step` with parameters: ...
reference
import math def isPrime(n): if n <= 1: return False for i in range(2, int(math . sqrt(n) + 1)): if n % i == 0: return False return True def step(g, m, n): if m >= n: return [] else: for i in range(m, n + 1 - g): if isPrime(i) and isPrime(i + g): retu...
Steps in Primes
5613d06cee1e7da6d5000055
[ "Mathematics", "Number Theory" ]
https://www.codewars.com/kata/5613d06cee1e7da6d5000055
6 kyu
# Allergies Write a program that, given a person's allergy score, can tell them whether or not they're allergic to a given item, and their full list of allergies. An allergy test produces a single numeric score which contains the information about all the allergies the person has (that they were tested for). The lis...
games
class Allergies (object): ALLERGY_SCORES = { 'eggs': 1, 'peanuts': 2, 'shellfish': 4, 'strawberries': 8, 'tomatoes': 16, 'chocolate': 32, 'pollen': 64, 'cats': 128 } def __init__(self, score): self . allergicTo = sorted( ...
Tom's Allergies
58be35e9e36224a33f000023
[ "Algorithms", "Puzzles", "Fundamentals" ]
https://www.codewars.com/kata/58be35e9e36224a33f000023
6 kyu
Implement [the Geohashing algorithm](https://xkcd.com/426/) proposed by xkcd. ![the Geohashing algorithm](https://imgs.xkcd.com/comics/geohashing.png) Specifically, given the the Dow opening and a date in date object (optional), return the geohashing coordinates, using the following steps (adapted from [explainxkcd](...
reference
from datetime import datetime import hashlib def geohash(dow, date=datetime . utcnow()): dow = "%.2f" % dow s = str(date)[: 10] + "-" + str(dow) m = hashlib . md5(s . encode('utf-8')). hexdigest() m1, m2 = float . fromhex('0.' + m[: 16]), float . fromhex('0.' + m[- 16:]) return [round(m1,...
Geohashing
58ca7afc92ce34dfa50001fa
[ "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/58ca7afc92ce34dfa50001fa
5 kyu
# Task You are given an array of up to four non-negative integers, each less than 256. Your task is to pack these integers into one number M in the following way: ``` The first element of the array occupies the first 8 bits of M; The second element occupies next 8 bits, and so on. ``` Return the obtained integer M a...
games
def array_packing(arr): return int . from_bytes(arr, 'little')
Simple Fun #9: Array Packing
588453ea56daa4af920000ca
[ "Puzzles" ]
https://www.codewars.com/kata/588453ea56daa4af920000ca
7 kyu
Complete the function that takes two numbers as input, ```num``` and ```nth``` and return the `nth` digit of `num` (counting from right to left). ## Note - If ```num``` is negative, ignore its sign and treat it as a positive value - If ```nth``` is not positive, return `-1` - Keep in mind that `42 = 00042`. This means...
reference
def find_digit(num, nth): if nth <= 0: return - 1 try: return int(str(num). lstrip('-')[- nth]) except IndexError: return 0
Find the nth Digit of a Number
577b9960df78c19bca00007e
[ "Fundamentals" ]
https://www.codewars.com/kata/577b9960df78c19bca00007e
7 kyu
Create a function that takes a Number as its argument and returns a Chinese numeral string. You don't need to validate the input argument, it will always be a Number in the range `[-99999.999, 99999.999]`, rounded to 8 decimal places. Simplified Chinese numerals have characters representing each number from 0 to 9 and...
algorithms
import re NEG, DOT, _, * DIGS = "负点 零一二三四五六七八九" POWS = " 十 百 千 万" . split(' ') NUMS = {str(i): c for i, c in enumerate(DIGS)} for n in range(10): NUMS[str(n + 10)] = POWS[1] + DIGS[n] * bool(n) def to_chinese_numeral(n): ss = str(abs(n)). split('.') return NEG * (n < 0) + parse (ss [...
Chinese Numeral Encoder
52608f5345d4a19bed000b31
[ "Algorithms" ]
https://www.codewars.com/kata/52608f5345d4a19bed000b31
4 kyu
## Description: Remove all exclamation marks from sentence but ensure a exclamation mark at the end of string. For a beginner kata, you can assume that the input data is always a non empty string, no need to verify it. ## Examples ``` "Hi!" ---> "Hi!" "Hi!!!" ---> "Hi!" "!Hi" ---> "Hi!" "!Hi!" ---> "Hi!...
reference
def remove(s): return s . replace("!", "") + "!"
Exclamation marks series #4: Remove all exclamation marks from sentence but ensure a exclamation mark at the end of string
57faf12b21c84b5ba30001b0
[ "Fundamentals" ]
https://www.codewars.com/kata/57faf12b21c84b5ba30001b0
8 kyu
### The problem How many zeroes are at the **end** of the [factorial](https://en.wikipedia.org/wiki/Factorial) of `10`? 10! = 36288<u>00</u>, i.e. there are `2` zeroes. 16! (or 0x10!) in [hexadecimal](https://en.wikipedia.org/wiki/Hexadecimal) would be 0x130777758<u>000</u>, which has `3` zeroes. ### Scalability Unf...
algorithms
PRIMES = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251] def find_multiplicity(n, p): m = 0 ...
Factorial tail
55c4eb777e07c13528000021
[ "Algorithms" ]
https://www.codewars.com/kata/55c4eb777e07c13528000021
4 kyu
Write a program to determine if a string contains only unique characters. Return true if it does and false otherwise. The string may contain any of the 128 ASCII characters. Characters are case-sensitive, e.g. 'a' and 'A' are considered different characters.
algorithms
def has_unique_chars(s): return len(s) == len(set(s))
All unique
553e8b195b853c6db4000048
[ "Algorithms", "Strings" ]
https://www.codewars.com/kata/553e8b195b853c6db4000048
7 kyu
Complete the function that receives as input a string, and produces outputs according to the following table: | Input | Output | ---- | ------ | "Jabroni" | "Patron Tequila" | "School Counselor" | "Anything with Alcohol" | "Programmer" | "Hipster Craft Beer" | "Bike Gang Member" | "Moonshine" | "Politician" | "Your t...
reference
d = { "jabroni": "Patron Tequila", "school counselor": "Anything with Alcohol", "programmer": "Hipster Craft Beer", "bike gang member": "Moonshine", "politician": "Your tax dollars", "rapper": "Cristal" } def get_drink_by_profession(s): return d . get(s . lower(), "Beer")
L1: Bartender, drinks!
568dc014440f03b13900001d
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/568dc014440f03b13900001d
8 kyu
# Safen User Input Part I - htmlspecialchars You are a(n) novice/average/experienced/professional/world-famous Web Developer (choose one) who owns a(n) simple/clean/slick/beautiful/complicated/professional/business website (choose one or more) which contains form fields so visitors can send emails or leave a comment o...
reference
def html_special_chars(data): symbols = {'<': '&lt;', '>': '&gt;', '"': '&quot;', '&': '&amp;'} return "" . join(symbols . get(x, x) for x in data)
Safen User Input Part I - htmlspecialchars
56bcaedfcf6b7f2125001118
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/56bcaedfcf6b7f2125001118
8 kyu
Time to test your basic knowledge in functions! Return the odds from a list: ``` [1, 2, 3, 4, 5] --> [1, 3, 5] [2, 4, 6] --> [] ```
reference
def odds(values): return [i for i in values if i % 2]
Are arrow functions odd?
559f80b87fa8512e3e0000f5
[ "Fundamentals" ]
https://www.codewars.com/kata/559f80b87fa8512e3e0000f5
8 kyu
Hi and welcome to team Gilded Rose. You are asked to fix the code for our store management system. All items have a `sell_in` value which denotes the number of days we have left to sell the item and a `quality` value which denotes how valuable the item is. (For Java specifics see ** Java Notes ** below) At the end o...
bug_fixes
def update_quality(items): for i in items: name = i . name . lower() if "sulfuras" in name: continue i . sell_in -= 1 if "aged brie" in name: deg = 1 elif "backstage passes" in name: deg = 1 if i . sell_in > 10 else 2 if i . sell_in > 5 else 3 if i . sell_in >= 0 else - i . ...
Shop Inventory Manager
55d1d06def244b18c100007c
[ "Debugging" ]
https://www.codewars.com/kata/55d1d06def244b18c100007c
6 kyu
<h3>Algorithmic predicament - Bug Fixing #9</h3> <p> Oh no! Timmy's algorithm has gone wrong! Help Timmy fix his algorithm! </p> <h2>Task</h2> <p> Your task is to fix Timmy's algorithm so it returns the group name with the highest total age. </p> <p> You will receive two groups of `people` objects, with ...
algorithms
def highest_age(g1, g2): d = {} for p in g1 + g2: name, age = p["name"], p["age"] d[name] = d . setdefault(name, 0) + age return max(sorted(d . keys()), key=d . __getitem__)
Algorithmic predicament- Bug Fixing #9
55d3b1f2c1b2f0d3470000a9
[ "Debugging", "Algorithms" ]
https://www.codewars.com/kata/55d3b1f2c1b2f0d3470000a9
7 kyu
In this example you have to validate if a user input string is alphanumeric. The given string is not `nil/null/NULL/None`, so you don't have to check that. The string has the following conditions to be alphanumeric: * At least one character (`""` is not valid) * Allowed characters are uppercase / lowercase latin lett...
bug_fixes
def alphanumeric(string): return string . isalnum()
Not very secure
526dbd6c8c0eb53254000110
[ "Regular Expressions", "Strings" ]
https://www.codewars.com/kata/526dbd6c8c0eb53254000110
5 kyu