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
This kata is a harder version of http://www.codewars.com/kata/sudoku-solver/python made by @pineappleclock Write a function that will solve a 9x9 Sudoku puzzle. The function will take one argument consisting of the 2D puzzle array, with the value 0 representing an unknown square. The Sudokus tested against your funct...
algorithms
def solve(puzzle): def guessAt(): _, x, y = min((len(s), x, y) for x, row in enumerate(grid) for y, s in enumerate(row) if s) return x, y, grid[x][y]. pop() def isValid(): return all(bool(s) ^ bool(ans[x][y]) for x, row in enumerate(grid) for y, s in enumerate(row)) ...
Hard Sudoku Solver
55171d87236c880cea0004c6
[ "Algorithms", "Games", "Puzzles", "Game Solvers" ]
https://www.codewars.com/kata/55171d87236c880cea0004c6
3 kyu
<i><font size=2><u>Note:</u> This kata is the improved/corrected version of [this one](https://www.codewars.com/kata/stargate-sg-1-cute-and-fuzzy).<br>I'm not the original author but, while the former has quit codewars without correcting the bugs in his kata and letting it inconsistent with the description, the latter ...
games
def wire_DHD_SG1(grid): neighbourhood = { dx + 1j * dy for dx in range(- 1, 2) for dy in range(- 1, 2)} # Convert grid start, end, maze = 0, 0, {} for x, l in enumerate(grid . splitlines()): for y, c in enumerate(l): maze[x + 1j * y] = c if c == 'S': start = x + 1j *...
Stargate SG-1: Cute and Fuzzy (Improved version)
59669eba1b229e32a300001a
[ "Algorithms", "Data Structures", "Graph Theory" ]
https://www.codewars.com/kata/59669eba1b229e32a300001a
3 kyu
Write a function that returns the smallest distance between two factors of a number. The input will always be a number greater than one. Example: `13013` has factors: `[ 1, 7, 11, 13, 77, 91, 143, 169, 1001, 1183, 1859, 13013]` Hence the asnwer will be `2` (`=13-11`)
reference
def min_distance(n): x = [i for i in range(1, n + 1) if n % i == 0] return min(j - i for i, j in zip(x, x[1:]))
Min Factor Distance
59b8614a5227dd64dc000008
[ "Fundamentals" ]
https://www.codewars.com/kata/59b8614a5227dd64dc000008
6 kyu
Your task in this kata is to implement the function `create_number_class` which will take a string parameter `alphabet` and return a class representing a number composed of this alphabet. The class number will implement the four classical arithmetic operations (`+`, `-`, `*`, `//`), a method to convert itself to strin...
algorithms
def create_number_class(alphabet): n = len(alphabet) class Number (object): def __init__(self, s): if isinstance(s, str): v = 0 for c in s: v = v * n + alphabet . index(c) else: v = s self . value = v def __add__(self, other): return Number(self . value + ot...
Generic number class
54baad292c471514820000a3
[ "Mathematics", "Metaprogramming", "Algorithms" ]
https://www.codewars.com/kata/54baad292c471514820000a3
4 kyu
Johnny is a farmer and he annually holds a beet farmers convention "Drop the beet". Every year he takes photos of farmers handshaking. Johnny knows that no two farmers handshake more than once. He also knows that some of the possible handshake combinations may not happen. However, Johnny would like to know the minima...
algorithms
from math import sqrt, ceil def get_participants(n: int) - > int: return ceil((1 + sqrt(1 + 8 * n)) / 2) if n > 0 else 0
Handshake problem
5574835e3e404a0bed00001b
[ "Algorithms" ]
https://www.codewars.com/kata/5574835e3e404a0bed00001b
6 kyu
In this Kata you are a detective! Your job is to understand if the possible solution of a murder is true or false, the only problem is that all the information that you have about the murder are in form of a logical expression. Example: Question - is it possible that: ```(1) The butler is innocent.``` ```(2) If the ...
algorithms
def is_possible(expression): expression = expression . replace("!", "1^") expression = expression . replace("OR", "|") expression = expression . replace("AND", "&") vrs = "" . join({x for x in expression if x . islower()}) n = len(vrs) for i in range(2 * * n): if eval(expression ....
Logic Detective
5595cd8f1fc2033caa000052
[ "Algorithms", "Mathematics", "Logic" ]
https://www.codewars.com/kata/5595cd8f1fc2033caa000052
5 kyu
Oh no! The junior sensei responsible for backups has failed in his primary task! We have lost some key code, and none of it was backed up... We can't earn money to pay our bills until you fix this problem! Luckily - when it comes to development - we do things the right way in this dojo, we have lots of tests, so ...
games
class InvoicePrinter (object): @ staticmethod def get_credit_rows(invoice): return [row for row in invoice . rows if is_credit(row)] @ staticmethod def get_debit_rows(invoice): return [row for row in invoice . rows if is_debit(row)] @ staticmethod def get_free_rows(invoice): ...
Recovering from a Disk Crash - Reverse Engineering Some Lost Code!
5589d3fa7e8b653faf0000cc
[ "Reverse Engineering", "Puzzles" ]
https://www.codewars.com/kata/5589d3fa7e8b653faf0000cc
5 kyu
A twin prime is a prime number that differs from another prime number by `2`. Write a function named `is_twin_prime` which takes an `int` parameter and returns `true` if it is a twin prime, else `false`. ### Examples ``` given 5, which is prime 5 + 2 = 7, which is prime 5 - 2 = 3, which is prime hence, 5 has two pri...
reference
def isPrime(n): return all(n % p for p in [2] + list(range(3, int(n * * .5) + 1))) if n > 2 else n == 2 def is_twinprime(n): return isPrime(n) and (isPrime(n - 2) or isPrime(n + 2))
Twin Prime
59b7ae14bf10a402d40000f3
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/59b7ae14bf10a402d40000f3
6 kyu
GET TO THE CHOPPA! DO IT NOW! For this kata you must create a function that will find the shortest possible path between two nodes in a 2D grid of nodes. Details: * Your function will take three arguments: a grid of nodes, a start node, and an end node. Your function will return a list of nodes that represent, in or...
algorithms
from collections import deque def find_shortest_path(grid, start_node, end_node): if not grid: return [] w, h = len(grid), len(grid[0]) prev, bag = {start_node: None}, deque([start_node]) while bag: node = bag . popleft() if node == end_node: path = [] while node: ...
GET TO THE CHOPPA!
5573f28798d3a46a4900007a
[ "Games", "Puzzles", "Algorithms", "Graph Theory" ]
https://www.codewars.com/kata/5573f28798d3a46a4900007a
3 kyu
You are given a binary tree: ```ruby class TreeNode attr_accessor :left attr_accessor :right attr_reader :value end ``` ```haskell data TreeNode a = TreeNode { left :: Maybe (TreeNode a), right :: Maybe (TreeNode a), value :: a } deriving Show ``` ```python class Node: def __init__(self, L, R, n): ...
algorithms
from collections import deque def tree_by_levels(node): if not node: return [] res, queue = [], deque([node,]) while queue: n = queue . popleft() res . append(n . value) if n . left is not None: queue . append(n . left) if n . right is not None: queue . append(n . ...
Sort binary tree by levels
52bef5e3588c56132c0003bc
[ "Trees", "Binary Trees", "Performance", "Algorithms", "Sorting" ]
https://www.codewars.com/kata/52bef5e3588c56132c0003bc
4 kyu
# Task Write a function that accepts `msg` string and returns local tops of string from the highest to the lowest. The string's tops are from displaying the string in the below way: ``` 3 p 2 4 g ...
reference
def tops(msg): i, d, s = 1, 5, '' while i < len(msg): s += msg[i] i += d d += 4 return s[:: - 1]
String tops
59b7571bbf10a48c75000070
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/59b7571bbf10a48c75000070
6 kyu
An array is said to be `hollow` if it contains `3` or more `0`s in the middle that are preceded and followed by the same number of non-zero elements. Furthermore, all the zeroes in the array must be in the middle of the array. Write a function named `isHollow`/`is_hollow`/`IsHollow` that accepts an integer array and ...
reference
def is_hollow(x): while x and x[0] != 0 and x[- 1] != 0: x = x[1: - 1] return len(x) > 2 and set(x) == {0}
Hollow array
59b72376460387017e000062
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/59b72376460387017e000062
6 kyu
A non-empty array `a` of length `n` is called an array of all possibilities if it contains all numbers between `0` and `a.length - 1` (both inclusive). Write a function that accepts an integer array and returns `true` if the array is an array of all possibilities, else `false`. Examples: ```python [1,2,0,3] => True ...
reference
def is_all_possibilities(arr): return bool(arr) and set(arr) == set(range(len(arr)))
Possibilities Array
59b710ed70a3b7dd8f000027
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/59b710ed70a3b7dd8f000027
7 kyu
# Story Carol's boss Bob thinks he is very smart. He says he made an app which renders messages unreadable without changing any letters, only by adding some new ones, while preserving message integrity (i. e. the original message can still be retrieved). He gave some limited access to his app to Carol to challenge her...
games
def decoder(encoded, marker): ss = encoded . split(marker) return '' . join(ss[:: 2]) + '' . join(ss[1:: 2])[:: - 1]
Bob's reversing obfuscator
559ee79ab98119dd0100001d
[ "Puzzles" ]
https://www.codewars.com/kata/559ee79ab98119dd0100001d
5 kyu
Write a function that receives two strings as parameter. This strings are in the following format of date: `YYYY/MM/DD`. Your job is: Take the `years` and calculate the difference between them. ### Examples: ``` '1997/10/10' and '2015/10/10' -> 2015 - 1997 = returns 18 '2015/10/10' and '1997/10/10' -> 2015 - 1997 = r...
reference
def how_many_years(date1, date2): return abs(int(date1 . split('/')[0]) - int(date2 . split('/')[0]))
Difference between years. (Level 1)
588f5a38ec641b411200005b
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/588f5a38ec641b411200005b
7 kyu
To give credit where credit is due: This problem was taken from the ACMICPC-Northwest Regional Programming Contest. Thank you problem writers. You are helping an archaeologist decipher some runes. He knows that this ancient society used a Base 10 system, and that they never start a number with a leading zero. He's fig...
games
import re def solve_runes(runes): for d in sorted(set("0123456789") - set(runes)): toTest = runes . replace("?", d) if re . search(r'([^\d]|\b)0\d+', toTest): continue l, r = toTest . split("=") if eval(l) == eval(r): return int(d) return - 1
Find the unknown digit
546d15cebed2e10334000ed9
[ "Mathematics", "Algorithms", "Puzzles" ]
https://www.codewars.com/kata/546d15cebed2e10334000ed9
4 kyu
## Task ~~~if-not:julia 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. ~~~ ~~~if:julia You are at position [1, 1] in maze NxN and you can **only** move in ...
algorithms
def path_finder(maze): matrix = list(map(list, maze . splitlines())) stack, length = [[0, 0]], len(matrix) while len(stack): x, y = stack . pop() if matrix[x][y] == '.': matrix[x][y] = 'x' for x, y in (x, y - 1), (x, y + 1), (x - 1, y), (x + 1, y): if 0 <= x < length and 0 <= y <...
Path Finder #1: can you reach the exit?
5765870e190b1472ec0022a2
[ "Algorithms" ]
https://www.codewars.com/kata/5765870e190b1472ec0022a2
4 kyu
# Do you ever wish you could talk like Siegfried of KAOS ? ## YES, of course you do! https://en.wikipedia.org/wiki/Get_Smart <img src="https://i.imgur.com/jpjLQXW.png"/> # Task Write the function ```siegfried``` to replace the letters of a given sentence. Apply the rules using the course notes below. Each week yo...
reference
import re PATTERNS = [re . compile(r'(?i)ci|ce|c(?!h)'), re . compile(r'(?i)ph'), re . compile(r'(?i)(?<!\b[a-z]{1})(?<!\b[a-z]{2})e\b|([a-z])\1'), re . compile(r'(?i)th|w[rh]?'), re . compile(r'(?i)ou|an|ing\b|\bsm')] CHANGES = {"ci": "si", "ce": "se", "c": "k", ...
Would you believe... Talk like Siegfried
57fd6c4fa5372ead1f0004aa
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/57fd6c4fa5372ead1f0004aa
5 kyu
The [Ones' Complement](https://en.wikipedia.org/wiki/Ones%27_complement) of a binary number is the number obtained by swapping all the 0s for 1s and all the 1s for 0s. For any given binary number,formatted as a string, return the Ones' Complement of that number. ## Examples ``` "0" -> "1" "1" -> "0" "000" ->...
reference
def ones_complement(n): return n . translate(str . maketrans("01", "10"))
Ones' Complement
59b11f57f322e5da45000254
[ "Fundamentals" ]
https://www.codewars.com/kata/59b11f57f322e5da45000254
7 kyu
There is a string of 32 alphanumeric characters hidden inside a dynamically generated function, which will then be passed into your function. Your task is to recover this string and return it.
reference
def find_the_secret(f): for string in f . __code__ . co_consts: if string is not None and len(string) == 32: return string
Python Reflection: Disassembling the secret
59b5896322f6bbe260002aa0
[ "Reflection", "Fundamentals" ]
https://www.codewars.com/kata/59b5896322f6bbe260002aa0
5 kyu
Write a function which makes a list of strings representing all of the ways you can balance `n` pairs of parentheses ### Examples ```haskell balancedParens 0 -> [""] balancedParens 1 -> ["()"] balancedParens 2 -> ["()()","(())"] balancedParens 3 -> ["()()()","(())()","()(())","(()())","((()))"] ``` ```javascript bala...
algorithms
def balanced_parens(n): ''' To construct all the possible strings with n pairs of balanced parentheses this function makes use of a stack of items with the following structure: (current, left, right) Where: current is the string being constructed left is the count of '(' remaini...
All Balanced Parentheses
5426d7a2c2c7784365000783
[ "Algorithms" ]
https://www.codewars.com/kata/5426d7a2c2c7784365000783
4 kyu
Make a function **"add"** that will be able to sum elements of **list** continuously and return a new list of sums. For example: ``` add [1,2,3,4,5] == [1, 3, 6, 10, 15], because it's calculated like this : [1, 1 + 2, 1 + 2 + 3, 1 + 2 + 3 + 4, 1 + 2 + 3 + 4 + 5] ``` If you want to learn more see https://en.wikiped...
reference
from itertools import accumulate def add(lst): return list(accumulate(lst))
Sum it continuously
59b44d00bf10a439dd00006f
[ "Fundamentals", "Lists" ]
https://www.codewars.com/kata/59b44d00bf10a439dd00006f
7 kyu
### Story You were asked to write a simple validator for a company that is planning to introduce lottery betting via text messages. The same validator will be used for multiple games: e.g. 5 out of 90, 7 out of 35, etc. (`N` out of `M`) The text messages should contain exactly `N` unique numbers between `1` and `M` (...
algorithms
def validate_bet(game, text): n, m = game if set(text) <= set('1234567890, '): nums = sorted(map(int, text . replace(',', ' '). split())) if len(nums) == len(set(nums)) == n and 1 <= min(nums) < max(nums) <= m: return nums
SMS Lottery Bet Validator
59a3e2897ac7fd05f800005f
[ "Algorithms" ]
https://www.codewars.com/kata/59a3e2897ac7fd05f800005f
6 kyu
Your task is to <font size="+1">Combine two Strings</font>. But consider the rule... By the way you don't have to check errors or incorrect input values, everything is ok without bad tricks, only two input strings and as result one output string;-)... <u>And here's the rule:</u> Input Strings `a` and `b`: For every...
reference
def work_on_strings(a, b): new_a = [letter if b . lower(). count(letter . lower()) % 2 == 0 else letter . swapcase() for letter in a] new_b = [letter if a . lower(). count(letter . lower()) % 2 == 0 else letter . swapcase() for letter in b] return '' . join(new_a) + '' . join(...
Play with two Strings
56c30ad8585d9ab99b000c54
[ "Fundamentals", "Strings", "Algorithms" ]
https://www.codewars.com/kata/56c30ad8585d9ab99b000c54
5 kyu
The `depth` of an integer `n` is defined to be how many multiples of `n` it is necessary to compute before all `10` digits have appeared at least once in some multiple. example: ``` let see n=42 Multiple value digits comment 42*1 42 2,4 42*2 84 8 ...
reference
def compute_depth(n): i = 0 digits = set() while len(digits) < 10: i += 1 digits . update(str(n * i)) return i
Integer depth
59b401e24f98a813f9000026
[ "Fundamentals" ]
https://www.codewars.com/kata/59b401e24f98a813f9000026
6 kyu
A number `n` is called `prime happy` if there is at least one prime less than `n` and the `sum of all primes less than n` is evenly divisible by `n`. Write `isPrimeHappy(n)` which returns `true` if `n` is `prime happy` else `false`.
reference
def is_prime_happy(n): return n in [5, 25, 32, 71, 2745, 10623, 63201, 85868]
Prime Happy
59b2ae6b1b5ca3ca240000c1
[ "Fundamentals" ]
https://www.codewars.com/kata/59b2ae6b1b5ca3ca240000c1
6 kyu
An onion array is an array that satisfies the following condition for all values of `j` and `k`: If all of the following are `true`: * `j >= 0` * `k >= 0` * `j + k = array.length - 1` * `j != k` then: * `a[j] + a[k] <= 10` ### Examples: ``` [1, 2, 19, 4, 5] => true (as 1+5 <= 10 and 2+4 <= 10) [1, 2, 19, 4,...
reference
def is_onion_array(a): return all(a[i] + a[- i - 1] <= 10 for i in range(len(a) / / 2))
Onion array
59b2883c5e2308b54d000013
[ "Fundamentals" ]
https://www.codewars.com/kata/59b2883c5e2308b54d000013
6 kyu
You have an array or list of coordinates or points (e.g. `[ [1, 1], [3, 4], ... , [5, 2] ]`), and your task is to find the area under the graph defined by these points (limited by `x` of the first and last coordinates as left and right borders, `y = 0` as the bottom border and the graph as top border). **Notes:** -...
algorithms
def find_area(points): return sum((p2 . X - p1 . X) * (p1 . Y + p2 . Y) / 2 for p1, p2 in zip(points, points[1:]))
Find an area
59b166f0a35510270800018d
[ "Algorithms", "Graphs" ]
https://www.codewars.com/kata/59b166f0a35510270800018d
6 kyu
In this kata you have to create a domain name validator mostly compliant with RFC 1035, RFC 1123, and RFC 2181 For purposes of this kata, following rules apply: - Domain name may contain subdomains (levels), hierarchically separated by . (period) character - Domain name must not contain more than 127 levels, includin...
reference
import re def validate(domain): return re . match(''' (?=^.{,253}$) # max. length 253 chars (?!^.+\.\d+$) # TLD is not fully numerical (?=^[^-.].+[^-.]$) # doesn't start/end with '-' or '.' (?!^.+(\.-|-\.).+$) # levels don't start/end with '-' (?:[a-z\d-] # uses only allowed chars {1,63}(\.|$)) # max....
Domain name validator
5893933e1a88084be10001a3
[ "Regular Expressions", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5893933e1a88084be10001a3
5 kyu
Have you ever had to aggregate data from a report that you queried from an API? </br>I needed to aggregate my data in code recently and thought it was an interesting exercise. # This is the task: Create a Rudimentary Pivot Table function that takes in a two dimensional array and returns an aggregated two dimensiona...
algorithms
from itertools import groupby def squash(c): try: return sum(float(v) for v in c) except: return '-' def squish(idx, k, g): return [k if i == idx else squash(r) for i, r in enumerate(zip(* g))] def pivot(table, idx): def key(r): return r[idx] return [squish(id...
Rudimentary Pivot Table
55807f415ff687ecac00005f
[ "Algorithms" ]
https://www.codewars.com/kata/55807f415ff687ecac00005f
5 kyu
### Task You are given a string consisting of `"D", "P" and "C"`. A positive integer N is called DPC of this string if it satisfies the following properties: ``` For each i = 1, 2, ... , size of the string: If i-th character is "D", then N can be divided by i If i-th character is "P", then N and i should be relativ...
games
def DPC_sequence(s): from math import lcm, gcd from functools import reduce d, p, c = [], [], [] dpc, h = [d, p, c], {"D": 0, "P": 1, "C": 2} for i, e in enumerate(s): dpc[h[e]]. append(i + 1) n = reduce(lcm, d, 1) return - 1 if any(gcd(m, n) != 1 for m in p) or any(gcd(m, n)...
Simple Fun #123: DPC Sequence
58a3b7185973c23795000049
[ "Puzzles" ]
https://www.codewars.com/kata/58a3b7185973c23795000049
5 kyu
This is a very simply formulated task. Let's call an integer number `N` 'green' if `N²` ends with all of the digits of `N`. Some examples: `5` is green, because `5² = 25` and `25` ends with `5`. `11` is not green, because `11² = 121` and `121` does not end with `11`. `376` is green, because `376² = 141376` and `1413...
algorithms
GREEN = [0, 1] p, f, s = 1, 5, 6 def green(n): global p, f, s while n >= len(GREEN): q = 10 * p # f, s = f**2 % q, (1 - (s-1)**2) % q f, s = pow(f, 2, q), 2 * s - pow(s, 2, q) if s < 0: s += q GREEN . extend(sorted(n for n in (f, s) if n > p)) p = q return GREEN[n]
Last digits of N^2 == N
584dee06fe9c9aef810001e8
[ "Algorithms" ]
https://www.codewars.com/kata/584dee06fe9c9aef810001e8
4 kyu
FLAMES game is a method to find out the status of a love relationship. Entering two names will give you the outcome of a relationship between them. To get the outcome, First, cross out all letters the names have in common. Second, remove the cross out letter on both names. Third, get the count of the c...
algorithms
def show_relationship(male, female): dct = {1: 'Friendship', 2: 'Love', 3: 'Affection', 4: 'Marriage', 5: 'Enemies', 6: 'Siblings'} common_letters = set(male) & set(female) m = sum(1 for c in male if c not in common_letters) fm = sum(1 for c in female if c not in common_letters) ret...
FLAMES Game version 1
553e0c3c8b8c2e1745000005
[ "Algorithms" ]
https://www.codewars.com/kata/553e0c3c8b8c2e1745000005
6 kyu
Define a method that accepts 2 strings as parameters. The method returns the first string sorted by the second. ```ruby sort_string('foos', 'of') => 'oofs' sort_string('string', 'gnirts') => 'gnirts' sort_string('banana', 'abn') => 'aaabnn' ``` ```crystal sort_string('foos', 'of') => 'oofs' sort_string('string', 'gnir...
algorithms
def sort_string(s, ordering): answer = '' for o in ordering: answer += o * s . count(o) s = s . replace(o, '') return answer + s
A String of Sorts
536c6b8749aa8b3c2600029a
[ "Strings", "Sorting", "Algorithms" ]
https://www.codewars.com/kata/536c6b8749aa8b3c2600029a
6 kyu
In genetics a reading frame is a way to divide a sequence of nucleotides (DNA bases) into a set of consecutive non-overlapping triplets (also called codon). Each of this triplets is translated into an amino-acid during a translation process to create proteins. Input --- In a single strand of DNA you find 3 Reading fra...
reference
def decompose_single_strand(dna): return '\n' . join('Frame {}: {}' . format(k + 1, frame(dna, k)) for k in range(3)) def frame(s, k): return ' ' . join(([s[: k]] if k else []) + [s[i: i + 3] for i in range(k, len(s), 3)])
Decompose single strand DNA into 3 reading frames
57507369b0b6d1b5a60001b3
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/57507369b0b6d1b5a60001b3
7 kyu
Create a method named "rotate" that returns a given array with the elements inside the array rotated `n` spaces. If n is greater than 0 it should rotate the array to the right. If n is less than 0 it should rotate the array to the left. If n is 0, then it should return the array unchanged. Example: ``` with array [1,...
algorithms
from collections import deque def rotate(data, n): data = deque(data) data.rotate(n) return list(data)
Rotate Array
5469e0798a3502f4a90005c9
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5469e0798a3502f4a90005c9
6 kyu
In this kata, you have to define a function named **func** that will take a list as input. You must try and guess the pattern how we get the output number and return list - **[output number,binary representation,octal representation,hexadecimal representation]**, but **you must convert that specific number without bui...
games
def func(l): n = sum(l) / / len(l) return [n] + [format(n, f) for f in "box"]
Guess and convert
59affdeb7d3c9de7ca0000ec
[ "Puzzles" ]
https://www.codewars.com/kata/59affdeb7d3c9de7ca0000ec
6 kyu
The goal of this little kata to implement - addition - multiplication - power functions for Church numerals that are represented as ```haskell newtype Number = Nr (forall a. (a -> a) -> a -> a) zero :: Number zero = Nr (\ _ z -> z) succ :: Number -> Number succ (Nr a) = Nr (\ s z -> s (a s z)) one :: Number one =...
games
def add(a): return lambda b: lambda f: lambda x: a(f)(b(f)(x)) def mul(a): return lambda b: lambda f: a(b(f)) def pow(a): return lambda b: b(a)
Church numbers
546dbd81018e956b51000077
[ "Puzzles" ]
https://www.codewars.com/kata/546dbd81018e956b51000077
4 kyu
The aim is to calculate `exponential(x)` (written `exp(x)` in most math libraries) as an irreducible fraction, the numerator of this fraction having a given number of digits. We call this function `expand`, it takes two parameters, `x` of which we want to evaluate the exponential, `digits` which is the required number...
reference
from fractions import Fraction def expand(x, digit): step = 0 fact = 1 expo = Fraction(1) n = 10 * * len(str(x). split('.')[- 1]) x = Fraction(int(x * n), n) while expo . numerator < 10 * * (digit - 1): step += 1 fact *= step expo += x * * step / fact return [expo . numerator, ...
Exponentials as fractions
54f5f22a00ecc4184c000034
[ "Fundamentals" ]
https://www.codewars.com/kata/54f5f22a00ecc4184c000034
4 kyu
Write a method named `getExponent(n,p)` that returns the largest integer exponent `x` such that p<sup>x</sup> evenly divides `n`. if `p<=1` the method should return `null`/`None` (throw an `ArgumentOutOfRange` exception in C#).
reference
def get_exponent(n, p): if p > 1: x = 0 while not n % p: x += 1 n / /= p return x
Largest integer exponent
59b139d69c56e8939700009d
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/59b139d69c56e8939700009d
6 kyu
An array is called `centered-N` if some `consecutive sequence` of elements of the array sum to `N` and this sequence is preceded and followed by the same number of elements. Example: ``` [3,2,10,4,1,6,9] is centered-15 because the sequence 10,4,1 sums to 15 and the sequence is preceded by two elements [3,2] and foll...
reference
def is_centered(arr, n): l = int(len(arr) / 2) if len(arr) % 2 == 0 else int((len(arr) - 1) / 2) return any(sum(arr[i: - i]) == n for i in range(1, l + 1)) or sum(arr) == n
N-centered Array
59b06d83cf33953dbb000010
[ "Fundamentals" ]
https://www.codewars.com/kata/59b06d83cf33953dbb000010
6 kyu
Hello everyone. I have a simple challenge for you today. In mathematics, the formula for finding the sum to infinity of a geometric sequence is: <img src="http://d2fhka9tf2vaj2.cloudfront.net/tuts/122_physics/tutorial/sum-geometric-series.jpg" alt="Sum to infinity of a geometric sequence"> **ONLY IF** `-1 < r < 1` ...
reference
def sum_to_infinity(sequence): return round(sequence[0] / (1 - (sequence[1] / sequence[0])), 3) if abs(sequence[1] / sequence[0]) < 1 else "No Solutions"
Sum to infinity of a Geometric Sequence
589b137753a9a4ab5700009a
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/589b137753a9a4ab5700009a
7 kyu
We have the following recursive function: <a href="http://imgur.com/1jHY37y"><img src="http://i.imgur.com/1jHY37y.png?1" title="source: imgur.com" /></a> The 15-th term; ```f(14)``` is the first term in having more that 100 digits. In fact, ``` f(14) = 259625304657687997376908240956605987957006151436333932471895398...
reference
def something_acci(num_digits): a, b, c, d, e, f = 1, 1, 2, 2, 3, 3 count = 6 while True: sf = str(f) if len(sf) >= num_digits: return (count, len(sf)) a, b, c, d, e, f = b, c, d, e, f, d * e * f - a * b * c count += 1
Something similar to RokuLiuYeoseot- Nacci
5683838837b2d1db32000021
[ "Fundamentals", "Mathematics", "Recursion" ]
https://www.codewars.com/kata/5683838837b2d1db32000021
6 kyu
Converting a 12-hour time like "8:30 am" or "8:30 pm" to 24-hour time (like "0830" or "2030") sounds easy enough, right? Well, let's see if you can do it! You will have to define a function, which will be given an hour (always in the range of 1 to 12, inclusive), a minute (always in the range of 0 to 59, inclusive), ...
algorithms
def to24hourtime(hour, minute, period): return '%02d%02d' % (hour % 12 + 12 * (period == 'pm'), minute)
Converting 12-hour time to 24-hour time
59b0a6da44a4b7080300008a
[ "Date Time", "Algorithms" ]
https://www.codewars.com/kata/59b0a6da44a4b7080300008a
7 kyu
Converting a 24-hour time like "0830" or "2030" to a 12-hour time (like "8:30 am" or "8:30 pm") sounds easy enough, right? Well, let's see if you can do it! You will have to define a function named "to12hourtime", and you will be given a four digit time string (in "hhmm" format) as input. Your task is to return a 12...
algorithms
from datetime import datetime def to12hourtime(t): return datetime . strptime(t, '%H%M'). strftime('%I:%M %p'). lstrip('0'). lower()
Converting 24-hour time to 12-hour time
59b0ab12cf3395ef68000081
[ "Date Time", "Algorithms" ]
https://www.codewars.com/kata/59b0ab12cf3395ef68000081
7 kyu
This is the performance version of [this kata](https://www.codewars.com/kata/59afff65f1c8274f270020f5). --- Imagine two rings with numbers on them. The inner ring spins clockwise and the outer ring spins anti-clockwise. We start with both rings aligned on 0 at the top, and on each move we spin each ring by 1. How man...
reference
def spinning_rings(inner_max, outer_max): inner = inner_max outer = 1 moves = 1 while inner != outer: if outer > inner_max: jump = outer_max + 1 - outer elif inner > outer_max: jump = inner - outer_max elif inner > outer: jump = (inner - outer + 1) / / 2 elif inner...
Spinning Rings - Fidget Spinner Edition
59b0b7cd2a00d219ab0000c5
[ "Performance" ]
https://www.codewars.com/kata/59b0b7cd2a00d219ab0000c5
4 kyu
A Madhav array has the following property: ```a[0] = a[1] + a[2] = a[3] + a[4] + a[5] = a[6] + a[7] + a[8] + a[9] = ...``` Complete the function/method that returns `true` if the given array is a Madhav array, otherwise it returns `false`. *Edge cases: An array of length* `0` *or* `1` *should not be considered a Mad...
algorithms
def is_madhav_array(arr): nTerms = ((1 + 8 * len(arr)) * * .5 - 1) / 2 return (len(arr) > 1 and not nTerms % 1 and len({sum(arr[int(i * (i + 1) / / 2): int(i * (i + 1) / / 2) + i + 1]) for i in range(int(nTerms))}) == 1)
Madhav array
59b0492f7d3c9d7d4a0000bd
[ "Algorithms" ]
https://www.codewars.com/kata/59b0492f7d3c9d7d4a0000bd
6 kyu
Imagine two rings with numbers on them. The inner ring spins clockwise (decreasing by 1 each spin) and the outer ring spins counter clockwise (increasing by 1 each spin). We start with both rings aligned on 0 at the top, and on each move we spin each ring one increment. How many moves will it take before both rings sho...
reference
from itertools import count def spinning_rings(inner_max, outer_max): return next(i for i in count(1) if i % (outer_max + 1) == - i % (inner_max + 1))
Spinning Rings
59afff65f1c8274f270020f5
[ "Fundamentals" ]
https://www.codewars.com/kata/59afff65f1c8274f270020f5
7 kyu
Traditionally in FizzBuzz, multiples of 3 are replaced by "Fizz" and multiples of 5 are replaced by "Buzz". But we could also play FizzBuzz with any other integer pair `[n, m]` whose multiples are replaced with Fizz and Buzz. For a sequence of numbers, Fizzes, Buzzes and FizzBuzzes, find the numbers whose multiples a...
reference
def reverse_fizz_buzz(array): fizz = array . index( "Fizz") if "Fizz" in array else array . index("FizzBuzz") buzz = array . index( "Buzz") if "Buzz" in array else array . index("FizzBuzz") return (fizz + 1, buzz + 1)
FizzBuzz Backwards
59ad13d5589d2a1d84000020
[ "Fundamentals" ]
https://www.codewars.com/kata/59ad13d5589d2a1d84000020
6 kyu
# Kata Task Given a list of random integers, return the <span style='color:red'>Three Amigos</span>. These are 3 numbers that live next to each other in the list, and who have the **most** in common with each other by these rules: * lowest statistical <a href="https://en.wikipedia.org/wiki/Range_(statistics)">range</...
algorithms
def three_amigos(numbers): return min( ([a, b, c] for a, b, c in zip(numbers, numbers[1:], numbers[2:]) if a & 1 == b & 1 == c & 1), key=lambda triple: max(triple) - min(triple), default=[])
The Three Amigos
59922d2ab14298db2b00003a
[ "Algorithms" ]
https://www.codewars.com/kata/59922d2ab14298db2b00003a
6 kyu
Your friend Robbie has successfully created an AI that is capable of communicating in English! Robbie's almost done with the project, however the machine's output isn't working as expected. Here's a sample of a sentence that it outputs: ``` ["this","is","a","sentence"] ``` Every time that it tries to say a sentence,...
algorithms
def sentencify(words): res = ' ' . join(words) + '.' return res[0]. upper() + res[1:]
Pull your words together, man!
59ad7d2e07157af687000070
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/59ad7d2e07157af687000070
7 kyu
Write a method that takes a string as an argument and groups the number of time each character appears in the string as a hash sorted by the highest number of occurrences. The characters should be sorted alphabetically e.g: ```ruby get_char_count("cba") => {1=>["a", "b", "c"]} ``` ```python get_char_count("cba") == {...
reference
def get_char_count(s): counts = {} for c in (c . lower() for c in s if c . isalnum()): counts[c] = counts[c] + 1 if c in counts else 1 m = {} for k, v in counts . items(): m[v] = sorted(m[v] + [k]) if v in m else [k] return m
Count and Group Character Occurrences in a String
543e8390386034b63b001f31
[ "Fundamentals" ]
https://www.codewars.com/kata/543e8390386034b63b001f31
6 kyu
###Introduction The [I Ching](https://en.wikipedia.org/wiki/I_Ching) (Yijing, or Book of Changes) is an ancient Chinese book of sixty-four hexagrams. A hexagram is a figure composed of six stacked horizontal lines, where each line is either Yang (an unbroken line) or Yin (a broken line): ``` --------- ---- ---- ...
reference
l = {'one': 5, 'two': 4, 'three': 3, 'four': 2, 'five': 1, 'six': 0} y = {'hhh': '----o----', 'hht': '---- ----', 'htt': '---------', 'ttt': '----x----'} def oracle(arr): s = [''] * 6 for x in arr: s[l[x[0]]] = y['' . join(sorted(x[1:]))] return '\n' . join(s)
Oracle: Coin Method
56e60e54517a8c167e00154d
[ "Algorithms", "Arrays", "Sorting", "Games", "Fundamentals" ]
https://www.codewars.com/kata/56e60e54517a8c167e00154d
6 kyu
A factorial (of a large number) will usually contain some trailing zeros. Your job is to make a function that calculates the number of trailing zeros, in any given base. Factorial is defined like this: ```n! = 1 * 2 * 3 * 4 * ... * n-2 * n-1 * n``` Here's two examples to get you started: ```ruby trailing_zeros(15, 10...
algorithms
from collections import defaultdict def factorise(x): factors = defaultdict(int) f = 2 while f * f <= x: while x % f == 0: factors[f] += 1 x / /= f f += 2 if f != 2 else 1 if x > 1: factors[x] += 1 return factors def trailing_zeros(number, base): # every time a num...
Trailing zeros in factorials, in any given integer base
544483c6435206617a00012c
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/544483c6435206617a00012c
4 kyu
Wait long enough and a single rotten orange can turn a whole box of oranges to trash. You will be given a box of oranges. Find out how long it takes until all oranges are rotten. * a rotten orange will rot every neighboring orange (use Von Neumann neighborhood) * a box of oranges will be given to you as an `int[][] o...
reference
def calc_rot_time(box): def neighbours(z): return {z + 1j * * d for d in range(4)} time, fresh, rotten = 0, set(), set() for x, row in enumerate(box): for y, orange in enumerate(row): if orange == 1: fresh . add(x + 1j * y) if orange == 2: rotten . add(x + 1j * y) wh...
Rotten Oranges
59ac15a0570190481d000049
[ "Fundamentals" ]
https://www.codewars.com/kata/59ac15a0570190481d000049
6 kyu
A [Mersenne prime](https://en.wikipedia.org/wiki/Mersenne_prime) is a prime number that can be represented as: M<sub>n</sub> = 2<sup>n</sup> - 1. Therefore, every Mersenne prime is one less than a power of two. Write a function that will return whether the given integer `n` will produce a Mersenne prime or not. The ...
algorithms
from gmpy2 import is_prime def valid_mersenne(n): return is_prime(2 * * n - 1)
Mersenne Primes
56af6e4198909ab73200013f
[ "Algorithms" ]
https://www.codewars.com/kata/56af6e4198909ab73200013f
7 kyu
```if-not:swift Create a method that takes an array/list as an input, and outputs the index at which the sole odd number is located. This method should work with arrays with negative numbers. If there are no odd numbers in the array, then the method should output `-1`. ``` ```if:swift reate a function `oddOne` that ta...
reference
def odd_one(arr): return next((i for i, v in enumerate(arr) if v & 1), - 1)
Odder Than the Rest
5983cba828b2f1fd55000114
[ "Fundamentals" ]
https://www.codewars.com/kata/5983cba828b2f1fd55000114
7 kyu
Create a simple calculator that given a string of operators (), +, -, *, / and numbers separated by spaces returns the value of that expression Example: ```python Calculator().evaluate("2 / 2 + 3 * 4 - 6") # => 7 ``` ```ruby Calculator.new.evaluate("2 / 2 + 3 * 4 - 6") # => 7 ``` ```java Calculator.evaluate("2 / 2 + ...
algorithms
OPS = '+-*/' class Calculator: def evaluate(self, s): ''' Evaluate an expression. Converts the expression to reverse polish notation using the shunting yard algorithm, evaluating each operator as it is produced. ''' nums = [] ops, precs = [], [] for token in s . split()...
Calculator
5235c913397cbf2508000048
[ "Algorithms", "Parsing", "Logic", "Strings", "Expressions", "Basic Language Features", "Fundamentals" ]
https://www.codewars.com/kata/5235c913397cbf2508000048
3 kyu
# Summation Of Primes The sum of the primes below or equal to 10 is **2 + 3 + 5 + 7 = 17**. Find the sum of all the primes **_below or equal to the number passed in_**. From Project Euler's [Problem #10](https://projecteuler.net/problem=10 "Project Euler - Problem 10").
algorithms
from bisect import bisect def sieve(n): sieve, primes = [0] * (n + 1), [] for i in range(2, n + 1): if not sieve[i]: primes . append(i) for j in range(i * * 2, n + 1, i): sieve[j] = 1 return primes PRIMES = sieve(1000000) def summationOfPrimes(n): return sum(...
Summation Of Primes
59ab0ca4243eae9fec000088
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/59ab0ca4243eae9fec000088
6 kyu
Complete the method that returns `true` if 2 integers share **at least two** `1` bits, otherwise return `false`. For simplicity assume that all numbers are non-negative. ## Examples ``` 7 = 0111 in binary 10 = 1010 15 = 1111 ``` - `7` and `10` share only a single `1`-bit (at index 2) --> `false` - `7` and `...
reference
def shared_bits(a, b): return bin(a & b). count('1') > 1
Shared Bit Counter
58a5aeb893b79949eb0000f1
[ "Fundamentals", "Binary", "Bits" ]
https://www.codewars.com/kata/58a5aeb893b79949eb0000f1
7 kyu
Lately, feature requests have been piling up and you need a way to make global estimates of the time it would take to implement them all. If you estimate feature A to take 4 to 6 hours to implement, and feature B to take 2 to 5 hours, then in the <strong>best</strong> case it will only take you 6 (4 + 2) hours to imple...
reference
def global_estimate(estimates): x, y = map(sum, zip(* estimates)) return (x, (x + y) / 2, y)
Global estimates
59aa2cccd0a5ffdfa000005b
[ "Fundamentals" ]
https://www.codewars.com/kata/59aa2cccd0a5ffdfa000005b
7 kyu
A group of N golfers wants to play in groups of G players for D days in such a way that no golfer plays more than once with any other golfer. For example, for N=20, G=4, D=5, the solution at Wolfram MathWorld is ``` Mon: ABCD EFGH IJKL MNOP QRST Tue: AEIM BJOQ CHNT DGLS FKPR Wed: AGKO BIPT CFMS DHJR ELNQ Thu: AHLP...
reference
def valid(a): d = {} day_length = len(a[0]) group_size = len(a[0][0]) golfers = {g for p in a[0] for g in p} for day in a: if len(day) != day_length: return False for group in day: if len(group) != group_size: return False for player in group: if pla...
Social Golfer Problem Validator
556c04c72ee1147ff20000c9
[ "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/556c04c72ee1147ff20000c9
4 kyu
Given a certain array of integers, create a function that may give the minimum number that may be divisible for all the numbers of the array. This will be a harder version of ```Find The Minimum Number Divisible by integers of an array I``` This is an example that shows how many times, a brute force algorithm cannot...
reference
from fractions import gcd def min_special_mult(arr): try: arr = [abs(int(x)) for x in arr if x is not None] return reduce(lambda x, y: x * y / gcd(x, y), arr) except ValueError: invalids = [x for x in arr if isinstance(x, str) and not x . isdigit()] if len(invalids) == 1: return ...
Find The Minimum Number Divisible by Integers of an Array II
56f1b3c94d0c330e4a000e95
[ "Fundamentals", "Mathematics", "Logic" ]
https://www.codewars.com/kata/56f1b3c94d0c330e4a000e95
5 kyu
##The Brief Microsoft Excel provides a number of useful functions for counting, summing, and averaging values if they meet a certain criteria. Your task is to write three functions that work similarly to Excel's COUNTIF, SUMIF and AVERAGEIF functions. ##Specifications Each function will take the same two arguments: *...
algorithms
def parse(values, criteria): if type(criteria) in [int, float] or (type(criteria) is str and criteria[0] not in "<>"): return [item for item in values if item == criteria] rel = criteria . translate(None, "0123456789.") limit = float(criteria . translate(None, "<>=")) if rel == "<>": r...
Excel's COUNTIF, SUMIF and AVERAGEIF functions
56055244356dc5c45c00001e
[ "Algorithms" ]
https://www.codewars.com/kata/56055244356dc5c45c00001e
5 kyu
Complete the function that calculates the derivative of a polynomial. A polynomial is an expression like: `$ 3x^4 - 2x^2 + x - 10 $` ### How to calculate the derivative: * Take the exponent and multiply it with the coefficient * Reduce the exponent by 1 For example, derivative of `$ 3x^4 $` is `$ (4\cdot3)x^{4-1} = ...
reference
import re my_regexp = (r'(?P<sign>[+\-]?)' r'(?P<coeff>\d*)' r'x' r'(?:\^(?P<exp>\d+))?') def as_int(s): return int(s) if s else 1 def derivative(eq): result = '' for monom in re . finditer(my_regexp, eq): sign, coeff, exp = monom . groups() coeff, exp = map(as...
Calculate the derivative of a polynomial
56d060d90f9408fb3b000b03
[ "Mathematics" ]
https://www.codewars.com/kata/56d060d90f9408fb3b000b03
5 kyu
A country has coins with denominations ```python coins_list = d1 < d2 < · · · < dn. ``` You want to make change for n cents, using the smallest number of coins. ```python # Example 1: U.S. coins d1 = 1 d2 = 5 d3 = 10 d4 = 25 ## Optimal change for 37 cents – 1 quarter, 1 dime, 2 pennies. # Example 2: Alien Planet Z c...
algorithms
from collections import deque def loose_change(coins_list, amount_of_change): q = deque([(0, amount_of_change)]) while q: l, a = q . popleft() if a == 0: return l q . extend((l + 1, a - i) for i in coins_list if a >= i)
Loose Change (Part 2)
55722d67355421ab510001ac
[ "Algorithms" ]
https://www.codewars.com/kata/55722d67355421ab510001ac
5 kyu
Given an array (a list in Python) of integers and an integer `n`, find all occurrences of `n` in the given array and return another array containing all the index positions of `n` in the given array. If `n` is not in the given array, return an empty array `[]`. Assume that `n` and all values in the given array will a...
reference
def find_all(array, n): return [index for index, item in enumerate(array) if item == n]
Find all occurrences of an element in an array
59a9919107157a45220000e1
[ "Fundamentals" ]
https://www.codewars.com/kata/59a9919107157a45220000e1
7 kyu
# Let's play Psychic A box contains green, red, and blue balls. The total number of balls is given by `n` (`0 < n < 50`). Each ball has a mass that depends on the ball color. Green balls weigh `5kg`, red balls weigh `4kg`, and blue balls weigh `3kg`. Given the total number of balls in the box, `n`, and a total mass...
games
def Guess_it(n, m): result = [] for x in range(0, n + 1): b, r, g = 4 * n + x - m, m - 3 * n - 2 * x, x if all(y >= 0 for y in (b, r, g)): result . append([g, r, b]) return result
Become The Ultimate Phychic
55b2d9bd2d3e974dfb000030
[ "Mathematics", "Logic", "Algorithms", "Puzzles" ]
https://www.codewars.com/kata/55b2d9bd2d3e974dfb000030
5 kyu
A website named "All for Five", sells many products to registered clients that cost all the same (5 dollars, the price is not relevant). Every user receives an ```alphanumeric id code```, like ```D085```. The page tracks all the purchases, that the clients do. For each purchase of a certain client, his/her id user will...
reference
def id_best_users(* args): from collections import Counter sum_counts = Counter(sum(args, [])) common_set = set . intersection(* (set(arg) for arg in args)) common_users = [user for user, _ in sum_counts . most_common() if user in common_set] from itertools import gro...
Identifying Top Users and their Corresponding Purchases On a Website
5838b5eb1adeb6b7220000f5
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic", "Strings" ]
https://www.codewars.com/kata/5838b5eb1adeb6b7220000f5
5 kyu
Given the root of a tree with an arbitrary number of child nodes, return a list containing the nodes' data in breadth-first order (left to right, top to bottom). Child nodes are stored in a list. An empty tree is represented by an empty list. Example: ``` 1 / \ 2 3 -> [1,2,3,4,5,6,7...
reference
class Node: def __init__(self, data, child_nodes=None): self . data = data self . child_nodes = [] if child_nodes is None else child_nodes def tree_to_list(tree_root): queue = [] result = [] if tree_root: queue . append(tree_root) result . append(tree_root . data) w...
Tree to list
56ef9790740d30a7ff000199
[ "Trees", "Fundamentals" ]
https://www.codewars.com/kata/56ef9790740d30a7ff000199
5 kyu
Given a square matrix, rotate the original matrix 90 degrees clockwise... in place! This means that you are not allowed to build a rotated matrix and return it. Modify the original matrix using a temporary variable to swap elements and return it. You are allowed to use a couple scalar variables if needed. Solutions si...
algorithms
def rotate_in_place(matrix): for r, row in enumerate(zip(* matrix)): matrix[r] = list(reversed(row)) return matrix
Rotate a square matrix in place
53fe3578d5679bf04900093f
[ "Matrix", "Algorithms" ]
https://www.codewars.com/kata/53fe3578d5679bf04900093f
5 kyu
### Story Sometimes we are faced with problems when we have a big nested dictionary with which it's hard to work. Now, we need to solve this problem by writing a function that will flatten a given dictionary. ### Info Python dictionaries are a convenient data type to store and process configurations. They allow you ...
algorithms
def flatten(dictionary): result = {} for k, v in dictionary . items(): if v == {}: result[k] = "" elif isinstance(v, dict): for l, w in flatten(v). items(): result[k + '/' + l] = w else: result[k] = v return result
Let's flat them out
572cc218aedd20cc83000679
[ "Algorithms" ]
https://www.codewars.com/kata/572cc218aedd20cc83000679
6 kyu
I will give you an integer. Give me back a shape that is as long and wide as the integer. The integer will be a whole number between 1 and 50. ## Example `n = 3`, so I expect a 3x3 square back just like below as a string: ``` +++ +++ +++ ```
reference
def generateShape(integer): return '\n' . join('+' * integer for i in range(integer))
Build a square
59a96d71dbe3b06c0200009c
[ "Fundamentals", "ASCII Art" ]
https://www.codewars.com/kata/59a96d71dbe3b06c0200009c
7 kyu
Write a function which outputs the positions of matching bracket pairs. The output should be a dictionary with keys the positions of the open brackets '(' and values the corresponding positions of the closing brackets ')'. For example: input = "(first)and(second)" should return {0:6, 10:17} If brackets cannot be pair...
algorithms
def bracket_pairs(string): brackets = {} open_brackets = [] for i, c in enumerate(string): if c == '(': open_brackets . append(i) elif c == ')': if not open_brackets: return False brackets[open_brackets . pop()] = i return False if open_brackets else brackets
Pairing brackets
5708e3f53f100874b60015ff
[ "Strings", "Parsing", "Algorithms" ]
https://www.codewars.com/kata/5708e3f53f100874b60015ff
6 kyu
Kate likes to count words in text blocks. By words she means continuous sequences of English alphabetic characters (from a to z ). Here are examples: `Hello there, little user5453 374 ())$. I’d been using my sphere as a stool. Slow-moving target 839342 was hit by OMGd-63 or K4mp.` contains "words" `['Hello', 'there', ...
reference
from re import compile, finditer OMIT = {'a', 'the', 'on', 'at', 'of', 'upon', 'in', 'as'} REGEX = compile(r'[a-z]+') def word_count(s): return sum(a . group() not in OMIT for a in finditer(REGEX, s . lower()))
Count words
56b3b27cadd4ad275500000c
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/56b3b27cadd4ad275500000c
6 kyu
This kata is a continuation of [Part 1](http://www.codewars.com/kata/the-fibfusc-function-part-1). The `fibfusc` function is defined recursively as follows: fibfusc(0) = (1, 0) fibfusc(1) = (0, 1) fibfusc(2n) = ((x + y)(x - y), y(2x + 3y)), where (x, y) = fibfusc(n) fibfusc(2n + 1) = (-y(2x + 3y), (x +...
algorithms
def fibfusc(n, num_digits=None): if n < 2: return (1 - n, n) b = bin(n)[2:] x, y = fibfusc(int(b[0])) for bit in b[1:]: if bit == "1": x, y = (- y * (2 * x + 3 * y), (x + 2 * y) * (x + 4 * y)) else: x, y = ((x + y) * (x - y), y * (2 * x + 3 * y)) if num_digits: ...
The fibfusc function -- Part 2
570f1c56cd0531d88e000832
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/570f1c56cd0531d88e000832
4 kyu
The `fibfusc` function is defined recursively as follows: fibfusc(0) = (1, 0) fibfusc(1) = (0, 1) fibfusc(2n) = ((x + y)(x - y), y(2x + 3y)), where (x, y) = fibfusc(n) fibfusc(2n + 1) = (-y(2x + 3y), (x + 2y)(x + 4y)), where (x, y) = fibfusc(n) Your job is to produce the code for the `fibfusc` functio...
reference
from gmpy2 import fib def fibfusc(n): return - fib(n * 2 - 2) if n else 1, fib(n * 2)
The fibfusc function -- Part 1
570f147ccd0531d55d000788
[ "Fundamentals" ]
https://www.codewars.com/kata/570f147ccd0531d55d000788
6 kyu
The [Pell sequence](https://en.wikipedia.org/wiki/Pell_number) is the sequence of integers defined by the initial values P(0) = 0, P(1) = 1 and the recurrence relation P(n) = 2 * P(n-1) + P(n-2) The first few values of `P(n)` are 0, 1, 2, 5, 12, 29, 70, 169, 408, 985, 2378, 5741, 13860, 33461, 80782, 1...
algorithms
class Pell (object): @ staticmethod def get(n): x, y = 0, 1 for i in range(n): x, y = y, x + 2 * y return x
Pell Numbers
5818d00a559ff57a2f000082
[ "Algorithms" ]
https://www.codewars.com/kata/5818d00a559ff57a2f000082
6 kyu
### Background One way to order a nested (reddit-style) commenting system is by giving each comment a rank. Generic comments on a thread start with rank 1 and increment, so the second comment on a thread would have rank 2. A reply to comment 1 will be ranked 1.1, and a reply to comment 1.1 will be ranked 1.1.1 . The ...
algorithms
from distutils . version import LooseVersion def sort_ranks(ranks): return sorted(ranks, key=LooseVersion)
Sort the comments!
58a0f18091e53d2ad1000039
[ "Sorting", "Algorithms" ]
https://www.codewars.com/kata/58a0f18091e53d2ad1000039
6 kyu
Consider the number `1176` and its square (`1176 * 1176) = 1382976`. Notice that: * the first two digits of `1176` form a prime. * the first two digits of the square `1382976` also form a prime. * the last two digits of `1176` and `1382976` are the same. Given two numbers representing a range (`a, b`), how many numb...
algorithms
ls = ['11', '13', '17', '19', '23', '29', '31', '37', '41', '43', '47', '53', '59', '61', '67', '71', '73', '79', '83', '89', '97'] def solve(a, b): i = a s = 0 while i < b: if (i * i - i) % 100 == 0 and str(i)[: 2] in ls and str(i * i)[: 2] in ls: s += 1 i += 1 return s
Last digit symmetry
59a9466f589d2af4c50001d8
[ "Algorithms" ]
https://www.codewars.com/kata/59a9466f589d2af4c50001d8
6 kyu
## Task You're given a year `n` (`1583 <= n < 10000`). You need to create a function which return `True` if `n` is a leap year and `False` otherwise. ## Restrictions Your code __mustn't__ contain: 1. `def` 2. `if` 3. `eval` or `exec` 4. `return` 5. `import` ## Note **Feel free to rate the kata when you finish it ...
games
def is_leap(y): return y % 4 == 0 and y % 100 != 0 or y % 400 == 0
Leap year (with restrictions)
5848947d59fdc010fe00023e
[ "Puzzles", "Restricted" ]
https://www.codewars.com/kata/5848947d59fdc010fe00023e
6 kyu
If we write out the digits of "60" as English words we get "sixzero"; the number of letters in "sixzero" is seven. The number of letters in "seven" is five. The number of letters in "five" is four. The number of letters in "four" is four: we have reached a stable equilibrium. Note: for integers larger than 9, write ou...
reference
NUM = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] def numbers_of_letters(n): s = '' . join(NUM[i] for i in map(int, str(n))) return [s] + (numbers_of_letters(len(s)) if len(s) != n else [])
Numbers of Letters of Numbers
599febdc3f64cd21d8000117
[ "Fundamentals" ]
https://www.codewars.com/kata/599febdc3f64cd21d8000117
6 kyu
Make a class Grid which accepts two arguments, `width` and `height` and makes a multiline string containing something like this: ``` width=10 height=10 0000000000 0000000000 0000000000 0000000000 0000000000 0000000000 0000000000 0000000000 0000000000 0000000000 ``` It has a function `plot_point` which plots an `X` o...
games
class Grid (): def __init__(self, width, height): self . cols = width self . rows = height self . body = [['0' for y in range(width)] for x in range(height)] def plot_point(self, x, y): self . body[y - 1][x - 1] = 'X' def __repr__(self): return "" . join(["{}\n" . format("" . j...
Plotting points on a grid.
587ac5616d360f6bed000088
[ "Strings", "ASCII Art", "Puzzles" ]
https://www.codewars.com/kata/587ac5616d360f6bed000088
6 kyu
Many people love dogs. Also, many people have or have had a dog, and would want to get a new dog with a similar personality as their current or previous dog, but they don't know where to look. Thankfully, you are here to help. <img src = 'https://scontent.cdninstagram.com/t51.2885-15/s320x320/e35/11909956_148541783841...
reference
from collections import defaultdict def find_similar_dogs(breed): simil = defaultdict(set) for dog, v in dogs . items(): if dog != breed: simil[len(v & dogs[breed])]. add(dog) return simil[max(simil)]
Dog recommendation system
596570c424ae4501f700003d
[ "Arrays", "Sets", "Sorting", "Fundamentals" ]
https://www.codewars.com/kata/596570c424ae4501f700003d
6 kyu
Imagine a triangle of numbers which follows this pattern: * Starting with the number "1", "1" is positioned at the top of the triangle. As this is the 1st row, it can only support a single number. * The 2nd row can support the next 2 numbers: "2" and "3" * Likewise, the 3rd row, can only support the next 3 numbers:...
algorithms
def cumulative_triangle(n): return n * (n * n + 1) / 2
Cumulative Triangle
5301329926d12b90cc000908
[ "Algorithms", "Geometry" ]
https://www.codewars.com/kata/5301329926d12b90cc000908
6 kyu
You probably know that the "mode" of a set of data is the data point that appears most frequently. Looking at the characters that make up the string `"sarsaparilla"` we can see that the letter `"a"` appears four times, more than any other letter, so the mode of `"sarsaparilla"` is `"a"`. But do you know what happens w...
reference
from collections import Counter def modes(data): cnts = Counter(data) mx, mn = max(cnts . values()), min(cnts . values()) return sorted([k for k in cnts if cnts[k] == mx and cnts[k] != mn])
Thinkful - Dictionary Drills: Multiple Modes
586f5808aa04285bc800009d
[ "Fundamentals", "Lists" ]
https://www.codewars.com/kata/586f5808aa04285bc800009d
6 kyu
The Earth has been invaded by aliens. They demand our beer and threaten to destroy the Earth if we do not supply the exact number of beers demanded. Unfortunately, the aliens only speak Morse code. Write a program to convert morse code into numbers using the following convention: 1 .---- 2 ..--- 3 ...-- 4 ....- 5 ......
reference
def morse_converter(s): it = ['-----', '.----', '..---', '...--', '....-', '.....', '-....', '--...', '---..', '----.'] return int('' . join(str(it . index(s[i: i + 5])) for i in range(0, len(s), 5)))
Alien Beer Morse Code
56dc4f570a10feaf0a000850
[ "Fundamentals" ]
https://www.codewars.com/kata/56dc4f570a10feaf0a000850
6 kyu
# Open/Closed Principle The open/closed principle states that code should be closed for modification, yet open for extension. That means you should be able to add new functionality to an object or method without altering it. One way to achieve this is by using a lambda, which by nature is lazily bound to the lexical ...
reference
def spoken(greeting): return greeting . title() + '.' def shouted(greeting): return greeting . upper() + '!' def whispered(greeting): return greeting . lower() + '.' def greet(style, msg): return style(msg)
Lambdas as a mechanism for Open/Closed
53574972e727385ad10002ca
[ "Fundamentals" ]
https://www.codewars.com/kata/53574972e727385ad10002ca
6 kyu
Well, for my first kata, I did a mess. Would you help me, please, to make my code work ? I'm sure I didn't mix the numbers, but all the rest...
bug_fixes
from math import pi def whatpimeans(alpha='abcdefghijklmnopqrstuvwxyz'): # Create a dictionnary linking alphabet to 'secret encryption' # dico = {85:'a', 24:'b',32:'c', [...],10:'z'} dico = dict(zip([85, 24, 32, 64, 11, 52, 91, 79, 78, 99, 62, 27, 74, 35, 14, 16, 66, 81, 19, 39, 13, 3...
getting started #let's piay
57c0484849324c4174000b18
[ "Debugging" ]
https://www.codewars.com/kata/57c0484849324c4174000b18
6 kyu
The objective is to write a method that takes two integer parameters and returns a single integer equal to the number of 1s in the binary representation of the greatest common divisor of the parameters. Taken from Wikipedia: "In mathematics, the greatest common divisor (gcd) of two or more integers, when at least one...
algorithms
from fractions import gcd def binary_gcd(x, y): return bin(gcd(x, y)). count('1')
Greatest Common Divisor Bitcount
54b45c37041df0caf800020f
[ "Binary", "Algorithms" ]
https://www.codewars.com/kata/54b45c37041df0caf800020f
7 kyu
# Description Your crazy uncle has found a new hobby - he will occasionally scream out random words of the same length. Since he was a renowned Computer Scientist, you think he must have some pattern to this craziness. The words seem to always have a few letters in the same place, so maybe if you find his pattern his ...
algorithms
def letter_pattern(words): return '' . join(e[0] if len(set(e)) == 1 else '*' for e in zip(* words))
Crazed Templating
58439be66f5fc42e30000076
[ "Algorithms" ]
https://www.codewars.com/kata/58439be66f5fc42e30000076
6 kyu
In this Kata you are to implement a function that parses a string which is composed from tokens of the form 'n1-n2,n3,n4-n5:n6' where 'nX' is a positive integer. Each token represent a different range: 'n1-n2' represents the range n1 to n2 (inclusive in both ends). 'n3' represents the single integer n3. 'n4-n5:n6' rep...
reference
def range_parser(string): res = [] for range_ in string . split(','): first_last, _, step = range_ . partition(':') first, _, last = first_last . partition('-') res += range(int(first), int(last or first) + 1, int(step or 1)) return res
Range Parser
57d307fb9d84633c5100007a
[ "Algorithms", "Parsing", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/57d307fb9d84633c5100007a
6 kyu
What adds up =========== Given three arrays of integers your task is to create an algorithm that finds the numbers in the first two arrays whose sum is equal to any number in the third. The return value should be an array containing the values from the argument arrays that adds up. The sort order of the resulting arra...
algorithms
def addsup(a1, a2, a3): return [[x, y, x + y] for x in a1 for y in a2 if x + y in a3]
What adds up
53cce49fdf221844de0004bd
[ "Arrays", "Searching", "Algorithms" ]
https://www.codewars.com/kata/53cce49fdf221844de0004bd
6 kyu
# Task: Write a function `get_honor` which accepts a username from someone at Codewars and returns an integer containing the user's honor. If input is invalid, raise an error. ### If you want/don't want your username to be in the tests, ask me in the discourse area. There can't be too many though because the server ma...
reference
def get_honor(username): import requests r = requests . get( 'https://www.codewars.com/api/v1/users/' + username). json()['honor'] return r
Get a User's Honor
58a9cff7ae929e4ad1000050
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/58a9cff7ae929e4ad1000050
6 kyu
# Do names have colors? *Now they do.* Make a function that takes in a name (Any string two chars or longer really, but the name is the idea) and use the ascii values of it's substrings to produce the hex value of its color! Here is how it's going to work: * The first two hexadecimal digits are the *SUM* of the valu...
algorithms
from operator import sub, mul from functools import reduce def string_color(string): if len(string) < 2: return None r = sum(map(ord, list(string))) % 256 g = reduce(mul, map(ord, list(string))) % 256 b = abs(reduce(sub, map(ord, list(string)))) % 256 return '{:02X}{:02X}{:02X}' . format(r, g,...
What Color is Your Name?
5705c699cb729350870003b7
[ "Puzzles", "Strings", "Algorithms" ]
https://www.codewars.com/kata/5705c699cb729350870003b7
6 kyu
Consider X as the <a href="https://www.mathsisfun.com/data/random-variables.html"> aleatory </a> variable that count the number of letters in a word. Write a function that, give in input an array of words (strings), calculate the <a href="https://en.wikipedia.org/wiki/Variance"> variance </a> of X. Max decimal of the v...
algorithms
from statistics import pvariance def variance(words): return round(pvariance(map(len, words)), 4)
Variance in a array of words
55f2afa960aeea545a000049
[ "Statistics", "Algorithms", "Data Science" ]
https://www.codewars.com/kata/55f2afa960aeea545a000049
6 kyu
You have to rebuild a string from an enumerated list. For this task, you have to check if input is correct beforehand. * Input must be a list of tuples * Each tuple has two elements. * Second element is an alphanumeric character. * First element is the index of this character into the reconstructed string. * Indexes s...
reference
def denumerate(enum_list): try: nums = dict(enum_list) maximum = max(nums) + 1 result = '' . join(nums[a] for a in xrange(maximum)) if result . isalnum() and len(result) == maximum: return result except (KeyError, TypeError, ValueError): pass return False
denumerate string
57197be09906af7c830016de
[ "Strings", "Sorting", "Fundamentals" ]
https://www.codewars.com/kata/57197be09906af7c830016de
6 kyu
Caesar Ciphers are one of the most basic forms of encryption. It consists of a message and a key, and it shifts the letters of the message for the value of the key. Read more about it here: https://en.wikipedia.org/wiki/Caesar_cipher ## Your task Your task is to create a function encryptor that takes 2 arguments -...
reference
from string import maketrans as mt, ascii_lowercase as lc, ascii_uppercase as uc def encryptor(key, message): key %= 26 return message . translate(mt(lc + uc, lc[key:] + lc[: key] + uc[key:] + uc[: key]))
Dbftbs Djqifs
546937989c0b6ab3c5000183
[ "Fundamentals" ]
https://www.codewars.com/kata/546937989c0b6ab3c5000183
6 kyu
Qwerty Coordinates -- Strings A typical QWERTY keyboard layout is similar to this: ``` [Q][W][E][R][T][Y][U][I][O][P] [A][S][D][F][G][H][J][K][L][;]['] [Z][X][C][V][B][N][M][,][.][?] [ ][ ][ <Space> ][ ][ ][ ] ``` (For this Kata, these are the only characters we're using) Given a list of tuples of length two, wh...
games
import re BASE = [['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P'], ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';', "'"], ['Z', 'X', 'C', 'V', 'B', 'N', 'M', ',', '.', '?'], ['', '', ' ', ' ', ' ', ' ', ' ', '', '', '']] KEYBOARD = {(x, y): BASE[y][x]. lower() for y in r...
Qwerty Coordinates -- Strings
588b72fcd0c108ef8f00009d
[ "Strings" ]
https://www.codewars.com/kata/588b72fcd0c108ef8f00009d
6 kyu
Goldbach's conjecture is one of the oldest and best-known unsolved problems in number theory and all of mathematics. It states: Every even integer greater than 2 can be expressed as the sum of two primes. For example: `6 = 3 + 3`</br> `8 = 3 + 5`</br> `10 = 3 + 7 = 5 + 5`</br> `12 = 5 + 7` Some rules for the conjec...
reference
from functools import lru_cache from gmpy2 import next_prime, is_prime next_p = lru_cache(maxsize=None)(next_prime) is_p = lru_cache(maxsize=None)(is_prime) def goldbach(even_number): result, p, mid = [], 2, even_number >> 1 while p <= mid: x = even_number - p if is_p(x): result . appen...
Goldbach's conjecture (Prime numbers)
56cf0eb69e14db4897000b97
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/56cf0eb69e14db4897000b97
6 kyu