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
We have an integer```n```, with a certain number of digits```k```, `$d_1d_2\dots d_k$`. We have a function, ```f()``` that produces a certain number ```n'```from ```n```, such that,```f(n) ---> n'``` ```math f(n) = \pm d_1^{|d_1-d_2|} \pm d_2^{|d_2-d_3|} \pm \dots \pm d_{k-1}^{|d_{k-1}-d_k|} + d_k ``` If the differ...
reference
def f(n): d = list(map(int, str(n))) return sum((- 1) * * (a > b) * a * * abs(a - b) for a, b in zip(d, d[1:])) + n % 10 seq = [n for n in range(1, 1000101) if not f(n)] from bisect import bisect_left def prev_next(n): idx = bisect_left(seq, n) return seq[max(0, idx - 1): idx + 1 + ...
Map and Filter to Get a Special Sequence of Integers
58224b5334c53a4294000b5a
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic", "Strings" ]
https://www.codewars.com/kata/58224b5334c53a4294000b5a
5 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 a string `str` consisting of some number of "(" and ")" characters, your task is to find the longest substring in `str` such that all "(" in the sub...
games
def find_longest(s): stack, m = [- 1], 0 for i, j in enumerate(s): if j == '(': stack . append(i) else: stack . pop() if stack: m = max(m, i - stack[- 1]) else: stack . append(i) return m
The longest bracket substring in the string
584c3e45710dca21be000088
[ "Puzzles", "Performance", "Algorithms" ]
https://www.codewars.com/kata/584c3e45710dca21be000088
5 kyu
<a href="https://imgur.com/ta6gv1i"><img src="https://i.imgur.com/ta6gv1i.png?1" title="source: imgur.com" /></a> # Kata Task You are given a ``grid``, which always includes exactly two end-points indicated by `X` You simply need to return true/false if you can detect a **one and only one** "valid" line joining thos...
algorithms
def line(grid): g = {(r, c): v for r, row in enumerate(grid) for c, v in enumerate(row) if v . strip()} ends = [k for k in g if g[k] == 'X'] if len(ends) != 2: return False for start, finish in [ends, ends[:: - 1]]: path = [start] while path[- 1] != finish: r, c = p...
Line Safari - Is that a line?
59c5d0b0a25c8c99ca000237
[ "Algorithms" ]
https://www.codewars.com/kata/59c5d0b0a25c8c99ca000237
3 kyu
In this Kata you are a builder and you are assigned a job of building a wall with a specific size (God knows why...). Create a function called `build_a_wall` (or `buildAWall` in JavaScript) that takes `x` and `y` as integer arguments (which represent the number of rows of bricks for the wall and the number of bricks i...
reference
def generateBricks(isCut, y): return "{0}|{1}|{0}" . format("■" * (1 + isCut), '|' . join("■■" for _ in range(y - 1 - isCut))) def build_a_wall(* args): if len(args) != 2 or any(type(z) != int or z <= 0 for z in args): return None x, y = args return ("Naah, too much...here\'s my resignat...
The Mysterious Wall
5939b753942a2700860000df
[ "Fundamentals", "Algorithms", "Strings", "ASCII Art" ]
https://www.codewars.com/kata/5939b753942a2700860000df
6 kyu
In this Kata, you will be given two integers `n` and `k` and your task is to remove `k-digits` from `n` and return the lowest number possible, without changing the order of the digits in `n`. Return the result as a string. Let's take an example of `solve(123056,4)`. We need to remove `4` digits from `123056` and retur...
algorithms
from itertools import combinations def solve(n, k): return '' . join(min(combinations(str(n), len(str(n)) - k)))
Integer reduction
59fd6d2332b8b9955200005f
[ "Algorithms" ]
https://www.codewars.com/kata/59fd6d2332b8b9955200005f
6 kyu
To increase the odds of the old fashioned game ([Rock, Paper, Scissors](https://en.wikipedia.org/wiki/Rock_paper_scissors)) Sam Kass and Karen Bryla reinvented the game with 5 different items instead of 3: [*Rock, Paper, Scissor, Lizard, Spock*](http://www.samkass.com/theories/RPSSL.html). It was later also featured in...
reference
N = ["scissor", "paper", "rock", "lizard", "spock"] O = [[0, 1, 2, 1, 2], [2, 0, 1, 2, 1], [1, 2, 0, 1, 2], [2, 1, 2, 0, 1], [1, 2, 1, 2, 0]] def result(p1, p2): try: i1, i2 = N . index(p1 . lower()), N . index(p2 . lower()) except: return "Oh, Unknown Thing" ...
Rock, Paper, Scissor, Lizard, Spock Game
569651a2d6a620b72e000059
[ "Games", "Fundamentals" ]
https://www.codewars.com/kata/569651a2d6a620b72e000059
6 kyu
You get an array of different numbers to sum up. But there is one problem, those numbers all have different bases. For example: ```javascript You get an array of numbers with their base as an input: [["101",16],["7640",8],["1",9]] ``` ```python You get an array of numbers with their base as an input: [["101",16],["76...
reference
def sum_it_up(a): return sum(int(n, b) for n, b in a)
Sum Array with different bases
5a005f4fba2a14897f000086
[ "Binary", "Arrays", "Lists", "Fundamentals" ]
https://www.codewars.com/kata/5a005f4fba2a14897f000086
7 kyu
Given an array of strings, sort the array into order of weight from light to heavy. Weight units are grams(G), kilo-grams(KG) and tonnes(T). Arrays will always contain correct and positive values aswell as uppercase letters.
reference
def arrange(arr): def normalized(weight): if weight . endswith("T"): return int(weight[: - 1]) * 10 * * 6 if weight . endswith("KG"): return int(weight[: - 2]) * 10 * * 3 if weight . endswith("G"): return int(weight[: - 1]) return sorted(arr, key=normalized)
Order of weight
59ff4709ba2a14501500003a
[ "Strings", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/59ff4709ba2a14501500003a
7 kyu
## Sixteen circles Sixteen circles with radius `r` are placed as shown in the picture. `r` is an integer and `≥ 1`. <center> <img alt="circles" src="https://i.imgur.com/1JuavE1.png"></center> Find the radius of the shaded circle in the centre, rounded to two decimal places.
games
import math def sixteen_circles(r): # coordinates a, b, c, d. Assuming the center (0, 0), x = radius of the center circle # then a = (0, x+r), b = (x+r, 0) # c=(2r*cos(30degree), x+r+2r*sin(30degree)) # d = (x+r+2r*cos(60d), 2r*sin(60d)) # the distance between c and d should be 2r # (x+r+2rcos...
Sixteen circles
589896b99c70093f3e00005b
[ "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/589896b99c70093f3e00005b
6 kyu
## Problem `John` and `Tom` are students of `Myjinxin`. In the classroom, `Myjinxin` often gives 10 judgment questions, let the students write the answer. `o` represents right and `x` represents wrong. i.e. If the students think that the 10 judgments are all right, his answer will be `"oooooooooo"`. Tom always answ...
reference
def possible_scores(answer_of_tom, score_of_tom, answer_of_john): """The minimum score for John is when every possible difference from Tom's answer is one that Tom got right. The maximum score for John is when every difference from Tom's answer is one that Tom got wrong. """ num_differences...
Simple Fun #373: The Possible Scores
59ffd493ba2a14d16f0000d9
[ "Fundamentals" ]
https://www.codewars.com/kata/59ffd493ba2a14d16f0000d9
6 kyu
# Task Make a custom esolang interpreter for the language Stick. Stick is a simple, stack-based esoteric programming language with only 7 commands. # Commands * `^`: Pop the stack. * `!`: Add new element to stack with the value of 0. * `+`: Increment element. 255+1=0. * `-`: Decrement element. 0-1=255. * `*`: Add ...
reference
def interpreter(tape): ptr, stack, output = 0, [0], [] while ptr < len(tape): command = tape[ptr] if command == '^': stack . pop() elif command == '!': stack . append(0) elif command == '+': stack[- 1] = (stack[- 1] + 1) % 256 elif command == '-': ...
Esolang: Stick
58855acc9e1de22dff0000ef
[ "Esoteric Languages", "Stacks" ]
https://www.codewars.com/kata/58855acc9e1de22dff0000ef
5 kyu
In this kata you're expected to sort an array of 32-bit integers in ascending order of the number of **on** bits they have. E.g Given the array **[7, 6, 15, 8]** - 7 has **3 on** bits (000...0**111**) - 6 has **2 on** bits (000...0**11**0) - 15 has **4 on** bits (000...**1111**) - 8 has **1 on** bit (000...**1**0...
reference
def sort_by_bit(arr): # they wanted to modify the input arr . sort(key=lambda x: (bin(x). count('1'), x)) return arr
Sorting by bits
59fa8e2646d8433ee200003f
[ "Logic", "Arrays", "Algorithms", "Data Structures", "Fundamentals", "Bits", "Binary", "Sorting" ]
https://www.codewars.com/kata/59fa8e2646d8433ee200003f
6 kyu
Given a matrix, find the cross (row and column) with the largest sum of elements. Return the sum. ```javascript [[1, 2, 3], [4, 5, 6], [7, 8, 9]] largest cross is the last column, [3,6,9], with the last row, [7,8,9]. Sum of elements is 3 + 6 + 7 + 8 + 9 = 33 therefore largestCrossSum(matrix) = 33 ``` ```csharp ...
reference
def largest_cross_sum(arr): h, w = range(len(arr)), range(len(arr[0])) rows = [sum(row) for row in arr] cols = [sum(col) for col in zip(* arr)] return max(rows[j] + cols[i] - arr[j][i] for j in h for i in w)
Largest Cross Sum
59fc9e7ec374cbbb8a0000a7
[ "Fundamentals" ]
https://www.codewars.com/kata/59fc9e7ec374cbbb8a0000a7
6 kyu
This calculator takes values that could be written in a browsers route path as a single string. It then returns the result as a number (or an error message). Route paths use the '/' symbol so this can't be in our calculator. Instead we are using the '$' symbol as our divide operator. You will be passed a string of an...
algorithms
def tokenize(expression): result = [] curr = '' for chr in expression: if chr . isdigit() or chr == '.': curr += chr elif chr in '$*-+': result . extend([float(curr), chr]) curr = '' else: raise ValueError('invalid input') if curr: result . append(float(curr))...
Route Calculator
581bc0629ad9ff9873000316
[ "Algorithms" ]
https://www.codewars.com/kata/581bc0629ad9ff9873000316
4 kyu
The new football league season is coming and the Football Association need some help resetting the league standings. Normally the initial league standing is done in alphabetical order (from A to Z) but this year the FA have decided to freshen it up. It has been decided that team who finished first last season will be...
algorithms
def premier_league_standings(teams): dct = {1: teams[1]} dct . update({i: t for i, t in enumerate( sorted(set(teams . values()) - {teams[1]}), 2)}) return dct
New season, new league
58de08d376f875dbb40000f1
[ "Algorithms" ]
https://www.codewars.com/kata/58de08d376f875dbb40000f1
7 kyu
In this Kata, we are going to see how a Hash (or Map or dict) can be used to keep track of characters in a string. Consider two strings `"aabcdefg"` and `"fbd"`. How many characters do we have to remove from the first string to get the second string? Although not the only way to solve this, we could create a Hash of...
reference
from collections import Counter def solve(a, b): return 0 if Counter(b) - Counter(a) else len(a) - len(b)
String reduction
59fab1f0c9fc0e7cd4000072
[ "Fundamentals" ]
https://www.codewars.com/kata/59fab1f0c9fc0e7cd4000072
6 kyu
In this Kata, you will be given a string that has lowercase letters and numbers. Your task is to compare the number groupings and return the largest number. Numbers will not have leading zeros. For example, `solve("gh12cdy695m1") = 695`, because this is the largest of all number groupings. Good luck! Please also t...
algorithms
import re def solve(s): return max(map(int, re . findall(r"(\d+)", s)))
Numbers in strings
59dd2c38f703c4ae5e000014
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/59dd2c38f703c4ae5e000014
7 kyu
In this Kata, you will be given two numbers, n and k and your task will be to return the k-digit array that sums to n and has the maximum possible GCD. For example, given `n = 12, k = 3`, there are a number of possible `3-digit` arrays that sum to `12`, such as `[1,2,9], [2,3,7], [2,4,6], ...` and so on. Of all the po...
algorithms
def solve(n, k): maxGcd = 2 * n / / (k * (k + 1)) for gcd in range(maxGcd, 0, - 1): last = n - gcd * k * (k - 1) / / 2 if not last % gcd: return [gcd * x if x != k else last for x in range(1, k + 1)] return []
Constrained GCD
59f61aada01431e8c200008d
[ "Arrays", "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/59f61aada01431e8c200008d
5 kyu
&ensp;It is necessary to define who of two players will win the game in the ideal moves of each.<br> &ensp;The NxM board is given, the players' figures are on opposite sides of the board. ``` 4x7 |X.....Y| |X.....Y| |X.....Y| |X.....Y| ``` &ensp;In his turn, the player <u>must</u> move one of his figures forward horizo...
games
def game(x, y): return 'second' if y == 2 else 'first' if x % 2 and y % 2 == 0 or x % 2 else 'second'
Simple Game
59831e3575ca6c8aea00003a
[ "Games", "Puzzles", "Logic", "Game Solvers" ]
https://www.codewars.com/kata/59831e3575ca6c8aea00003a
7 kyu
# Task Given a string which represents a valid arithmetic expression, find the index of the character in the given expression corresponding to the arithmetic operation which needs to be computed first. Note that several operations of the same type with equal priority are computed from left to right. # Example For...
games
def first_operation_character(expr): res, lvl = (1, None, None), 0 for i, c in enumerate(expr): match c: case '(': lvl -= 1 case ')': lvl += 1 case '+' | '*': res = min(res, (lvl, c, i)) return res[2]
Challenge Fun #13: First Operation Character
58aa50372223a30e4f000068
[ "Puzzles" ]
https://www.codewars.com/kata/58aa50372223a30e4f000068
5 kyu
An expression is formed by taking the digits 1 to 9 in numerical order and then inserting into each gap between the numbers either a plus sign or a minus sign or neither. Your task is to write a method which takes one parameter and returns the **smallest possible number** of plus and minus signs necessary to form such...
games
from itertools import product def operator_insertor(n): result = [] for ops in product(["+", "-", ""], repeat=8): expression = "" . join( a + b for a, b in zip("123456789", list(ops) + [""])) res = eval(expression) if res == n: result . append(len(expression) - 9) re...
Operator Insertion
596b7f284f232df61e00001b
[ "Puzzles" ]
https://www.codewars.com/kata/596b7f284f232df61e00001b
5 kyu
It's the fourth quater of the Super Bowl and your team is down by 4 points. You're 10 yards away from the endzone, if your team doesn't score a touchdown in the next four plays you lose. On a previous play, you were injured and rushed to the hospital. Your hospital room has no internet, tv, or radio and you don't know ...
reference
def did_we_win(plays): plays = [p for p in plays if p] return all(p != 'turnover' for y, p in plays) and sum(- y if p == 'sack' else y for y, p in plays) > 10
Did we win the Super Bowl?
59f69fefa0143109e5000019
[ "Games", "Arrays", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/59f69fefa0143109e5000019
7 kyu
<h3>Bit Vectors/Bitmaps</h3> <p>A bitmap is one way of efficiently representing sets of unique integers using single bits.<br> To see how this works, we can represent a set of unique integers between `0` and `< 20` using a vector/array of 20 bits:</p> ``` var set = [3, 14, 2, 11, 16, 4, 6];``` ``` var bitmap = [0, 0, 1...
algorithms
def to_bits(s): lst = [0] * 5000 for i in map(int, s . split()): lst[i] = 1 return lst
Basic Bitmapping
59f8dd1132b8b9af150001ea
[ "Bits", "Arrays", "Sets", "Lists", "Algorithms", "Recursion" ]
https://www.codewars.com/kata/59f8dd1132b8b9af150001ea
6 kyu
# Introduction The goal of this kata is to check whether a network of water pipes is leaking anywhere. # Task Create a function which accepts a `map` input and validates if water is leaking anywhere. In case water is leaking return `false`. In case the pipe network is correct -- i.e. there are no leaks anywhere -...
reference
def check_pipe(pipe_map): def get(y, x): return pipe_map[y][x] if 0 <= y < len( pipe_map) and 0 <= x < len(pipe_map[0]) else None UP, LEFT, DOWN, RIGHT = (- 1, 0), (0, - 1), (1, 0), (0, 1) pipes = { '┗': (UP, RIGHT), '┓': (LEFT, DOWN), '┏': (RIGHT, DOWN), '┛':...
Fix the pipes - #2 - is it leaking?
59f81fe146d84322ed00001e
[ "Arrays", "Strings" ]
https://www.codewars.com/kata/59f81fe146d84322ed00001e
3 kyu
Lets talk like a monkey. Find out how! Look at the test cases an engineer code to pass them.
reference
def monkey_talk(phrase): return ' ' . join(['ook', 'eek'][w[0]. lower() in 'aeiou'] for w in phrase . split()). capitalize() + '.'
Monkey Talk
59f897ecc374cb9ed90000c2
[ "Fundamentals", "Strings", "Puzzles" ]
https://www.codewars.com/kata/59f897ecc374cb9ed90000c2
6 kyu
# Introduction The goal of the kata is to connect water pipes from the water source to end of the pipe line without leaking anywhere. # Task Create a function which replaces all `x` in the `map` array with one of available pipes : `┗`,`┓`,`┏`,`┛`,`━`,`┃` and returns new map as an output. The water source is loc...
reference
def connect_pipes(pipes, s, e): zipped = [] for l in map('' . join, zip(* pipes)): s1, s2 = l . find('x'), l . rfind('x') waterline = [0 if c == '.' else 9473 if i == s == s1 == s2 else 9499 if i == s == s2 else 9487 if i == s1 != s else ...
Fix the pipes
59f2e89601601434ae000055
[ "Fundamentals", "Strings", "Arrays" ]
https://www.codewars.com/kata/59f2e89601601434ae000055
5 kyu
I have the `par` value for each hole on a golf course and my stroke `score` on each hole. I have them stored as strings, because I wrote them down on a sheet of paper. Right now, I'm using those strings to calculate my golf score by hand: take the difference between my actual `score` and the `par` of the hole, and add...
reference
def golf_score_calculator(par, score): return sum(int(b) - int(a) for a, b in zip(par, score))
What's my golf score?
59f7a0a77eb74bf96b00006a
[ "Strings", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/59f7a0a77eb74bf96b00006a
7 kyu
Consider an array that has no prime numbers, and none of its elements has any prime digit. It would start with: `[1,4,6,8,9,10,14,16,18,40,44..]`. `12` and `15` are not in the list because `2` and `5` are primes. You will be given an integer `n` and your task will be return the number at that index in the array. Fo...
algorithms
from gmpy2 import is_prime as ip def solve(n): a = 1 while n > - 1: if not ip(a) and all(i not in '2357' for i in str(a)): n -= 1 a += 1 return a - 1
Life without primes
59f8750ac374cba8f0000033
[ "Algorithms" ]
https://www.codewars.com/kata/59f8750ac374cba8f0000033
6 kyu
A trick I learned in elementary school to determine whether or not a number was divisible by three is to add all of the integers in the number together and to divide the resulting sum by three. If there is no remainder from dividing the sum by three, then the original number is divisible by three as well. Given a seri...
reference
def divisible_by_three(st): while len(st) != 1: st = str(sum(int(n) for n in st)) return int(st) in [0, 3, 6, 9]
By 3, or not by 3? That is the question . . .
59f7fc109f0e86d705000043
[ "Arrays", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/59f7fc109f0e86d705000043
7 kyu
## Task ~~~if:javascript,python, You are at position `[0, 0]` in maze NxN and you can **only** move in one of the four cardinal directions (i.e. North, East, South, West). Return the minimal number of steps to exit position `[N-1, N-1]` *if* it is possible to reach the exit from the starting position. Otherwise, retu...
algorithms
""" Task You are at position [0, 0] in maze NxN and you can only move in one of the four cardinal directions (i.e. North, East, South, West). Return true if you can reach position [N-1, N-1] or false otherwise. Empty positions are marked .. Walls are marked W. Start and exit positions are empty in all test case...
Path Finder #2: shortest path
57658bfa28ed87ecfa00058a
[ "Algorithms" ]
https://www.codewars.com/kata/57658bfa28ed87ecfa00058a
4 kyu
Consider the numbers `6969` and `9116`. When you rotate them `180 degrees` (upside down), these numbers remain the same. To clarify, if we write them down on a paper and turn the paper upside down, the numbers will be the same. Try it and see! Some numbers such as `2` or `5` don't yield numbers when rotated. Given a r...
algorithms
REV = {'6': '9', '9': '6'} BASE = set("01869") def isReversible(n): s = str(n) return (not (set(s) - BASE) # contains only reversible characters # does not contain 6 or 9 right in the middle (only for odd number of digits) and (not len(s) % 2 or s[len(s) / / 2] not in "69") ...
Upside down numbers
59f7597716049833200001eb
[ "Algorithms" ]
https://www.codewars.com/kata/59f7597716049833200001eb
6 kyu
With regular expressions you can find information and even split the found information into parts. This will be a recognition test, although it is important to know how regular expression groups work. The assignment will be to create a regular expression that will match with (dutch) phone numbers. These phone numbers...
algorithms
first = '(?:(?:\+|00)([1-9][0-9])(?: ))?' second = '(?:((?(1)[1-9][0-9]|0[1-9][0-9]))(?: ))?' third = '([1-9][0-9]{5})' regex_str = r'^{}{}{}$' . format(first, second, third)
Regular Expressions (groups): Splitting phone numbers into their separate parts.
57a492607cb1f315ec0000bb
[ "Regular Expressions", "Parsing", "Algorithms" ]
https://www.codewars.com/kata/57a492607cb1f315ec0000bb
4 kyu
Someone was hacking the score. Each student's record is given as an array The objects in the array are given again as an array of scores for each name and total score. ex> ```javascript var array = [ ["name1", 445, ["B", "A", "A", "C", "A", "A"]], ["name2", 110, ["B", "A", "A", "A"]], ["name3", 200, ["B", "A", "A...
games
PTS = {'A': 30, 'B': 20, 'C': 10, 'D': 5} MAX_PTS = 200 HAS_BONUS = set('AB') BONUS_PTS = 20 def find_hack(arr): return [name for name, pts, card in arr if pts != min(MAX_PTS, sum(PTS . get(n, 0) for n in card) + BONUS_PTS * (len(card) > 4 and set(...
Find Cracker.
59f70440bee845599c000085
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/59f70440bee845599c000085
6 kyu
A little weird green frog speaks in a very strange variation of English: it reverses sentence, omitting all puntuation marks `, ; ( ) - ` except the final exclamation, question or period. We urgently need help with building a proper translator. To simplify the task, we always use lower-case letters. Apostrophes are fo...
reference
import re def frogify(s): return ' ' . join(' ' . join(re . findall(r'[a-z]+', sentence)[:: - 1]) + punct for sentence, punct in re . findall(r'(.*?)([.!?])', s))
Frogificator
59f6d96d27402f9329000081
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/59f6d96d27402f9329000081
6 kyu
Imagine you have a number of jobs to execute. Your workers are not permanently connected to your network, so you have to distribute all your jobs in the beginning. Luckily, you know exactly how long each job is going to take. Let ``` x = [2,3,4,6,8,2] ``` be the amount of time each of your jobs is going to take. Yo...
algorithms
def splitlist(lst): target = sum(lst) / / 2 l = len(lst) best = 0 for n in range(2 * * l): bits = bin(n)[2:]. zfill(l) tot = sum((lst[i] for i in range(l) if bits[i] == '1')) if best <= tot <= target: indices = bits best = tot a, b = [], [] for i in range(l): ...
Splitting the Workload (part I)
587387d169b6fddc16000002
[ "Algorithms" ]
https://www.codewars.com/kata/587387d169b6fddc16000002
5 kyu
This is the second part of a two-part challenge. See [part I](https://www.codewars.com/kata/587387d169b6fddc16000002) if you haven't done so already. The problem is the same, only with longer lists and larger values. Imagine you have a number of jobs to execute. Your workers are not permanently connected to your netwo...
algorithms
def splitlist(l): half = sum(l) / / 2 sums = [(0, [])] for i, n in enumerate(l): sums = sums + [(m + n, a + [i]) for m, a in sums if m + n <= half] if max(s[0] for s in sums) == half: break sums . sort(key=lambda v: abs(v[0] - half)) indices = sums[0][1] return [n for i, n i...
Splitting the Workload (part II)
586e6b54c66d18ff6c0015cd
[ "Algorithms" ]
https://www.codewars.com/kata/586e6b54c66d18ff6c0015cd
4 kyu
## Sum Even Fibonacci Numbers * Write a func named SumEvenFibonacci that takes a parameter of type int and returns a value of type int * Generate all of the Fibonacci numbers starting with 1 and 2 and ending on the highest number before exceeding the parameter's value #### Each new number in the Fibonacci sequence...
reference
def SumEvenFibonacci(limit): a, b, s = 1, 1, 0 while a <= limit: if not a % 2: s += a a, b = b, a + b return s
Sum Even Fibonacci Numbers
5926624c9b424d10390000bf
[ "Fundamentals" ]
https://www.codewars.com/kata/5926624c9b424d10390000bf
7 kyu
Consider the array `[3,6,9,12]`. If we generate all the combinations with repetition that sum to `12`, we get `5` combinations: `[12], [6,6], [3,9], [3,3,6], [3,3,3,3]`. The length of the sub-arrays (such as `[3,3,3,3]` should be less than or equal to the length of the initial array (`[3,6,9,12]`). Given an array of...
reference
from itertools import combinations_with_replacement def find(arr, n): return sum(sum(c) == n for x in range(1, len(arr) + 1) for c in combinations_with_replacement(arr, x))
Sum of integer combinations
59f3178e3640cef6d90000d5
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/59f3178e3640cef6d90000d5
6 kyu
In this Kata, you will be given an integer array and your task is to return the sum of elements occupying prime-numbered indices. ~~~if-not:fortran The first element of the array is at index `0`. ~~~ ~~~if:fortran The first element of an array is at index `1`. ~~~ Good luck! If you like this Kata, try: [Dominan...
reference
def is_prime(n): return n >= 2 and all(n % i for i in range(2, 1 + int(n * * .5))) def total(arr): return sum(n for i, n in enumerate(arr) if is_prime(i))
Sum of prime-indexed elements
59f38b033640ce9fc700015b
[ "Lists", "Fundamentals" ]
https://www.codewars.com/kata/59f38b033640ce9fc700015b
6 kyu
In this Kata, you will implement a function `count` that takes an integer and returns the number of digits in `factorial(n)`. For example, `count(5) = 3`, because `5! = 120`, and `120` has `3` digits. More examples in the test cases. Brute force is not possible. A little research will go a long way, as this is a...
algorithms
from math import * def count(n): return ceil(lgamma(n + 1) / log(10))
Factorial length
59f34ec5a01431ab7600005a
[ "Algorithms" ]
https://www.codewars.com/kata/59f34ec5a01431ab7600005a
6 kyu
The [half-life](https://en.wikipedia.org/wiki/Half-life) of a radioactive substance is the time it takes (on average) for one-half of its atoms to undergo radioactive decay. # Task Overview Given the initial quantity of a radioactive substance, the quantity remaining after a given period of time, and the period of tim...
reference
from math import log def half_life(N0, N, t): return t / log(N0 / N, 2)
Half Life
59f33b86a01431d5ae000032
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/59f33b86a01431d5ae000032
7 kyu
Given a number of points on a plane, your task is to find two points with the smallest distance between them in linearithmic [O(n log n)](http://en.wikipedia.org/wiki/Time_complexity#Linearithmic_time) time. ### Example ``` 1 2 3 4 5 6 7 8 9 1 2 . A 3 . D 4 . F 5...
algorithms
def distance(a, b): return ((b[0] - a[0]) * * 2 + (b[1] - a[1]) * * 2) * * 0.5 def iterative_closest(arr): n = len(arr) mini = ((arr[0], arr[1]), distance(arr[0], arr[1])) for i in range(n - 1): for j in range(i + 1, n): dij = distance(arr[i], arr[j]) if dij < mini[1]: mini ...
Closest pair of points in linearithmic time
5376b901424ed4f8c20002b7
[ "Algorithms", "Geometry", "Mathematics" ]
https://www.codewars.com/kata/5376b901424ed4f8c20002b7
3 kyu
Bob has a server farm crunching numbers. He has `nodes` servers in his farm. His company has a lot of work to do. The work comes as a number `workload` which indicates how many jobs there are. Bob wants his servers to get an equal number of jobs each. If that is impossible, he wants the first servers to receive more ...
algorithms
def distribute(n, w): g, (d, r) = iter(range(w)), divmod(w, n) return [[next(g) for _ in range(d + (i < r))] for i in range(n)]
Distribute server workload
59f22b3cf0a83ff3e3003d8c
[ "Arrays", "Lists", "Algorithms" ]
https://www.codewars.com/kata/59f22b3cf0a83ff3e3003d8c
6 kyu
You are given `num` (up to `15 digits`, `never less than 0`).</br> If the `length of num is even`, return `odd numbers as ints` and `even ones as strings`, based on their `position` in the given number. Strings alternate in type cases: starting in `lowercase` to `uppercase` and so on based on position. If the `length ...
reference
numbers = ("zeroZERO" * 3, "ONEone" * 3, "twoTWO" * 3, "THREEthree" * 3, "fourFOUR" * 3, "FIVEfive" * 3, "sixSIX" * 3, "SEVENseven" * 3, "eightEIGHT" * 3, "NINEnine" * 3) def conv(num): s = str(num) check = ("13579", "02468")[len(s) & 1] return '' . join(d if d in check else numbers[int(...
1 Two 3 Four 5!
59f2746e50c8c2b55d000085
[ "Algorithms" ]
https://www.codewars.com/kata/59f2746e50c8c2b55d000085
6 kyu
Given a certain array of positive and negative numbers, give the longest increasing or decreasing combination of at least 3 elements of the array. If our array is ```a = [a[0], a[1], ....a[n-1]]```: i) For the increasing case: there is a combination: ```a[i] < a[j] < a[k]..< a[p]```, such that ```0 ≤ i < j < k < ...<...
reference
from itertools import starmap, combinations from operator import lt, gt def longest_comb(arr, command): check = lt if command . startswith('<') else gt for i in range(len(arr), 2, - 1): # if all(map(check, x, x[1:])) In Python 3 result = [list(x) for x in combinations(arr, i) if all(...
Find the Longest Increasing or Decreasing Combination in an Array
5715508de1bf8174c1001832
[ "Data Structures", "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/5715508de1bf8174c1001832
5 kyu
Create a function that returns an array containing the first `l` numbers from the `n`th diagonal of [Pascal's triangle](https://en.wikipedia.org/wiki/Pascal's_triangle). `n = 0` should generate the first diagonal of the triangle (the ones). The first number in each diagonal should be `1`. If `l = 0`, return an emp...
algorithms
def generate_diagonal(d, l): result = [1] if l else [] for k in range(1, l): result . append(result[- 1] * (d + k) / / k) return result
Pascal's Diagonals
576b072359b1161a7b000a17
[ "Algorithms" ]
https://www.codewars.com/kata/576b072359b1161a7b000a17
5 kyu
Kate constantly finds herself in some kind of a maze. Help her to find a way out!. For a given maze and Kate's position find if there is a way out. Your function should return True or False. Each maze is defined as a list of strings, where each char stays for a single maze "cell". ' ' (space) can be stepped on, '#' m...
algorithms
MOVES = {(0, 1), (0, - 1), (1, 0), (- 1, 0)} def has_exit(maze): posSet = {(x, y) for x in range(len(maze)) for y in range(len(maze[x])) if maze[x][y] == 'k'} if len(posSet) != 1: raise ValueError("There shouldn't be more than one kate") seen = set(posSet) while posSet: ...
Simple maze
56bb9b7838dd34d7d8001b3c
[ "Queues", "Recursion", "Algorithms" ]
https://www.codewars.com/kata/56bb9b7838dd34d7d8001b3c
4 kyu
The following figure shows a cell grid with 6 cells (2 rows by 3 columns), each cell separated from the others by walls: +--+--+--+ | | | | +--+--+--+ | | | | +--+--+--+ This grid has 6 connectivity components of size 1. We can describe the size and number of connectivity components by the li...
algorithms
from collections import deque, Counter def fill(grid, x, y): h, w = len(grid), len(grid[x]) unexplored = deque([(x, y)]) size = 0 while unexplored: x, y = unexplored . popleft() if 0 <= x < h and 0 <= y < w and grid[x][y] == ' ': grid[x][y] = '#' unexplored . extend(((x + 1,...
Count Connectivity Components
5856f3ecf37aec45e6000091
[ "Strings", "Algorithms", "Graph Theory" ]
https://www.codewars.com/kata/5856f3ecf37aec45e6000091
3 kyu
###Instructions A time period starting from ```'hh:mm'``` lasting until ```'hh:mm'``` is stored in an array: ``` ['08:14', '11:34'] ``` A set of different time periods is then stored in a 2D Array like so, each in its own sub-array: ``` [['08:14','11:34'], ['08:16','08:18'], ['22:18','01:14'], ['09:30','10:32'], ['04:...
algorithms
def sort_time(arr): arr, s = sorted(arr, key=lambda t: t[0]), [] while arr: nextTP = next((i for i, t in enumerate( arr) if not s or t[0] >= s[- 1][1]), 0) s . append(arr . pop(nextTP)) return s
Sorting Time
57024825005264fe9200057d
[ "Sorting", "Arrays", "Algorithms", "Date Time" ]
https://www.codewars.com/kata/57024825005264fe9200057d
6 kyu
Create an OR function that takes a list of boolean values and runs OR against all of them, without ( depending on language ) the `or` keyword or the `||` operator,. There will be between `0` and `6` elements ( inclusive ). Return `None`, `nil` or a similar empty value for an empty list.
algorithms
def alt_or(lst): return any(lst) if lst else None
Alternate Logic
58f625e20290fb29c3000056
[ "Algorithms" ]
https://www.codewars.com/kata/58f625e20290fb29c3000056
7 kyu
In computing, there are two primary byte order formats: big-endian and little-endian. Big-endian is used primarily for networking (e.g., IP addresses are transmitted in big-endian) whereas little-endian is used mainly by computers with microprocessors. Here is an example (using 32-bit integers in hex format): Little-...
algorithms
def switch_endian(n, bits): out = 0 while bits > 7: bits -= 8 out <<= 8 out |= n & 255 n >>= 8 return None if n or bits else out
Endianness Conversion
56f2dd31e40b7042ad001026
[ "Algorithms" ]
https://www.codewars.com/kata/56f2dd31e40b7042ad001026
5 kyu
Four-digit palindromes start with `[1001,1111,1221,1331,1441,1551,1551,...]` and the number at position `2` is `1111`. You will be given two numbers `a` and `b`. Your task is to return the `a-digit` palindrome at position `b` if the palindromes were arranged in increasing order. Therefore, `palin(4,2) = 1111`, bec...
algorithms
def palin(length, pos): left = str(10 * * ((length - 1) / / 2) + (pos - 1)) right = left[:: - 1][length % 2:] return int(left + right)
Fixed length palindromes
59f0ee47a5e12962cb0000bf
[ "Algorithms" ]
https://www.codewars.com/kata/59f0ee47a5e12962cb0000bf
6 kyu
In this Kata, you will be given an array of numbers in which two numbers occur once and the rest occur only twice. Your task will be to return the sum of the numbers that occur only once. For example, `repeats([4,5,7,5,4,8]) = 15` because only the numbers `7` and `8` occur once, and their sum is `15`. Every other num...
algorithms
def repeats(arr): return sum([x for x in arr if arr . count(x) == 1])
Sum of array singles
59f11118a5e129e591000134
[ "Algorithms" ]
https://www.codewars.com/kata/59f11118a5e129e591000134
7 kyu
In this Kata, you will be given an array of strings and your task is to remove all consecutive duplicate letters from each string in the array. For example: * `dup(["abracadabra","allottee","assessee"]) = ["abracadabra","alote","asese"]`. * `dup(["kelless","keenness"]) = ["keles","kenes"]`. Strings will be ...
algorithms
from itertools import groupby def dup(arry): return ["" . join(c for c, grouper in groupby(i)) for i in arry]
String array duplicates
59f08f89a5e129c543000069
[ "Strings", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/59f08f89a5e129c543000069
6 kyu
The number ```1331``` is the first positive perfect cube, higher than ```1```, having all its digits odd (its cubic root is ```11```). The next one is ```3375```. In the interval [-5000, 5000] there are six pure odd digit perfect cubic numbers and are: ```[-3375,-1331, -1, 1, 1331, 3375]``` Give the numbers of this...
reference
CUBICS = [1, 1331, 3375, 35937, 59319, 357911, 753571, 5177717, 5359375, 5735339, 9393931, 17373979, 37595375, 37159393753, 99317171591, 175333911173, 397551775977, 1913551573375, 9735913353977, 11997979755957, 17171515157399, 335571975137771, 1331399339931331, 1951953359359375, 7979737131773191, 11751737113...
# 2 Sequences: Pure Odd Digit Perfect Cubic (P.O.D.P.C)
59f04228e63f8ceb92000038
[ "Mathematics", "Arrays", "Algorithms", "Logic", "Memoization", "Fundamentals" ]
https://www.codewars.com/kata/59f04228e63f8ceb92000038
6 kyu
Imagine you start on the 5th floor of a building, then travel down to the 2nd floor, then back up to the 8th floor. You have travelled a total of 3 + 6 = 9 floors of distance. Given an array representing a series of floors you must reach by elevator, return an integer representing the total distance travelled for visi...
reference
def elevator_distance(array): return sum(abs(a - b) for a, b in zip(array, array[1:]))
Elevator Distance
59f061773e532d0c87000d16
[ "Fundamentals" ]
https://www.codewars.com/kata/59f061773e532d0c87000d16
7 kyu
Odd bits are getting ready for [Bits Battles](https://www.codewars.com/kata/world-bits-war/). Therefore the `n` bits march from right to left along an `8` bits path. Once the most-significant bit reaches the left their march is done. Each step will be saved as an array of `8` integers. Return an array of all the ste...
reference
def bit_march(n: int) - > list: return [[0] * (8 - n - i) + [1] * n + [0] * i for i in range(8 - n + 1)]
Odd March Bits 8 bits
58ee4db3e479611e6f000086
[ "Bits", "Binary", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/58ee4db3e479611e6f000086
7 kyu
Your task is to implement a simple regular expression parser. We will have a parser that outputs the following AST of a regular expression: ```haskell data RegExp = Normal Char -- ^ A character that is not in "()*|." | Any -- ^ Any character | ZeroOrMore RegExp -- ^ Zero or ...
algorithms
""" GRAMMAR Root ::= Or Or ::= Str ( '|' Str )? Str ::= ZeroMul+ ZeroMul ::= Term '*'? Term ::= Normal | Any | '(' Or ')' Normal ::= [^()|*.] Any ::= '.' """ def parseRegExp(input): return Parser(input). parse() class InvalidRegex (Exception): pass class Parser (object): ...
Regular expression parser
5470c635304c127cad000f0d
[ "Parsing", "Functional Programming", "Algorithms" ]
https://www.codewars.com/kata/5470c635304c127cad000f0d
2 kyu
In this Kata, you will be given an array of numbers and a number `n`, and your task will be to determine if `any` array elements, when summed (or taken individually), are divisible by `n`. For example: * `solve([1,3,4,7,6],9) == true`, because `3 + 6` is divisible by `9` * `solve([1,2,3,4,5],10) == true` for sim...
reference
from itertools import combinations def solve(a, n): return any(sum(c) % n == 0 for i in range(len(a)) for c in combinations(a, i + 1))
Sub-array division
59eb64cba954273cd4000099
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/59eb64cba954273cd4000099
6 kyu
## Witamy! You are in Poland and want to order a drink. You need to ask "One beer please": "Jedno piwo poprosze" ``` java Translator.orderingBeers(1) = "Jedno piwo poprosze" ``` But let's say you are really thirsty and want several beers. Then you need to count in Polish. And more difficult, you need to understand t...
algorithms
def ordering_beers(beers): assert 0 <= beers < 100 units = ["", "jeden", "dwa", "trzy", "cztery", "piec", "szesc", "siedem", "osiem", "dziewiec", "dziesiec", "jedenascie", "dwanascie", "trzynascie", "czternascie", "pietnascie", "szesnascie", "siedemnascie", "osiemnascie", "dziewietnascie"] ...
Ordering Beers in Poland
54f4e56e00ecc43c6d000220
[ "Algorithms" ]
https://www.codewars.com/kata/54f4e56e00ecc43c6d000220
5 kyu
Given an **unsorted** array of 3 positive integers ```[ n1, n2, n3 ]```, determine if it is possible to form a [Pythagorean Triple](https://en.wikipedia.org/wiki/Pythagorean_triple) using those 3 integers. A [Pythagorean Triple](https://en.wikipedia.org/wiki/Pythagorean_triple) consists of arranging 3 integers, such t...
reference
def pythagorean_triple(integers): a, b, c = sorted(integers) return a * a + b * b == c * c
Pythagorean Triple
5951d30ce99cf2467e000013
[ "Algebra", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5951d30ce99cf2467e000013
8 kyu
A [Power Law](https://en.wikipedia.org/wiki/Power_law) distribution occurs whenever "a relative change in one quantity results in a proportional relative change in the other quantity." For example, if *y* = 120 when *x* = 1 and *y* = 60 when *x* = 2 (i.e. *y* halves whenever *x* doubles) then when *x* = 4, *y* = 30 and...
reference
from math import log def power_law(p1, p2, x3): (x1, y1), (x2, y2) = p1, p2 x1 += 1e-9 y1 += 1e-9 return round(y1 * (y2 / y1) * * log(x3 / x1, x2 / x1))
Power Laws
59b6ae2e5227dd0fbc000005
[ "Fundamentals" ]
https://www.codewars.com/kata/59b6ae2e5227dd0fbc000005
6 kyu
It's 9 time! I want to count from 1 to n. How many times will I use a '9'? 9, 19, 91.. will contribute one '9' each, 99, 199, 919.. wil contribute two '9's each...etc **Note:** `n` will always be a positive integer. ### Examples (input -> output) ``` 8 -> 0 9 -> 1 10 -> 1 98 -> 18 100 -> 20 ```
algorithms
def count_nines(n): num = 0 l = len(str(n)) i = l while i > 0: k = 10 * * i m = 10 * * (i - 1) num += n / / k * (i * m) n = n % k if n >= k - m: num += n % m + 1 i -= 1 return int(num)
count '9's from 1 to n
55143152820d22cdf00001bb
[ "Puzzles", "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/55143152820d22cdf00001bb
5 kyu
A rectangle is can be defined by two factors: height and width. Its area is defined as the multiplication of the two: height * width. Its perimeter is the sum of its four edges: height + height + width + width. It is possible to create rectangles of the same area but different perimeters. For example, given an area ...
algorithms
from math import sqrt def minimum_perimeter(area): a, b = 0, area while a <= sqrt(area): a += 1 if a * b == area: p = 2 * (a + b) if not area % (a + 1): b = area / (a + 1) return p
Minimum Perimeter of a Rectangle
5826f54cc60c7e5266000baf
[ "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/5826f54cc60c7e5266000baf
7 kyu
Assume you are creating a webshop and you would like to help the user in the search. You have products with brands, prices and name. You have the history of opened products (the most recently opened being the first item). Your task is to create a list of brands ordered by popularity, if two brands have the same popula...
algorithms
from collections import Counter def sorted_brands(history): brands = [x['brand'] for x in history] counter = Counter(brands) return sorted(set(brands), key=lambda x: (- counter[x], brands . index(x)))
Personalized brand list
57cb12aa40e3020bb4001d2e
[ "Algorithms" ]
https://www.codewars.com/kata/57cb12aa40e3020bb4001d2e
6 kyu
Just another day in the world of Minecraft, Steve is working on his new project -- building a beacon pyramid in front of his house. ![Beacon pyramid](http://www.minecraft101.net/reference/images/beacon_pyramid_thb.jpg) Steve has already obtained the beacon (the glass wrapped blue thingy on the top), he just needs to ...
algorithms
def blocks_to_collect(level): answer = { 'total': sum([(i + 3 + i) * * 2 for i in range(level)]), 'gold': sum([(i + 3 + i) * * 2 for i in range(0, level, 4)]), 'diamond': sum([(i + 3 + i) * * 2 for i in range(1, level, 4)]), 'emerald': sum([(i + 3 + i) * * 2 for i in range(2, le...
[Minecraft Series #1] Steve wants to build a beacon pyramid
5839cd780426f5d0ec00009a
[ "Algorithms" ]
https://www.codewars.com/kata/5839cd780426f5d0ec00009a
6 kyu
German mathematician Christian Goldbach (1690-1764) [conjectured](https://en.wikipedia.org/wiki/Goldbach%27s_conjecture) that every even number greater than 2 can be represented by the sum of two prime numbers. For example, `10` can be represented as `3+7` or `5+5`. Your job is to make the function return a list conta...
algorithms
from gmpy2 import is_prime, next_prime from functools import lru_cache is_p = lru_cache(maxsize=None)(is_prime) next_p = lru_cache(maxsize=None)(next_prime) def gen(n): prime, limit = 2, n >> 1 while prime <= limit: yield prime, n - prime prime = next_p(prime) def goldbach_partitions(...
Goldbach’s Conjecture
578dec07deaed9b17d0001b8
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/578dec07deaed9b17d0001b8
6 kyu
In this Kata, you will be given two numbers, `a` and `b`, and your task is to determine if the first number `a` is divisible by `all` the prime factors of the second number `b`. For example: `solve(15,12) = False` because `15` is not divisible by all the prime factors of `12` (which include`2`). See test cases for mor...
reference
import fractions def solve(a, b): c = fractions . gcd(a, b) while c > 1: b / /= c c = fractions . gcd(a, b) return b == 1
Simple division
59ec2d112332430ce9000005
[ "Fundamentals" ]
https://www.codewars.com/kata/59ec2d112332430ce9000005
6 kyu
The triangular numbers, ```Tn```, may be obtained by this formula: ``` T(n) = n * (n + 1) / 2 ``` We select, for example, the first ```5 (n terms)``` consecutive terms of this sequence. They will be: ```1, 3, 6, 10 and 15``` Now we want to obtain, again for example, the first ```8 (m terms)``` consecutive multiples ...
reference
import math def sum_mult_triangnum(n, m): LCM = math . lcm(* [int(i * (i + 1) / 2) for i in range(1, n + 1)]) return sum(i * LCM for i in range(1, m + 1))
Get the Sum of Multiples of Triangular Numbers
566afbfc8595f2e751000040
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/566afbfc8595f2e751000040
6 kyu
In this example you need to implement a function that sort a list of integers based on it's binary representation. The rules are simple: 1. sort the list based on the amount of 1's in the binary representation of each number. 2. if two numbers have the same amount of 1's, the shorter string goes first. (ex: "11...
algorithms
def sortByBinaryOnes(a): return sorted(a, key=lambda k: (- bin(k). count('1'), k))
Sort by binary ones
59eb28fb0a2bffafbb0000d6
[ "Arrays", "Lists", "Algorithms", "Sorting", "Binary", "Bits" ]
https://www.codewars.com/kata/59eb28fb0a2bffafbb0000d6
7 kyu
Make your strings more nerdy: Replace all 'a'/'A' with 4, 'e'/'E' with 3 and 'l' with 1 e.g. "Fundamentals" --> "Fund4m3nt41s" <!-- C# documentation --> ```if:csharp <h1>Documentation:</h1> <h2>Kata.Nerdify Method (String)</h2> Nerdifies a string. Returns a copy of the original string with 'a'/'A' characters replaced...
reference
def nerdify(txt): return txt . translate(str . maketrans("aAeEl", "44331"))
Ch4113ng3
59e9f404fc3c49ab24000112
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/59e9f404fc3c49ab24000112
7 kyu
# Fourier transformations are hard. Fouriest transformations are harder. [<img src="http://smbc-comics.com/comics/20130201.gif">](http://smbc-comics.com/comic/2013-02-01) This Kata is based on the SMBC Comic on fourier transformations (2874). (click on the comic to go to the website) A fourier transformation on a nu...
algorithms
def transform(num, base): digits = [] while num > 0: num, remainder = divmod(num, base) digits . append(remainder if remainder < 10 else "x") return digits def fouriest(i): max_fours, base, best = 0, 5, [None, None] while i >= base * * (max_fours): digits = transform(i...
Fouriest transformation
59e1254d0863c7808d0000ef
[ "Algorithms" ]
https://www.codewars.com/kata/59e1254d0863c7808d0000ef
5 kyu
Based on the well known ['Eight Queens' problem](https://en.wikipedia.org/wiki/Eight_queens_puzzle). #### Summary Your challenge is to place N queens on a chess board such that none of the queens are attacking each other. #### Details A standard 8x8 chess board has its rows (aka ranks) labelled 1-8 from bottom to top...
games
def queens(fixQ, S): def areClashing(i, x): j, y = qs[i], qs[x] return j == y or abs(i - x) == abs(j - y) def dfs(i=0): if i == iQ: return dfs(i + 1) if i == len(qs): return 1 for y in range(S): qs[i] = y if (not any(areClashing(i, ii) for ii in range(i...
N queens puzzle (with one mandatory queen position)
561bed6a31daa8df7400000e
[ "Algorithms", "Combinatorics", "Puzzles" ]
https://www.codewars.com/kata/561bed6a31daa8df7400000e
4 kyu
You live in a communal house. Each night, one room's residents are required to clean the dayroom. Your task is to make a random rota for the entire week. Write a function that takes a list/array of the current occupied rooms in the house, and returns a list of 7 random rooms. If the number of occupied rooms is equal t...
reference
import random def rota(rooms): if len(rooms) >= 7: return random . sample(rooms, 7) return [random . choice(rooms) for i in range(7)]
Create a House Cleaning Rota
56c89644b2f1981874000046
[ "Fundamentals" ]
https://www.codewars.com/kata/56c89644b2f1981874000046
6 kyu
Seven is a hungry number and its favourite food is number 9. Whenever it spots 9 through the hoops of 8, it eats it! Well, not anymore, because you are going to help the 9 by locating that particular sequence (7,8,9) in an array of digits and tell 7 to come after 9 instead. Seven "ate" nine, no more! (If 9 is not in d...
reference
import re def hungry_seven(arr): ss, s = '', '' . join(map(str, arr)) while ss != s: ss, s = s, re . sub(r'(7+)(89)', r'\2\1', s) return list(map(int, s))
Seven "ate" nine!
59e61c577905df540000016b
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/59e61c577905df540000016b
6 kyu
The pizza store wants to know how long each order will take. They know: - Prepping a pizza takes 3 mins - Cook a pizza takes 10 mins - Every salad takes 3 mins to make - Every appetizer takes 5 mins to make - There are 2 pizza ovens - 5 pizzas can fit in a oven - Prepping for a pizza must be done before it can be put ...
games
from math import ceil def order(pizzas, salads, appetizers): tp = 3 * pizzas / 2 + 10 * math . ceil(pizzas / 10) ts = 3 * salads + 5 * appetizers return max(tp, ts)
How long each order will take
59e255c07997cb248500008c
[ "Puzzles" ]
https://www.codewars.com/kata/59e255c07997cb248500008c
6 kyu
<img src="http://bestanimations.com/Science/Gears/loadinggears/loading-gears-animation-6-4.gif"/> # Kata Task You are given a list of cogs in a <a href ="https://en.wikipedia.org/wiki/Gear_train">gear train</a> Each element represents the number of teeth of that cog e.g. `[100, 50, 25]` means * 1st cog has 100 tee...
reference
def cog_RPM(cogs, n): return [ cogs[n] / cogs[0] * (- 1 if n % 2 else 1), cogs[n] / cogs[- 1] * (1 if (len(cogs) - n) % 2 else - 1), ]
Cogs 2
59e72bdcfc3c4974190000d9
[ "Fundamentals" ]
https://www.codewars.com/kata/59e72bdcfc3c4974190000d9
7 kyu
Take a look at this [pirate game](https://youtu.be/Mc6VA7Q1vXQ). Give Amaro an array to confirm his logic for the next time, when the number of pirates changes. Keep in mind that each time the pirates find a treasure, the amount of gold equals to the ```number of pirates * 20```. **Example:** If number of pirates ...
reference
def amaro_plan(pirate_num): return [1 + 39 * pirate_num / / 2, * (c % 2 for c in range(pirate_num - 1))]
Pirate Code
59e77930233243a7b7000026
[ "Puzzles", "Games", "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/59e77930233243a7b7000026
7 kyu
Background ---------- In another dimension, there exist two immortal brothers: Solomon and Goromon. As sworn loyal subjects to the time elemental, Chronixus, both Solomon and Goromon were granted the power to create temporal folds. By sliding through these temporal folds, one can gain entry to parallel dimensions where...
reference
def solomons_quest(arr): pos, lvl = [0, 0], 0 for dilat, dir, dist in arr: lvl += dilat pos[dir in [0, 2]] += dist * 2 * * lvl * (- 1) * * (dir in [2, 3]) return pos
Solomon's Quest for the Temporal Crystal
59d7c910f703c460a2000034
[ "Fundamentals" ]
https://www.codewars.com/kata/59d7c910f703c460a2000034
6 kyu
## Description Give you the number of year and month, make a monthly calendar board. ## Task Complete function `calendar()` that accepts two arguments `year` and `month`. Returns a calendar board of this month. Note: The first line is centered(see following example). ## Rules & Examples An example of `calendar...
games
from calendar import TextCalendar, month_name class MyTextCalender (TextCalendar): def formatmonthname(self, theyear, themonth, width, _=True): return f" { f' { theyear } { month_name [ themonth ]} ' : ^ { width }} " def formatweekheader(self, _): return "SUN MON TUE WED THU FRI SAT" def f...
T.T.T.56: Make a monthly calendar board
57c671eaf8392d75b9000033
[ "Puzzles", "Games", "ASCII Art" ]
https://www.codewars.com/kata/57c671eaf8392d75b9000033
5 kyu
## Description Given a string representing an integer, return a string with every sequence of ascending or descending digits reversed. Examples: ``` 123456 ---> 654321 // ascending sequence 123456 654321 ---> 123456 // descending sequence 654321 135246 ---> 531642 // ascending sequence 135, ascending seque...
games
def reverse_number(n): sub, var, s = '', 0, '-' * (n[0] == '-') for c in n . strip('-'): if len(sub) < 2: sub += c if len(sub) == 2: var = (sub[1] > sub[0]) - (sub[1] < sub[0]) continue new_var = (c > sub[- 1]) - (c < sub[- 1]) if var in (- 1, 1) and var == - new_var: s...
T.T.T.57: Reverse a number
57c786e858da9e5ed20000ea
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/57c786e858da9e5ed20000ea
5 kyu
## Description You find a treasure map that record the location of the hidden treasure: ``` [ ["X" ,"W3","E2","S3","S4"], ["S1","E1","N1","S2","W1"], ["S2","E1","N2","S1","N3"], ["N1","X" ,"S2","E1","W4"], ["X" ,"E3","X" ,"N2","W4"] ] ``` `"X"` is the place where the treasure is likely to be buried. But there are more...
games
DIRS = dict(zip('NSEW', ((- 1, 0), (1, 0), (0, 1), (0, - 1)))) def find_x(bd): X, Y = len(bd), bd and len(bd[0]) x, y = X >> 1, Y >> 1 bd = list(map(list, bd)) while 0 <= x < X and 0 <= y < Y and (d := bd[x][y]) != 'Z': if d == 'X': return x, y bd[x][y] = 'Z' (dx, dy), n...
#8: Treasure Map
57d63b45ec1670518c000259
[ "Puzzles" ]
https://www.codewars.com/kata/57d63b45ec1670518c000259
6 kyu
My third kata, write a function `check_generator` that examines the status of a Python generator expression `gen` and returns `'Created'`, `'Started'` or `'Finished'`. For example: `gen = (i for i in range(1))` >>> returns `'Created'` (the generator has been initiated) `gen = (i for i in range(1)); next(gen, None)` >...
reference
def check_generator(gen): if gen . gi_frame is None: return "Finished" if gen . gi_frame . f_lasti == - 1: return "Created" return "Started"
Check the status of the generator expression
585e6eb2eec14124ea000120
[ "Fundamentals" ]
https://www.codewars.com/kata/585e6eb2eec14124ea000120
5 kyu
# Task In a black and white image we can use `1` instead of black pixels and `0` instead of white pixels. For compression image file we can reserve pixels by consecutive pixels who have the same color. Your task is to determine how much of black and white pixels is in each row sorted by place of those. # Exa...
games
from enum import Enum class Colors (Enum): White = 0 Black = 1 class Entry: @ staticmethod def parse(amount, index): return Entry(amount, Colors((index % 2) ^ 1)) def __init__(self, amount, color): self . amount = amount self . color = color def take(self, amou...
Simple Fun #139: Black And White
58a6a56942fd72afdd000161
[ "Puzzles" ]
https://www.codewars.com/kata/58a6a56942fd72afdd000161
5 kyu
In this Kata, you will be given an array of arrays and your task will be to return the number of unique arrays that can be formed by picking exactly one element from each subarray. For example: `solve([[1,2],[4],[5,6]]) = 4`, because it results in only `4` possibilites. They are `[1,4,5],[1,4,6],[2,4,5],[2,4,6]`. `...
reference
def solve(arr): x = 1 for a in arr: x *= len(set(a)) return x
Array combinations
59e66e48fc3c499ec5000103
[ "Fundamentals" ]
https://www.codewars.com/kata/59e66e48fc3c499ec5000103
6 kyu
# Letterss of Natac In a game I just made up that doesn’t have anything to do with any other game that you may or may not have played, you collect resources on each turn and then use those resources to build settlements, roads, and cities or buy a development. Other kata about this game can be found [here](https://www....
reference
def build_or_buy(hand): d = {'bw': 'road', 'bwsg': 'settlement', 'ooogg': 'city', 'osg': 'development'} res = [] for r, build in d . items(): if all(hand . count(i) >= r . count(i) for i in set(r)): res . append(build) return res
Letterss of natac: build or buy
59e6aec2b2c32c9d8b000184
[ "Fundamentals" ]
https://www.codewars.com/kata/59e6aec2b2c32c9d8b000184
7 kyu
You are tasked with implementing a representation of [complex numbers](https://en.wikipedia.org/wiki/Complex_number). Starting with the basics, we only require to be able to: - Extract the real and imaginary parts of a complex number - Add two complex numbers - Multiply two complex numbers Since complex numbers are, ...
reference
class Complex (complex): @ property def imaginary(self): return super(). imag def __add__(self, other): return Complex(complex(self) + other) def __mul__(self, other): return Complex(complex(self) * other)
Representing complex numbers
59e5fe367905df7f5c000072
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/59e5fe367905df7f5c000072
7 kyu
Take an input string and return a string that is made up of the number of occurences of each english letter in the input followed by that letter, sorted alphabetically. The output string shouldn't contain chars missing from input (chars with 0 occurence); leave them out. An empty string, or one with no letters, should...
reference
from collections import Counter def string_letter_count(s): cnt = Counter(c for c in s . lower() if c . isalpha()) return '' . join(str(n) + c for c, n in sorted(cnt . items()))
String Letter Counting
59e19a747905df23cb000024
[ "Strings", "Sorting", "Fundamentals" ]
https://www.codewars.com/kata/59e19a747905df23cb000024
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: Complete function `findSequences`. It accepts a positive integer `n`. Your task is to find such integer sequences: <span style="background:#000000"><font...
algorithms
from math import isqrt def find_sequences(n: int) - > list[list[int]]: seq = [] for k in range(2, isqrt(2 * n) + 1): s = n - k * (k - 1) / / 2 if s % k == 0: x = s / / k seq . append(list(range(x, x + k))) return seq
Find the integer sequences
582aad136755daf91a000021
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/582aad136755daf91a000021
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
from itertools import zip_longest as zip def collatz(n): seq = [n % 10] while n > 1: n = 3 * n + 1 if n % 2 else n / / 2 seq . append(n % 10 if n > 1 else ".") return map(str, seq) def test_it(arr): return "\n" . join("|" . join(a) for a in zip(* map(collatz, arr), fillvalue="....
Thinking & Testing : Hail and Waterfall
56f167455b913928a8000c49
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/56f167455b913928a8000c49
6 kyu
An array of different positive integers is given. We should create a code that gives us the number (or the numbers) that has (or have) the highest number of divisors among other data. The function ```proc_arrInt()```, (Javascript: ```procArrInt()```) will receive an array of unsorted integers and should output a list ...
reference
def divisors(n): return sum(2 if i != n / / i else 1 for i in range(1, int(n * * 0.5) + 1) if n % i == 0) def proc_arrInt(arr): n_divs = {i: divisors(i) for i in arr} max_div = max(n_divs . values()) return [len(arr), sum(divisors(i) == 2 for i in arr), [max_div, sorted([i for i, v in n_div...
Numbers with The Highest Amount of Divisors
55ef57064cb8418a3f000061
[ "Fundamentals", "Algorithms", "Data Structures", "Mathematics", "Arrays" ]
https://www.codewars.com/kata/55ef57064cb8418a3f000061
5 kyu
Let's take an integer number, ``` start``` and let's do the iterative process described below: - we take its digits and raise each of them to a certain power, ```n```, and add all those values up. (result = ```r1```) - we repeat the same process with the value ```r1``` and so on, ```k``` times. Let's do it with ```...
reference
def sum_pow_dig_seq(num, exp, k): seq = [] for step in range(k): seq . append(num) num = sum(int(dig) * * exp for dig in str(num)) if num in seq: cycle_start = seq . index(num) cycle = seq[cycle_start:] last_term = cycle[(k - cycle_start) % len(cycle)] return [cycle_star...
Sequence of Power Digits Sum
572f32ed3bd44719f8000a54
[ "Algorithms", "Recursion", "Data Structures", "Mathematics" ]
https://www.codewars.com/kata/572f32ed3bd44719f8000a54
5 kyu
You will be given the prime factors of a number as an array. E.g: ```[2,2,2,3,3,5,5,13]``` You need to find the number, n, to which that prime factorization belongs. It will be: ``` n = 2³.3².5².13 = 23400 ``` Then, generate the divisors of this number. Your function ```get_num() or getNum()``` will receive an array ...
reference
def get_num(arr): c, n, r = 1, 1, {} arr . sort() for a in arr: n *= a r[a] = r[a] + 1 if a in r else 1 for a in r: c *= r[a] + 1 return [n, c - 1, arr[0], n / / arr[0]]
Following the Paths of Numbers Through Prime Factorization
58f301633f5066830c000092
[ "Mathematics", "Data Structures", "Fundamentals" ]
https://www.codewars.com/kata/58f301633f5066830c000092
5 kyu
## Task The prisoners from previous challenges love playing chess so they make extra plan C in communcation , it goes as follows. They distribute the 26 letters on the standard 8 x 8 chess board as shown below : <div> <img src="http://i.imgur.com/Sbdzpaa.jpg"> <img src="http://i.imgur.com/zO5VwkV.png"> </div> ...
games
D = {r: c + str(i) for l, c in zip(['vw', 'ux', 'ty', 'szabcde', 'rkjihgf', 'ql', 'pm', 'on'], 'abcdefgh') for i, r in enumerate(l, 1)} def chess_encryption(s): return '' . join(D . get(c, c) for c in s)
Chess Fun #10: Chess Encryption
58a3f0662f949eba5c00004f
[ "Puzzles" ]
https://www.codewars.com/kata/58a3f0662f949eba5c00004f
6 kyu
Johnny is working as an intern for a publishing company, and was tasked with cleaning up old code. He is working on a program that determines how many digits are in all of the page numbers in a book with pages from 1 to n (inclusive). For example, a book with 4 pages has 4 digits (one for each page), while a 12 page b...
refactoring
def page_digits(pages): total = 0 start = 0 tens = 10 while pages > start: total += pages - start start = tens - 1 tens *= 10 return total
Paginating a huge book
55905b7597175ffc1a00005a
[ "Performance", "Refactoring" ]
https://www.codewars.com/kata/55905b7597175ffc1a00005a
5 kyu
### Background In the world of investment banking, when the quantities bought and sold are so large that pricing is significant at less then the smallest available unit of 'real' currency. This is why you'll often see things quoted with a pair of buy-sell prices for a single producty that are less than a cent. Once ...
reference
class PriceDisplayFraction (object): def __init__(self, denominator=16): self . d = denominator def to_display(self, cents): return "{}/{}" . format(int(cents) / 100, int((cents % 1) * self . d)) def to_internal(self, display): cents, num = map(int, display . replace('.', ''). split('/')...
Fractions of a currency' smallest value
55c4a2a2586d8706be0000d0
[ "Fundamentals" ]
https://www.codewars.com/kata/55c4a2a2586d8706be0000d0
6 kyu
We are interested in obtaining some different features of given arrays. For that purpose we will define a ```class Array``` that will have the following methods: - ```num_elements```, will give the total of elements of the array. - ```num_values```, will give the total amount of different values of the array. - `...
reference
from collections import OrderedDict class Array (object): def __init__(self, arr=[]): self . arr = arr self . num_elements = lambda: len(self . arr) self . num_values = lambda: len(set(self . arr)) self . start_end = lambda: [self . arr[0], self . arr[- 1]] self . range_ = lambda: [mi...
Features of a Given Array
569ff2622f71816610000048
[ "Fundamentals", "Data Structures", "Algorithms", "Sorting", "Mathematics", "Logic", "Object-oriented Programming" ]
https://www.codewars.com/kata/569ff2622f71816610000048
5 kyu
Run Length Encoding is used to compress data. RLE works like this: characters = "AAAALOTOOOOFTEEEEXXXXXXT" then the encoding will store AAAA = A4 and L1 So all together: ``` python encode("AAAALOTOOOOFTEEEEXXXXXXT") == "A4L1O1T1O4F1T1E4X6T1" # or encode("HELLO WORLD") == "H1E1L2O1 1W1O1R1L1D1" # or encode("FOO+BAR") ==...
algorithms
from itertools import groupby def encode(s): return '' . join(k + str(sum(1 for _ in g)) for k, g in groupby(s))
Compress/Encode a Message with RLE (Run Length Encoding)
57d6c3fb950d84fcfb0015c8
[ "Algorithms" ]
https://www.codewars.com/kata/57d6c3fb950d84fcfb0015c8
6 kyu
<h2>Sort the Vowels!</h2> In this kata, we want to sort the vowels in a special format. <h3>Task</h3> Write a function which takes a input string <code>s</code> and return a string in the following way: <pre> <code> C| R| |O n|...
reference
def sort_vowels(s): try: return '\n' . join('|' + i if i . lower() in 'aioue' else i + '|' for i in s) except: return ''
Sort the Vowels!
59e49b2afc3c494d5d00002a
[ "Fundamentals", "Algorithms", "Strings" ]
https://www.codewars.com/kata/59e49b2afc3c494d5d00002a
7 kyu
Think in all the primes that: if ```p``` is prime and ```p < n``` , all these following numbers ``` (p + 2) ``` , ``` (p + h) ``` and ```(p + 2h)``` are all primes, being ``` h ``` an even number such that: ``` 2 <= h <= hMax ``` Your function, ```give_max_h()``` , will receive 2 arguments ``` n ``` an...
reference
from gmpy2 import next_prime as np, is_prime as ip def give_max_h(n, k): a, h, d, p, v = 2, 2, [[0, 0]], [], 0 while a < n: p, a = p + [a], np(a) while h <= k: v = sum(ip(i + 2) and ip(i + h) and ip(i + (2 * h)) for i in p) d, h, v = d + [[h, v]] if v == d[0][1] else [[h, v] ...
Primes with Two, Even and Double Even Jumps
55df9798b87f0f87d100019a
[ "Fundamentals", "Algorithms", "Mathematics", "Data Structures" ]
https://www.codewars.com/kata/55df9798b87f0f87d100019a
5 kyu