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 function will be "insane" and can have multiple solutions. The solution only need to give one valid solution in the case of the multiple solution sodoku. It might require some sort of brute force. Consider applying algorithm with - Backtracking https://www.wikiwand.com/en/Sudoku_solving_algorithms#Backtracking - Brute Force For Sudoku rules, see the Wikipedia : http://www.wikiwand.com/en/Sudoku Used puzzle from : http://www.extremesudoku.info/sudoku.html ```python puzzle = [[5,3,0,0,7,0,0,0,0], [6,0,0,1,9,5,0,0,0], [0,9,8,0,0,0,0,6,0], [8,0,0,0,6,0,0,0,3], [4,0,0,8,0,3,0,0,1], [7,0,0,0,2,0,0,0,6], [0,6,0,0,0,0,2,8,0], [0,0,0,4,1,9,0,0,5], [0,0,0,0,8,0,0,7,9]] solve(puzzle) ``` ```ruby puzzle = [[5,3,0,0,7,0,0,0,0], [6,0,0,1,9,5,0,0,0], [0,9,8,0,0,0,0,6,0], [8,0,0,0,6,0,0,0,3], [4,0,0,8,0,3,0,0,1], [7,0,0,0,2,0,0,0,6], [0,6,0,0,0,0,2,8,0], [0,0,0,4,1,9,0,0,5], [0,0,0,0,8,0,0,7,9]] solve(puzzle) ```
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)) def filterGridSets(i, j, v): nonlocal counts counts += 1 ans[i][j] = v xS, yS = i / / 3 * 3, j / / 3 * 3 for z in range(9): for a, b in ((i, z), (z, j), (xS + z / / 3, yS + z % 3)): # in row, in col, in square grid[a][b]. discard(v) grid = [[{puzzle[x][y]} if puzzle[x][y] else {1, 2, 3, 4, 5, 6, 7, 8, 9} for y in range(9)] for x in range(9)] stk, counts, ans = [], 0, [[0] * 9 for _ in range(9)] while counts != 81: change = True while change: change = False for x in range(9): for y in range(9): if len(grid[x][y]) == 1: change = True filterGridSets(x, y, grid[x][y]. pop()) if counts == 81: break if isValid(): x, y, guess = guessAt() stk . append(([[set(s) for s in r] for r in grid], [r[:] for r in ans], x, y, guess, counts)) grid[x][y]. clear() filterGridSets(x, y, guess) else: grid, ans, x, y, guess, counts = stk . pop() grid[x][y]. discard(guess) return ans
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 took a lot of time to debug the thing and improve it (the original algorithm didn't have full coverage), so I published it on my side <font size=1>(and that will make the maintenance easier...)</font>. Enjoy!</font></i> <hr> <br> <blockquote><i>I don't even know what they look like. <br>Furling... Sounds cute and fuzzy to me.</i> <br><br>- Jonas Quinn and Jack O'Neill, "Paradise Lost".</blockquote> <br> <h1>Previously on Stargate SG-1</h1> Arriving on P4F-976, SG-1 finally come into contact with the <i>Furlings</i>, one of the four great races within the Milky Way. After several days of deliberation with the Furling Directorate, the Tauri finally have access to the knowledge they have been searching for. The Furlings, having provided assistance with the Ancient's expansion into the Milky Way, have extensive knowledge of the Stargate Network and it's components. One such component, the Dial Home Device, has caused many disasters at Stargate Command through it's absence. Thankfully, the Furlings have all the necessary blueprints for it's construction, and have handed copies over to the Tauri. After beginning mass production of the control crystals necessary for it's function, Stargate Command has hit a snag. The Ancients had designed the control crystals to function if their inner pathways are as efficient as possible - essentially, the pathways must choose the shortest path between two nodes. Stargate Command has turned to you - a software engineer - to fix their problems. <br> <h1>Your Mission</h1> Given a string containing the current state of the control crystals inner pathways (labeled as `"X"`) and its gaps (labeled as `"."`), generate the shortest path from the start node (labeled as `"S"`) to the goal node (labeled as `"G"`) and return the new pathway (labeled with `"P"` characters).<br>If no solution is possible, return the string `"Oh for crying out loud..."` (in frustration). <br> <h1>The Rules</h1> - Nodes labeled as `"X"` are not traversable. - Nodes labeled as `"."` are traversable. - A pathway can be grown in eight directions (up, down, left, right, up-left, up-right, down-left, down-right), so diagonals are possible. - Nodes labeled `"S"` and `"G"` are not to be replaced with `"P"` in the case of a solution. - The shortest path is defined as the path with the shortest euclidiean distance going from one node to the next. - If several paths are possible with the same shortest distance, return any one of them. Note that the mazes won't always be squares. <br> <b>Example #1: Valid solution</b> ``` .S... .SP.. XXX.. XXXP. .X.XX => .XPXX ..X.. .PX.. G...X G...X ``` <br> <b>Example #2: No solution</b> ``` S.... XX... ...XX => "Oh for crying out loud..." .XXX. XX..G ``` <br> <hr> <br> Note: Your solution will have to be efficient because it will have to deal with a lot of maps and big ones. Caracteristics of the random tests: * map sizes from 3x3 to 73x73 (step is 5 from one size to the other, mazes won't always be squares) * 20 random maps for each size. * Overall, 311 tests to pass with the fixed ones.
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 * y if c == 'G': end = x + 1j * y height, width = x + 1, y + 1 # Search for shortest path bag, dists, prec = {start}, {start: 0}, {start: 0} while bag: pos = bag . pop() for dz in neighbourhood: z, new_dist = pos + dz, dists[pos] + abs(dz) if new_dist >= dists . get(end, float('inf')): continue if maze . get(z, 'X') != 'X' and new_dist < dists . get(z, float('inf')): bag . add(z) prec[z], dists[z] = pos, new_dist # Reconstruct path if end not in prec: return "Oh for crying out loud..." pos = prec[end] while pos != start: maze[pos] = 'P' pos = prec[pos] return '\n' . join('' . join(maze[x + y * 1j] for y in range(width)) for x in range(height))
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 string, and a `convert_to` method which will take another class number as parameter and will return the value of the actual class number converted to the equivalent value with tha alphabet of the parameter class (return a new instance of this one). Example: ```python BinClass = create_number_class('01') HexClass = create_number_class('0123456789ABCDEF') x = BinClass('1010') y = BinClass('10') print(x+y) => '1100' isinstance(x+y, BinClass) => True print(x.convert_to(HexClass) => 'A' ``` ___Notes:___ * Only positives integers will be used (either as parameters or results of calculations). * You'll never encounter invalid calculations (divisions by zero or things like that). * Alphabets will contain at least 2 characters.
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 + other . value) def __sub__(self, other): return Number(self . value - other . value) def __mul__(self, other): return Number(self . value * other . value) def __floordiv__(self, other): return Number(self . value / / other . value) def __str__(self): ret = [] v = int(self . value) while v: (v, r) = divmod(v, n) ret . append(alphabet[r]) return '' . join(reversed(ret or alphabet[0])) def convert_to(self, cls): return cls(self . value) return Number
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 minimal amount of people that participated this year just by counting all the handshakes. Help Johnny by writing a function, that takes the amount of handshakes and returns the minimal amount of people needed to perform these handshakes (a pair of farmers handshake only once).
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 butler is innocent the murder was done outside of the kitchen.``` ```(3) The murder was done at midnight and in the kitchen.``` But to you are given only logical informations: ```(b)AND(!bOR!k)AND(n)AND(k)``` where: ``` b = the butler is innocent``` ``` k = the murder was done in the kitchen``` ``` n = the murder was done at midnight``` You can see that with k and n both = true, the poor butler can't be innocent. Why? Because if k is true and b is true then !bOR!k can't be true -> the logical expression is false. You need to write a method that take in input a String that contains a logical expression and then must return a boolean value; the method need to evaluate the logic expression and return false if the expression can't be true and true otherwise. The logic expression is always in the form with OR inside parentheses and AND outside, all the logical predicates are in lowercase (so there is a maximum of predicates) and inside parentheses. there aren't spaces or other characters except for exclamation point (that means not), parentheses and letters Same examples: ``` (p) ``` is OK ``` (P) ``` is NOT OK because P is not in lowercase ``` (pOR!q)AND(z) ``` is OK ``` (p)OR(z) ``` is NOT OK because the OR is outside parentheses ``` p ``` is NOT OK because p is outside parentheses ``` ((a)AND(b)ORc) ``` is NOT OK because parentheses can't be inside other parentheses HINT: Use the structure of the logical expression to your advantage, it is in the right shape to facilitate the resolution of the problem! HINT2: You can check the Davis-Putnam algorithm for an input to resolve this Kata, <a href="https://en.wikipedia.org/wiki/Davis%E2%80%93Putnam_algorithm">Wikipedia link</a>.
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 . translate(str . maketrans(vrs, bin(i)[2:]. zfill(n)))): return True return False
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 we will know when we have fixed things. In this kata, you must fill in the missing code, using only your whits and skill! You have been given the `InvoicePrinter` class, this collects the data that is passed onto another class for layout and eventual printing. But it seems we have lost the classes `InvoiceRow` and `Invoice` and some useful helper functions. You know what to do, get reverse engineering!
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): return [row for row in invoice . rows if not (is_debit(row) or is_credit(row))] @ staticmethod def get_sub_total(invoice): return sum([row . value for row in invoice . rows]) @ staticmethod def get_tax_total(invoice): return sum([row . value for row in invoice . rows if is_taxable(row)]) * invoice . tax_rate @ staticmethod def get_grand_total(invoice): return InvoicePrinter . get_sub_total(invoice) + InvoicePrinter . get_tax_total(invoice) @ staticmethod def generate_invoice(invoice): lines = 0 items = 0 tax_rate = round(invoice . tax_rate, 2) for row in InvoicePrinter . get_credit_rows(invoice): lines += 1 items += row . quantity yield printable_row(row, tax_rate) for row in InvoicePrinter . get_debit_rows(invoice): lines += 1 items += row . quantity yield printable_row(row, tax_rate) for row in InvoicePrinter . get_free_rows(invoice): lines += 1 items += row . quantity yield printable_row(row, tax_rate) yield ("Lines", str(lines)) yield ("Items", str(items)) yield ("Sub Total", "{:.2f}" . format(InvoicePrinter . get_sub_total(invoice))) yield ("Tax", "{:.2f}" . format(InvoicePrinter . get_tax_total(invoice))) yield ("Total", "{:.2f}" . format(InvoicePrinter . get_grand_total(invoice))) from itertools import count class InvoiceRow (object): new_id = count() def __init__(self, description, unit_cost, quantity=1, taxable=True): self . id = next(InvoiceRow . new_id) self . description = description self . quantity = quantity self . unit_cost = unit_cost self . taxable = taxable self . value = unit_cost * quantity class Invoice (object): def __init__(self, tax_rate=0.20): self . tax_rate = tax_rate self . rows = [] def add_row(self, row): self . rows . append(row) def is_debit(row): return row . value < 0 def is_credit(row): return row . value > 0 def is_taxable(row): return row . taxable def printable_cost(cost): return f" { cost : .2 f } " if cost else "Gratis" def printable_row(row, rate): if not row . taxable: rate = 0 return ( row . description, f" { row . quantity :,} ", f" { row . unit_cost :, .2 f } ", f" { rate :, .2 f } ", f" { row . quantity * row . unit_cost :, .2 f } ", f" { row . quantity * row . unit_cost * ( 1 + rate ):, .2 f } ")
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 prime twins and it is a Twin Prime. ``` ``` given 7, which is prime 7 - 2 = 5, which is prime 7 + 2 = 9. which is not prime hence, 7 has one prime twin, and it is a Twin Prime. ``` ``` given 9, which is not prime hence, 9 is not a Twin Prime ``` ``` given 953, which is prime 953 - 2 = 951, which is not prime 953 + 2 = 955, which is not prime hence, 953 is not a Twin Prime ```
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 order, the path that one must follow to get from the start node to the end node. The path must begin with the start node and end with the end node. No single node should be repeated in the path (ie. no backtracking). ````if:python ```python def find_shortest_path(grid, start_node, end_node): pass ``` ```` ````if:haskell ```haskell shortestPath :: Grid -> Pos -> Pos -> Path ``` ```` * The grid is a list of lists of nodes. Each node object has a position that indicates where in the grid the node is (it's indices). ````if:python ```python node.position.x # 2 node.position.y # 5 node.position # (2,5) node is grid[2][5] # True ``` ```` ````if:haskell ```haskell -- The following types are defined in Haskell : type Pos = (Int,Int) data Node = Passable | NotPassable -- A grid is a list of list of nodes, which are Passable / NotPassable type Grid = [[Node]] type Path = [Pos] ``` ```` * Each node may or may not be 'passable'. All nodes in a path must be passable. A node that is not passable is effectively a wall that the shortest path must go around. ````if:python ```python a_node.passable # True ``` ```` ````if:haskell ```haskell (grid !! y !! x) == Passable -- True ``` ```` * Diagonal traversals between nodes are NOT allowed in this kata. Your path must move in one of 4 directions at any given step along the path: left, right, up, or down. * Grids will always be rectangular (NxM), but they may or may not be square (NxN). * Your function must return a shortest path for grid widths and heights ranging between 0 and 200. This includes 0x0 and 200x200 grids. * 0x0 grids should return an empty path list * When more than one shortest path exists (different paths, all viable, with the same number of steps) then any one of these paths will be considered a correct answer. * Your function must be efficient enough (in terms of time complexity) to pass all the included tests within the allowed timeframe (6 seconds). ````if:python * In python, for your convenience, a `print_grid` function exists that you can use to print a grid. You can also use `print_grid` to visualize a given path on the given grid. The print_grid function has the following signature: ```python def print_grid(grid, start_node=None, end_node=None, path=None) # output without a path """ S0110 01000 01010 00010 0001E """ # output with a path """ S0110 #1### #1#1# ###1# 0001E """ ``` ```` Good luck!
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: path . append(node) node = prev[node] return path[:: - 1] x, y = node . position . x, node . position . y for i, j in (0, 1), (1, 0), (0, - 1), (- 1, 0): m, n = x + i, y + j if not (0 <= m < w and 0 <= n < h): continue next_node = grid[m][n] if next_node not in prev and next_node . passable: prev[next_node] = node bag . append(next_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): self.left = L self.right = R self.value = n ``` ```groovy class Node { Integer value Node left Node right Node(left, right, value) { this.value = value this.left = left this.right = right } } ``` ```csharp public class Node { public Node Left; public Node Right; public int Value; public Node(Node l, Node r, int v) { Left = l; Right = r; Value = v; } } ``` ```java public class Node { public Node left; public Node right; public int value; public Node(Node l, Node r, int v) { left = l; right = r; value = v; } } ``` ```javascript class Node { constructor(value, left = null, right = null) { this.value = value; this.left = left; this.right = right; } } ``` ```lambdacalc # Available in preloaded # data Tree a = Leaf | Node a Tree Tree Leaf = \ leaf _node . leaf Node = \ v l r . \ _leaf node . node v l r ``` ```c typedef struct Tree { struct Tree *left, *right; int value; } Tree; ``` ```rust struct Node { value: u32, left: Option<Box<Node>>, right: Option<Box<Node>> } ``` ```scala case class Node( left: Option[Node], right: Option[Node], value: Int ) ``` Your task is to return the list with elements from tree sorted by levels, which means the root element goes first, then root children (from left to right) are second and third, and so on. ```if:ruby Return empty array if root is `nil`. ``` ```if:haskell Return empty list if root is `Nothing`. ``` ```if:python Return empty list if root is `None`. ``` ```if:csharp Return empty list if root is 'null'. ``` ```if:java Return empty list if root is 'null'. ``` ```if:javascript Return empty array if root is `null`. ``` ```if:c Set `tree_size` to `0` if root is `NULL`. ``` ```if:lambdacalc Return empty list if root is `Leaf`. Please also provide `foldr` for your chosen list encoding. Purity is `LetRec`. ``` ```if:rust Inputs will always contain at least one node. ``` ```if:scala Inputs will always contain at least one node. ``` Example 1 - following tree: 2 8 9 1 3 4 5 Should return following list: [2,8,9,1,3,4,5] Example 2 - following tree: 1 8 4 3 5 7 Should return following list: [1,8,4,3,5,7] ```if:rust **Note**: A `Node`'s tree can be displayed via Debug: `println!("{:?}", node)` ```
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 . right) return res
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 o q 1 b f h n r z a c e i m s y d j l t x k u w v ``` The next top is always 1 character higher than the previous one. For the above example, the solution for the `abcdefghijklmnopqrstuvwxyz1234` input string is `3pgb`. - When the `msg` string is empty, return an empty string. - The input strings may be very long. Make sure your solution has good performance. Check the test cases for more samples. ~~~if:cpp ## Note Do not post an issue in my solution without checking if your returned string doesn't have some invisible characters. You read most probably outside of `msg` string. ~~~
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 returns `true` if it is a hollow array,else `false`.
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 # Includes all numbers between 0 and a.length - 1 (4 - 1 = 3) [0,1,2,2,3] => False # Doesn't include all numbers between 0 and a.length - 1 (5 - 1 = 4) [0] => True # Includes all numbers between 0 and a.length - 1 (1 - 1 = 0). ```
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, and hinted that if Carol cannot crack this simple task, she might be fired. Carol was trying to crack this code herself, but got too tired, so she came to you for help. However, she succeeded to hack Bob's app and found a data field called 'marker'. She thinks it can be helpful for cracking Bob's app. Help Carol keep her job! # Function features ## Arguments * `encoded` - the encoded string which we are trying to revert to its original form. * `marker` - a short string used in the encoding process somehow. ## Expected value Your function must decode and return the original string.
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 = returns 18 ``` At this level, you don't need validate months and days to calculate the difference.
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 figured out most of the digits as well as a few operators, but he needs your help to figure out the rest. The professor will give you a simple math expression, of the form ``` [number][op][number]=[number] ``` He has converted all of the runes he knows into digits. The only operators he knows are addition (`+`),subtraction(`-`), and multiplication (`*`), so those are the only ones that will appear. Each number will be in the range from -1000000 to 1000000, and will consist of only the digits 0-9, possibly a leading -, and maybe a few ?s. If there are ?s in an expression, they represent a digit rune that the professor doesn't know (never an operator, and never a leading -). All of the ?s in an expression will represent the same digit (0-9), and it won't be one of the other given digits in the expression. No number will begin with a 0 unless the number itself is 0, therefore 00 would not be a valid number. Given an expression, figure out the value of the rune represented by the question mark. If more than one digit works, give the lowest one. If no digit works, well, that's bad news for the professor - it means that he's got some of his runes wrong. output -1 in that case. Complete the method to solve the expression to find the value of the unknown rune. The method takes a string as a paramater repressenting the expression and will return an int value representing the unknown rune or -1 if no such rune exists. ~~~if:php **Most of the time, the professor will be able to figure out most of the runes himself, but sometimes, there may be exactly 1 rune present in the expression that the professor cannot figure out (resulting in all question marks where the digits are in the expression) so be careful ;)** ~~~
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 one of the four cardinal directions (i.e. North, East, South, West). Return `true` if you can reach position [N, N] or `false` otherwise. ~~~ * Empty positions are marked `.`. * Walls are marked `W`. * Start and exit positions are empty in all test cases. ## Path Finder Series: - [#1: can you reach the exit?](https://www.codewars.com/kata/5765870e190b1472ec0022a2) - [#2: shortest path](https://www.codewars.com/kata/57658bfa28ed87ecfa00058a) - [#3: the Alpinist](https://www.codewars.com/kata/576986639772456f6f00030c) - [#4: where are you?](https://www.codewars.com/kata/5a0573c446d8435b8e00009f) - [#5: there's someone here](https://www.codewars.com/kata/5a05969cba2a14e541000129)
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 < length: stack . append((x, y)) return matrix[length - 1][length - 1] == 'x'
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 you will learn some more rules. <div style='font-weight:bold;color:orange'>Und by ze fifz vek yu vil be speakink viz un aksent lik Siegfried viz no trubl at al!</div> <hr> # Lessons ## Week 1 * ```ci``` -> ```si``` * ```ce``` -> ```se``` * ```c``` -> ```k``` (except ```ch``` leave alone) ## Week 2 * ```ph``` -> ```f``` ## Week 3 * remove trailing ```e``` (except for all 2 and 3 letter words) * replace double letters with single letters (e.g. ```tt``` -> ```t```) ## Week 4 * ```th``` -> ```z``` * ```wr``` -> ```r``` * ```wh``` -> ```v``` * ```w``` -> ```v``` ## Week 5 * ```ou``` -> ```u``` * ```an``` -> ```un``` * ```ing``` -> ```ink``` (but only when ending words) * ```sm``` -> ```schm``` (but only when beginning words) <hr> # Notes * The transformations described in the "Lessons" are case-insensitive * The output must retain the case of the original sentence * Apply rules strictly in the order given above * Rules are cummulative. So for week 3 first apply week 1 rules, then week 2 rules, then week 3 rules
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", # Week 1 "ph": "f", # Week 2 "th": "z", "wr": "r", "wh": "v", "w": "v", # Week 4 "ou": "u", "an": "un", "ing": "ink", "sm": "schm"} # Week 5 def change(m): tok = m . group(0) rep = CHANGES . get(tok . lower(), "" if None in m . groups() else m . group()[ 0]) # default value used for week 3 only if tok[0]. isupper(): rep = rep . title() return rep def siegfried(week, txt): for n in range(week): txt = PATTERNS[n]. sub(change, txt) return txt
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" -> "111" "1001" -> "0110" "1001" -> "0110" ```
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 balancedParens(0) => [""] balancedParens(1) => ["()"] balancedParens(2) => ["()()","(())"] balancedParens(3) => ["()()()","(())()","()(())","(()())","((()))"] ``` ```java balancedParens(0) returns ArrayList<String> with element: "" balancedParens(1) returns ArrayList<String> with element: "()" balancedParens(2) returns ArrayList<String> with elements: "()()","(())" balancedParens(3) returns ArrayList<String> with elements: "()()()","(())()","()(())","(()())","((()))" ``` ```ruby balanced_parens(0) => [""] balanced_parens(1) => ["()"] balanced_parens(2) => ["()()","(())"] balanced_parens(3) => ["()()()","(())()","()(())","(()())","((()))"] ``` ```python balanced_parens(0) => [""] balanced_parens(1) => ["()"] balanced_parens(2) => ["()()","(())"] balanced_parens(3) => ["()()()","(())()","()(())","(()())","((()))"] ``` ```csharp BalancedParens(0) returns List<string> with element: "" BalancedParens(1) returns List<string> with element: "()" BalancedParens(2) returns List<string> with elements: "()()","(())" BalancedParens(3) returns List<string> with elements: "()()()","(())()","()(())","(()())","((()))" ``` ```elixir balanced_parens(0) => [""] balanced_parens(1) => ["()"] balanced_parens(2) => ["()()","(())"] balanced_parens(3) => ["()()()","(())()","()(())","(()())","((()))"] ``` ```julia balancedParens(0) --> [""] balancedParens(1) --> ["()"] balancedParens(2) --> ["()()","(())"] balancedParens(3) --> ["()()()","(())()","()(())","(()())","((()))"] ```
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 '(' remaining right is the count of ')' remaining ''' stack = [('', n, 0)] result = [] # Loop until we run out of items in the stack while stack: current, left, right = stack . pop() # if no '(' or ')' left to add, add current to the result if left == 0 and right == 0: result . append(current) # if we can, add a '(' and return to the stack if left > 0: stack . append((current + '(', left - 1, right + 1)) # if we can, add a ')' and return to the stack if right > 0: stack . append((current + ')', left, right - 1)) return result
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.wikipedia.org/wiki/Prefix_sum
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` (both included), separated by a comma (`,`) and/or space(s). Any other character makes the bet invalid. ### Your task You receive the game type and the user's text message as input, and you need to check if the bet is valid or not. If it's valid, return the chosen numbers as a list, sorted in increasing order. If it's invalid, return `None`, `null`, `nil` as appropriate to your language. Note: Leading and trailing spaces will not be tested. Tabs, newlines and other whitespaces are not tested either. Think of a classic Nokia 3310 user for reference :-) ### Examples ``` validate_bet([5, 90], "1 2 3 4 5") --> [1, 2, 3, 4, 5] validate_bet([5, 90], "5 , 3, 1 4,2") --> [1, 2, 3, 4, 5] validate_bet([5, 90], "1, 2; 3, 4, 5") --> None / null / nil validate_bet([5, 90], "1, 2, 3, 4") --> None / null / nil validate_bet([5, 90], "1, 2, 3, 4, 95") --> None / null / nil ``` --- ### My other katas If you enjoyed this kata then please try [my other katas](https://www.codewars.com/users/anter69/authored)! :-) #### *Translations are welcome!*
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 character in string `a` swap the casing of every occurrence of the same character in string `b`. Then do the same casing swap with the inputs reversed. Return a single string consisting of the changed version of `a` followed by the changed version of `b`. A char of `a` is in `b` regardless if it's in upper or lower case - see the testcases too. I think that's all;-)... Some easy examples: ```` Input: "abc" and "cde" => Output: "abCCde" Input: "ab" and "aba" => Output: "aBABA" Input: "abab" and "bababa" => Output: "ABABbababa" ```` Once again for the last example - description from `KenKamau`, see discourse;-): a) swap the case of characters in string `b` for every occurrence of that character in string `a` char `'a'` occurs twice in string `a`, so we swap all `'a'` in string `b` twice. This means we start with `"bababa"` then `"bAbAbA"` => `"bababa"` char `'b'` occurs twice in string `a` and so string `b` moves as follows: start with `"bababa"` then `"BaBaBa"` => `"bababa"` b) then, swap the case of characters in string `a` for every occurrence in string `b` char `'a'` occurs `3` times in string `b`. So string `a` swaps cases as follows: start with `"abab"` then => `"AbAb"` => `"abab"` => `"AbAb"` char `'b'` occurs `3` times in string `b`. So string `a` swaps as follow: start with `"AbAb"` then => `"ABAB"` => `"AbAb"` => `"ABAB"`. c) merge new strings `a` and `b` return `"ABABbababa"` There are some static tests at the beginning and many random tests if you submit your solution. <h2><font color="red">Hope you have fun:-)!</font></h2>
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(new_b)
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 4 existed 42*3 126 1,6 2 existed 42*4 168 - all existed 42*5 210 0 2,1 existed 42*6 252 5 2 existed 42*7 294 9 2,4 existed 42*8 336 3 6 existed 42*9 378 7 3,8 existed ``` Looking at the above table under `digits` column you can find all the digits from `0` to `9`, Hence it required `9` multiples of `42` to get all the digits. So the depth of `42` is `9`. Write a function named `computeDepth` which computes the depth of its integer argument.Only positive numbers greater than zero will be passed as an input.
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, 10] => false (as 1+10 > 10) ``` Write a function named `isOnionArray`/`IsOnionArray`/`is_onion_array()` that returns `true` if its argument is an onion array and returns `false` if it is not. ~~~if:php Your solution should at least be moderately efficient. Make sure you don't do any unnecessary looping ;) ~~~
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:** - `x` can be negative; - `x` of the next pair of coordinates will **always** be greater then previous one; - `y >= 0`; - the array will contain more than 2 coordinates. ## Example ``` x=1 (left border) x=5 (right border) | x,y | | /\ | | / \ | | x,y / \ | | /\ / \ | | / \ x,y / \ | | / \ /\ / \ | |/ \/ \ / \ | |x,y x,y \/ \ | | x,y \ | |_____________________________ \x,y_____ y=0 (bottom border) ``` The required area: ``` | | | /\ | | /\\\ | | /\\\\\ | | /\ /\\\\\\\ | | /\\\ /\\\\\\\\\ | | /\\\\\ /\ /\\\\\\\\\\\ | |/\\\\\\\/\\\ /\\\\\\\\\\\\\ | |\\\\\\\\\\\\\/\\\\\\\\\\\\\\\ | |\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ | |\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\| ``` --- ## Definition of points ```csharp public class Point { public Point(double x, double y) { X = x; Y = y; } public double X { get; set; } public double Y { get; set; } } ``` ```fsharp type Point = { X: float; Y: float } ``` ```javascript var Point = function (x,y) { this.X = x; this.Y = y; } ``` ```fortran type Point real(8) :: x, y end type Point ``` ```python class Point: def __init__(self, x, y): self.X = x self.Y = y ``` ```c struct Point { int x, y; }; ```
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, including [top level (TLD)](https://en.wikipedia.org/wiki/Top-level_domain) - Domain name must not be longer than 253 characters (RFC specifies 255, but 2 characters are reserved for trailing dot and null character for root level) - Level names must be composed out of lowercase and uppercase ASCII letters, digits and - (minus sign) character - Level names must not start or end with - (minus sign) character - Level names must not be longer than 63 characters - Top level (TLD) must not be fully numerical Additionally, in this kata - Domain name must contain at least one subdomain (level) apart from TLD - Top level validation must be naive - ie. TLDs nonexistent in IANA register are still considered valid as long as they adhere to the rules given above. The validation function accepts string with the full domain name and returns boolean value indicating whether the domain name is valid or not. Examples: ```python validate('codewars') == False validate('g.co') == True validate('codewars.com') == True validate('CODEWARS.COM') == True validate('sub.codewars.com') == True validate('codewars.com-') == False validate('.codewars.com') == False validate('example@codewars.com') == False validate('127.0.0.1') == False ```
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. level length 63 chars {2,127} # max. 127 levels ''', domain, re . X | re . I)
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 dimensional array based on the values of a certain column. <span style="color:red">pivot</span>(<span style="color:orange">two_dimensional_array</span>, <span style="color:orange">index_to_pivot</span>) ### Input: A report showing shopping items and their related metrics report = [ ["Item 1", "Man", "2500", "500", "Yellow"], ["Item 2", "Woman", "42", "8.4", "Blue"], ["Item 3", "Woman", "56", "11.2", "Purple"], ["Item 4", "Woman", "11", "2.2", "Yellow"], ["Item 5", "Man", "3600", "720", "Red"], ["Item 6", "Woman", "32", "6.4", "Red"], ["Item 7", "Man", "6700", "1340", "Yellow"], ["Item 8", "Woman", "25", "5", "Green"] ] The function would aggregate the data based on the an index column (in the data above, index 1 would be the column that states whether the item is for a Man or Woman). To invoke the function:</br> <span style="color:red">pivot</span>(<span style="color:orange">report</span>, <span style="color:orange">1</span>) The returned output would be also be a two dimensional array: [ ['-', 'Man', 12800.0, 2560.0, '-'], ['-', 'Woman', 166.0, 33.2, '-'] ] # Assumptions: 1. You will never be given an empty array. 2. You will never pivot on numerical columns. 3. The index given is zero indexed (index 3 means column 4). # Rules: * The function should aggregate numbers for each numerical column based on the value in the pivot column. * Numbers (floats or ints) will always be strings so they need to be parsed and returned as actual number values. * Make sure no precision is lost when floats are involed (meaning: do not round anywhere. But don't use `Decimal`: if you use it, your code won't pass the performance tests). * Any strings that aren't numbers and aren't in the index column should be overwritten with a "-". * Your returned array should be in alphabetical order according to the values you pivoted on. * Since database manipulations turn often in manipulations of big data, your code will have to be fast enough to handle some tests with arrays of 1 300 000 lines without timing out (several approaches are still possible in terms of time complexity, though be clever about what you choose to implement). </br> Good luck!
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(idx, * g) for g in groupby(sorted(table, key=key), key)]
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 relatively prime If i-th character is "C", then N should neither be divided by i nor be relatively prime with i ``` Your task is to find the smallest DPC of a given string, or return `-1` if there is no such. The result is guaranteed to be `<= 10^9`. ### Example For `s = "DDPDD"`, the result should be `20`. `"DDPDD"` means `N` should `divided by 1,2,4,5`, and `N,3` should be relatively prime. The smallest N should be `20`. ### Input/Output - `[input]` string `s` The given string - `[output]` an integer The smallest DPC of `s` or `-1` if it doesn't exist.
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) == 1 or n % m == 0 for m in c) else 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 `141376` ends with `376`. Your task is to write a function `green` that returns the `n`<sup>th</sup> green number, starting with `1` - `green (1) == 1` --- ## Input range ```if:haskell,javascript, n <= 4000 ``` ```if:java,python,csharp, n <= 5000 ```
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 characters that are left. Fourth, given the word FLAMES, with each letter, starting from the left, count up to the number you got in the previous step and return to the F on the left with each pass. Finally, the letter you land on has a word that it stands for in the acronym 'flames'. F = Friendship L = Love A = Affection M = Marriage E = Enemies S = Siblings Now, write a method, showRelationship() that takes two names, one male and one female, and that would return the relationship between them. Example of FLAMES Game Given names are NEIL and MAE, respectively. 1. E is common on NEIL and MAE. 2. Removing E from NEIL and MAE, will left NIL and MA on both names, respectively 3. NIL have 3 characters and MA have 2 characters, a total of 5 characters 4. FLAMES --> 1>F 2>L 3>A 4>M 5>E 5. E stands for "Enemies" NEIL and MAE are enemies
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) return dct . get((m + fm) % 6, 'Siblings')
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', 'gnirts') => 'gnirts' sort_string('banana', 'abn') => 'aaabnn' ``` ```javascript sortString("foos", "of") => "oofs" sortString("string", "gnirts") => "gnirts" sortString("banana", "abn") => "aaabnn" ``` ```haskell sortString "foos" "of" -> "oofs" sortString "string" "gnirts" -> "gnirts" sortString "banana" "abn" -> "aaabnn" ``` ```c sort_string("foos", "of") == "oofs" sort_string("string", "gnirts") == "gnirts" sort_string("banana", "abn") == "aaabnn" ``` ```julia sortstring("foos", "of") => "oofs" sortstring("string", "gnirts") => "gnirts" sortstring("banana", "abn") => "aaabnn" ``` ```python sort_string("foos", "of") == "oofs" sort_string("string", "gnirts") == "gnirts" sort_string("banana", "abn") == "aaabnn" ``` To elaborate, the second string defines the ordering. It is possible that in the second string characters repeat, so you should remove repeating characters, leaving only the first occurrence. Any character in the first string that does not appear in the second string should be sorted to the end of the result in original order.
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 frames, take for example the following input sequence: AGGTGACACCGCAAGCCTTATATTAGC Output --- For the output we are going to take the combinations and show them in the following manner: ```` Frame 1: AGG TGA CAC CGC AAG CCT TAT ATT AGC Frame 2: A GGT GAC ACC GCA AGC CTT ATA TTA GC Frame 3: AG GTG ACA CCG CAA GCC TTA TAT TAG C ```` For frame 1 split all of them in groups of three starting by the first base (letter). For frame 2 split all of them in groups of three starting by the second base (letter) but having the first base (letter) at the beggining. For frame 3 split all of them in groups of three starting by the third letter, but having the first and second bases (letters) at the beginning in the same order. Series --- 1. [Decompose single strand DNA into 3 reading frames](http://www.codewars.com/kata/57507369b0b6d1b5a60001b3) 2. [Decompose double strand DNA into 6 reading frames](http://www.codewars.com/kata/57519060f2dac7ec95000c8e/) 3. [Translate DNA to protein in 6 frames](http://www.codewars.com/kata/5708ef48fe2d018413000776)
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, 2, 3, 4, 5] n = 1 => [5, 1, 2, 3, 4] n = 2 => [4, 5, 1, 2, 3] n = 3 => [3, 4, 5, 1, 2] n = 4 => [2, 3, 4, 5, 1] n = 5 => [1, 2, 3, 4, 5] n = 0 => [1, 2, 3, 4, 5] n = -1 => [2, 3, 4, 5, 1] n = -2 => [3, 4, 5, 1, 2] n = -3 => [4, 5, 1, 2, 3] n = -4 => [5, 1, 2, 3, 4] n = -5 => [1, 2, 3, 4, 5] ``` The rotation shouldn't be limited by the indices available in the array. Meaning that if we exceed the indices of the array it keeps rotating. Example: ``` with array [1, 2, 3, 4, 5] n = 7 => [4, 5, 1, 2, 3] n = 11 => [5, 1, 2, 3, 4] n = 12478 => [3, 4, 5, 1, 2] ```
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 built-in : bin,oct and hex functions.** Examples : ```python func([12,13,6,3,6,45,123]) returns - [29,'11101','35','1d'] func([1,9,23,43,65,31,63,99]) returns - [41,'101001','51','29'] func([2,4,6,8,10,12,14,16,18,19]) returns - [10,'1010','12','a'] ```
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 = succ zero ``` ```purescript newtype Church = Church (forall a. (a -> a) -> a -> a) zero :: Church zero = Church (\_ x -> x) succ :: Church -> Church succ (Church n) = Church (\f x -> f (n f x)) one :: Church one = succ zero ``` ```javascript zero = f => x => x succ = n => f => x => f (n (f) (x)) one = succ( zero ) // These definitions are actually in Preloaded ``` ```lambdacalc zero = \ f x . x succ = \ n . f x . f (n f x) one = succ zero ``` ```python succ = lambda n: lambda f: lambda x: f(n(f)(x)) zero = lambda f: lambda x: x one = succ(zero) # These definitions are actually in Preloaded ``` ~~~if:haskell,purescript, **hints** - you can finish it by just replacing the `undefined` placeholders in Haskell / typed holes in PureScript - no need to change the arguments - they might provide some hints. - the solutions can be very short - you don't have to write much if you think about it - you don't really need lambda-functions - But if you feel like it replace them with your own ideas. ~~~ ~~~if:javascript # Syntax You can define constants in Lambda Calculus syntax only: variables, function expressions, and function calls. Declare your definitions with `const`. Function expressions must use fat arrow syntax ( `=>` ). Functions can have zero or one argument. You can define and use helper constants. Empty applications are allowed. Recursion is not restricted. Some examples of *valid* syntax: ```javascript const pair = a => b => c => c(a)(b) const zero = f => x => x const cons = pair ``` Some examples of *invalid* syntax: ```javascript one = f => x => f(x); // semicolons (;) are not allowed function head(l) { return l(true) } // functions must use fat arrow notation fold = f => x => l => l.reduce(f, x) // only variables, functions and applications are allowed; property accessors (.), or functions taking multiple arguments, are not allowed ``` ~~~ ~~~if:python # Syntax You can define constants in Lambda Calculus syntax only: variables, function expressions, and function calls. Function expressions must use lambda syntax. Functions can have zero or one argument. You can define and use helper constants. Empty applications are allowed. Recursion is not restricted. Some examples of *valid* syntax: ```python pair = lambda a: lambda b: lambda c: c(a)(b) zero = lambda f: lambda x: x cons = pair ``` Some examples of *invalid* syntax: ```python def head(l): return l(true) // functions must lambda notation add = lambda a: lambda b: int.__add__(a, b) // only variables, functions and applications are allowed; property accessors (.), or functions taking multiple arguments, are not allowed ``` ~~~ ~~~if:lambdacalc #### Encodings - Numbers: `Church` - Purity: `Let` ~~~
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 of digits for the numerator. The function `expand` will return an array of the form `[numerator, denominator]`; we stop the loop in the Taylor expansion (see references below) when the numerator has a number of digits `>=` the required number of digits # Examples: ``` expand(1, 2) --> 65/24 (we will write this [65, 24] or (65, 24) in Haskell; 65/24 ~ 2.708...) expand(2, 5) --> [20947, 2835] expand(3, 10) --> [7205850259, 358758400] expand(1.5, 10) --> [36185315027,8074035200] ``` **Note** ```expand(1,5) = [109601, 40320]``` is the same as ```expand(1, 6)``` #Method: As said above the way here is to use `Taylor expansion` of the exponential function though it is not always the best approximation by a rational. #References: https://en.wikipedia.org/wiki/Exponential_function#Formal_definition http://www.efunda.com/math/taylor_series/exponential.cfm
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, expo . denominator]
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 followed by two elements [6,9] ``` Write a method called `isCenteredN` that returns : - `true` if its array argument is `not empty` and `centered-N` or empty and centered-0 - otherwise returns `false`.
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` where: * `a` is the first term of the sequence * `r` is the common ratio of the sequence (calculated by dividing one term in the sequence by the previous term) For example: `1 + 0.5 + 0.25 + 0.125 + ... = 2` Your challenge is to calculate the sum to infinity of the given sequence. The solution must be rounded to 3 decimal places. If there are no solutions, for example if `r` is out of the above boundaries, return `"No Solutions"`. Hope you enjoy, let me know of any issues or improvements!
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) = 2596253046576879973769082409566059879570061514363339324718953988724415850732046186170181072783243503881471037546575506836249417271830960970629933033088 It has 151 digits. ``` Make the function ```something_acci()```, that receives ```num_dig``` (number of digits of the value) as unique argument. ```something_acci()``` will output a tuple/array with the ordinal number in the sequence for the least value in having equal or more than the given number of digits. Let's see some cases: ```python something_acci(20) == (12, 25) # f(11) = 1422313222839141753028416 something_acci(100) == (15, 151) ``` ```ruby something_acci(20) == [12, 25] # f(11) = 1422313222839141753028416 something_acci(100) == [15, 151] ``` The number of digits given will be always more than 5. ```num_dig > 5```. Happy coding!!! And the name for this kata? You have three words of the same meaning in Asian Languages.
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), and a period (either **a.m.** or **p.m.**) as input. Your task is to return a four-digit string that encodes that time in 24-hour time. ### Notes - By convention, noon is `12:00 pm`, and midnight is `12:00 am`. - On 12-hours clock, there is no 0 hour, and time just after midnight is denoted as, for example, `12:15 am`. On 24-hour clock, this translates to `0015`.
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-hour time string in the form of "h:mm am" or "h:mm pm". (Of course, the "h" part will be two digits if the hour is greater than 9.) If you like this kata, try converting 12-hour time to 24-hour time: https://www.codewars.com/kata/converting-12-hour-time-to-24-hour-time
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 many moves will it take before both rings show the same number at the top again? The inner ring has integers from 0 to innerMax and the outer ring has integers from 0 to outerMax, where innerMax and outerMax are integers >= 1. ``` e.g. if innerMax is 2 and outerMax is 3 then after 1 move: inner = 2, outer = 1 2 moves: inner = 1, outer = 2 3 moves: inner = 0, outer = 3 4 moves: inner = 2, outer = 0 5 moves: inner = 1, outer = 1 Therefore it takes 5 moves for the two rings to reach the same number Therefore spinningRings(2, 3) = 5 ``` ``` e.g. if innerMax is 3 and outerMax is 2 then after 1 move: inner = 3, outer = 1 2 moves: inner = 2, outer = 2 Therefore it takes 2 moves for the two rings to reach the same number spinningRings(3, 2) = 2 ``` --- Test input range: - `100` tests with `1 <= innerMax, outerMax <= 10000` - `400` tests with `1 <= innerMax, outerMax <= 2^48`
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 == (outer_max + 1 - outer): jump = inner else: jump = min(inner + 1, outer_max + 1 - outer) outer = (outer + jump) % (outer_max + 1) inner = (inner - jump) % (inner_max + 1) moves += jump return moves
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 Madhav array as there is nothing to compare.*
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 show the same number at the top again? The inner ring has integers from 0 to innerMax and the outer ring has integers from 0 to outerMax, where innerMax and outerMax are integers >= 1. ``` e.g. if innerMax is 2 and outerMax is 3 then after 1 move: inner = 2, outer = 1 2 moves: inner = 1, outer = 2 3 moves: inner = 0, outer = 3 4 moves: inner = 2, outer = 0 5 moves: inner = 1, outer = 1 Therefore it takes 5 moves for the two rings to reach the same number Therefore spinningRings(2, 3) = 5 ``` ``` e.g. if innerMax is 3 and outerMax is 2 then after 1 move: inner = 3, outer = 1 2 moves: inner = 2, outer = 2 Therefore it takes 2 moves for the two rings to reach the same number spinningRings(3, 2) = 2 ``` --- for a bigger challenge, check out the [Performance Version](https://www.codewars.com/kata/59b0b7cd2a00d219ab0000c5) of this kata by @Voile
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 are being replaced by Fizz and Buzz. Return them as an array `[n, m]` The Fizz and Buzz numbers will always be integers between 1 and 50, and the sequence will have a maximum length of 100. The Fizz and Buzz numbers might be equal, and might be equal to 1. ## Examples * Classic FizzBuzz; multiples of 3 are replaced by Fizz, multiples of 5 are replaced by Buzz: ``` [1, 2, "Fizz", 4, "Buzz", 6] ==> [3, 5] ``` * Multiples of 2 are replaced by Fizz, multiples of 3 are replaced by Buzz: ``` [1, "Fizz", "Buzz", "Fizz", 5, "FizzBuzz"] ==> [2, 3] ``` * Multiples of 2 are replaced by Fizz and Buzz: ``` [1, "FizzBuzz", 3, "FizzBuzz", 5, "FizzBuzz"] ==> [2, 2] ``` * Fizz = 1, Buzz = 6: ``` ["Fizz", "Fizz", "Fizz", "Fizz", "Fizz", "FizzBuzz"] ==> [1, 6] ```
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</a> * same <a href="https://en.wikipedia.org/wiki/Parity_(mathematics)">parity</a> # Notes * The list will contain at least 3 numbers * If there is more than one answer then return the first one found (reading the list left to right) * If there is no answer (e.g. no 3 adjacent numbers with same parity) then return an empty list. # Examples * ex1 * Input = ```[1, 2, 34, 2, 1, 5, 3, 5, 7, 234, 2, 1]``` * Result = ```[5,3,5]``` * ex2 * Input = ```[2, 4, 6, 8, 10, 2, 2, 2, 1, 1, 1, 5, 3]``` * Result = ```[2,2,2]``` * ex3 * Input = ```[2, 4, 5, 3, 6, 3, 1, 56, 7, 6, 3, 12]``` * Result = ```[]```
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, instead of formatting it in normal English orthography, it just outputs a list of words. Robbie has pulled multiple all-nighters to get this project finished, and he needs some beauty sleep. So, he wants you to write the last part of his code, a `sentencify` function, which takes the output that the machine gives, and formats it into proper English orthography. Your function should: 1. Capitalise the first letter of the first word. 2. Add a period (`.`) to the end of the sentence. 3. Join the words into a complete string, with spaces. 4. Do *no other manipulation* on the words. ----- Here are a few examples of what your function should do: | Input | Output | | --- | --- | | `["i", "am", "an", "AI"]` | `"I am an AI."` | | `["FIELDS","of","CORN","are","to","be","sown"]` | `"FIELDS of CORN are to be sown."` | | `["i'm","afraid","I","can't","let","you","do","that"]` | `"I'm afraid I can't let you do that."` | **_(Any translations (eg: to Java/C#/C++/Typescript) would be greatly appreciated!)_**
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") == {1: ["a", "b", "c"]} ``` You should ignore spaces, special characters and count uppercase letters as lowercase ones. For example: ```ruby get_char_count("Mississippi") => {4=>["i", "s"], 2=>["p"], 1=>["m"]} get_char_count("Hello. Hello? HELLO!!") => {6=>["l"], 3=>["e", "h", "o"]} get_char_count("aaa...bb...c!") => {3=>["a"], 2=>["b"], 1=>["c"]} get_char_count("aaabbbccc") => {3=>["a", "b", "c"]} get_char_count("abc123") => {1=>["1", "2", "3", "a", "b", "c"]} ``` ```python get_char_count("Mississippi") == {4: ["i", "s"], 2: ["p"], 1: ["m"]} get_char_count("Hello. Hello? HELLO!") == {6: ["l"], 3: ["e", "h", "o"]} get_char_count("aaa...bb...c!") == {3: ["a"], 2: ["b"], 1: ["c"]} get_char_count("abc123") == {1: ["1", "2", "3", "a", "b", "c"]} get_char_count("aaabbbccc") == {3: ["a", "b", "c"]} ```
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): ``` --------- ---- ---- --------- ---- ---- ---- ---- --------- ---- ---- ---- ---- --------- --------- ---- ---- ---- ---- --------- --------- ---- ---- ---- ---- ---- ---- --------- ``` The book is commonly used as an oracle. After asking it a question about one's present scenario, each line is determined by random methods to be Yang or Yin. The resulting hexagram is then interpreted by the querent as a symbol of their current situation, and how it might unfold. This kata will consult the I Ching using the three coin method. ###Instructions A coin is flipped three times and lands heads or tails. The three results are used to determine a line as being either: ``` 3 tails ----x---- Yin (Moving Line*) 2 tails 1 heads --------- Yang 1 tails 2 heads ---- ---- Yin 3 heads ----o---- Yang (Moving Line*) *See bottom of description if curious. ``` This process is repeated six times to determine each line of the hexagram. The results of these operations are then stored in a 2D Array like so: ```javascript [['two','h','h','t'],['six','t','h','t'],['four','t','t','t'], ['one','h','t','h'],['three','h','h','h'],['five','t','t','h']] ``` In each array the first index will always be the number of the line ('one' is the bottom line, and 'six' the top), and the other three values will be the results of the coin flips that belong to that line as heads ('h') and tails ('t'). Write a function that will take a 2D Array like the above as argument and return its hexagram as a string. Each line of the hexagram should begin on a new line. ```javascript oracle([['two','h','h','t'],['six','t','h','t'],['four','t','t','t'], ['one','h','t','h'],['three','h','h','h'],['five','t','t','h']]); ``` should return: ``` --------- --------- ----x---- ----o---- ---- ---- ---- ---- ``` You are welcome to consult your new oracle program with a question before pressing submit. You can compare your result [here](http://www.ichingfortune.com/hexagrams.php). The last test case is random and can be used for your query. *[1] A Moving Line is a Yang line that will change to Yin or vice versa. The hexagram made by the coin throws represents the querent's current situation, and the hexagram that results from changing its moving lines represents their upcoming situation.*
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) == 3 #15! = 1307674368000, which has 3 zeros at the end trailing_zeros(7, 2) == 4 #7! = 5030 = 0b1001110110000, which has 4 zeros at the end ``` ```javascript trailingZeros(15, 10) == 3 //15! = 1307674368000, which has 3 zeros at the end trailingZeros(7, 2) == 4 //7! = 5030 = 0b1001110110000, which has 4 zeros at the end ``` ```python trailing_zeros(15, 10) == 3 #15! = 1307674368000, which has 3 zeros at the end trailing_zeros(7, 2) == 4 #7! = 5030 = 0b1001110110000, which has 4 zeros at the end ``` ```java trailingZeros(BigInteger.valueOf(15),BigInteger.valueOf(10)) == BigInteger.valueOf(3) //#15! = 1307674368000, which has 3 zeros at the end trailingZeros(BigInteger.valueOf(7),BigInteger.valueOf(2)) == BigInteger.valueOf(4) //7! = 5030 = 0b1001110110000, which has 4 zeros at the end ``` Your code should be able to handle some very large numbers, so write some smart code. Note: ```num``` will be a non-negative integer, ```base``` will be an integer larger or equal to two. HINT: Should you not make any headway after trying a long time, you should try [this kata](https://www.codewars.com/kata/number-of-trailing-zeros-of-n) first.
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 number is powered up by base, a zero is added # e.g. base 4: 10 = 4(dec), 100 = 16(dec), 1000 = 64(dec) # 6! = 6*5*4*3*2*1 = 2*3*5*4*3*2*1 = 5*4*4*3*3 = powered up by 4 twice => 2 zeroes # technique in counting how many 2s: # multiple of 2 contributes one 2 # multiple of 4 contributes additional 2 # multiple of 8 contributes additional 2 etc # e.g. 17!: 17//2 + 17//4 + 17//8 + 17//16 = 8 + 4 + 2 + 1 = 15 # then divide 15 by number of 2s required by each base power-up basefactors = factorise(base) answer = float("inf") for bf in basefactors: bfx = bf temp = 0 while number >= bfx: temp += number / / bfx bfx *= bf answer = min(answer, temp / / basefactors[bf]) return answer
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[][] orangeBox` (or a list of lists `orange_box` in Python) * all inner lists have an equal length * rotten oranges are represented by ``2`` * fresh oranges are represented by ``1`` * empty spaces are represented by ``0`` * return an ``int`` value noting the time needed to fully rot the box * return ``-1`` in case the box will never completely rot ## Example: orangeBox: ``` 2 1 1 1 1 1 ``` orangeBox after 1 time unit: ``` 2 2 1 2 1 1 ``` orangeBox after 2 time units: ``` 2 2 2 2 2 1 ``` orangeBox after 3 time units: ``` 2 2 2 2 2 2 ``` The box is now fully rotten. Result: ``3``.
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) while fresh and rotten: time += 1 rotten . update(* map(neighbours, rotten)) rotten &= fresh fresh -= rotten return - 1 if fresh else time
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 tests will check random integers up to 2000.
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 takes an `[Int]` as 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 `nil`. ``` Examples: ```ruby oddOne([2,4,6,7,10]) # => 3 oddOne([2,16,98,10,13,78]) # => 4 oddOne([4,-8,98,-12,-7,90,100]) # => 4 oddOne([2,4,6,8]) # => -1 ``` ```javascript oddOne([2,4,6,7,10]) // => 3 oddOne([2,16,98,10,13,78]) // => 4 oddOne([4,-8,98,-12,-7,90,100]) // => 4 oddOne([2,4,6,8]) // => -1 ``` ```python odd_one([2,4,6,7,10]) # => 3 odd_one([2,16,98,10,13,78]) # => 4 odd_one([4,-8,98,-12,-7,90,100]) # => 4 odd_one([2,4,6,8]) # => -1 ``` ```haskell oddOne [2,4,6,7,10] -- -> 3 oddOne [2,16,98,10,13,78] -- -> 4 oddOne [4,-8,98,-12,-7,90,100] -- -> 4 oddOne [2,4,6,8] -- -> -1 ``` ```csharp Kata.OddOne(new List<int> {2,4,6,7,10}) => 3 Kata.OddOne(new List<int> {2,16,98,10,13,78}) => 4 Kata.OddOne(new List<int> {4,-8,98,-12,-7,90,100}) => 4 Kata.OddOne(new List<int> {2,4,6,8}) => -1 ``` ```swift oddOne([2,4,6,7,10]) // => 3 oddOne([2,16,98,10,13,78]) // => 4 oddOne([4,-8,98,-12,-7,90,100]) // => 4 oddOne([2,4,6,8]) // => nil ``` ```c odd_one({2, 4, 6, 7, 10}, 5); // == 3 odd_one({2, 16, 98, 10, 13, 78}, 6); // == 4 odd_one({4, -8, 98, -12, -7, 90, 100}, 7); // == 4 odd_one({2, 4, 6, 8}, 4); // == -1 ```
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 + 3 * 4 - 6") // => 7 ``` ```haskell Calculator.evaluate "2 / 2 + 3 * 4 - 6" // => 7.0 ``` Remember about the order of operations! Multiplications and divisions have a higher priority and should be performed left-to-right. Additions and subtractions have a lower priority and should also be performed left-to-right.
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(): if token[0]. isdigit() or token[0] == '.': nums . append(float(token)) elif token == '(': # special case, no need to add precedence ops . append('(') elif token == ')': while ops[- 1] != '(': precs . pop() self . _evaluate_op(nums, ops . pop()) ops . pop() elif token in OPS: # sneaky integer division prec = OPS . index(token) / / 2 while ops and ops[- 1] != '(' and precs[- 1] >= prec: precs . pop() self . _evaluate_op(nums, ops . pop()) ops . append(token) precs . append(prec) for op in reversed(ops): self . _evaluate_op(nums, op) return nums[0] def _evaluate_op(self, nums, op): b, a = nums . pop(), nums . pop() if op == '+': nums . append(a + b) elif op == '-': nums . append(a - b) elif op == '*': nums . append(a * b) else: nums . append(a / b)
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(PRIMES[: bisect(PRIMES, n)])
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 `15` share 3 `1`-bits (at indexes 1, 2, and 3) --> `true` - `10` and `15` share 2 `1`-bits (at indexes 0 and 2) --> `true` *Hint:* you can do this with just string manipulation, but binary operators will make your life much easier.
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 implement both features, and in the <strong>worst</strong> case it will take you 11 (6 + 5). In the <strong>average</strong> case, it will take you 8.5 hours. To help you streamline the estimation process, write a function that returns a tuple (**JS**: array) of the global <strong>best</strong> case, <strong>average</strong> case and <strong>worst</strong> case given a tuple of tuples (**JS**: array of arrays) representing best case and worst case guesses. For example, ```python estimates = ((1, 2), (3, 4)) global_estimate(estimates) == (4, 5, 6) ``` For example, ```javascript estimates = [[1, 2], [3, 4]] globalEstimate(estimates) == [4, 5, 6] ``` *Don't worry about rounding or invalid input.*
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 BKNS CEOR DFIQ GJMT Fri: AFJN BLMR CGPQ DEKT HIOS ``` Write a function that validates a proposed solution, a list of list of strings, as being a solution to the social golfer problem. Each character represents a golfer, and each string is a group of players. Rows represent days. The solution above would be encoded as: ``` [ ['ABCD', 'EFGH', 'IJKL', 'MNOP', 'QRST'], ['AEIM', 'BJOQ', 'CHNT', 'DGLS', 'FKPR'], ['AGKO', 'BIPT', 'CFMS', 'DHJR', 'ELNQ'], ['AHLP', 'BKNS', 'CEOR', 'DFIQ', 'GJMT'], ['AFJN', 'BLMR', 'CGPQ', 'DEKT', 'HIOS'] ] ``` You need to make sure (1) that each golfer plays exactly once every day, (2) that the number and size of the groups is the same every day, and (3) that each player plays with every other player *at most* once. So although each player must play every day, there can be particular pairs of players that never play together. It is not necessary to consider the case where the number of golfers is zero; no tests will check for that. If you do wish to consider that case, note that you should accept as valid all possible solutions for zero golfers, who (vacuously) can indeed play in an unlimited number of groups of zero.
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 player not in golfers: return False if player not in d: d[player] = set(group) else: if len(d[player] & set(group)) > 1: return False else: d[player]. add(group) return True
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 give a fast solution. We need the help of maths, in this case of number theory. We need to apply the prime factorization of a number: <a href="http://imgur.com/KYanmyW"><img src="http://i.imgur.com/KYanmyW.png?1" title="source: imgur.com" /></a> Think in doing the prime factorization of the product of all the different values of the array and think how to obtain from it the minimum number that is divisible by all the values of the array. See the same cases as the previous part: ```python min_special_mult([2, 3 ,4 ,5, 6, 7]) == 420 ``` The array may have integers that occurs more than once: ```python min_special_mult([18, 22, 4, 3, 21, 6, 3]) == 2772 ``` The array should have all its elements integer values. If the function finds an invalid entry (or invalid entries) like strings of the alphabet or symbols will not do the calculation and will compute and register them, outputting a message in singular or plural, depending on the number of invalid entries. ```python min_special_mult([16, 15, 23, 'a', '&', '12']) == "There are 2 invalid entries: ['a', '&']" min_special_mult([16, 15, 23, 'a', '&', '12', 'a']) == "There are 3 invalid entries: ['a', '&', 'a']" min_special_mult([16, 15, 23, 'a', '12']) == "There is 1 invalid entry: a" ``` If the string is a valid number, the function will convert it as an integer. ```python min_special_mult([16, 15, 23, '12']) == 5520 min_special_mult([16, 15, 23, '012']) == 5520 ``` All the None elements of the array will be ignored: ```python min_special_mult([18, 22, 4, , None, 3, 21, 6, 3]) == 2772 ``` If the array has a negative number, the function will convert to a positive one. ```python min_special_mult([18, 22, 4, , None, 3, -21, 6, 3]) == 2772 min_special_mult([16, 15, 23, '-012']) == 5520 ``` The test for this part will be more challenging having arrays up to 5000 elements and up to 800 different values. A simple brute force algorithm will not be able to pass the tests. Enjoy it!
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 "There is 1 invalid entry: {}" . format(invalids[0]) else: return "There are {} invalid entries: {}" . format(len(invalids), invalids)
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: * A list object containing `values` to be counted, summed, or averaged. * A `criteria` in either an integer, float, or string * Integer or float indicates equality * Strings can indicate >, >=, <, <= or <> (use the Excel-style "Not equal to" operator) to a number (ex. ">=3"). In the `count_if` function, a string without an operater indicates equality to this string. The tests will all include properly formatted inputs. The test cases all avoid rounding issues associated with floats. ##Examples ```python count_if([1,3,5,7,9], 3) 1 count_if(["John","Steve","John"], "John") 2 sum_if([2,4,6,-1,3,1.5],">0") 16.5 average_if([99,95.5,0,83],"<>0") 92.5 ``` ##Excel Function Documentation: * [COUNTIF](https://support.office.com/en-us/article/COUNTIF-function-e0de10c6-f885-4e71-abb4-1f464816df34) * [SUMIF](https://support.office.com/en-us/article/SUMIF-function-169b8c99-c05c-4483-a712-1697a653039b) * [AVERAGEIF](https://support.office.com/en-us/article/AVERAGEIF-function-faec8e2e-0dec-4308-af69-f5576d8ac642)
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 == "<>": return [item for item in values if item < > limit] elif rel == "<=": return [item for item in values if item <= limit] elif rel == ">=": return [item for item in values if item >= limit] elif rel == "<": return [item for item in values if item < limit] elif rel == ">": return [item for item in values if item > limit] def count_if(values, criteria): return len(parse(values, criteria)) def sum_if(values, criteria): return sum(parse(values, criteria)) def average_if(values, criteria): return sum(parse(values, criteria)) * 1.0 / len(parse(values, criteria))
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} = 12x^3 $` ### Good to know: * The derivative of a constant is 0. * Anything to the 0th exponent equals 1 (e.g. `$ x^0 = 1 $`). * The derivative of the sum of two function is the sum of the derivatives. ### Notes: * The exponentiation is marked with `^` * Exponents are always integers and >= 0 * Exponents are written only if > 1 * There are no spaces around the operators * Leading `+` signs are omitted ### Examples ```text Derivative of "-100" is "0" Derivative of "4x+1" is "4" Derivative of "-x^2+3x+4" is "-2x+3" ```
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_int, (coeff, exp)) coeff *= exp exp -= 1 result += ('{sign}{coeff}' if exp == 0 else '{sign}{coeff}x' if exp == 1 else '{sign}{coeff}x^{exp}' ). format(sign=sign, coeff=coeff, exp=exp) return result if result else '0'
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 coins Z_coin_a = 1 Z_coin_b = 3 Z_coin_c = 4 ## Optimal change for 6 cents - 2 Z_coin_b's ``` Write a function that will take a list of coin denominations and a desired amount and provide the least amount of coins needed.
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 always be integers. Example: ```c find_all(7, {6, 9, 3, 4, 3, 82, 11}, 3, *z) // returns pointer to {2, 4} // assigns array length to `*z` ``` ```python find_all([6, 9, 3, 4, 3, 82, 11], 3) > [2, 4] ``` ```javascript findAll([6, 9, 3, 4, 3, 82, 11], 3) => [2, 4] ``` ```csharp Kata.FindAll(new int[] {6, 9, 3, 4, 3, 82, 11}, 3) => new int[] {2, 4} ``` ```haskell findAll [6, 9, 3, 4, 3, 82, 11] 3 = [2, 4] ``` ```ruby find_all([6, 9, 3, 4, 3, 82, 11], 3) = [2, 4] ``` ```prolog find_all([6, 9, 3, 4, 3, 82, 11], 3) = [2, 4] ```
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, `m`, your task is to craft a program that will determine the quantities of each colored ball. Return a list of these quantities as the answer. Don't forget that some combinations of `n` and `m` may have more than one possibility! # Examples ## Python ```python >>> Guess_it(3, 12) [[0,3,0], [1,1,1]] ``` ## Elixir ```elixir iex(1)> GuessIt.guess(3, 12) [{0,3,0}, {1,1,1}] ``` *Note: Order of the returned elements is unimportant in the Elixir version.* # Assumptions 1. You can assume that all inputs are of the correct type 2. You can assume that the range of `n` will be `[1, 50]` 3. Each element of the returned list should return the quantities in the order of `g`, `r`, `b`. ## Python ```python [[green, red, blue]] ``` ## Elixir ```elixir [{green, red, blue}] ```
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 be registered once. You will be given an uncertain number of arrays that contains strings (the id code users). Each array will represent the purchases that the users do in a month. You should find the total number of purchases of the users that have bought in **all the given months** (the clients that their id code are present in all the arrays). e.g.: ``` a1 = ['A042', 'B004', 'A025', 'A042', 'C025'] a2 = ['B009', 'B040', 'B004', 'A042', 'A025', 'A042'] a3 = ['A042', 'A025', 'B004'] ``` The result will be: ``` 'A042'---> 5 times 'A025'---> 3 times 'B004'---> 3 times ``` It may be that not even a single user has purchased in all the months ``` a1 = ['A043', 'B004', 'A025', 'A042', 'C025'] a2 = ['B009', 'B040', 'B003', 'A042', 'A027', 'A044'] a3 = ['A041', 'A026', 'B005'] ``` Even though '0042' is present in two arrays, is not present in all the arrays. The function that solves this challenge will be called as: ```id_best_users()```. The entries of the function and the output for the cases above will be: ```python a1 = ['A042', 'B004', 'A025', 'A042', 'C025'] a2 = ['B009', 'B040', 'B004', 'A042', 'A025', 'A042'] a3 = ['A042', 'A025', 'B004'] id_best_users(a1, a2, a3) == [[5, ['A042']], [3, ['A025', 'B004']]] a1 = ['A043', 'B004', 'A025', 'A042', 'C025'] a2 = ['B009', 'B040', 'B003', 'A042', 'A027', 'A044'] a3 = ['A041', 'A026', 'B005'] id_best_users(a1, a2, a3) == [] ``` As you can see the output will have the total number of purchases in decreasing order. If two users have the same amount of total purchases, they will be sorted by their id user string value. More examples will be given in the example tests. Features of the Random Tests: ``` Low Performance Tests maximum amount of users: 200 maximum number of months: 8 maximum amount of purchases per month: 100 High Performance Tests maximum amount of users: 90000 maximum number of months: 12 maximum amount of purchases per month: 80000 ``` Enjoy it!!
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 groupby return [[count, sorted(users)] for count, users in groupby(common_users, sum_counts . get)]
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] /|\ \ 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) while len(queue) != 0: tree = queue . pop(0) for child in tree . child_nodes: queue . append(child) result . append(child . data) return result
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 similar to the following are correct, but not allowed for this kata: ```python def rotate_not_in_place(matrix): return [[row[i] for row in reversed(matrix)] for i in range(len(matrix))] ``` Esentially any method that involves generating a new matrix isn't allowed. To sum up, given a square matrix of any size as an input: ``` [[1, 2, 3], [4, 5, 6], [7, 8, 9]] ``` Modify the original matrix rotating it in place 90 degrees clockwise and return it: ``` [[7, 4, 1], [8, 5, 2], [9, 6, 3]] ``` This problem is very googleable so I suggest trying it out without looking for help.
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 to store data by keys to create nested structures. You are given a dictionary where the keys are strings and the values are strings or dictionaries. The goal is flatten the dictionary, but save the structures in the keys. The result should be a dictionary without the nested dictionaries. The keys should contain paths that contain the parent keys from the original dictionary. The keys in the path are separated by a `/`. If a value is an empty dictionary, then it should be replaced by an empty string `""`. ### Examples ```python { "name": { "first": "One", "last": "Drone" }, "job": "scout", "recent": {}, "additional": { "place": { "zone": "1", "cell": "2" } } } ``` The result will be: ```python {"name/first": "One", #one parent "name/last": "Drone", "job": "scout", #root key "recent": "", #empty dict "additional/place/zone": "1", #third level "additional/place/cell": "2"} ``` ***`Input: An original dictionary as a dict.`*** ***`Output: The flattened dictionary as a dict.`*** ***`Precondition: Keys in a dictionary are non-empty strings. Values in a dictionary are strings or dicts. root_dictionary != {}`*** ```python flatten({"key": "value"}) == {"key": "value"} flatten({"key": {"deeper": {"more": {"enough": "value"}}}}) == {"key/deeper/more/enough": "value"} flatten({"empty": {}}) == {"empty": ""} ```
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 paired or if the order is invalid (e.g. ')(') return False. In this kata we care only about the positions of round brackets '()', other types of brackets should be ignored.
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', 'little', 'user', 'I', 'd', 'been', 'using', 'my','sphere', 'as', 'a', 'stool', 'Slow', 'moving', 'target', 'was', 'hit', 'by', 'OMGd', 'or', 'K', 'mp']` Kate doesn't like some of words and doesn't count them. Words to be excluded are "a", "the", "on", "at", "of", "upon", "in" and "as", case-insensitive. Today Kate's too lazy and have decided to teach her computer to count "words" for her. Example Input 1 ------------- Hello there, little user5453 374 ())$. Example Output 1 ------------- 4 Example Input 2 ------------- I’d been using my sphere as a stool. I traced counterclockwise circles on it with my fingertips and it shrank until I could palm it. My bolt had shifted while I’d been sitting. I pulled it up and yanked the pleats straight as I careered around tables, chairs, globes, and slow-moving fraas. I passed under a stone arch into the Scriptorium. The place smelled richly of ink. Maybe it was because an ancient fraa and his two fids were copying out books there. But I wondered how long it would take to stop smelling that way if no one ever used it at all; a lot of ink had been spent there, and the wet smell of it must be deep into everything. Example Output 2 -------------- 112
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 + 2y)(x + 4y)), where (x, y) = fibfusc(n) Your job is to produce the code for the `fibfusc` function. In this kata, your function will be tested with large values of n (up to 2000 bits), so you should be concerned about stack overflow and timeouts. Moreover, since the `fibfusc` function grows exponentially, your function should take an extra argument `num_digits` with a default value of `None`. When not `None`, `num_digits` takes a positive `int` value and the returned values shall be truncated to the last `num_digits` digits. For example, let `n = 101`. With `num_digits` not set or set to `None`, `fibfusc` should return: `(-280571172992510140037611932413038677189525L, 734544867157818093234908902110449296423351L)`. If `num_digits = 12`, the function should return `(-38677189525L, 449296423351L)`. Notice in particular, that for any value of `n` greater than 1, `x` is negative, and the truncated value of `x` should also be negative. Hint 1: Use modulo `10 ** num_digits` arithmetic to keep all intermediary results small. Hint 2: Consider using an iterative ["number climber"](http://www.codewars.com/kata/number-climber) to avoid stack overflows.
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: x, y = x % 10 * * num_digits - 10 * * num_digits, y % 10 * * num_digits return x, y
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` function. In this kata, your function will be tested with small values of n, so you should not need to be concerned about stack overflow or timeouts. When done, move on to [Part 2](http://www.codewars.com/kata/the-fibfusc-function-part-2).
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, 195025, 470832, .. ## Task Your task is to return the `n`th Pell number
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 second comment to reply to comment 1 would be ranked 1.2 . Note that since 1.1.1 is a valid rank, the ranks given are of type string. ### Task: Given a list of comment ranks (strings), order them as a comment thread would appear ### Assumptions: * there will always be a rank 1 in the given input * ranks are of type string * rank numbers are incremented, and not skippped (1.1 could be followed by 1.2, not 1.3) ### Example order: ``` [ '1', '1.1', '1.2', '1.2.1', '2', '3', '3.1', '3.1.1', '3.2' ] ```
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 numbers satisfy this property within that range? (`a <= n < b`) ## Example `solve(2, 1200) = 1`, because only `1176` satisfies this property within the range `2 <= n < 1200`. See test cases for more examples. The upper bound for the range will not exceed `1,000,000`. Good luck! If you like this Kata, please try: [Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3) [Alphabet symmetry](https://www.codewars.com/kata/59d9ff9f7905dfeed50000b0) [Upside down numbers](https://www.codewars.com/kata/59f7597716049833200001eb)
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 :)** P.S.: Sofisticated cheats, **which do not circumvent the testing framework itself**, are welcome.
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 out the names of each digit in a single word (instead of the proper name of the number in English). For example, write 12 as "onetwo" (instead of twelve), and 999 as "nineninenine" (instead of nine hundred and ninety-nine). For any integer between 0 and 999, return an array showing the path from that integer to a stable equilibrium: ## Examples ```javascript numbersOfLetters(60) --> ["sixzero", "seven", "five", "four"] numbersOfLetters(1) --> ["one", "three", "five", "four"] ``` ```haskell numbersOfLetters 60 -> ["sixzero", "seven", "five", "four"] numbersOfLetters 1 -> ["one", "three", "five", "four"] ```
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` on the grid. It accepts two arguments, x and y. x and y should be 1-based. ``` x = 5 y = 3 0000000000 0000000000 0000X00000 0000000000 0000000000 0000000000 0000000000 0000000000 0000000000 0000000000 ``` It also has an attribute `grid` which contains the multiline string. Your job is to create a class `Grid` which does that.
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("" . join(self . body[r])) for r in range(self . rows)])[: - 1] @ property def grid(self): return self . __repr__()
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_1485417838419207_185415143_n.jpg'> Your task in this kata is to implement a dog recommendation system. You will be given the name of a dog <code>breed</code> (as a string), for which you will have to return a <strong>set</strong> of the breeds that are most similar to this breed in temper <strong>(excluding itself)</strong>. To aid you in this task, you are given a dictionary, <code>dogs</code>, mapping dog breeds (e.g., <code>"Chihuahua"</code>) to a <strong>set</strong> of adjectives describing that breed's typical temperament (e.g., <code>{"Lively", "Devoted", "Courageous", "Alert", "Quick"}</code>). The dictionary is preloaded, so you may access it as if you had defined it in your own code. <strong>To be clear, </strong>two breeds are more similar in temper the more adjectives they share. For example, if dog breed A has adjectives <code>{"Lively", "Devoted"}</code>, it is more similar to dog breed B (<code>{"Lively", "Devoted"}</code>, two adjectives in common) than to dog breed C (<code>{"Lively", "Alert"}</code>, one adjective in common) or even dog breed D (<code>{"Alert", "Quick"}</code>, zero adjectives in common). If one breed has more adjectives in common with the original breed than any other, return a <strong>set</strong> containing only this breed. If more than one breed has the same number of adjectives in common with the original breed, return a <strong>set</strong> of these breeds. Dog breeds taken <a href = 'https://en.wikipedia.org/wiki/List_of_dog_breeds'>here</a>. Dog temperaments taken from Google (search, e.g., <a href = 'https://www.google.ca/search?q=chihuahua+temperament'>"Chihuahua temperament"</a>).
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: "4", "5", "6" * And so on; this pattern continues. ``` 1 2 3 4 5 6 7 8 9 10 ... ``` Given N, return the sum of all numbers on the Nth Row: 1 <= N <= 10,000
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 when two or more data points occur the most? For example, what is the mode of the letters in `"tomato"`? Both `"t"` and `"o"` seem to be tied for appearing most frequently. Turns out that a set of data can, in fact, have multiple modes, so `"tomato"` has two modes: `"t"` and `"o"`. It's important to note, though, that if *all* data appears the same number of times there is no mode. So `"cat"`, `"redder"`, and `[1, 2, 3, 4, 5]` do not have a mode. Your job is to write a function `modes()` that will accept one argument `data` that is a sequence like a string or a list of numbers and return a sorted list containing the mode(s) of the input sequence. If data does not contain a mode you should return an empty list. For example: ```python >>> modes("tomato") ["o", "t"] >>> modes([1, 3, 3, 7]) [3] >>> modes(["redder"]) [] ``` You can trust that your input data will always be a sequence and will always contain orderable types (no inputs like `[1, 2, 2, "a", "b", "b"]`).
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 ..... 6 -.... 7 --... 8 ---.. 9 ----. 0 -----
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 context. Until you ```call``` a lambda, it is just a piece of data you can pass around. ## Task at hand Implement 3 lambdas that alter a message based on emotion: ```ruby spoken =->(greeting) { ... } # "hello WORLD" --> "Hello world." shouted =->(greeting) { ... } # "Hello world" --> "HELLO WORLD!" whispered =->(greeting) { ... } # "HELLO WORLD" --> "hello world." ``` ```python spoken = lambda greeting: ... # "hello WORLD" --> "Hello world." shouted = lambda greeting: ... # "Hello world" --> "HELLO WORLD!" whispered = lambda greeting: ... # "HELLO WORLD" --> "hello world." ``` Then create a fourth lambda, this one will take one of the above lambdas and a message, and the last lambda will delegate the emotion and the message up the chain. ```ruby greet =->(style, msg) { ... } ``` ```python greet = lambda style, msg: ... ``` ## Input Input message contains only ASCII alphabets and spaces. --- While here we only test for `spoken`, `shouted`, and `whispered` emotions, the open/closed principle allows us to add functionality to the greet function using other emotions/lambdas as well. For example, feeling like `L33tsp34k1ng` or `sPoNgEbOb MeMe-ing` today? No need to change the original greet function (**closed** for modification), you can just extend the greet function (**open** for extension) by passing a new lambda and message to the greet function. So, embrace the power of open/closed principle now and make your code more flexible and easier to extend!
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, 33, 45, 49, 95, 10], alpha . upper())) # Take the number PI as string, reverse the string and prepare it for decoding crypt = str(pi). replace('.', '')[:: - 1] # Group 2 by 2 to form a list code = [int(crypt[i: i + 2]) for i in range(0, len(crypt), 2)] # Take the modified string and try to decode return '' . join(dico[binom] for binom in code) # hopefully...
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 of them is not zero, is the largest positive integer that divides the numbers without a remainder. For example, the GCD of 8 and 12 is 4." For example: the greatest common divisor of 300 and 45 is 15. The binary representation of 15 is 1111, so the correct output would be 4. If both parameters are 0, the method should return 0. The function must be able to handle negative input.
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 new amusement will stop annoying you. Your task then, is to design a function `letter_pattern` that takes in a list of strings (all lowercase, and only including letters). It should return a string with every letter that is always there in place. ## Example `['war', 'rad', 'dad']` should return `"*a*"`, since only the second place stays constant `['general', 'admiral', 'piglets', 'secrets']` should return `"*******"` `['family']` should return `"family"`
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' represents the range n4 to n5 (inclusive in both ends) but only includes every other n6 integer. Notes:<br/> 1. The input string doesn't not have to include all the token types.<br/> 2. All integers are assumed to be positive.<br/> 3. Tokens may be separated by `','`, `', '` or ` , `. Some examples: ```python '1-10,14, 20-25:2' -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 14, 20, 22, 24] '5-10' -> [5, 6, 7, 8, 9, 10] '2' -> [2] ``` The output should be a list of integers.
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 array is not important. If no combination of numbers adds up return a empty array. ### Example A small example: Given the three input arrays `a1 = [1, 2]; a2 = [4,3]; a3 = [6,5,8]`, we need to find the number pairs from `a1` and `a2` that sum up to a number in `a3` and return those three numbers in an array. In this example, the result from the function would be `[[1, 4, 5] , [2, 4, 6], [2, 3, 5]]`. ``` Given three arrays a1 a2 a3 1 4 6 (a1 a2 a3) (a1 a2 a3) (a1 a2 a3) 2 3 5 => [[1, 4, 5] , [2, 4, 6], [2, 3, 5]] 8 each value in the result array contains one part from each of the arguments. ``` ### Testing A function `compare_array` is given. This function takes two arrays and compares them invariant of sort order. ```ruby Test.expect(compare_arrays(addsup([1,2], [3,1], [5,4]), [[1,3,4], [2,3,5]])) ``` ```python test.expect(compare_arrays(addsup([1,2], [3,1], [5,4]), [[1,3,4], [2,3,5]])) ``` ### Greater goal For extra honor try and make it as effective as possible. Discuss whats the most effective way of doing this. The fastest way i can do this is in *O(n^2)*. Can you do it quicker?
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 may time out. # Example¹: ```python >>> get_honor('dpleshkov') 4418 >>> get_honor('jhoffner') 21949 ``` ```Fsharp F# examples >>> GetHonor('dpleshkov') 4418 >>> GetHonor('jhoffner') 21949 ``` ¹ Honor may or may not be current to the user # Libraries/Recommendations: ## Fsharp: * `open System.Net`: use this namespace for opening a webpage(It's just a suggestion). * `open System.Text.RegularExpressions`: this namepsace will give you access to Regex. ## Python: * `urllib.request.urlopen`: Opens up a webpage. * `re`: The RegEx library for Python. * `bs4`([BeautifulSoup](https://www.crummy.com/software/BeautifulSoup/bs4/doc)): A tool for scraping HTML and XML. # Notes: * Time out / server errors often happen with the test cases depending on the status of the codewars website. Try submitting your code a few times or at different hours of the day if needed. * Feel free to voice your comments and concerns in the discourse area. * There is no example tests. Sorry, the honor may vary from time to time. I apologize for the inconvenience.
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 value of characters (modulo 256). * The second two are the *PRODUCT* of all the characters (again, modulo 256, which is one more than `FF` in hexadecimal). * The last two are the *ABSOLUTE VALUE of the DIFFERENCE* between the first letter, and the sum of every other letter. (I think you get the idea with the modulo thing). For example `"Jack"` returns `"79CAE5"`, which is... **<span style="color:#79CAE5">baby blue!</span>** ``` "Jack" # "J" = 74, "a" = 97, "c" = 99, "k" = 107 74 + 97 + 99 + 107 = 377 --> mod 256 = 121 --> hex: 79 74 * 97 * 99 * 107 = 76036554 --> mod 256 = 202 --> hex: CA 74 - (97 + 99 + 107) = -229 --> abs: 229 --> mod 256 = 229 --> hex: E5 ``` NOTE: The function should return `None/nil` when the input is less than two chars.
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, b)
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 variance : 4. Some wiki: <a href="https://en.wikipedia.org/wiki/Variance">Variance </a>, <a href="https://www.mathsisfun.com/data/random-variables.html"> Aleatory variable </a> <p> Example: Consider "Hello" and "World": X is { 5 } with P(X = 5) = 1 because the two words have the same length. So E[X] = 5 x 1 = 5 and the standard formula for variance is E[(X - u)^2] so 1 x (5-5)^2 = 0 or you can calculate with the other formula E[X^2] - E[X]^2 = 5^2 x 1 - 5^2 = 0 Consider "Hi" and "World": X is { 2, 5 } with P(X = 5) = 1/2 and P(X = 2) = 1/2. So E[X] = 5 x 1/2 + 2 x 1/2 = 3.5 and the standard formula for variance is E[(X - u)^2] so 1/2 x (2-3.5)^2 + 1/2 x (5 - 3.5)^2 = 2.25 or you can calculate with the other formula E[X^2] - E[X]^2 = (5^2 x 1/2 + 2^2 x 1/2) - 3.5^2 = 2.25
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 start at 0 and have to match with output indexing: no gap is allowed. * Finally tuples aren't necessarily ordered by index. If any condition is invalid, the function should return `False`. Input example: ```python [(4,'y'),(1,'o'),(3,'t'),(0,'m'),(2,'n')] ``` Returns ```python 'monty' ```
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 - key and message - and returns the encrypted message. Make sure to only shift letters, and be sure to keep the cases of the letters the same. All punctuation, numbers, spaces, and so on should remain the same. Also be aware of keys greater than 26 and less than -26. There's only 26 letters in the alphabet! ## Examples A message `'Caesar Cipher'` and a key of `1` returns `'Dbftbs Djqifs'`. A message `'Caesar Cipher'` and a key of `-1` returns `'Bzdrzq Bhogdq'`.
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, where the tuple describes `(x, y)` on the keyboard, and where x and y start at 0, positioned at `[Q]`, and where `[<Space>]` occupies all coordinates from (2, 3) to (6, 3) inclusive, create the string as if it had been typed on this keyboard. Assume all letters are lowercase, except the first letter in the string, the first letter following a period or a question mark, and of course the letter "I" ('eye') by itself (no alpha characters before or after it). (Note on Question Mark -- there is no shift key in this kata, so assume all keys are their un-shifted variant, except [/] which should be [?], as shown in the diagram). Use provided test cases if necessary to determine exactly what qualifies as "by itself" for the letter I. Hint: For capitalization, letters are alpha (a-z). If a letter should be capitalized following some punctuation, e.g. after a period, the first alpha character after that period should be capitalized. E.g. 'This., Is a test' is valid, 'This., is a test' is not. Examples: ```python key_strokes([(5, 1), (2, 0), (8, 1), (8, 1), (8, 0), (7, 2), (5, 3), (1, 0), (8, 0), (3, 0), (8, 1), (2, 1)]) 'Hello, world' ``` Other Constraints: 1) Aside from coordinates in the range representing spacebar, you will not receive any coordinates with a y value of 3. 2) All strings will start with an alpha character.
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 range(len(BASE)) for x in range(len(BASE[y]))} def key_strokes(lst): return re . sub(r'\bi\b|^\w|[.?]\W*\w', lambda m: m . group( 0). upper(), '' . join(KEYBOARD . get(tup, '') for tup in lst))
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 conjecture: - pairs should be descending like [3,5] not [5,3] - all pairs should be in ascending order based on the first element of the pair: `[[5, 13], [7, 11]]` is accepted </br> but `[[7, 11],[5, 13]]` is not accepted. Write the a function that find all identical pairs of prime numbers: ```python def goldbach(even_number) ``` You should return an array of containing pairs of primes, like: ```python [[5, 13], [7, 11]] # even_number = 18 ``` or ```python [[3, 31], [5, 29], [11, 23], [17, 17]] # even_number = 34 ```
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 . append([p, x]) p = next_p(p) return result
Goldbach's conjecture (Prime numbers)
56cf0eb69e14db4897000b97
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/56cf0eb69e14db4897000b97
6 kyu