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
# Task Two teams are playing a game of tennis. The team sizes are the same and each player from the first team plays against the corresponding player from the second team. ![](http://i.imgur.com/YB1dsAm.jpg) Each player has a certain power level. If a player has a higher power level than her opponent, she is guara...
reference
def maximize_points(team1, team2): team1 . sort() team2 . sort() ans = 0 for p2 in team2[:: - 1]: if p2 < max(team1): team1 . remove(max(team1)) ans += 1 return ans
Simple Fun #210: Maximize Points
58fec262184b6dc30800000d
[ "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/58fec262184b6dc30800000d
6 kyu
In this Kata you have to find the factors of <code>integer</code> down to the <code>limit</code> including the limiting number. There will be no negative numbers. Return the result as an array of numbers in ascending order. If the <code>limit</code> is more than the <code>integer</code>, return an empty list As a ch...
reference
def factors(integer, limit): return [x for x in range(limit, integer + 1) if integer % x == 0]
Find Factors Down to Limit
58f6024e1e26ec376900004f
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/58f6024e1e26ec376900004f
7 kyu
# Task You are given a decimal number `n` as a **string**. Transform it into an array of numbers (given as **strings** again), such that each number has only one nonzero digit and their sum equals n. Each number in the output array should be written without any leading and trailing zeros. # Input/Output - `[inpu...
algorithms
def split_exp(n): dot = n . find('.') if dot == - 1: dot = len(n) return [d + "0" * (dot - i - 1) if i < dot else ".{}{}" . format("0" * (i - dot - 1), d) for i, d in enumerate(n) if i != dot and d != '0']
Simple Fun #205: Split Exp
58fd9f6213b00172ce0000c9
[ "Algorithms" ]
https://www.codewars.com/kata/58fd9f6213b00172ce0000c9
7 kyu
# Task You are given three integers `l, d and x`. Your task is: ``` • determine the minimal integer n such that l ≤ n ≤ d, and the sum of its digits equals x. • determine the maximal integer m such that l ≤ m ≤ d, and the sum of its digits equals x. ``` It is guaranteed that such numbers always exist. # Inp...
reference
def min_and_max(l, d, x): for n in range(l, d + 1): if sum(map(int, str(n))) == x: break for m in range(d, l - 1, - 1): if sum(map(int, str(m))) == x: break return [n, m]
Simple Fun #202: Min And Max
58fd52b59a9f65c398000096
[ "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/58fd52b59a9f65c398000096
7 kyu
# Task You're given a two-dimensional array of integers `matrix`. Your task is to determine the smallest non-negative integer that is not present in this array. # Input/Output - `[input]` 2D integer array `matrix` A non-empty rectangular matrix. `1 ≤ matrix.length ≤ 10` `1 ≤ matrix[0].length ≤ 10` - `[o...
reference
def smallest_integer(matrix): nums = set(sum(matrix, [])) n = 0 while n in nums: n += 1 return n
Simple Fun #204: Smallest Integer
58fd96a59a9f65c2e900008d
[ "Fundamentals" ]
https://www.codewars.com/kata/58fd96a59a9f65c2e900008d
7 kyu
# Task Mirko has been moving up in the world of basketball. He started as a mere spectator, but has already reached the coveted position of the national team coach! Mirco is now facing a difficult task: selecting five primary players for the upcoming match against Tajikistan. Since Mirko is incredibly lazy, he doesn...
reference
from collections import Counter def strange_coach(players): return '' . join( sorted(i for i, j in Counter(map(lambda x: x[0], players)). most_common() if j >= 5)) or 'forfeit'
Simple Fun #203: Strange Coach
58fd91af13b0012e8e000010
[ "Fundamentals" ]
https://www.codewars.com/kata/58fd91af13b0012e8e000010
7 kyu
### Help Kiyo きよ solve her problems LCM Fun! Kiyo has been given a series of problems and she needs your help to solve them! You will be given a two-dimensional array such as the one below. ``` a = [ [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7...
reference
from math import lcm def kiyo_lcm(a): return lcm(* (sum(v for v in r if isinstance(v, int) and v % 2) for r in a))
Help Kiyo きよ solve her problems LCM Fun!
5872bb7faa04282110000124
[ "Algorithms", "Data Structures", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5872bb7faa04282110000124
6 kyu
Create a program that will take in a string as input and, if there are duplicates of more than two alphabetical characters in the string, returns the string with all the extra characters in a bracket. For example, the input "aaaabbcdefffffffg" should return "aa[aa]bbcdeff[fffff]g" Please also ensure that the input ...
algorithms
import re def string_parse(string): return re . sub(r'(.)\1(\1+)', r'\1\1[\2]', string) if isinstance(string, str) else 'Please enter a valid string'
Bracket Duplicates
5411c4205f3a7fd3f90009ea
[ "Strings", "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/5411c4205f3a7fd3f90009ea
6 kyu
No Story No Description Only by Thinking and Testing Look at result of testcase, guess the code! # #Series:<br> <a href="http://www.codewars.com/kata/56d904db9963e9cf5000037d">01:A and B?</a><br> <a href="http://www.codewars.com/kata/56d9292cc11bcc3629000533">02:Incomplete string</a><br> <a href="http://www.c...
games
def testit(stg): try: return eval("" . join(str(ord(c) - 96) if i % 2 == 0 else "+-*/" [(ord(c) - 1) % 4] for i, c in enumerate(stg))) except SyntaxError: return
Thinking & Testing : Operator hidden in a string
56e1161fef93568228000aad
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/56e1161fef93568228000aad
6 kyu
## Background - the Collatz Conjecture: Imagine you are given a positive integer, `n`, then: * if `n` is even, calculate: `n / 2` * if `n` is odd, calculate: `3 * n + 1` Repeat until your answer is `1`. The Collatz conjecture states that performing this operation repeatedly, you will always eventually reach `1`. Yo...
reference
def collatz_length(nm): cntr = 0 while nm != 1: nm = 3 * nm + 1 if nm % 2 else nm / / 2 cntr += 1 return cntr def longest_collatz(input_array): return max(input_array, key=collatz_length)
Integer with the longest Collatz sequence
57acc8c3e298a7ae4e0007e3
[ "Algorithms", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/57acc8c3e298a7ae4e0007e3
6 kyu
## Preface A collatz sequence, starting with a positive integer<i>n</i>, is found by repeatedly applying the following function to <i>n</i> until <i>n</i> == 1 : `$f(n) = \begin{cases} n/2, \text{ if $n$ is even} \\ 3n+1, \text{ if $n$ is odd} \end{cases}$` ---- A more detailed description of the collatz conjec...
algorithms
def collatz_step(n): if n % 2 == 0: return n / / 2 else: return n * 3 + 1 def collatz_seq(n): while n != 1: yield n n = collatz_step(n) yield 1 def collatz(n): return '->' . join(str(x) for x in collatz_seq(n))
Collatz
5286b2e162056fd0cb000c20
[ "Number Theory", "Algorithms" ]
https://www.codewars.com/kata/5286b2e162056fd0cb000c20
6 kyu
Write a generator `sequence_gen` ( `sequenceGen` in JavaScript) that, given the first terms of a sequence will generate a (potentially) infinite amount of terms, where each subsequent term is the sum of the previous `x` terms where `x` is the amount of initial arguments (examples of such sequences are the Fibonacci, Tr...
reference
def sequence_gen(* args): values = list(args) while True: yield values[0] values = values[1:] + [sum(values)]
Sequence generator
55eee789637477c94200008e
[ "Fundamentals" ]
https://www.codewars.com/kata/55eee789637477c94200008e
6 kyu
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said # Description: Given two array of integers(`arr1`,`arr2`). Your task is going to find a pair of numbers(an element in arr1, and another element in arr2), their difference...
reference
def max_and_min(arr1, arr2): diffs = [abs(x - y) for x in arr1 for y in arr2] return [max(diffs), min(diffs)]
The maximum and minimum difference -- Simple version
583c5469977933319f000403
[ "Fundamentals" ]
https://www.codewars.com/kata/583c5469977933319f000403
6 kyu
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said # Description: Given two array of integers(`arr1`,`arr2`). Your task is going to find a pair of numbers(an element in arr1, and another element in arr2), their difference...
algorithms
def max_and_min(seq1, seq2): # your code here seq1 . sort() seq2 . sort() if abs(seq1[- 1] - seq2[0]) > abs(seq1[0] - seq2[- 1]): max_difference = abs(seq1[- 1] - seq2[0]) else: max_difference = abs(seq1[0] - seq2[- 1]) i, j = 0, 0 while i < len(seq1) and j < len(seq2): ...
The maximum and minimum difference -- Challenge version
583c592928a0c0449d000099
[ "Algorithms" ]
https://www.codewars.com/kata/583c592928a0c0449d000099
5 kyu
<b><a href="https://en.wikipedia.org/wiki/Hofstadter_sequence">Hofstadter sequences</a></b> are a family of related integer sequences, among which the first ones were described by an American professor <a href="https://en.wikipedia.org/wiki/Douglas_Hofstadter">Douglas Hofstadter</a> in his book <a href="https://en.wiki...
algorithms
def hofstadter_Q(n): try: return hofstadter_Q . seq[n] except IndexError: ans = hofstadter_Q(n - hofstadter_Q(n - 1)) + \ hofstadter_Q(n - hofstadter_Q(n - 2)) hofstadter_Q . seq . append(ans) return ans hofstadter_Q . seq = [None, 1, 1]
Hofstadter Q
5897cdc26551af891c000124
[ "Recursion", "Algorithms" ]
https://www.codewars.com/kata/5897cdc26551af891c000124
6 kyu
# Task Miss X has only two combs in her possession, both of which are old and miss a tooth or two. She also has many purses of different length, in which she carries the combs. The only way they fit is horizontally and without overlapping. Given teeth' positions on both combs, find the minimum length of the purse she ...
games
def combs(a, b): return min(mesh(a, b), mesh(b, a)) def mesh(a, b): for i in range(len(a)): for j, k in zip(a[i:], b): if j + k == '**': break else: return max(i + len(b), len(a)) return len(a) + len(b)
Simple Fun #53: Combs
58898b50b832f8046a0000ec
[ "Puzzles" ]
https://www.codewars.com/kata/58898b50b832f8046a0000ec
5 kyu
## Task Pac-Man got lucky today! Due to minor performance issue all his enemies have frozen. Too bad Pac-Man is not brave enough to face them right now, so he doesn't want any enemy to see him. Given a gamefield of size `N` x `N`, Pac-Man's position(`PM`) and his enemies' positions(`enemies`), your task is to coun...
algorithms
def pac_man(size, pacman, enemies): px, py = pacman mx, my, Mx, My = - 1, - 1, size, size for x, y in enemies: if x < px and x > mx: mx = x if y < py and y > my: my = y if x > px and x < Mx: Mx = x if y > py and y < My: My = y return (Mx - mx - 1) * (My - ...
Simple Fun #155: Pac-Man
58ad0e0a154165a1c80000ea
[ "Algorithms", "Puzzles" ]
https://www.codewars.com/kata/58ad0e0a154165a1c80000ea
5 kyu
## Task Compute the [Mobius function](https://en.wikipedia.org/wiki/M%C3%B6bius_function) `$\mu (n)$` for a given value of `n`. For a given `n`, the Mobius function is equal to: - `0` if `n` is divisible by the square of any prime number. For example `n` = `4, 8, 9` are all divisible by the square of at least one...
games
def mobius(n): sP, p = set(), 2 while n > 1 and p <= n * * .5: while not n % p: if p in sP: return 0 sP . add(p) n / /= p p += 1 + (p != 2) return (- 1) * * ((len(sP) + (n != 1)) % 2)
Simple Fun #142: Mobius function
58aa5d32c9eb04d90b000107
[ "Puzzles" ]
https://www.codewars.com/kata/58aa5d32c9eb04d90b000107
6 kyu
## The story you are about to hear is true Our cat, <a href="https://www.flickr.com/photos/tachyon/tags/balor/">Balor</a>, sadly died of cancer in 2015. While he was alive, the three neighborhood cats <a href="https://www.flickr.com/photos/tachyon/tags/lou/">Lou</a>, <a href="https://www.flickr.com/photos/tachyon/tags...
reference
from itertools import combinations from math import hypot def peaceful_yard(yard, d): cats = ((i, j) for i, r in enumerate(yard) for j, c in enumerate(r) if c in 'LMR') return all(hypot(q[0] - p[0], q[1] - p[1]) >= d for p, q in combinations(cats, 2))
Cat Kata, Part 1
5869848f2d52095be20001d1
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5869848f2d52095be20001d1
6 kyu
You are asked to write a simple cypher that rotates every character (in range [a-zA-Z], special chars will be ignored by the cipher) by 13 chars. As an addition to the original ROT13 cipher, this cypher will also cypher numerical digits ([0-9]) with 5 chars. Example: "The quick brown fox jumps over the 2 lazy dog...
algorithms
trans = "abcdefghijklmnopqrstuvwxyz" * 2 trans += trans . upper() + "0123456789" * 2 def ROT135(input): output = [] for c in input: if c . isalpha(): c = trans[trans . index(c) + 13] elif c . isdigit(): c = trans[trans . index(c) + 5] output . append(c) return "" . join(out...
Simple ROT13.5 cypher
5894986e2ddc8f6805000036
[ "Algorithms", "Fundamentals", "Ciphers", "Cryptography" ]
https://www.codewars.com/kata/5894986e2ddc8f6805000036
6 kyu
# Task Consider a sequence of numbers a<sub>0</sub>, a<sub>1</sub>, ..., a<sub>n</sub>, in which an element is equal to the sum of squared digits of the previous element. The sequence ends once an element that has already been in the sequence appears again. Given the first element `a0`, find the length of the sequen...
games
def square_digits_sequence(n): a, seq = n, set() while a not in seq: seq . add(a) a = sum(int(d) * * 2 for d in str(a)) return len(seq) + 1
Simple Fun #23: Square Digits Sequence
5886d65e427c27afeb0000c1
[ "Puzzles" ]
https://www.codewars.com/kata/5886d65e427c27afeb0000c1
6 kyu
# Task You've intercepted an encrypted message, and you are really curious about its contents. You were able to find out that the message initially contained only lowercase English letters, and was encrypted with the following cipher: Let all letters from 'a' to 'z' correspond to the numbers from 0 to 25, respective...
games
from itertools import pairwise, chain def cipher26(message): return '' . join(chr((y - x) % 26 + 97) for x, y in pairwise(chain([97], map(ord, message))))
Simple Fun #46: Cipher26
588847702ffea657ba00001b
[ "Puzzles" ]
https://www.codewars.com/kata/588847702ffea657ba00001b
6 kyu
# Task Suppose there are `n` people standing in a circle and they are numbered 1 through n in order. Person 1 starts off with a sword and kills person 2. He then passes the sword to the next person still standing, in this case person 3. Person 3 then uses the sword to kill person 4, and passes it to person 5. This...
games
def circle_slash(n): return int(bin(n)[3:] + '1', 2)
Simple Fun #140: Circle Slash
58a6ac309b5762b7aa000030
[ "Puzzles" ]
https://www.codewars.com/kata/58a6ac309b5762b7aa000030
6 kyu
Your task is to find all the elements of an array that are non consecutive. A number is non consecutive if it is not exactly one larger than the previous element in the array. The first element gets a pass and is never considered non consecutive. ~~~if:javascript,haskell,swift Create a function named `allNonConsecuti...
reference
def all_non_consecutive(a): return [{"i": i, "n": y} for i, (x, y) in enumerate(zip(a, a[1:]), 1) if x != y - 1]
Find all non-consecutive numbers
58f8b35fda19c0c79400020f
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/58f8b35fda19c0c79400020f
7 kyu
Your task in this Kata is to emulate text justify right in monospace font. You will be given a single-lined text and the expected justification width. The longest word will never be greater than this width. Here are the rules: - Use spaces to fill in the gaps on the left side of the words. - Each line should contain ...
algorithms
import textwrap def align_right(text, width): return "\n" . join([l . rjust(width, ' ') for l in textwrap . wrap(text, width)])
Text align right
583601518d3b9b8d3b0000c9
[ "Algorithms", "Strings" ]
https://www.codewars.com/kata/583601518d3b9b8d3b0000c9
6 kyu
# Task Given a sorted array of integers `A`, find such an integer x that the value of `abs(A[0] - x) + abs(A[1] - x) + ... + abs(A[A.length - 1] - x)` is the smallest possible (here abs denotes the `absolute value`). If there are several possible answers, output the smallest one. # Example For `A = [2, 4, 7]`, th...
games
from statistics import median_low as absolute_values_sum_minimization
Simple Fun #72: Absolute Values Sum Minimization
589414918afa367b4800015c
[ "Puzzles" ]
https://www.codewars.com/kata/589414918afa367b4800015c
6 kyu
#Detail [Countdown](https://en.wikipedia.org/wiki/Countdown_(game_show) is a British game show with number and word puzzles. The letters round consists of the contestant picking 9 shuffled letters - either picking from the vowel pile or the consonant pile. The contestants are given 30 seconds to try to come up with th...
reference
def longest_word(letters): unscrambled = [] for word in words: if set(word). issubset(set(letters)) and all(word . count(l) <= letters . count(l) for l in set(letters)): unscrambled . append(word) return [x for x in unscrambled if len(x) == max(map(len, unscrambled))] or None
Countdown - Longest Word
57a4c85de298a795210002da
[ "Strings", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/57a4c85de298a795210002da
6 kyu
This is the simple version of Shortest Code series. If you need some challenges, please try the [challenge version](http://www.codewars.com/kata/56ffd817140fcc0c3900099b) ## Task Your apple has a virus, and the infection is spreading. The ```apple``` is a two-dimensional array, containing strings ```"V"``` (virus) a...
games
def infect_apple(apple, n): A = {(r, c): v for r, row in enumerate(apple) for c, v in enumerate(row)} for _ in range(n): for n in {(r, c) for r, c in A if any(A . get((r + rr, c + cc), '') == 'V' for rr, cc in [(1, 0), (- 1, 0), (0, 1), (0, - 1)])}: A[n] = 'V' return [[A[(r, c)] for c in rang...
Coding 3min: Virus in Apple
5700af83d1acef83fd000048
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/5700af83d1acef83fd000048
6 kyu
Let's do a simple approximation of the integral of a continuous function. In this kata, we will implement: *left_riemann(f, n, a, b)* In the test, we will pass a function that takes a single float argument to compute the value of the function. Your job is to approximate the integral of that function on the closed i...
reference
def left_riemann(f, n: int, a: float, b: float) - > float: dx = (b - a) / n return dx * sum(f(a + i * dx) for i in range(n))
riemann sums I (left side rule)
5562ab5d6dca8009f7000050
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5562ab5d6dca8009f7000050
6 kyu
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said # Description: Give you two number `m`(a positive integer with 5 digits) and `n`(a positive odd integer >= 3), make a `n*n` matrix pattern using the digits of `m`: ``` ...
games
def make_matrix(m: int, n: int) - > str: m = str(m) matrix = [] for i in range(n): st = [] for j in range(n): if i == j or i + j == n - 1: st . append(m[0]) elif i + j > n - 1 and i > j: st . append(m[2]) elif i + j < n - 1 and i > j: # ok st . append(m[3]) ...
Complete the matrix pattern
582c01ad3fd1cc5736000348
[ "Puzzles", "Algorithms", "Matrix" ]
https://www.codewars.com/kata/582c01ad3fd1cc5736000348
6 kyu
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said # Description: Give you two number `rows` , `columns` and a string `str`. Returns a `rows x columns` table pattern and fill in the `str`(each grid fill in a char, the len...
games
def pattern(rows, cols, s): txt, border, row = iter(s), '+' + '---+' * cols, '|' + ' {} |' * cols def linerAndSep( _): return f" { row . format ( * ( next ( txt , ' ' ) for _ in range ( cols )) ) } \n { border } " return f' { border } \n' + '\n' . join(map(linerAndSep, range(rows)))
Complete the table pattern
5827e2efc983ca6f230000e0
[ "ASCII Art", "Puzzles" ]
https://www.codewars.com/kata/5827e2efc983ca6f230000e0
6 kyu
Figure out and complete the very pointless function. [THIS KATA HAS BEEN RETIRED. I WOULD DELETE IT BUT IT SEEMS ONLY ADMIN CAN DO IT.]
games
def pointless(* args): return "rickastley"
What is the point? [THIS KATA HAS BEEN RETIRED. ATTEMPT AT OWN PERIL]
55ed10a402a0c6e3c3000021
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/55ed10a402a0c6e3c3000021
6 kyu
Given an array, return the reversed version of the array (a different kind of reverse though), you reverse portions of the array, you'll be given a length argument which represents the length of each portion you are to reverse. E.g ```javascript selReverse([1,2,3,4,5,6], 2) //=> [2,1, 4,3, 6,5] ``` if after reve...
algorithms
def sel_reverse(arr, l): return [elt for i in range(0, len(arr), l) for elt in arr[i: i + l][:: - 1]] if l != 0 else arr
Selective Array Reversing
58f6000bc0ec6451960000fd
[ "Algorithms", "Logic", "Arrays" ]
https://www.codewars.com/kata/58f6000bc0ec6451960000fd
6 kyu
In programming you know the use of the logical negation operator (**!**), it reverses the meaning of a condition. ```javascript !false = true !!false = false ``` Your task is to complete the function 'negationValue()' that takes a string of negations with a value and returns what the value would be if those negations...
reference
def negation_value(s, x): return len(s) % 2 ^ bool(x)
Negation of a Value
58f6f87a55d759439b000073
[ "Logic", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/58f6f87a55d759439b000073
7 kyu
Kontti language is a finnish word play game. You add `-kontti` to the end of each word and then swap their characters until and including the first vowel ("aeiouy"); For example the word `tame` becomes `kome-tantti`; `fruity` becomes `koity-fruntti` and so on. If no vowel is present, the word stays the same. Write...
reference
import re def kontti(s): return " " . join([re . sub("([^aeiouy]*[aeiouy])(.*)", r"ko\2-\1ntti", w, flags=re . I) for w in s . split()])
Kontti Language
570e1271e5c9a0cf2f000d11
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/570e1271e5c9a0cf2f000d11
6 kyu
# Task A lock has `n` buttons in it, numbered from `1 to n`. To open the lock, you have to press all buttons in some order, i.e. a key to the lock is a permutation of the first `n` integers. If you push the right button in the right order, it will be pressed into the lock. Otherwise all pressed buttons will pop out. W...
games
def press_button(n): return (n * n + 5) * n / 6
Simple Fun #169: Press Button
58b3bb9347117f4aa7000096
[ "Puzzles" ]
https://www.codewars.com/kata/58b3bb9347117f4aa7000096
6 kyu
Our AAA company is in need of some software to help with logistics: you will be given the width and height of a map, a list of x coordinates and a list of y coordinates of the supply points, starting to count from the top left corner of the map as 0. Your goal is to return a two dimensional array/list with every item ...
algorithms
def manhattan_dist(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2) def logistic_map(width, height, xs, ys): field = [[None] * width for _ in range(height)] if xs and ys: for row in range(height): for col in range(width): field[row][col] = min(manhattan_dist(col, row, xi, yi) ...
Logistic Map
5779624bae28070489000146
[ "Graph Theory", "Matrix", "Arrays", "Lists", "Algorithms" ]
https://www.codewars.com/kata/5779624bae28070489000146
6 kyu
MongoDB is a noSQL database which uses the concept of a document, rather than a table as in SQL. Its popularity is growing. As in any database, you can create, read, update, and delete elements. But in constrast to SQL, when you create an element, a new field `_id` is created. This field is unique and contains some in...
reference
from datetime import datetime import re class Mongo (object): @ classmethod def is_valid(cls, s): return isinstance(s, str) and bool(re . match(r'[0-9a-f]{24}$', s)) @ classmethod def get_timestamp(cls, s): return cls . is_valid(s) and datetime . fromtimestamp(int(s[: 8], 16))
Mongodb ObjectID
52fefe6cb0091856db00030e
[ "MongoDB", "Regular Expressions", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/52fefe6cb0091856db00030e
5 kyu
Primes that have only odd digits are pure odd digits primes, obvious but necessary definition. Examples of pure odd digit primes are: 11, 13, 17, 19, 31... If a prime has only one even digit does not belong to pure odd digits prime, no matter the amount of odd digits that may have. Create a function, only_oddDigPrime...
reference
from bisect import bisect_right as bisect ODDS, n = set("13579"), 150000 sieve, PODP = [0] * (n + 1), [] for i in range(2, n + 1): if not sieve[i]: for j in range(i * * 2, n + 1, i): sieve[j] = 1 if set(str(i)) <= ODDS: PODP . append(i) def only_oddDigPrimes(n): idx = bis...
Pure odd digits primes
55e0a2af50adf50699000126
[ "Fundamentals", "Algorithms", "Mathematics", "Data Structures" ]
https://www.codewars.com/kata/55e0a2af50adf50699000126
6 kyu
# Task A range-collapse representation of an array of integers looks like this: `"1,3-6,8"`, where `3-6` denotes the range from `3-6`, i.e. `[3,4,5,6]`. Hence `"1,3-6,8"` = `[1,3,4,5,6,8]`. Some other range-collapse representations of `[1,3,4,5,6,8]` include `"1,3-5,6,8", "1,3,4,5,6,8", etc`. Each range is writt...
games
def descriptions(arr): return 2 * * sum(a + 1 == b for a, b in zip(arr, arr[1:]))
Simple Fun #120: Range Collapse Representation
589d6bc33b368ea992000035
[ "Puzzles" ]
https://www.codewars.com/kata/589d6bc33b368ea992000035
6 kyu
# Task Fred Mapper is considering purchasing some land in Louisiana to build his house on. In the process of investigating the land, he learned that the state of Louisiana is actually shrinking by 50 square miles each year, due to erosion caused by the Mississippi River. Since Fred is hoping to live in this house the ...
algorithms
from math import ceil, pi def does_fred_need_houseboat(x, y): return ceil(pi * (x * * 2 + y * * 2) / 100)
Simple Fun #187: Does Fred Need A Houseboat?
58bf72b02d1c7c18d9000127
[ "Algorithms" ]
https://www.codewars.com/kata/58bf72b02d1c7c18d9000127
7 kyu
## Task `zipWith` ( or `zip_with` ) takes a function and two arrays and zips the arrays together, applying the function to every pair of values. The function value is one new array. If the arrays are of unequal length, the output will only be as long as the shorter one. (Values of the longer array are simply not ...
algorithms
def zip_with(fn, a1, a2): return list(map(fn, a1, a2))
zipWith
5825792ada030e9601000782
[ "Lists", "Arrays", "Functional Programming", "Algorithms" ]
https://www.codewars.com/kata/5825792ada030e9601000782
6 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;"> The wave (known as the Mexican wave in the English-speaking world outside North America) is an example of metachronal rhythm achieved in a packed stadium when successive ...
reference
def wave(str): return [str[: i] + str[i]. upper() + str[i + 1:] for i in range(len(str)) if str[i]. isalpha()]
Mexican Wave
58f5c63f1e26ecda7e000029
[ "Arrays", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/58f5c63f1e26ecda7e000029
6 kyu
Clients place orders to a stockbroker as strings. The order can be simple or multiple or empty. Type of a simple order: Quote/white-space/Quantity/white-space/Price/white-space/Status where Quote is formed of non-whitespace character, Quantity is an int, Price a double (with mandatory decimal point "." ...
reference
import re def balance_statement(lst): bad_formed, prices = [], {'B': 0, 'S': 0} for order in filter(None, lst . split(', ')): if not re . match('\S+ \d+ \d*\.\d+ (B|S)', order): bad_formed . append(order + ' ;') else: _, quantity, price, status = order . split() prices[status] +=...
Ease the StockBroker
54de3257f565801d96001200
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/54de3257f565801d96001200
6 kyu
Write a program that performs a search for solutions to a word game. The goal of the game is to find sets of five words that share a vowel alternation. E.g., one solution to the game might be the words: ['last', 'lest', 'list', 'lost', 'lust'] This list above is a valid solution instance since the vowels `'a'`,...
games
def find_solutions(words): vowels = set('aeiou') seen = {} for w in words: for s in seen: if len(w) == len(s) and sum((len(ltrs) > 1) * (1 if ltrs <= vowels else 2) for ltrs in map(set, zip(* seen[s], w))) == 1: seen[s]. add(w) break else: seen[w] = {w} return sorte...
Vowel Alternations
54221c16dda52609b1000ffb
[ "Puzzles" ]
https://www.codewars.com/kata/54221c16dda52609b1000ffb
5 kyu
In this kata, you have to implement two functions: `isCheck` and `isMate`. Both of the functions are given two parameters: `player` signifies whose turn it is (0: white, 1: black) and `pieces` is an array of objects (***PHP:*** Array of associative arrays) describing a piece and its location in the following fashion: ...
algorithms
# Shortest and fastest solution, passing under 120ms from copy import deepcopy directions = { 'rook': [(1, 0), (- 1, 0), (0, 1), (0, - 1)], 'knight': [(- 2, 1), (- 2, - 1), (- 1, 2), (- 1, - 2), (1, 2), (1, - 2), (2, 1), (2, - 1)], 'bishop': [(- 1, - 1), (- 1, 1), (1, - 1), (1, 1)], 'queen': [(1, ...
Check and Mate?
52fcc820f7214727bc0004b7
[ "Logic", "Arrays", "Data Structures", "Games", "Algorithms" ]
https://www.codewars.com/kata/52fcc820f7214727bc0004b7
null
"The Shell Game" involves cups upturned on a playing surface, with a ball placed underneath one of them. The index of the cups are swapped around multiple times. After that the players will try to find which cup contains the ball. Your task is as follows. Given the cup that the ball starts under, and list of swaps, ...
reference
def find_the_ball(start, swaps): pos = start for (a, b) in swaps: if a == pos: pos = b elif b == pos: pos = a return pos
The Shell Game
546a3fea8a3502302a000cd2
[ "Fundamentals" ]
https://www.codewars.com/kata/546a3fea8a3502302a000cd2
6 kyu
DNA is a biomolecule that carries genetic information. It is composed of four different building blocks, called nucleotides: adenine (A), thymine (T), cytosine (C) and guanine (G). Two DNA strands join to form a double helix, whereby the nucleotides of one strand bond to the nucleotides of the other strand at the corre...
reference
table = str . maketrans("ACGT", "TGCA") def check_DNA(seq1, seq2): seq1, seq2 = sorted((seq1, seq2), key=len) return seq1 in seq2[:: - 1]. translate(table)
DNA Sequence Tester
56fbb2b8fca8b97e4d000a31
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/56fbb2b8fca8b97e4d000a31
6 kyu
See the following triangle: ``` ____________________________________ 1 2 4 2 3 6 9 6 3 4 8 12 16 12 8 4 5 10 15 20 25 20 15 10 5 ___________________________________ ``` The <b>...
reference
def mult_triangle(n): total = (n * (n + 1) / 2) * * 2 odds = ((n + 1) / / 2) * * 4 return [total, total - odds, odds]
Triangle of Multiples (Easy One)
58ecc0a8342ee5e920000115
[ "Mathematics", "Data Structures", "Fundamentals" ]
https://www.codewars.com/kata/58ecc0a8342ee5e920000115
6 kyu
Complete the function/method (depending on the language) to return `true`/`True` when its argument is an array that has the same nesting structures and same corresponding length of nested arrays as the first array. For example: ```javascript // should return true [ 1, 1, 1 ].sameStructureAs( [ 2, 2, 2 ] ); ...
algorithms
def same_structure_as(original, other): if isinstance(original, list) and isinstance(other, list) and len(original) == len(other): for o1, o2 in zip(original, other): if not same_structure_as(o1, o2): return False else: return True else: return not isinstance(original...
Nesting Structure Comparison
520446778469526ec0000001
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/520446778469526ec0000001
4 kyu
# Task Your task is to write a function for calculating the score of a 10 pin bowling game. The input for the function is a list of pins knocked down per roll for one player. Output is the player's total score. # Rules ## General rules Rules of bowling in a nutshell: * A game consists of 10 frames. In each frame th...
algorithms
def bowling_score(rolls): "Compute the total score for a player's game of bowling." def is_spare(rolls): return 10 == sum(rolls[: 2]) def is_strike(rolls): return 10 == rolls[0] def calc_score(rolls, frame): return (sum(rolls) if frame == 10 else sum(rolls[: 3]) + cal...
Bowling score calculator
5427db696f30afd74b0006a3
[ "Games", "Algorithms" ]
https://www.codewars.com/kata/5427db696f30afd74b0006a3
5 kyu
## Mount the Bowling Pins! ### Task: Did you ever play Bowling? Short: You have to throw a bowl into 10 Pins arranged like this: ``` I I I I # each Pin has a Number: 7 8 9 10 I I I 4 5 6 I I 2 3 I 1 ``` You ...
reference
pins = "{7} {8} {9} {10}\n" + \ " {4} {5} {6} \n" + \ " {2} {3} \n" + \ " {1} " def bowling_pins(arr): return pins . format(* (" " if i in arr else "I" for i in range(11)))
Bowling Pins
585cf93f6ad5e0d9bf000010
[ "Arrays", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/585cf93f6ad5e0d9bf000010
6 kyu
Given the root node of a binary tree, write a function that will traverse the tree in a serpentine fashion. You could also think of this as a zig-zag. We want to visit the first level from left to right, the second level from right to left, third level from left to right, and so on... The function will return a list ...
algorithms
def serpentine_traversal(tree) - > list: def bfs(root): depth = [root] if root else [] while depth: yield [node . data for node in depth] depth = [child for node in depth for child in (node . left, node . right) if child] return [node for i, line in enumerate(bfs(tree), 1) fo...
Binary Tree Serpentine Traversal
5268988a1034287628000156
[ "Binary Trees", "Trees", "Recursion", "Algorithms" ]
https://www.codewars.com/kata/5268988a1034287628000156
5 kyu
Implement a class/function, which should parse time expressed as `HH:MM:SS`, or `null/nil/None` otherwise. Any extra characters, or minutes/seconds higher than 59 make the input invalid, and so should return `null/nil/None`.
reference
import re def to_seconds(time): if bool(re . match('[0-9][0-9]:[0-5][0-9]:[0-5][0-9]\Z', time)): return int(time[: 2]) * 3600 + int(time[3: 5]) * 60 + int(time[6: 8]) else: return None
Regexp basics - parsing time
568338ea371e86728c000002
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/568338ea371e86728c000002
6 kyu
## Task You are given n rectangular boxes, the ith box has the length length<sub>i</sub>, the width width<sub>i</sub> and the height height<sub>i</sub>. Your task is to check if it is possible to pack all boxes into one so that inside each box there is no more than one another box (which, in turn, can contain at m...
games
def boxes_packing(l, w, h): boxes = sorted(sorted(t) for t in zip(l, w, h)) return all(s < l for b1, b2 in zip(boxes[: - 1], boxes[1:]) for s, l in zip(b1, b2))
Simple Fun #89: Boxes Packing
58957c5041c979cf9e00002f
[ "Puzzles" ]
https://www.codewars.com/kata/58957c5041c979cf9e00002f
5 kyu
### Task Dudka has `n` details. He must keep exactly 3 of them. To do this, he performs the following operations until he has only 3 details left: ``` He numbers them. He keeps those with either odd or even numbers and throws the others away. ``` Dudka wants to know how many ways there are to get exactly 3 details. ...
games
def three_details(n): m = 1 << n . bit_length() return min(n - (m >> 1), m - n)
Simple Fun #192: Three Details
58c212c6f130b7c4660000a5
[ "Puzzles" ]
https://www.codewars.com/kata/58c212c6f130b7c4660000a5
6 kyu
# Task Vanya gets bored one day and decides to enumerate a large pile of rocks. He first counts the rocks and finds out that he has `n` rocks in the pile, then he goes to the store to buy labels for enumeration. Each of the labels is a digit from 0 to 9 and each of the `n` rocks should be assigned a unique number ...
algorithms
from math import log10 def rocks(n): return (n + 1) * int(log10(n) + 1) - (10 * * int(log10(n) + 1) - 1) / / 9
Simple Fun #151: Rocks
58acf6c20b3b251d6d00002d
[ "Algorithms" ]
https://www.codewars.com/kata/58acf6c20b3b251d6d00002d
6 kyu
# Task A common way for prisoners to communicate secret messages with each other is to encrypt them. One such encryption algorithm goes as follows. You take the message and place it inside an `nx6` matrix (adjust the number of rows depending on the message length) going from top left to bottom right (one row at a ti...
games
def six_column_encryption(msg): msg = msg . replace(' ', '.') + '.' * ((6 - len(msg) % 6) % 6) return ' ' . join(msg[n:: 6] for n in range(6))
Simple Fun #133: Six Column Encryption
58a65945fd7051d5e1000041
[ "Puzzles" ]
https://www.codewars.com/kata/58a65945fd7051d5e1000041
6 kyu
# Task A robot is standing at the `(0, 0)` point of the Cartesian plane and is oriented towards the vertical (y) axis in the direction of increasing y values (in other words, he's facing up, or north). The robot executes several commands each of which is a single positive integer. When the robot is given a positive in...
games
def robot_walk(a): i = 3 while (i < len(a) and a[i] < a[i - 2]): i += 1 return i < len(a)
Simple Fun #130: Robot Walk
58a64b48586e9828df000109
[ "Puzzles" ]
https://www.codewars.com/kata/58a64b48586e9828df000109
6 kyu
# Task You're standing at the top left corner of an `n × m` grid and facing towards the `right`. Then you start walking one square at a time in the direction you are facing. If you reach the border of the grid or if the next square you are about to visit has already been visited, you turn right. You stop w...
games
def direction_in_grid(n, m): return "LR" [n % 2] if m >= n else "UD" [m % 2]
Simple Fun #183: Direction In Grid
58bcd7f2f6d3b11fce000025
[ "Puzzles" ]
https://www.codewars.com/kata/58bcd7f2f6d3b11fce000025
6 kyu
## Task * Complete the pattern, using the special characters ```■ □``` * In this kata, let's us draw a square, with a zoom effect. ## Rules - parameter `n`: The side length of the square, always be a positive odd number. - return a string square that `■` and `□` alternate expansion and each line is separated by `\...
games
def zoom(n): pattern = "" center = (n - 1) / 2 for y in range(n): for x in range(n): d = max(abs(x - center), abs(y - center)) pattern += "□" if d % 2 else "■" pattern += "\n" if y < n - 1 else "" return pattern
■□ Pattern □■ : Zoom
56e6705b715e72fef0000647
[ "ASCII Art", "Puzzles" ]
https://www.codewars.com/kata/56e6705b715e72fef0000647
5 kyu
# Task Two integer numbers are added using the column addition method. When using this method, some additions of digits produce non-zero carries to the next positions. Your task is to calculate the number of non-zero carries that will occur while adding the given numbers. The numbers are added in base 10. # Example...
games
def number_of_carries(a, b): ans, carrie = 0, 0 while a > 0 or b > 0: carrie = (a % 10 + b % 10 + carrie) / / 10 ans += [0, 1][carrie > 0] a / /= 10 b / /= 10 return ans
Simple Fun #132: Number Of Carries
58a6568827f9546931000027
[ "Puzzles" ]
https://www.codewars.com/kata/58a6568827f9546931000027
6 kyu
# Task If string has more than one neighboring dashes(e.g. --) replace they with one dash(-). Dashes are considered neighbors even if there is some whitespace **between** them. # Example For `str = "we-are- - - code----warriors.-"` The result should be `"we-are- code-warriors.-"` # Input/Output - `[inpu...
algorithms
from re import sub def replace_dashes_as_one(s): return sub("-[\s-]*-", '-', s)
Simple Fun #161: Replace Dashes As One
58af9f7320a9ecedb30000f1
[ "Algorithms" ]
https://www.codewars.com/kata/58af9f7320a9ecedb30000f1
6 kyu
# Task You are a magician. You're going to perform a trick. You have `b` black marbles and `w` white marbles in your magic hat, and an infinite supply of black and white marbles that you can pull out of nowhere. You ask your audience to repeatedly remove a pair of marbles from your hat and, for each pair removed, y...
games
def not_so_random(b, w): return ['White', 'Black'][b % 2]
Simple Fun #158: Not So Random
58ad2e9c0e3c08126000003f
[ "Puzzles" ]
https://www.codewars.com/kata/58ad2e9c0e3c08126000003f
6 kyu
## Decode the diagonal. Given a grid of characters. Output a decoded message as a string. Input ``` H Z R R Q D I F C A E A ! G H T E L A E L M N H P R F X Z R P E ``` Output `HITHERE!` (diagonally down right `↘` and diagonally up right `↗` if you can't go further). The message ends when there is n...
algorithms
def get_diagonale_code(grid): grid = [line . split() for line in grid . split("\n")] i, j, d, word = 0, 0, 1, "" while 0 <= i < len(grid) and j < len(grid[i]): if 0 <= j < len(grid[i]): word += grid[i][j] i, j = i + d, j + 1 else: i += d if i == 0 or i == len(grid) - 1: ...
Decode Diagonal
55af0d33f9b829d0a800008d
[ "Algorithms" ]
https://www.codewars.com/kata/55af0d33f9b829d0a800008d
6 kyu
_A mad sociopath scientist just came out with a brilliant invention! He extracted his own memories to forget all the people he hates! Now there's a lot of information in there, so he needs your talent as a developer to automatize that task for him._ > You are given the memories as a string containing people's surname ...
reference
def select(memory): lst = memory . split(', ') bad = {who . strip('!') for prev, who in zip( [''] + lst, lst + ['']) if who . startswith('!') or prev . startswith('!')} return ', ' . join(who for who in map(lambda s: s . strip('!'), lst) if who not in bad)
Selective memory
58bee820e9f98b215200007c
[ "Fundamentals" ]
https://www.codewars.com/kata/58bee820e9f98b215200007c
6 kyu
In the morning all the doors in the school are closed. The school is quite big: there are **N** doors. Then pupils start coming. It might be hard to believe, but all of them want to study! Also, there are exactly **N** children studying in this school, and they come one by one. When these strange children pass by some...
algorithms
def doors(n): return int(n * * .5)
Doors in the school
57c15d314677bb2bd4000017
[ "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/57c15d314677bb2bd4000017
6 kyu
You are the Head of the Department and your responsibilities include creating monthly schedules for your employees. Your employees work in shifts. Each shift is 24 hours. Employment policy prohibits employee from working more than 24 hours in a row, so one employee cannot have two consecutive shifts. There must b...
algorithms
from calendar import monthrange from itertools import cycle, islice def schedule(staff, date, n): if len(staff) < 2 * n: return None days = monthrange(int(date[2:]), int(date[: 2]))[1] istaff = cycle(staff) return [list(islice(istaff, n)) for _ in range(days)]
Department scheduler [simple]
5558bb17f7ba7532de0000aa
[ "Scheduling", "Algorithms" ]
https://www.codewars.com/kata/5558bb17f7ba7532de0000aa
5 kyu
# Task Calculate a chess player's new Elo rating using their previous ratings (`experience`), their opponent's rating (`opponent`), the outcome of the new game (`score`), and the Factor k function (`k`). ## Arguments * `experience` is an array/list containing the history of the player's ratings, with the last item in ...
algorithms
def k_fide2010(experience): if len(experience) < 30: return 25 elif experience and max(experience) < 2400: return 15 return 10 def elo(experience, opponent, game_result, k=k_fide2010): try: last = experience[- 1] except IndexError: last = 1000 expected = 1.0 / (1 +...
Elo rating - one game, one pair
55633765da97b266e3000067
[ "Games", "Algorithms" ]
https://www.codewars.com/kata/55633765da97b266e3000067
5 kyu
#Split all even numbers to odd ones in different ways Your task is to split all even numbers from an array to odd ones. So your method has to return a new array with only odd numbers. For "splitting" the numbers there are four ways. ``` 0 -> Split into two odd numbers, that are closest to each other. (e.g.: 8 -...
algorithms
from itertools import chain def split_all_even_numbers(lst, way): def convert(n): s = 1 - (n / / 2) % 2 # Shift for closest odd numbers return ([n] if n % 2 else # Is already odd [n / / 2 - s, n / / 2 + s] if way == 0 else # Two closest odd sum [1, n - 1] if way == 1 e...
Split all even numbers to odd ones in different ways
5883b79101b769456e000003
[ "Arrays", "Logic", "Algorithms" ]
https://www.codewars.com/kata/5883b79101b769456e000003
6 kyu
We are given two arrays of integers A and B and we have to output a sorted array with the integers that fulfill the following constraints: - they are present in both ones - they occur more than once in A and more than once in B - their values are within a given range - thay are odd or even according as it is reques...
reference
from collections import Counter def find_arr(arrA, arrB, rng, wanted): ca, cb = Counter(arrA), Counter(arrB) m, n = rng m += (m % 2 == 1) == (wanted == 'even') r = range(m, n + 1, 2) return [v for v in r if ca[v] > 1 and cb[v] > 1]
Find a Bunch of Common Elements of Two Lists in a Certain Range
58161c5ac7e37d17fc00002f
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic", "Strings" ]
https://www.codewars.com/kata/58161c5ac7e37d17fc00002f
6 kyu
Given two strings s1 and s2, we want to visualize how different the two strings are. We will only take into account the *lowercase* letters (a to z). First let us count the frequency of each *lowercase* letters in s1 and s2. `s1 = "A aaaa bb c"` `s2 = "& aaa bbb c d"` `s1 has 4 'a', 2 'b', 1 'c'` `s2 has 3 'a', 3 '...
reference
def mix(s1, s2): hist = {} for ch in "abcdefghijklmnopqrstuvwxyz": val1, val2 = s1 . count(ch), s2 . count(ch) if max(val1, val2) > 1: which = "1" if val1 > val2 else "2" if val2 > val1 else "=" hist[ch] = (- max(val1, val2), which + ":" + ch * max(val1, val2)) return "/" . join(hist[...
Strings Mix
5629db57620258aa9d000014
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/5629db57620258aa9d000014
4 kyu
Check that the two provided arrays both contain the same number of different unique items, regardless of order. For example in the following: ``` [a,a,a,a,b,b] and [c,c,c,d,c,d] ``` Both arrays have four of one item and two of another, so balance should return ```true```. #Have fun!
reference
from collections import Counter def balance(arr1, arr2): return sorted(Counter(arr1). values()) == sorted(Counter(arr2). values())
Balance the arrays
58429d526312ce1d940000ee
[ "Fundamentals" ]
https://www.codewars.com/kata/58429d526312ce1d940000ee
6 kyu
# Task: This kata asks you to make a custom esolang interpreter for the language [MiniBitMove](https://esolangs.org/wiki/MiniBitMove). MiniBitMove has only two commands and operates on a array of bits. It works like this: - `1`: Flip the bit at the current cell - `0`: Move selector by 1 It takes two inputs, the progr...
reference
from itertools import cycle def interpreter(tape, array): idx, result = 0, list(map(int, array)) for cmd in cycle(map(int, tape)): if idx == len(array): break if cmd: result[idx] = 1 - result[idx] else: idx += 1 return '' . join(map(str, result))
Esolang: MiniBitMove
587c0138110b20624e000253
[ "Interpreters", "Strings", "Arrays", "Bits", "Esoteric Languages", "Fundamentals" ]
https://www.codewars.com/kata/587c0138110b20624e000253
6 kyu
Karan's company makes software that provides different features based on the version of operating system of the user. To compare versions, Karan currently parses both version numbers as floats. While this worked for OS versions 10.6, 10.7, 10.8 and 10.9, the operating system company just released OS version 10.10. Th...
reference
def compare_versions(ver1, ver2): return [int(i) for i in ver1 . split(".")] >= [int(i) for i in ver2 . split(".")]
Compare Versions
53b138b3b987275b46000115
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/53b138b3b987275b46000115
6 kyu
Aoccdrnig to a rscheearch at Cmabrigde Uinervtisy, it deosn't mttaer in waht oredr the ltteers in a wrod are, the olny iprmoetnt tihng is taht the frist and lsat ltteer be at the rghit pclae. The rset can be a toatl mses and you can sitll raed it wouthit porbelm. Tihs is bcuseae the huamn mnid deos not raed ervey ltete...
reference
def jumble(strng): return __import__("re"). sub(r'(\w{3,})', lambda m: m . group(0)[0] + m . group(0)[1: - 1][:: - 1] + m . group(0)[- 1], strng)
Jumble words
589b30ddcf7d024850000089
[ "Strings", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/589b30ddcf7d024850000089
6 kyu
Write a function that returns only the decimal part of the given number. You only have to handle valid numbers, not `Infinity`, `NaN`, or similar. Always return a positive decimal part. ### Examples ``` javascript getDecimal(2.4) === 0.4 getDecimal(-0.2) === 0.2 ``` ``` python get_decimal(2.4) # 0.4 get_decimal(...
reference
def get_decimal(n): return abs(n) % 1
Get decimal part of the given number
586e4c61aa0428f04e000069
[ "Fundamentals" ]
https://www.codewars.com/kata/586e4c61aa0428f04e000069
7 kyu
Write a function that will check whether ANY permutation of the characters of the input string is a palindrome. Bonus points for a solution that is efficient and/or that uses _only_ built-in language functions. Deem yourself **brilliant** if you can come up with a version that does not use _any_ function whatsoever. ...
reference
def permute_a_palindrome(input): return sum(input . count(c) % 2 for c in set(input)) < 2
Permute a Palindrome
58ae6ae22c3aaafc58000079
[ "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/58ae6ae22c3aaafc58000079
6 kyu
An array is **circularly sorted** if the elements are sorted in ascending order, but displaced, or rotated, by any number of steps. Complete the function/method that determines if the given array of integers is circularly sorted. ## Examples These arrays are circularly sorted (`true`): ``` [2, 3, 4, 5, 0, 1] ...
algorithms
def circularly_sorted(arr): return sum(x > y for x, y in zip(arr, arr[1:] + [arr[0]])) < 2
Circularly Sorted Array
544975fc18f47481ba00107b
[ "Algorithms", "Sorting" ]
https://www.codewars.com/kata/544975fc18f47481ba00107b
6 kyu
Your task is to write a regular expression (regex) that will match a string only if it contains at least one valid date, in the format `[mm-dd]` (that is, a two-digit month, followed by a dash, followed by a two-digit date, surrounded by square brackets). You should assume the year in question is _not_ a leap year. Th...
reference
import re months_30 = '(04|06|09|11)' months_31 = '(01|03|05|07|08|10|12)' months_28 = '02' days_30 = '(0[1-9]|[1-2][0-9]|30)' days_31 = '(0[1-9]|[12][0-9]|3[01])' days_28 = '(0[1-9]|1[0-9]|2[0-8])' valid_date = re . compile('\[(%s-%s|%s-%s|%s-%s)\]' % (months_30, days_30, months_31, days_31, ...
validDate Regex
548db0bd1df5bbf29b0000b7
[ "Date Time", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/548db0bd1df5bbf29b0000b7
5 kyu
In this kata you are given an array to sort but you're expected to start sorting from a specific position of the array (in ascending order) and optionally you're given the number of items to sort. #### Examples: ```php sect_sort([1, 2, 5, 7, 4, 6, 3, 9, 8], 2) //=> [1, 2, 3, 4, 5, 6, 7, 8, 9] sect_sort([9, 7, 4, 2, 5...
algorithms
def sect_sort(lst, start, length=0): end = start + length if length else len(lst) return lst[: start] + sorted(lst[start: end]) + lst[end:]
Sectional Array Sort
58ef87dc4db9b24c6c000092
[ "Arrays", "Sorting", "Data Structures", "Algorithms" ]
https://www.codewars.com/kata/58ef87dc4db9b24c6c000092
7 kyu
You are standing on top of an amazing Himalayan mountain. The view is absolutely breathtaking! you want to take a picture on your phone, but... your memory is full again! ok, time to sort through your shuffled photos and make some space... Given a gallery of photos, write a function to sort through your pictures. You ...
reference
import re _PAT = re . compile(r'(\d{4})\.img(\d+)') def _KEY(pic): return map(int, _PAT . match(pic). groups()) def sort_photos(pics): pics = sorted(pics, key=_KEY)[- 5:] year, idx = _KEY(pics[- 1]) return pics + ['{}.img{}' . format(year, idx + 1)]
Take a picture !
56c9f47b0844d85f81000fc2
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/56c9f47b0844d85f81000fc2
6 kyu
Your granny, who lives in town X0, has friends. These friends are given in an array, for example: array of friends is `["A1", "A2", "A3", "A4", "A5"]`. **The order of friends in this array must *not be changed* since this order gives the order in which they will be visited.** Friends inhabit towns and you get an ar...
reference
def tour(friends, friend_towns, home_to_town_distances): res = 0 s = 0 for i in friend_towns: if i[0] in friends: res = res + (home_to_town_distances[i[1]] * * 2 - s * * 2) * * (0.5) s = home_to_town_distances[i[1]] res = res + s return int(res)
Help your granny!
5536a85b6ed4ee5a78000035
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/5536a85b6ed4ee5a78000035
5 kyu
We search non-negative integer numbers, with at **most** 3 digits, such as the sum of the cubes of their digits is the number itself; we will call them "cubic" numbers. ``` 153 is such a "cubic" number : 1^3 + 5^3 + 3^3 = 153 ``` These "cubic" numbers of at most 3 digits are easy to find, even by hand, so they are "hid...
reference
import re PATTERN = re . compile(r'(\d{1,3})') def is_sum_of_cubes(s): found = list(filter(lambda nStr: int(nStr) == sum(int(d) * * 3 for d in nStr), PATTERN . findall(s))) return "Unlucky" if not found else "{} {} {}" . format(' ' . join(found), sum(map(int, found)), 'Lucky')
Hidden "Cubic" numbers
55031bba8cba40ada90011c4
[ "Algorithms", "Strings" ]
https://www.codewars.com/kata/55031bba8cba40ada90011c4
6 kyu
Your task is to write a function that receives as its single argument a string that contains numbers delimited by single spaces. Each number has a single alphabet letter somewhere within it. ``` Example : "24z6 1x23 y369 89a 900b" ``` As shown above, this alphabet letter can appear anywhere within the number. You have ...
reference
from functools import reduce from itertools import cycle from operator import add, truediv, mul, sub def do_math(s): xs = sorted(s . split(), key=lambda x: next(c for c in x if c . isalpha())) xs = [int('' . join(filter(str . isdigit, x))) for x in xs] ops = cycle([add, sub, mul, truediv]) re...
Number , number ... wait LETTER !
5782dd86202c0e43410001f6
[ "Strings", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5782dd86202c0e43410001f6
6 kyu
You will have a list of rationals in the form ``` lst = [ [numer_1, denom_1] , ... , [numer_n, denom_n] ] ``` or ``` lst = [ (numer_1, denom_1) , ... , (numer_n, denom_n) ] ``` where all numbers are positive integers. You have to produce their sum `N / D` in an irreducible form: this means that `N` and `D` have only `1...
reference
from fractions import Fraction def sum_fracts(lst): if lst: ret = sum(Fraction(a, b) for (a, b) in lst) return ret . numerator if ret . denominator == 1 else [ret . numerator, ret . denominator]
Irreducible Sum of Rationals
5517fcb0236c8826940003c9
[ "Fundamentals" ]
https://www.codewars.com/kata/5517fcb0236c8826940003c9
6 kyu
To participate in a prize draw each one gives his/her firstname. Each letter of a firstname has a value which is its rank in the English alphabet. `A` and `a` have rank `1`, `B` and `b` rank `2` and so on. The *length* of the firstname is added to the *sum* of these ranks hence a number `som`. An array of random ...
reference
def rank(st, we, n): if not st: return "No participants" if n > len(we): return "Not enough participants" def name_score(name, w): return w * (len(name) + sum([ord(c . lower()) - 96 for c in name])) scores = [name_score(s, we[i]) for i, s in en...
Prize Draw
5616868c81a0f281e500005c
[ "Fundamentals", "Strings", "Sorting" ]
https://www.codewars.com/kata/5616868c81a0f281e500005c
6 kyu
Implement a function that receives a string, and lets you extend it with repeated calls. When no argument is passed you should return a string consisting of space-separated words you've received earlier. **Note**: There will always be at least 1 string; all inputs will be non-empty. For example: ```javascript create...
reference
class create_message (str): def __call__(self, s=''): return create_message(f' { self } { s } ' . strip())
"Stringing"+"Me"+"Along"
55f4a44eb72a0fa91600001e
[ "Functional Programming", "Fundamentals" ]
https://www.codewars.com/kata/55f4a44eb72a0fa91600001e
6 kyu
`data`and `data1` are two strings with rainfall records of a few cities for months from January to December. The records of towns are separated by `\n`. The name of each town is followed by `:`. `data` and `towns` can be seen in "Your Test Cases:". #### Task: - function: `mean(town, strng)` should return the average...
reference
def get_towndata(town, strng): for line in strng . split('\n'): s_town, s_data = line . split(':') if s_town == town: return [s . split(' ') for s in s_data . split(',')] return None def mean(town, strng): data = get_towndata(town, strng) if data is not None: return sum([flo...
Rainfall
56a32dd6e4f4748cc3000006
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/56a32dd6e4f4748cc3000006
6 kyu
[Langton's ant](https://en.wikipedia.org/wiki/Langton%27s_ant) is a two-dimensional Turing machine invented in the late 1980s. The ant starts out on a grid of black and white cells and follows a simple set of rules that has complex emergent behavior. ## Task Complete the function and return the `n`th iteration of La...
algorithms
def ant(grid, col, row, n, dir=0): for _ in range(n): # turn color = grid[row][col] if color == 1: dir = (dir + 1) % 4 elif color == 0: dir = (dir - 1) % 4 # flip color grid[row][col] ^= 1 # move forward if dir == 0: row -= 1 elif dir == 1...
Langton's ant
58e6996019af2cff71000081
[ "Recursion", "Algorithms" ]
https://www.codewars.com/kata/58e6996019af2cff71000081
5 kyu
You know combinations: for example, if you take `5` cards from a `52` cards deck you have `2,598,960` different combinations. In mathematics the number of `x` combinations you can take from a set of `n` elements is called the *binomial coefficient of n and x*, or more often `n choose x`. The formula to compute `n cho...
reference
def checkchoose(m, n): c = 1 for x in range(n / / 2 + 1): if c == m: return x c = c * (n - x) / / (x + 1) else: return - 1
Color Choice
55be10de92aad5ef28000023
[ "Combinatorics", "Mathematics" ]
https://www.codewars.com/kata/55be10de92aad5ef28000023
6 kyu
The numbers 6, 12, 18, 24, 36, 48 have a common property. They have the same two prime factors that are 2 and 3. If we see their prime factorization we will see it more clearly: ```python 6 = 2 * 3 12 = 2^2 * 3 18 = 2 * 3^2 24 = 2^3 * 3 36 = 2^2 * 3^2 48 = 2^4 * 3 ``` 48 is the maximum of them bellow the value 50 We ...
reference
def highest_biPrimefac(p1, p2, n): # p1, p2 primes and p1 < p2 factors = {} k1, k2 = 1, 1 while p1 * * k1 * p2 * * k2 <= n: while p1 * * k1 * p2 * * (k2 + 1) <= n: k2 += 1 factors[p1 * * k1 * p2 * * k2] = (k1, k2) k1, k2 = k1 + 1, 1 m = max(factors) return [m, factors[m][0]...
Highest number with two prime factors
55f347cfb44b879e1e00000d
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/55f347cfb44b879e1e00000d
6 kyu
<h5 style='color:#ffff00'>Task:</h5> This kata requires you to write an object that receives a file path and does operations on it. <b style='color:#ff0000'>NOTE FOR PYTHON USERS</b>: You cannot use modules os.path, glob, and re <h5 style='color:#00ff00'>The purpose of this kata is to use string parsing, so you're not...
reference
class FileMaster (): def __init__(self, filepath): lk = filepath . rfind('.') ls = filepath . rfind('/') self . ext = filepath[lk + 1:] self . file = filepath[ls + 1: lk] self . path = filepath[: ls + 1] def extension(self): return self . ext def filename(self): return ...
File Path Operations
5844e0890d3bedc5c5000e54
[ "Fundamentals", "Strings", "Restricted" ]
https://www.codewars.com/kata/5844e0890d3bedc5c5000e54
6 kyu
Implement a function, so it will produce a sentence out of the given parts. Array of parts could contain:<br> - words;<br> - commas in the middle;<br> - multiple periods at the end.<br> Sentence making rules:<br> - there must always be a space between words;<br> - there must not be a space between a comma and word on...
reference
def make_sentences(parts): return ' ' . join(parts). replace(' ,', ','). strip(' .') + '.'
Simple Sentences
5297bf69649be865e6000922
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/5297bf69649be865e6000922
6 kyu
~~~if-not:java You have to code a function **getAllPrimeFactors**, which takes an integer as parameter and returns an array containing its prime decomposition by ascending factors. If a factor appears multiple times in the decomposition, it should appear as many times in the array. exemple: `getAllPrimeFactors(100)` ...
reference
import math import collections def getAllPrimeFactors(n): numberToDecompose = n if (not isinstance(numberToDecompose, (int, long)) or numberToDecompose <= 0): return [] answer = ([1] if (numberToDecompose == 1) else []) for possibleFactor in range(2, numberToDecompose + 1): while...
Prime number decompositions
53c93982689f84e321000d62
[ "Fundamentals" ]
https://www.codewars.com/kata/53c93982689f84e321000d62
5 kyu
Complete the method which returns the number which is most frequent in the given input array. If there is a tie for most frequent number, return the largest number among them. Note: no empty arrays will be given. ## Examples ``` [12, 10, 8, 12, 7, 6, 4, 10, 12] --> 12 [12, 10, 8, 12, 7, 6, 4, 10, 12, ...
reference
from collections import Counter def highest_rank(arr): if arr: c = Counter(arr) m = max(c . values()) return max(k for k, v in c . items() if v == m)
Highest Rank Number in an Array
5420fc9bb5b2c7fd57000004
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5420fc9bb5b2c7fd57000004
6 kyu
Write a function ```convert_temp(temp, from_scale, to_scale)``` converting temperature from one scale to another. Return converted temp value. Round converted temp value to an integer(!). Reading: http://en.wikipedia.org/wiki/Conversion_of_units_of_temperature ``` possible scale inputs: "C" for Celsius "F...
reference
TO_KELVIN = { 'C': (1, 273.15), 'F': (5.0 / 9, 459.67 * 5.0 / 9), 'R': (5.0 / 9, 0), 'De': (- 2.0 / 3, 373.15), 'N': (100.0 / 33, 273.15), 'Re': (5.0 / 4, 273.15), 'Ro': (40.0 / 21, - 7.5 * 40 / 21 + 273.15), } def convert_temp(temp, from_scale, to_scale): if from_scale == ...
Temperature converter
54ce9497975ca65e1a0008c6
[ "Functional Programming", "Data Structures", "Strings", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/54ce9497975ca65e1a0008c6
6 kyu
You will be given a string (`x`) featuring a cat `'C'`, a dog `'D'` and a mouse `'m'`. The rest of the string will be made up of `'.'`. You need to find out if the cat can catch the mouse from its current position. The cat can jump at most (`j`) characters, and cannot jump over the dog. So: * if `j` = `5`: `..C.....
reference
def cat_mouse(x, j): d, c, m = x . find('D'), x . find('C'), x . find('m') if - 1 in [d, c, m]: return 'boring without all three' if abs(c - m) <= j: return 'Protected!' if c < d < m or m < d < c else 'Caught!' return 'Escaped!'
Cat and Mouse - Harder Version
57ee2a1b7b45efcf700001bf
[ "Fundamentals", "Strings", "Arrays" ]
https://www.codewars.com/kata/57ee2a1b7b45efcf700001bf
6 kyu
<h2>The Rhinestone Cowboy - Count the dollars in his boots!</h2> ``` ,|___|, | | | | | | | == | |[(1)]| / &| .-'` , )**** | | ** `~~~~~~~~~~ ^ ^ ...
reference
def cowboys_dollars(boots): return "This Rhinestone Cowboy has %d dollar bills in his right boot and %d in the left" \ % tuple([boots[i]. split("&")[0]. count("[(1)]") for i in (1, 0)])
The Rhinestone Cowboy ~ Count the dollars in his boots!
58a2a561f749ed763c00000b
[ "Algorithms", "ASCII Art" ]
https://www.codewars.com/kata/58a2a561f749ed763c00000b
6 kyu
Have you heard about the myth that [if you fold a paper enough times, you can reach the moon with it](http://scienceblogs.com/startswithabang/2009/08/31/paper-folding-to-the-moon/)? Sure you have, but exactly how many? Maybe it's time to write a program to figure it out. You know that a piece of paper has a thickness ...
reference
def fold_to(distance, thickness=0.0001, folds=0): if distance < 0: return while thickness < distance: thickness *= 2 folds += 1 return folds
Folding your way to the moon
58f0ba42e89aa6158400000e
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/58f0ba42e89aa6158400000e
7 kyu