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
Given two different positions on a chess board, find the least number of moves it would take a knight to get from one to the other. The positions will be passed as two arguments in algebraic notation. For example, `knight("a3", "b5")` should return 1. The knight is not allowed to move off the board. The board is 8x8. For information on knight moves, see https://en.wikipedia.org/wiki/Knight_%28chess%29 For information on algebraic notation, see https://en.wikipedia.org/wiki/Algebraic_notation_%28chess%29 (Warning: many of the tests were generated randomly. If any do not work, the test cases will return the input, output, and expected output; please post them.)
algorithms
from collections import deque moves = ((1, 2), (1, - 2), (- 1, 2), (- 1, - 2), (2, 1), (2, - 1), (- 2, 1), (- 2, - 1)) def knight(p1, p2): x, y = ord(p2[0]) - 97, int(p2[1]) - 1 left, seen = deque([(ord(p1[0]) - 97, int(p1[1]) - 1, 0)]), set() while left: i, j, v = left . popleft() if i == x and j == y: return v if (i, j) in seen: continue seen . add((i, j)) for a, b in moves: if 0 <= i + a < 8 and 0 <= j + b < 8: left . append((i + a, j + b, v + 1))
Shortest Knight Path
549ee8b47111a81214000941
[ "Algorithms" ]
https://www.codewars.com/kata/549ee8b47111a81214000941
4 kyu
In [Geometry A-1](http://www.codewars.com/kata/554c8a93e466e794fe000001) kata, `point_vs_vector(point, vector)` function was defined. This function allows to check whether a point is in the right subplane, in the left subplane, or at the line of the vector. However, that function was not required to check for zero-length of the vector, and it could return false results in case of very small distances between a point and a vector due to precision-related error. You have to refactor the function, calling new one `point_vs_vector_v2(point, vector)`, so that it: - returns `None` if vector length is zero; - handles precision errors, so that the formula calculating whether a point belongs to vector's line allows approximately 1.0000000000000005e-09 (`10**-9`) error. ### Examples: * for vector `[[5, 5], [5, 5]]` any point must return `None` * for vector `[[5, 5], [0, 5]]` point at `[1, (5 + 10 **-10)]` must return `0` * for vector `[[5, 5], [0, 5]]` point at `[1, (5 + 10 ** -9)]` must return `1` ### DRY help The function from [Geometry A-1], `point_vs_vector(point, vector)`, is already defined, but does not meet the requirements. You can use it for basic tests, but you have to define new function under the new name.
refactoring
def point_vs_vector_v2(p, v): EPS = 10 * * - 9 (x, y), ((x1, y1), (x2, y2)) = p, v res = (x - x1) * (y2 - y1) - (y - y1) * (x2 - x1) return (- 1) * * (res < 0) * (abs(res) > EPS) if abs(x1 - x2) + abs(y1 - y2) > EPS else None
[Geometry A-1.1] Modify point location detector to handle zero-length vectors and precision errors [DRY]
5550f37131caf073b8000025
[ "Geometry", "Refactoring" ]
https://www.codewars.com/kata/5550f37131caf073b8000025
6 kyu
# Binary Search Trees A `Tree` consists of a root, which is of type `Node`, possibly a left subtree of type `Tree`, and possibly a right subtree of type `Tree`. If the left subtree is present, then all its nodes are less than the parent tree's root; if the right tree is present, then all its nodes are greater than the parent tree's root. ~~~if:python, In this kata, classes `Tree` and `Node` have been provided. However, the methods `__eq__`, `__ne__`, and `__str__` are missing from the `Tree` class. Your job is to provide the implementation of these methods. The example test cases should provide enough information to implement these methods correctly. ~~~ ~~~if:haskell, In this kata, types `Tree` and `Node` have been provided. However, the `Show` and `Eq` instances are missing from the `Tree` type. Your job is to provide the implementation of these instances. The example test cases should provide enough information to implement them correctly. ~~~ As an illustrative example, here is the string representation of a tree that has two nodes, 'B' at the root and 'C' at the root of the right subtree. The left subtree is missing and the right subtree is a leaf, i.e., has no subtrees: ``` "[_ B [C]]" ``` This tree is obtained by evaluating the following expression: ```python Tree(Node('B'), None, Tree(Node('C'))) ``` ```haskell Tree (Node 'B') Nothing (Just $ Tree (Node 'C') Nothing Nothing) ``` Notice in particular that when one subtree, but not both, is missing, an underscore is in its place, a single space separates the root node from the subtrees, and when both subtrees are missing, the root node is enclosed in brackets.
reference
class Tree (object): def __init__(self, root, left=None, right=None): assert root and isinstance(root, Node) assert left is None or isinstance( left, Tree) and left . _max(). root < root assert right is None or isinstance( right, Tree) and root < right . _min(). root self . left = left self . root = root self . right = right def is_leaf(self): return not self . left and not self . right def _max(self): tree = self while tree . right: tree = tree . right return tree def _min(self): tree = self while tree . left: tree = tree . left return tree def __str__(self): if self . is_leaf(): return "[%s]" % self . root return "[%s %s %s]" % ( self . left if self . left else "_", self . root, self . right if self . right else "_") def __eq__(self, other): if not other: return False return ( self . root == other . root and self . left == other . left and self . right == other . right) def __ne__(self, other): return not (self == other) class Node (object): def __init__(self, value): self . value = value def __str__(self): return str(self . value) def __lt__(self, other): return self . value < other . value def __eq__(self, other): return self . value == other . value
Binary Search Trees
571a551a196bb0567f000603
[ "Object-oriented Programming", "Algorithms", "Data Structures" ]
https://www.codewars.com/kata/571a551a196bb0567f000603
5 kyu
A generalization of Bézier surfaces, called the S-patch, uses an interesting scheme for indexing its control points. In the case of an n-sided surface of degree d, each index has n non-negative integers that sum to d, and all possible configurations are used. For example, for a 3-sided quadratic (degree 2) surface the control points are: > indices 3 2 => [[0,0,2],[0,1,1],[0,2,0],[1,0,1],[1,1,0],[2,0,0]] Given the degree and the number of sides, generate all control point indices. The order of the indices in the list can be arbitrary, so for the above example > [[1,1,0],[2,0,0],[0,0,2],[0,2,0],[0,1,1],[1,0,1]] is also a good solution.
algorithms
def gen(n, d): if d == 0 or n == 1: yield [d] * n else: for x in range(d + 1): for y in gen(n - 1, d - x): yield [x] + y def indices(n, d): return list(gen(n, d))
Fixed-length integer partitions
553291f451ab4fbcdc0001c6
[ "Algorithms" ]
https://www.codewars.com/kata/553291f451ab4fbcdc0001c6
5 kyu
A function receives a certain numbers of integers ```n1, n2, n3 ..., np```(all positive and different from 0) and a factor ```k, k > 0``` The function rearranges the numbers ```n1, n2, ..., np``` in such order that generates the minimum number concatenating the digits and this number should be divisible by ```k```. The order that the function receives their arguments is: ```python rearranger(k, n1, n2, n3,....,np) ``` ~~~if:ruby,python ## Examples ``` rearranger(4, 32, 3, 34, 7, 12) returns "Rearrangement: 12, 3, 34, 7, 32 generates: 12334732 divisible by 4" rearranger(10, 32, 3, 34, 7, 12) returns "There is no possible rearrangement" ``` If there are more than one possible arrangements for the same minimum number, your code should be able to handle those cases: ``` rearranger(6, 19, 32, 2, 124, 20, 22) returns "Rearrangements: 124, 19, 20, 2, 22, 32 and 124, 19, 20, 22, 2, 32 generates: 124192022232 divisible by 6" ``` ~~~ ~~~if-not:ruby,python ## Examples (input --> output) ``` rearranger(4, 32, 3, 34, 7, 12) --> "Rearrangement: 12, 3, 34, 7, 32 generates: 12334732 divisible by 4" rearranger(10, 32, 3, 34, 7, 12) --> "There is no possible rearrangement" ``` If there are more than one possible arrangements for the same minimum number, your code should be able to handle those cases: ``` 6, [19, 32, 2, 124, 20, 22] --> "Rearrangements: 124, 19, 20, 2, 22, 32 and 124, 19, 20, 22, 2, 32 generate: 124192022232 divisible by 6" ``` ~~~ The arrangements should be in sorted order, as you see: `124, 19, 20, 2, 22, 32` comes first than `124, 19, 20, 22, 2, 32`. Have an enjoyable time! (Thanks to `ChristianE.Cooper` for his contribution to this kata)
algorithms
from itertools import permutations def rearranger(k, * args): perms = permutations(map(str, args), len(args)) divisible_by_k = filter(lambda x: int('' . join(x)) % k == 0, perms) try: rearranged = min(divisible_by_k, key=lambda x: int('' . join(x))) return 'Rearrangement: {} generates: {} divisible by {}' . format(', ' . join(rearranged), '' . join(rearranged), k) except ValueError: return "There is no possible rearrangement"
Rearrangement of Numbers to Have The Minimum Divisible by a Given Factor
569e8353166da6908500003d
[ "Fundamentals", "Mathematics", "Sorting", "Logic", "Strings", "Algorithms" ]
https://www.codewars.com/kata/569e8353166da6908500003d
5 kyu
### Description Here is a rope with a length of `x cm`. We will cut it in the following way: each `m cm` to make a mark, and then each `n cm` to make a mark. Finally, We cut the rope from the marked place. Please calculate that we have a total of several kinds of length of the rope, and how many of each kind of rope? For example: ``` length=10 -----here is a rope with length of 10 cm, each "-" is 1cm ---------- m=2 -----------we make marks at each 2cm, "." is the mark --.--.--.--.-- n=3 -----------we make marks at each 3cm, "." is the mark --.-.-.--.--.-.- cut the rope from these marked place, we got: -- - - -- -- - - so the result should be: 1cm rope x 4 and 2cm rope x 3 ``` ### Task Complete function `cutRope()` that accepts three arguments `length`, `m` and `n`(three positive integer). Their meaning please refer to the above explanation. You should return an object that contains all kinds of rope and its numbers. Like the example above, should return: `{"1cm":4,"2cm":3}` ### Examples ``` cutRope(6,2,3) === {"1cm":2,"2cm":2} cutRope(7,2,3) === {"1cm":3,"2cm":2} cutRope(10,2,3) === {"1cm":4,"2cm":3} cutRope(10,2,5) === {"1cm":2,"2cm":4} cutRope(11,2,5) === {"1cm":3,"2cm":4} ```
games
from collections import Counter from itertools import pairwise def cut_rope(length, m, n): cuts = sorted([0, * range(m, length, m), * range(n, length, n), length]) return {f' { k } cm': v for k, v in Counter(b - a for a, b in pairwise(cuts)). items() if k}
T.T.T.39: Cut rope
57b2a9631fae8a30fa000013
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/57b2a9631fae8a30fa000013
6 kyu
You have been tasked with converting a number from base i (sqrt of -1) to base 10. Recall how bases are defined: abcdef = a * 10^5 + b * 10^4 + c * 10^3 + d * 10^2 + e * 10^1 + f * 10^0 Base i follows then like this: ... i^4 + i^3 + i^2 + i^1 + i^0 The only numbers in any place will be 1 or 0 Examples: 101 in base i would be: 1 * i^2 + 0 * i^1 + 1*i^0 = -1 + 0 + 1 = 0 10010 in base i would be: 1*i^4 + 0 * i^3 + 0 * i^2 + 1 * i^1 + 0 * i^0 = 1 + i = 1+i You must take some number, n, in base i and convert it into a number in base 10, in the format of a 2x1 vector. [a,b] = a+b*i The number will always be some combination of 0 and 1 In Python you will be given an integer. In Javascript and C++ you will be given a string
algorithms
def convert(n): ds = list(map(int, reversed(str(n)))) return [sum(ds[:: 4]) - sum(ds[2:: 4]), sum(ds[1:: 4]) - sum(ds[3:: 4])]
Imaginary Base Conversion
583a47342fb0ba1418000060
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/583a47342fb0ba1418000060
6 kyu
In mathematics, a <a href="https://en.wikipedia.org/wiki/Matrix_%28mathematics%29">matrix</a> (plural matrices) is a rectangular array of numbers. Matrices have many applications in programming, from <a href="http://www.mathplanet.com/education/geometry/transformations/transformation-using-matrices">performing transformations in 2D space</a> to <a href="http://videolectures.net/icml09_dhillon_itmcml/">machine learning</a>. One of the most useful operations to perform on matrices is <a href="https://en.wikipedia.org/wiki/Matrix_multiplication">matrix multiplication</a>, which takes a pair of matrices and produces another matrix – known as the dot product. Multiplying matrices is very different to multiplying real numbers, and follows its own set of rules. Unlike multiplying real numbers, multiplying matrices is <b>non-commutative</b>: in other words, multiplying matrix ```a``` by matrix ```b``` will not give the same result as multiplying matrix ```b``` by matrix ```a```. Additionally, not all pairs of matrix can be multiplied. For two matrices to be multipliable, the number of columns in matrix ```a``` must match the number of rows in matrix ```b```. There are many introductions to matrix multiplication online, including at <a href="https://www.khanacademy.org/math/precalculus/precalc-matrices/multiplying-matrices-by-matrices/v/matrix-multiplication-intro">Khan Academy</a>, and in the <a href="https://www.youtube.com/watch?v=MfN1lqArwAg">classic MIT lecture series by Herbert Gross</a>. To complete this kata, write a function that takes two matrices - ```a``` and ```b``` - and returns the dot product of those matrices. If the matrices cannot be multiplied, return `null`/`None`/`Nothing` or similar. Each matrix will be represented by a two-dimensional list (a list of lists). Each inner list will contain one or more numbers, representing a row in the matrix. For example, the following matrix: ```|1 2|```<br>```|3 4|``` Would be represented as: ```[[1, 2], [3, 4]]``` It can be assumed that all lists will be valid matrices, composed of lists with equal numbers of elements, and which contain only numbers. The numbers may include integers and/or decimal points.
algorithms
import numpy as np def get_matrix_product(a, b): try: return np . array(a). dot(np . array(b)). tolist() except: return None
Matrix Multiplier
573248f48e531896770001f9
[ "Matrix", "Algorithms", "Linear Algebra", "Mathematics" ]
https://www.codewars.com/kata/573248f48e531896770001f9
6 kyu
# Task You are given integer `n` determining set S = {1, 2, ..., n}. Determine if the number of k-element subsets of S is `ODD` or `EVEN` for given integer k. # Example For `n = 3, k = 2`, the result should be `"ODD"` In this case, we have 3 2-element subsets of {1, 2, 3}: `{1, 2}, {1, 3}, {2, 3}` For `n = 2, k = 1`, the result should be `"EVEN"`. In this case, we have 2 1-element subsets of {1, 2}: `{1}, {2}` `Don't bother with naive solution - numbers here are really big.` # Input/Output - `[input]` integer `n` `1 <= n <= 10^9` - `[input]` integer `k` `1 <= k <= n` - `[output]` a string `"EVEN"` or `"ODD"` depending if the number of k-element subsets of S = {1, 2, ..., n} is ODD or EVEN.
games
def subsets_parity(n, k): return 'EVEN' if ~ n & k else 'ODD'
Simple Fun #119: Sub Sets Parity
589d5c80c31aa590e300006b
[ "Puzzles" ]
https://www.codewars.com/kata/589d5c80c31aa590e300006b
4 kyu
For a given 2D point with coordinates presented as `[x, y]`, determine if it belongs to a vector presented as `[[x1, y1],[x2, y2]]`, and return `True` if point belongs to the vector (including vector's ends) or `False` if not. Vector may have a zero length (i. e. start and end in the same point). Random test cases will have a lot of float coordinates. For any possible precision-related errors, you have to handle those errors in your function. In tests, distance between a point not belonging to the vector and the vector will never be less than `0.001`. **DRY help:** In this kata, functions from [Geometry A-1.1](http://www.codewars.com/kata/5550f37131caf073b8000025) and [Geometry A-2](http://www.codewars.com/kata/554dc2b88fbafd2e95000125) katas are avialble. You can reuse them if you want.
algorithms
class Point: __slots__ = ['x', 'y'] def __init__(self, x, y): self . x = x self . y = y def colinear(self, p, q): t1 = (self . x - p . x) * (self . y - q . y) t2 = (self . x - q . x) * (self . y - p . y) return abs(t1 - t2) <= 1e-9 def within(self, p, q): if p . x <= self . x <= q . x or p . x >= self . x >= q . x: return p . y <= self . y <= q . y or p . y >= self . y >= q . y return False def point_in_vector(point, vector): a = Point(* point) b = Point(* vector[0]) c = Point(* vector[1]) return a . colinear(b, c) and a . within(b, c)
[Geometry A-3] Does point belong to the vector? [DRY]
554e5ef27daf4082f6000071
[ "Geometry", "Algorithms" ]
https://www.codewars.com/kata/554e5ef27daf4082f6000071
6 kyu
> When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said # Description: In this Kata, we have to try to create a mysterious pattern. Given a positive integer `m`, you can generate a Fibonacci sequence with a length of `m`: ``` 1 1 2 3 5 8 13 21 34 ... ``` Given a positive integer `n`, you need to execute `%` operation on each element of the Fibonacci sequence: ``` m = 9, n = 3 Fibonacci sequence: 1 1 2 3 5 8 13 21 34 ---> 1%3 1%3 2%3 3%3 5%3 8%3 13%3 21%3 34%3 ---> 1 1 2 0 2 2 1 0 1 ``` Finally, make `n` rows string to show the pattern: ``` 112022101 ||||||||| o o oo o o o oo ``` Please note: * Each row is separated by `"\n"`; * You should trim the end of each row; * If there are some empty rows at the start or end of string, you should trim them too. But, if the empty row is in the middle(see the last example), you should not trim it. # Examples: For m = 5, n = 5, the output should be: ``` o oo o o ``` For m = 12, n = 4, the output should be: ``` o o oo o oo o o o o o ``` For m = 1, n = 1, the output should be:`"o"` For: m = 6, n = 15, the output should be: ``` oo o o o o ```
games
def mysterious_pattern(m, n): rows = [[' '] * m for _ in range(n)] a, b = 1, 1 for i in range(m): rows[a % n][i] = 'o' a, b = b, a + b rows = ['' . join(r). rstrip() for r in rows] return '\n' . join(rows). strip('\n')
Mysterious Pattern
580ec64394291d946b0002a1
[ "ASCII Art", "Puzzles" ]
https://www.codewars.com/kata/580ec64394291d946b0002a1
6 kyu
An array is called *zero-plentiful* if it contains multiple zeros, and **every** sequence of zeros is at least 4 items long. Your task is to return the number of zero sequences if the given array is *zero-plentiful*, oherwise `0`. ## Examples ```python [0, 0, 0, 0, 0, 1] --> 1 # 1 group of 5 zeros (>= 4), thus the result is 1 [0, 0, 0, 0, 1, 0, 0, 0, 0] --> 2 # 2 group of 4 zeros (>= 4), thus the result is 2 [0, 0, 0, 0, 1, 0] --> 0 # 1 group of 4 zeros and 1 group of 1 zero (< 4) # _every_ sequence of zeros must be at least 4 long, thus the result is 0 [0, 0, 0, 1, 0, 0] --> 0 # 1 group of 3 zeros (< 4) and 1 group of 2 zeros (< 4) [1, 2, 3, 4, 5] --> 0 # no zeros [] --> 0 # no zeros ```
reference
from itertools import groupby def zero_plentiful(arr): r = [len(list(g)) > 3 for k, g in groupby(arr) if k == 0] return all(r) * len(r)
Zero-plentiful Array
59e270da7997cba3d3000041
[ "Fundamentals" ]
https://www.codewars.com/kata/59e270da7997cba3d3000041
6 kyu
## Screen Locking Patterns You might already be familiar with many smartphones that allow you to use a geometric pattern as a security measure. To unlock the device, you need to connect a sequence of dots/points in a grid by swiping your finger **without lifting it** as you trace the pattern through the screen. The image below has an example pattern of 7 dots/points: (A -> B -> I -> E -> D -> G -> C). ![lock_example.png](https://i.imgur.com/zmPNYdv.png) For this kata, your job is to implement a function that returns **the number of possible patterns starting from a given first point, that have a given length**. ```if-not:commonlisp More specifically, for a function `countPatternsFrom(firstPoint, length)`, the parameter `firstPoint` is a single-character string corresponding to the point in the grid (e.g.: `'A'`) where your patterns start, and the parameter `length` is an integer indicating the number of points (length) every pattern must have. For example, `countPatternsFrom("C", 2)`, should return the number of patterns starting from `'C'` that have `2` two points. The return value in this case would be `5`, because there are 5 possible patterns: ``` ```if:commonlisp More specifically, for a function `(count-patterns-from first-dot length)`, the parameter `first-dot` is a single-character string corresponding to the point in the grid (e.g.: `"A"`) where your patterns start, and the parameter `length` is an integer indicating the number of points (length) every pattern must have. For example, `(count-patterns-from "C" 2)`, should return the number of patterns starting from `"C"` that have `2` two points. The return value in this case would be `5`, because there are 5 possible patterns: ``` (C -> B), (C -> D), (C -> E), (C -> F) and (C -> H). Bear in mind that this kata requires returning the **number** of patterns, **not the patterns themselves**, so you only need to count them. Also, **the name of the function might be different depending on the programming language used**, but the idea remains the same. ## Rules 1. In a pattern, the dots/points **cannot be repeated**: they can only be used once, at most. 2. In a pattern, any two subsequent dots/points can only be connected with **direct straight lines** in either of these ways: 1. **Horizontally:** like (A -> B) in the example pattern image. 2. **Vertically:** like (D -> G) in the example pattern image. 3. **Diagonally:** like (I -> E), *as well as* (B -> I), in the example pattern image. 4. **Passing over a point between them that has already been 'used':** like (G -> C) passing over E, in the example pattern image. This is the trickiest rule. Normally, you wouldn't be able to connect G to C, because E is between them, **however** when E has already been used as part the pattern you are tracing, you **can** connect G to C **passing over E**, because E is **ignored**, as it was already used once. <br/>The sample tests have some examples of the number of combinations for some cases to help you check your code. **Haskell Note:** A data type `Vertex` is provided in place of the single-character strings. See the solution setup code for more details. **Fun fact:** In case you're wondering out of curiosity, for the Android lock screen, the valid patterns must have between 4 and 9 dots/points. There are 389112 possible valid patterns in total; that is, patterns with a length between 4 and 9 dots/points.
algorithms
EQUIV_PTS = {same: src for src, seq in ( ('A', 'CGI'), ('B', 'DFH')) for same in seq} ALL = set('ABCDEFGHI') LINKED_TO = {'A': ('BC', 'DG', 'EI', 'F', 'H'), 'B': ('A', 'C', 'D', 'EH', 'F', 'G', 'I'), 'C': ('BA', 'D', 'EG', 'FI', 'H'), 'D': ('A', 'B', 'C', 'EF', 'G', 'H', 'I'), 'E': tuple('ABCDFGHI'), 'F': ('A', 'B', 'C', 'ED', 'G', 'H', 'I'), 'G': ('DA', 'B', 'EC', 'F', 'HI'), 'H': ('A', 'EB', 'C', 'D', 'F', 'G', 'I'), 'I': ('EA', 'B', 'FC', 'D', 'HG') } def DFS(c, depth, root, seens, patterns): if depth > len(ALL): return patterns[root][depth] += 1 seens . add(c) toExplore = '' . join(next((n for n in seq if n not in seens), '') for seq in LINKED_TO[c]) for nextC in toExplore: DFS(nextC, depth + 1, root, seens, patterns) seens . discard(c) PATTERNS = {} for c in "ABE": PATTERNS[c] = [0] * 10 DFS(c, 1, c, set(), PATTERNS) def count_patterns_from(start, length): if not (0 < length < 10) or start not in ALL: return 0 actualStart = EQUIV_PTS . get(start, start) return PATTERNS[actualStart][length]
Screen Locking Patterns
585894545a8a07255e0002f1
[ "Mathematics", "Combinatorics", "Geometry", "Algorithms", "Graph Theory" ]
https://www.codewars.com/kata/585894545a8a07255e0002f1
3 kyu
<img src="http://bestanimations.com/Science/Gears/loadinggears/loading-gears-animation-6-4.gif"/> # Kata Task You are given a list of cogs in a <a href ="https://en.wikipedia.org/wiki/Gear_train">gear train</a> Each element represents the number of teeth of that cog e.g. `[100, 75]` means * 1st cog has 100 teeth * 2nd cog has 75 teeth If the first cog rotates clockwise at 1 RPM what is the RPM of the final cog? (use negative numbers for anti-clockwise rotation) # Notes * no two cogs share the same shaft --- Series: * Cogs * <a href="https://www.codewars.com/kata/cogs-2">Cogs 2</a>
reference
def cog_RPM(l): return (- 1 + len(l) % 2 * 2) * l[0] / l[- 1]
Cogs
59e1b9ce7997cbecb9000014
[ "Fundamentals" ]
https://www.codewars.com/kata/59e1b9ce7997cbecb9000014
7 kyu
Two integers are coprimes if the their only greatest common divisor is 1. ## Task In this kata you'll be given a number ```n >= 2``` and output a list with all positive integers less than ```gcd(n, k) == 1```, with ```k``` being any of the output numbers. The list cannot include duplicated entries and has to be sorted. ## Examples ``` 2 -> [1] 3 -> [1, 2] 6 -> [1, 5] 10 -> [1, 3, 7, 9] 20 -> [1, 3, 7, 9, 11, 13, 17, 19] 25 -> [1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19, 21, 22, 23, 24] 30 -> [1, 7, 11, 13, 17, 19, 23, 29] ```
algorithms
from fractions import gcd def coprimes(n): return [i for i in range(1, n + 1) if gcd(n, i) == 1]
Coprimes up to N
59e0dbb72a7acc3610000017
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/59e0dbb72a7acc3610000017
6 kyu
Given a string (`str`) containing a base-10 integer between `0` and `10000`, convert the integer to its binary representation. At that point, obtain a count of the maximum amount of consecutive 0s. From there, return the count in written form with a capital letter. ```ruby max_consec_zeros("9") => "Two" max_consec_zeros("13") => "One" max_consec_zeros("15") => "Zero" max_consec_zeros("42") => "One" max_consec_zeros("550") => "Three" ``` In the very first example, we have an argument of `"9"` which is being passed to the method. The binary representation of `9` is `1001` which can be read as: one, zero, zero, one. There are, at most, two consecutive 0s, resulting in the integer `2` as the value of the count. The output in the block of code above reflects the final step of taking `2` from standard form to the written form `"Two"` as prompted. In the very last example, we have an argument of `"550"` which is being passed to the method. The binary representation of `550` is `1000100110` which can be read as: one, zero, zero, zero, one, zero, zero, one, one, zero. There are, at most, three consecutive 0s, resulting in the integer `3` as the value of the count. The output in the block of code above reflects the final step of taking `3` from standard form to the written form of `"Three"` as prompted. One way, among many, to visualize the end of each step might look like: ``` max_consec_zeros("777") 1: "777" 2: 777 3: 1100001001 4: 4 5: "Four" max_consec_zeros("777") => "Four" ``` Happy coding!
reference
import re ls = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen"] def max_consec_zeros(n): return ls[max(map(lambda x: len(x), re . findall(r'0*', bin(int(n))[2:])))]
Most Consecutive Zeros of a Binary Number
59decdf40863c76ae3000080
[ "Fundamentals", "Mathematics", "Strings" ]
https://www.codewars.com/kata/59decdf40863c76ae3000080
6 kyu
# Letterss of Natac In a game I just made up that doesn’t have anything to do with any other game that you may or may not have played, you collect resources on each turn and then use those resources to build things like roads, settlements and cities. If you would like to try other kata about this game, they can be found **[here](https://www.codewars.com/collections/59e6938afc3c49005900011f)** ## Task This kata asks you to implement a time efficient version of the function `play_if_enough(hand, play)` , which takes as input a `hand`, the resources you have (a string of letters representing the resources you have), and a `play`, (a string of letters representing the resources required to build a certain game object), and returns a tuple (list in r) of a boolean value, corresponding to whether you have enough resources, and your hand. If you had enough to build the object, the returned hand is your resources minus those you used to build the object. If not, it is your original hand (the one passed to the function). For example, if it takes 3 ore and 2 grain to build a city, `play` is `”ooogg”`. If `hand` is `”ooooogggssbbb”`, then `play_if_enough(hand, play)` returns `(True, “oogssbbb”)`. ## Examples ```python play_if_enough("ooooogggssbbb", "ooogg") => (True, "oogssbbb") play_if_enough("oogssbbb", "bwsg") => (False, "oogssbbb") play_if_enough("", "bw") => (False, "") play_if_enough("abcdefghij", "aa") => (False, "abcdefghij") ``` ```r play_if_enough("ooooogggssbbb", "ooogg") [[1]] [1] TRUE [[2]] [1] "oogssbbb" play_if_enough("oogssbbb", "bwsg") [[1]] [1] FALSE [[2]] [1] "oogssbbb" play_if_enough("", "bw") [[1]] [1] FALSE [[2]] [1] "" play_if_enough("abcdefghij", "aa") [[1]] [1] FALSE [[2]] [1] "abcdefghij" ``` ## Notes: 1. The order of resources in your hand (or play) is not relevant. You can shuffle your hand any way you'd like, so long as you have the same number of each resource. 2. There are 26 different resources, each represented by a lower case letter a-z, so a valid hand is a string of lower case letters. 3. A valid play is a string of any number of lower case letters. 4. You do not have to test for whether a hand or play is valid. 5. A hand can be empty, but a play can't. In the event a hand is empty, you don't have the cards to play, so return `(False, "")`, in the correct data structure for your language, see example 4 above. 6. Tests include hand sizes of up to 150000 elements and play sizes up to 10000 elements.
reference
from collections import Counter def play_if_enough(hand, play): h = Counter(hand) p = Counter(play) if p & h == p: h . subtract(p) return (True, "" . join(h . elements())) return (False, hand)
Letterss of Natac
59e0069781618a7950000995
[ "Fundamentals" ]
https://www.codewars.com/kata/59e0069781618a7950000995
5 kyu
Imagine two arrays/lists where elements are linked by their positions in the array. For example: ``` HowMany = [ 1 , 6 , 5 , 0 ]; Type = ['house', 'car','pen','jeans']; ``` Means I have 1 house, 6 cars,5 pens and 0 jeans. Now if we sort one array we lose the connectivity. The goal is to create a sorting function that keeps the position link ```linkedSort(arrayToSort,linkedArray,compareFunction)```. So for every element that moves in ```arrayToSort```(HowMany in the example), the corresponding element in ```linkedArray```(Type in the example) needs to move similarly. For example in Javascript: ``` //INPUT HowMany = [ 1 , 6 , 5 , 0 ]; Type = ['house', 'car','pen','jeans']; //SORT res = linkedSort(HowMany,Type,function(a,b){return a-b;}) //OUTPUT HowMany === res === [ 0 , 1 , 5 , 6 ]; Type === ['jeans','house','pen','car']; ``` ```linkedSort(...)``` return the "arrayToSort" sorted only. If no compare function is provided you should handle like an alphabetical sorting would do, e.g: ```javascript [-71,-6,35,0].sort() === [-6,-71,0,35] != [-71,-6,0,35] ``` ```python yoursortingfunction([-71,-6,35,0]) === [-6,-71,0,35] != [-71,-6,0,35] ``` ```ruby yoursortingfunction([-71,-6,35,0]) === [-6,-71,0,35] != [-71,-6,0,35] ``` Note: it is assumed that array are same length.
algorithms
def linked_sort(a, b, key=str): a[:], b[:] = zip(* sorted(zip(a, b), key=key)) return a
2 Arrays 1 Sort
546b22225874d24fbd00005b
[ "Arrays", "Algorithms", "Sorting" ]
https://www.codewars.com/kata/546b22225874d24fbd00005b
6 kyu
We have the following function of two variables x, y (values of x, y are in determined ranges of values): <a href="http://imgur.com/0HdIVic"><img src="http://i.imgur.com/0HdIVic.png?1" title="source: imgur.com" /></a> The function above is studied for ```x, y```, positive integers, and ```x ≠ y```. ```⌊ ⌋``` - represents the function floor and ```| |``` the absolute value. In the image below there is 3D graph that may show some features of the function: <a href="http://imgur.com/pF8WR77"><img src="http://i.imgur.com/pF8WR77.png" title="source: imgur.com" /></a> ```xmin = 0, xmax = 10 ; ymin = 0, ymax = 10 and zmax (the same value of hMax) near 250```. The function has extremely high values for wider ranges of x and y. We need a function ```max_val_f()```, that accepts four arguments: (1) ```range1```: ```m ≤ x ≤ n``` -----> ```[m, n]``` (The values of ```x``` belong to the interval range1) (2) ```range2```: ```p ≤ y ≤ q``` -----> ```[p, q]``` (The values of ```y``` belong to the interval range2) (3) ```hMax```: ```f(x, y) ≤ hMax``` (The values of ```f(x, y)``` selected should be bellow or equal ```hMax```) (4) the length for the wanted array for the output The function should output the largest values of ```f(x, y)``` less or equal than hMax, in increasing order (the amount of highest values coincides with the entry (4)) To explain graphicaly the features of our asked function: ``` max_val_f([m, n], [p, q], hMax, k) -------> [f(x1, y1), f(x2, y2), ....f(xk, yk)] # f(x1, y1) < f(x2, y2) < ....< f(xk, yk) ≤ hMax ``` Let's see some cases: ```python range1 = [1, 10] range2 = [1, 10] hMax = 500 k = 4 max_val_f(range1, range2, hMax, k) -----> [81.0, 125.0, 243.0, 256.0] range1 = [1, 50] range2 = [1, 50] hMax = 500 k = 4 max_val_f(range1, range2, hMax, k) -----> [361.0, 400.0, 441.0, 484.0] range1 = [1, 50] range2 = [1, 50] hMax = 1000 k = 5 max_val_f(range1, range2, hMax, k) -----> [784.0, 841.0, 900.0, 961.0, 1000.0] ``` ```ruby range1 = [1, 10] range2 = [1, 10] hMax = 500 k = 4 max_val_f(range1, range2, hMax, k) -----> [81.0, 125.0, 243.0, 256.0] range1 = [1, 50] range2 = [1, 50] hMax = 500 k = 4 max_val_f(range1, range2, hMax, k) -----> [361.0, 400.0, 441.0, 484.0] range1 = [1, 50] range2 = [1, 50] hMax = 1000 k = 5 max_val_f(range1, range2, hMax, k) -----> [784.0, 841.0, 900.0, 961.0, 1000.0] ``` ```haskell range1 = (1, 10) range2 = (1, 10) hMax = 500 k = 4 maxValF range1 range2 hMax k -----> [81.0, 125.0, 243.0, 256.0] range1 = (1, 50) range2 = (1, 50) hMax = 500 k = 4 maxValF range1 range2 hMax k -----> [361.0, 400.0, 441.0, 484.0] range1 = (1, 50) range2 = (1, 50) hMax = 1000 k = 5 maxValF range1 range2 hMax k -----> [784.0, 841.0, 900.0, 961.0, 1000.0] ``` ```javascript range1 = [1, 10] range2 = [1, 10] hMax = 500 k = 4 max_val_f(range1, range2, hMax, k) -----> [81.0, 125.0, 243.0, 256.0] range1 = [1, 50] range2 = [1, 50] hMax = 500 k = 4 max_val_f(range1, range2, hMax, k) -----> [361.0, 400.0, 441.0, 484.0] range1 = [1, 50] range2 = [1, 50] hMax = 1000 k = 5 max_val_f(range1, range2, hMax, k) -----> [784.0, 841.0, 900.0, 961.0, 1000.0] ``` Enjoy it and happy coding!
reference
from math import pow, floor def max_val_f(range1, range2, hMax, k): m, n = range1[0], range1[1] p, q = range2[0], range2[1] res = [] for x in range(m, n + 1): for y in range(p, q + 1): if x != y: ab = float(abs(x - y)) val = pow(floor((x + y) / ab), ab) if val <= hMax: res . append(val) res = list(set(res)) res . sort() return res[- k:]
Finding the Closest Maximum Values of a Function to an Upper Limit
56085481f82c1672d000001f
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/56085481f82c1672d000001f
5 kyu
This kata is a very basic introduction to compression. Your task is to make a program which **takes in a sentence** and returns a string which shows the **unique position** of each word in the sentence. If a word appears more than once in the sentence, your string should return the position of the **first occurrence** of the word. Unique position in this case means the position of the word **excluding repeated words**. Capitalisation of words should be accounted for: 'BEE' should be considered the same as 'bee'. The sentences include no punctuation. Example ----- `"man hello man"` becomes `"010"` Example ----- `"THE ONE BUMBLE BEE one bumble the bee"` becomes `"01231203"` Example ----- `"Ask not what your COUNTRY can do for you ASK WHAT YOU CAN DO FOR YOUR country"` becomes `"01234567802856734"`
algorithms
def compress(sentence): ref = [] for i in sentence . lower(). split(): if i not in ref: ref . append(i) return '' . join([str(ref . index(n)) for n in sentence . lower(). split()])
Compress sentences
59de469cfc3c492da80000c5
[ "Lists", "Algorithms" ]
https://www.codewars.com/kata/59de469cfc3c492da80000c5
7 kyu
It happened decades before Snapchat, years before Twitter and even before Facebook. Targeted advertising was a bit of a challenge back then. One day, the marketing professor at my university told us a story that I am yet to confirm using reliable sources. Nevertheless, I retold the story to dozens of my students already, so, sorry BMW if it is all a big lie. Allegedly, BMW, in an attempt to target the educated, produced billboard posters featuring the English alphabet with three letters missing: B, M and W. Needless to say, many were confused, some to the extent of road accidents. Your task is to write a function that takes one parameter str that MUST be a string and removes all capital and small letters B, M and W. If data of the wrong data type was sent as a parameter the function must throw an error with the following specific message: ```python TypeError("This program only works for text.") ``` ```javascript new Error("This program only works for text."); ``` ```ruby "This program only works for text." ``` ```groovy new IllegalArgumentException("This program only works for text.") ``` For Python [here](https://docs.python.org/3/library/exceptions.html)'s a good resource you might need for the exception type ;)
reference
def remove_bmw(string): try: return string . translate(str . maketrans('', '', "BMWbmw")) except AttributeError: raise TypeError("This program only works for text.")
Remove B M W
59de795c289ef9197f000c48
[ "Fundamentals", "Strings", "Regular Expressions" ]
https://www.codewars.com/kata/59de795c289ef9197f000c48
7 kyu
Your task is to create a magic square for any positive odd integer `N`. The magic square contains the integers from `1` to `N * N`, arranged in an `NxN` matrix, such that the columns, rows and both main diagonals add up to the same number. **Note**: use have to use the [Siamese method](https://en.wikipedia.org/wiki/Siamese_method) for this task. ## Examples: ``` n = 3 result = [ [8, 1, 6], [3, 5, 7], [4, 9, 2] ] n = 5 result = [ [17, 24, 1, 8, 15], [23, 5, 7, 14, 16], [ 4, 6, 13, 20, 22], [10, 12, 19, 21, 3], [11, 18, 25, 2, 9] ] ```
games
def magicSquare(n): if n % 2: square = [[0] * n for _ in range(n)] for i in range(n * * 2): x, y = (2 * (i / / n) - i) % n, (n / / 2 + i - i / / n) % n square[x][y] = i + 1 return square else: return "Please enter an odd integer."
Odd Magic Square
570b69d96731d4cf9c001597
[ "Puzzles", "Arrays", "Mathematics" ]
https://www.codewars.com/kata/570b69d96731d4cf9c001597
6 kyu
You need to write a function, that returns the first non-repeated character in the given string. If all the characters are unique, return the first character of the string. If there is no unique character, return `null` in JS or Java, `None` in Python, `'\0'` in C. You can assume, that the input string has always non-zero length. ## Examples ``` "test" returns "e" "teeter" returns "r" "trend" returns "t" (all the characters are unique) "aabbcc" returns null (all the characters are repeated) ```
reference
def first_non_repeated(s): for c in s: if s . count(c) == 1: return c
The First Non Repeated Character In A String
570f6436b29c708a32000826
[ "Algorithms", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/570f6436b29c708a32000826
7 kyu
## Task ```if:haskell Create a function `eqAll` that determines if all elements of a `list` are equal. `list` can be any `Foldable` structure, of any `Eq` instance, and may be infinite. Return value is a `Bool`. ``` ```if:javascript Create a function `eqAll` that determines if all elements of a `list` are equal. `list` can be any [iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable), and may be infinite. Return value is a `Boolean`. ``` ```if:python Create a function `eq_all` that determines if all elements of any [iterable](https://docs.python.org/3/glossary.html#term-iterable) are equal; the iterable may be infinite. Return value is a `bool`. ``` ## Examples ```haskell eqAll "aaa" -> True eqAll "abc" -> False eqAll "" -> True eqAll [0,0,0] -> True eqAll [0,1,2] -> False eqAll [] -> True eqAll Nothing -> True eqAll (Just 0) -> True ``` ```javascript eqAll("aaa") => true eqAll("abc") => false eqAll("") => true eqAll([0,0,0]) => true eqAll([0,1,2]) => false eqAll([]) => true ``` ```python eq_all('aaa') : True eq_all('abc') : False eq_all('') : True eq_all([0,0,0]) : True eq_all([0,1,2]) : False eq_all([]) : True ``` ## Notes ```if:haskell For the function result to be `True`, the `Foldable` must be finite; `False`, however, can result from an element finitely far from the left end. There will be no tests with infinite series of equal elements. ``` ```if:javascript For the function result to be `true`, the `iterable` must be finite; `false`, however, can result from an element finitely far from the left end. There will be no tests with infinite series of equal elements. Elements will be primitive values; equality should be strict `(===)`. ``` ```if:python For the function result to be `True`, the `iterable` must be finite; `False`, however, can result from an element finitely far from the left end. There will be no tests with infinite series of equal elements. Elements will be primitive values. ```
reference
from itertools import islice, groupby def eq_all(iterable): return not next(islice(groupby(iterable), 1, None), False)
Are all elements equal? (Infinity version)
59dce15af703c42af6000035
[ "Fundamentals" ]
https://www.codewars.com/kata/59dce15af703c42af6000035
6 kyu
Two strings ```a``` and b are called isomorphic if there is a one to one mapping possible for every character of ```a``` to every character of ```b```. And all occurrences of every character in ```a``` map to same character in ```b```. ## Task In this kata you will create a function that return ```True``` if two given strings are isomorphic to each other, and ```False``` otherwise. Remember that order is important. Your solution must be able to handle words with more than 10 characters. ## Example True: ``` CBAABC DEFFED XXX YYY RAMBUNCTIOUSLY THERMODYNAMICS ``` False: ``` AB CC XXY XYY ABAB CD ```
algorithms
def isomorph(a, b): return [a . index(x) for x in a] == [b . index(y) for y in b]
Check if two words are isomorphic to each other
59dbab4d7997cb350000007f
[ "Algorithms" ]
https://www.codewars.com/kata/59dbab4d7997cb350000007f
6 kyu
## A Knight's Tour A knight's tour is a sequence of moves of a knight on a chessboard such that the knight visits every square only once. https://en.wikipedia.org/wiki/Knight%27s_tour Traditional chess boards are 8x8 grids, but for this kata we are interested in generating tours for any square board sizes. You will be asked to find a knight's path for any NxN board from any start position. I have provided a tool to visualize the output of your code at the following link: http://jsfiddle.net/7sbyya59/2/ EDIT: The expected output is a 2D array `(n x 2)` comprised of the `[x,y]` coordinates of the Knight's path taken in sequential order. (e.g. `[[2,3],[4,4],...,[x,y]]`) All test cases will have a passing solution. -dg
algorithms
def knights_tour(start, size): MOVES = [(- 2, 1), (- 2, - 1), (- 1, - 2), (1, - 2), (2, - 1), (2, 1), (1, 2), (- 1, 2)] def genNeighs(pos): return ((pos[0] + dx, pos[1] + dy) for dx, dy in MOVES if (pos[0] + dx, pos[1] + dy) in Warnsdorf_DP) def travel(pos): neighs = sorted((Warnsdorf_DP[n], n) for n in genNeighs(pos)) for nSubNeighs, neigh in neighs: del Warnsdorf_DP[neigh] path . append(neigh) subNeighs = list(genNeighs(neigh)) for n in subNeighs: Warnsdorf_DP[n] -= 1 travel(neigh) if not Warnsdorf_DP: break else: for n in subNeighs: Warnsdorf_DP[n] += 1 Warnsdorf_DP[path . pop()] = nSubNeighs path, Warnsdorf_DP = [start], {(x, y): 0 for x in range( size) for y in range(size) if (x, y) != start} for pos in Warnsdorf_DP: Warnsdorf_DP[pos] = sum(1 for _ in genNeighs(pos)) travel(start) return path
A Knight's Tour
5664740e6072d2eebe00001b
[ "Algorithms" ]
https://www.codewars.com/kata/5664740e6072d2eebe00001b
4 kyu
# What's in a name? ...Or rather, what's a name in? For us, a particular string is where we are looking for a name. ## Task Write a function, taking two strings in parameter, that tests whether or not the first string contains all of the letters of the second string, in order. The function should return `true` if that is the case, and else `false`. Letter comparison should be case-INsensitive. ## Examples ``` "Across the rivers", "chris" --> true ^ ^ ^^ ^ c h ri s Contains all of the letters in "chris", in order. ---------------------------------------------------------- "Next to a lake", "chris" --> false Contains none of the letters in "chris". -------------------------------------------------------------------- "Under a sea", "chris" --> false ^ ^ r s Contains only some of the letters in "chris". -------------------------------------------------------------------- "A crew that boards the ship", "chris" --> false cr h s i cr h s i c h r s i ... Contains all of the letters in "chris", but not in order. -------------------------------------------------------------------- "A live son", "Allison" --> false ^ ^^ ^^^ A li son Contains all of the correct letters in "Allison", in order, but not enough of all of them (missing an 'l'). ```
reference
def name_in_str(str, name): it = iter(str . lower()) return all(c in it for c in name . lower())
What's A Name In?
59daf400beec9780a9000045
[ "Fundamentals" ]
https://www.codewars.com/kata/59daf400beec9780a9000045
6 kyu
We have three numbers: ```123489, 5, and 67```. With these numbers we form the list from their digits in this order ```[1, 5, 6, 2, 7, 3, 4, 8, 9]```. It shouldn't take you long to figure out what to do to achieve this ordering. Furthermore, we want to put a limit to the number of terms of the above list. Instead of having 9 numbers, we only want 7, so we discard the two last numbers. So, our list will be reduced to ```[1, 5, 6, 2, 7, 3, 4]``` (base list) We form all the possible arrays, from the list above, and we calculate, for each array, the addition of their respective digits. See the table below: we will put only some of them ``` array for the list sum (terms of arrays) [1] 1 # arrays with only one term (7 different arrays) [5] 5 [6] 6 [2] 2 [7] 7 [3] 3 [4] 4 [1, 5] 6 # arrays with two terms (42 different arrays) [1, 6] 7 [1, 2] 3 [1, 7] 8 [1, 3] 4 [1, 4] 5 ..... ... [1, 5, 6] 12 # arrays with three terms(210 different arrays) [1, 5, 2] 8 [1, 5, 7] 13 [1, 5, 3] 9 ........ ... [1, 5, 6, 2] 14 # arrays with four terms(840 different arrays) [1, 5, 6, 7] 19 [1, 5, 6, 3] 15 [1, 5, 6, 4] 16 ............ .. [1, 5, 6, 2, 7] 21 # arrays with five terms(2520 different arrays) [1, 5, 6, 2, 3] 17 [1, 5, 6, 2, 4] 18 [1, 5, 6, 7, 2] 21 ............... .. [1, 5, 6, 2, 7, 3] 24 # arrays with six terms(5040 different arrays) [1, 5, 6, 2, 7, 4] 25 [1, 5, 6, 2, 3, 7] 24 [1, 5, 6, 2, 3, 4] 21 .................. .. [1, 5, 6, 2, 7, 3, 4] 28 # arrays with seven terms(5040 different arrays) [1, 5, 6, 2, 7, 4, 3] 28 # arrays of max length = limit [1, 5, 6, 2, 3, 7, 4] 28 [1, 5, 6, 2, 3, 4, 7] 28 ::::::::::::::::::::::::::: GreatT0talAdditions 328804 (GTA).(The total addition of the sum values corresponding to each permutation). A total 0f 13699 arrays, all of them different. ``` So we say that for the three numbers, ```123489, 5, and 67``` with a limit = ```7```, the GTA value is ```328804```. Let's see now a case where we have digits occurring more than once. If we have a digit duplicated or more, just continue for the corresponding digit in turn of the next number. The result will be a list with no duplicated digits. For the numbers: ```12348, 47, 3639 ``` with ``` limit = 8``` we will have the list ```[1, 4, 3, 2, 7, 6, 9, 8]``` (base list) We should not have duplications in the permutations because there are no duplicated digits in our base list. For this case we have: ``` number of different array number of terms the array has 8 1 56 2 336 3 1680 4 6720 5 20160 6 40320 7 40320 8 GTA = 3836040 with a limit of eight terms ``` The challenge: create the function ```gta()```, that receives a number that limits the amount of terms for the base list, ```limit```, and an uncertain number of integers that can have and will have different amount of digits that may have digits occuring more than once. Just to understand the structure of the function will be like: ```gta(limit, n1, n2, ...nk)``` Let's see our functions with the examples shown above. ``` python # case1 gta(7, 123489, 5, 67) == 328804 # base_list = [1, 5, 6, 2, 7, 3, 4] # case2 gta(8, 12348, 47, 3639) == 3836040 # base_list = [1, 4, 3, 2, 7, 6, 9, 8] ``` You may assume that ```limit``` will be always lower or equal than the total available digits of all the numbers. The total available digits are all the digits of all the numbers. (E.g.the numbers ```12348, 47, 3639 ```have 8 available digits.) You will always be receiving positive integers in an amount between 2 and 6. For the tests ```limit <= 9``` (obviously). Enjoy it!! (Hint: the module itertools for python may be very useful, but there are many ways to solve it.) (The arrays [1, 5, 6] and [1, 6, 5] have the same elements but are different arrays. The order matters)
reference
from itertools import permutations def make_array_from_args(* args: int) - > list[int]: its = [iter(f' { arg } ') for arg in args] result_array = [] for it in its: try: value = int(next(it)) except StopIteration: continue else: its . append(it) if value not in result_array: result_array . append(value) return result_array def gta(limit: int, * args: int) - > int: arr = make_array_from_args(* args)[: limit] return sum( sum(p) for i in range(1, limit + 1) for p in permutations(arr, r=i) )
Great Total Additions of All Possible Arrays from a List.
568f2d5762282da21d000011
[ "Fundamentals", "Mathematics", "Permutations" ]
https://www.codewars.com/kata/568f2d5762282da21d000011
4 kyu
We need a function, closest_points3D() that may give an accurate result to find the closest pair or pairs of points that are contained in cube volumes of size l. The function will receive a list of variable number of points in a list (each point represented with cartesian coordinates(x, y, z)). All the values of x, y and z, will be positive integers. The function closest_points3D(), should display the results in the following way: [(1), (2), (3)] (1) - Number of points received (2) - Pair or pairs of closest points in a sorted list of tuples(each tuple having the 3D coordinates (x, y, z) of the encountered closest points) (3) - The distance of this pair or these pairs of found closes points, that is the minimal distance between every possible pair of the given of points. This value will be expessed as a float with at most, 5 decimal digits (rounded result). Let's see some cases. ```python l(size of the cube) = 10 listPointsI = [(9, 8, 5), (4, 2, 3), (10, 7, 4), (0, 9, 7), (3, 2, 6), (5, 8, 4), (1, 9, 6), (4, 5, 6), (5, 10, 10), (8, 8, 2)] closest_points3D(listPointsI) -----> [10, [[(0, 9, 7), (1, 9, 6)]], 1.41421] l = 20 listPointsII = [(19, 0, 1), (15, 17, 19), (19, 17, 0), (14, 5, 3), (18, 11, 7),\ (12, 15, 19), (19, 7, 6), (12, 13, 3), (1, 2, 17), (10, 19, 20), (1, 4, 16),\ (3, 17, 10), (18, 17, 15), (6, 3, 2), (17, 8, 3), (4, 14, 17), (7, 0, 3),\ (3, 17, 18), (9, 4, 18), (16, 15, 13)] closest_points3D(listPointsII) ------> [20, [[(1, 2, 17), (1, 4, 16)]], 2.23607] ``` (Your code should be able to process lists of points up to 1000 length in the allowed runtime for testing) (You don't have to deal with the size of the cube (l) in your function, each set of points have been prepared for you with different values of l.) Happy coding!!
reference
from itertools import combinations def closest_points3D(points): pairs = list(set([tuple(sorted(p)) for p in combinations(points, 2)])) dists = [round(sum((i - j) * * 2 for i, j in zip(a, b)) * * 0.5, 5) for a, b in pairs] mdist = min(dists) return [len(points), sorted([[pairs[i][0], pairs[i][1]] for i, d in enumerate(dists) if d == mdist]), mdist]
Closest Neighbouring Points II
55e47815d7055e1a97000128
[ "Fundamentals", "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/55e47815d7055e1a97000128
5 kyu
We need a function, closest_points() that may give an accurate result to find the closest pair or pairs of points that are contained in square areas of size l. The function will receive a list of variable number of points in a list (each point represented with cartesian coordinates) and should display the results in the following way `[(1), (2), (3)]` (1) - Number of points received (2) - Pair or pairs of closest points in a sorted list of tuples (each tuple having the cartesian coordinates (x, y) of the encountered closest points) (3) - the distance of this pair or these pairs of found closest points, that is the minimal distance between every possible pair of the given of points. This value will be expressed as a float with at most, 4 decimal digits (rounded result). Let's see some cases. ```python l (size of square containing the points) = 10 list_points = [(5, 10), (3, 6), (1, 4), (6, 2), (4, 3), (0, 4), (10, 3), (9, 1)] closest_points(list_points) ---------> [8, [[(0, 4), (1, 4)]], 1.0] # 8 given points, [(0, 4), (1, 4)] is the pair of points with minimal distance (1.0) l = 20 list_points = [(8, 14), (16, 5), (5, 5), (15, 18), (17, 10), (0, 14), (4, 15), (19, 17), (13, 16), (10, 18), (14, 13), (12, 14), (11, 15), (7, 15)] closest_points(list_points) -------> [14, [[(7, 15), (8, 14)], [(11, 15), (12, 14)]], 1.4142] /// Now list_points has 14 points, we can find two pairs of points [(7, 15), (8, 14)] and [(11, 15), (12, 14)] that have the minimal possible distance, 1.4142 ``` Your code should be able to process lists of points up to 1000 length in the allowed runtime for tests. Happy coding!!
reference
from collections import defaultdict from itertools import combinations as combo def closest_points(l): d = defaultdict(list) for (x1, y1), (x2, y2) in combo(sorted(l), 2): d[(x2 - x1) * * 2 + (y2 - y1) * * 2]. append([(x1, y1), (x2, y2)]) return [len(l), sorted(d[min(d)]), round(min(d) * * .5, 4)]
Closest Neighbouring Points I
55e4419eb589793709000044
[ "Fundamentals", "Mathematics", "Data Structures", "Algorithms" ]
https://www.codewars.com/kata/55e4419eb589793709000044
5 kyu
#Task: Write a function `get_member_since` which accepts a username from someone at Codewars and returns an string containing the month and year separated by a space that they joined CodeWars. ###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_member_since('dpleshkov') Jul 2016 >>> get_member_since('jhoffner') Oct 2012 ``` #Libraries/Recommendations: ##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. * **Python 2 is not working for this kata. :(** #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.
reference
from urllib . request import urlopen from bs4 import BeautifulSoup as bs def get_member_since(username): html = urlopen(f'https://www.codewars.com/users/ { username } ') soup = bs(html . read(), "html.parser") tags = soup . find_all("div", {"class": "stat"}) member_tag = [x . text for x in tags if 'Member Since' in x . text][0] return member_tag . split(':')[1]
Scraping: Get the Year a CodeWarrior Joined
58ab2ed1acbab2eacc00010e
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/58ab2ed1acbab2eacc00010e
5 kyu
> When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process -- myjinxin2015 said ## Description: In a dark, deserted night, a thief entered a shop. There are some items in the room, and the items have different weight (in kg) and price (in $). The thief is greedy, his desire is to take away all the goods. But unfortunately, his bag can only hold `n` kg of items. So he has to make a choice, try to take away more valuable items. Please complete the function to help the thief to make the best choices. Two arguments will be given: `items` (an array that contains all items) and `n` (the maximum weight the package can accommodate). ```if:haskell, The list of items is provided as `[Item]`, where `Item` is: ~~~haskell data Item = Item { weight, price:: Int } deriving (Show,Eq,Ord) -- this definition is `Preloaded` ~~~ ``` ```if:python, The list of items is provided as a `list[Item]`, where `Item` is: ~~~python Item = namedtuple('Item', 'weight price') ~~~ ``` ```if:javascript, The list of items is provided as an array of objects: ~~~javascript [ {weight:2, price:6}, ... ] ~~~ ``` The result should be a list of the original items that the thief should take away and that has the maximum possible total price. Notes: * Order of the items in the output do not matter * If more than one valid solutions exist, you should return one of them * If no valid solution should return `[]` * You should not modify argument `items` or the items themselves (in languages where they are mutable). * Pay attention to performance: the thief doesn't have all night to decide what to take or not! ## Examples For a list of the following available items: <div style="width:100px"> | weight | price | |:-:|:-:| |2|6| |2|3| |6|5| |5|4| |4|6| </div> ... and with a maximum weight of `n=10`, the best option could be a total price of `15$`, collecting the following items: <div style="width:100px"> | weight | price | |:-:|:-:| |2|6| |2|3| |4|6| </div> More examples please see the example tests ;-)
algorithms
from preloaded import Item # 0/1 Knapsack Problem def greedy_thief(items: list[Item], n: int) - > list[Item]: dp = [(0, []) for _ in range(n + 1)] for item in items: for w in range(n, 0, - 1): if item . weight <= w: x, y = dp[w - item . weight] if x + item . price > dp[w][0]: dp[w] = (x + item . price, y + [item]) return dp[n][1]
Greedy thief
58296c407da141e2c7000271
[ "Algorithms", "Puzzles" ]
https://www.codewars.com/kata/58296c407da141e2c7000271
4 kyu
# Task You are given a positive integer `n`. Now we want to choose some numbers from 1 to n, and then doing some addition and subtraction(or doing nothing), all these numbers are used at most once. Eventually, all the numbers from 1 to n can be calculated. Your task is to find the minimum amount of numbers you need to complete such calculations. Still not understand the task? Look at the following example ;-) # Example For `n = 1`, the output should be `1`. The number 1 is the only option and requires no addition and subtraction. For `n = 4`, the output should be `2`. We can choose two numbers: `1` and `3`. ``` 1 == 1 3 - 1 == 2 3 == 3 3 + 1 == 4 All number from 1 to 4 can be calculated. ``` For `n = 10`, the output should be `3`. We can choose three numbers: `1, 3` and `6`. ``` 1 == 1 3 - 1 == 2 3 == 3 3 + 1 == 4 6 - 1 == 5 6 == 6 6 + 1 == 7 6 + 3 - 1 == 8 6 + 3 == 9 6 + 3 + 1 == 10 All numbers from 1 to 10 can be calculated. ``` # Note - `0 < n < 10^10` - In order to avoid timeout, be aware of the code's performance ;-) - Happy Coding `^_^`
algorithms
from itertools import count def fewest_numbers(target): top, n = 1, 1 for d in count(1): if n >= target: return d top = 2 * n + 1 n += top
Simple Fun #360: Calculate 1 to n Using The Fewest Numbers
59dad2177997cb2a1300008d
[ "Algorithms" ]
https://www.codewars.com/kata/59dad2177997cb2a1300008d
6 kyu
Given a string of integers, return the number of odd-numbered substrings that can be formed. For example, in the case of `"1341"`, they are `1, 1, 3, 13, 41, 341, 1341`, a total of `7` numbers. `solve("1341") = 7`. See test cases for more examples. Good luck! If you like substring Katas, please try [Longest vowel chain](https://www.codewars.com/kata/59c5f4e9d751df43cf000035) [Alphabet symmetry](https://www.codewars.com/kata/59d9ff9f7905dfeed50000b0)
reference
def solve(s): return sum(i + 1 for i, d in enumerate(list(s)) if d in '13579')
Non-even substrings
59da47fa27ee00a8b90000b4
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/59da47fa27ee00a8b90000b4
6 kyu
Consider the word `"abode"`. We can see that the letter `a` is in position `1` and `b` is in position `2`. In the alphabet, `a` and `b` are also in positions `1` and `2`. Notice also that `d` and `e` in `abode` occupy the positions they would occupy in the alphabet, which are positions `4` and `5`. Given an array of words, return an array of the number of letters that occupy their positions in the alphabet for each word. For example, ``` solve(["abode","ABc","xyzD"]) = [4, 3, 1] ``` See test cases for more examples. Input will consist of alphabet characters, both uppercase and lowercase. No spaces. Good luck! If you like this Kata, please try: [Last digit symmetry](https://www.codewars.com/kata/59a9466f589d2af4c50001d8) [Alternate capitalization](https://www.codewars.com/kata/59cfc000aeb2844d16000075) ~~~if:fortran ## Fortran-Specific Notes Due to how strings and arrays work in Fortran, some of the strings in the input array will inevitably contain trailing whitespace. **For this reason, please [trim](https://gcc.gnu.org/onlinedocs/gcc-4.3.4/gfortran/TRIM.html) your input strings before processing them.** ~~~
reference
def solve(arr): return [sum(c == chr(97 + i) for i, c in enumerate(w[: 26]. lower())) for w in arr]
Alphabet symmetry
59d9ff9f7905dfeed50000b0
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/59d9ff9f7905dfeed50000b0
7 kyu
Create a function that takes a list of one or more non-negative integers, and arranges them such that they form the largest possible number. Examples: `largestArrangement([4, 50, 8, 145])` returns 8504145 (8-50-4-145) `largestArrangement([4, 40, 7])` returns 7440 (7-4-40) `largestArrangement([4, 46, 7])` returns 7464 (7-46-4) `largestArrangement([5, 60, 299, 56])` returns 60565299 (60-56-5-299) `largestArrangement([5, 2, 1, 9, 50, 56])` returns 95655021 (9-56-5-50-21)
reference
from functools import cmp_to_key def cmp(a, b): return int('%i%i' % (b, a)) - int('%i%i' % (a, b)) def largest_arrangement(n): return int('' . join(str(i) for i in sorted(n, key=cmp_to_key(cmp))))
Largest Number Arrangement
59d902f627ee004281000160
[ "Permutations", "Fundamentals" ]
https://www.codewars.com/kata/59d902f627ee004281000160
6 kyu
Alex is a devoted fan of snooker Masters and in particular, he recorded results of all matches. Help Alex to know the score of matches. <i>Hint:</i><br> A string with a score presented as follows: <b>"24-79(72); 16-101(53); ..."</b><br> "24" - Points scored the first player;<br> "79" - the number of points of the second player.<br> "(72)" - the maximum score for one approach.<br> Also, the player's account may be expressed as 105(53,52):<br> "105" - points in the frame, "53" and "52" - two separate numbers(not float) maximum points in the frame.<br> Frames are separated by ";" and players score - "-"<br> It should count the number of frames won by one and another player, and output the data as a "[10,7]"<br> Statistics URL:
algorithms
import re def frame(score): frames = [0, 0] for s1, _, s2 in re . findall(r'(\d+)(\([\d,]+\))?-(\d+)', score): frames[int(s1) < int(s2)] += 1 return frames
Alex & snooker: scores.
58b28e5830473070e5000007
[ "Statistics", "Arrays", "Strings", "Algorithms" ]
https://www.codewars.com/kata/58b28e5830473070e5000007
6 kyu
We have the following sequence: ```python f(0) = 0 f(1) = 1 f(2) = 1 f(3) = 2 f(4) = 4; f(n) = f(n-1) + f(n-2) - f(n-3) + f(n-4) - f(n-5); ``` The first term of the sequence that has its last nine digits forms a prime number is the value, 8480150779 (total of 10 digits), and corresponds to the 92-th term, because 480150779 is prime. We can follow this observation in the next terms of the sequence and see the behaviour. ```python n-th term k-th lastDig prime term value total digits last9Digit isPrime(last9Digit) 92 1 8480150779 10 480150779 True 98 2 35922495169 11 922495169 True 110 3 644603021049 12 603021049 True 122 4 11566931883761 14 931883761 True 134 5 207560170886697 15 170886697 True ``` Create a function kth_lastDigPrime(), that receives the value of k as an argument and outputs, the ordinal number that corresponds to the term value and the number formed by the last nine digits. Let's see some cases: ```python k_thlastDigPrime(1)--------> [92, 480150779] k_thlastDigPrime(2)--------> [98, 922495169] k_thlastDigPrime(5)--------> [134, 170886697] ``` (Advise: Use a fast primality test, Miller Rabin test or similar) Happy coding!
reference
from gmpy2 import is_prime def k_thlastDigPrime(k): result = [0, 1, 1, 2, 4, 6, 8, 11, 15, 20, 26, 34, 44, 57, 73, 94, 120, 154, 196, 251, 319, 408, 518, 662, 840, 1073, 1361, 1738, 2204, 2814, 3568, 4555, 5775, 7372, 9346, 11930, 15124, 19305, 24473, 31238, 39600, 50546, 64076, 81787, 103679, 132336, 167758, 214126, 271440, 346465, 439201, 560594, 710644, 907062, 1149848, 1467659, 1860495, 2374724, 3010346, 3842386, 4870844, 6217113, 7881193, 10059502, 12752040, 16276618, 20633236, 26336123, 33385279, 42612744, 54018518, 68948870, 87403800, 111561617, 141422321, 180510490, 228826124, 292072110, 370248448, 472582603, 599074575, 764654716, 969323026, 1237237322, 1568397604, 2001892041, 2537720633, 3239129366, 4106118240, 5241021410, 6643838876] while k > 0: while not is_prime(int(str(result[-1])[-9:])): result += [int(result[-1]+result[-2]-result[-3]+result[-4]-result[-5])] k -= 1 if k > 0: result += [int(result[-1]+result[-2]-result[-3]+result[-4]-result[-5])] return [len(result), int(str(result[-1])[-9:])]
Primes in the Last Digits of Huge Numbers
55e61967663140aafb0001d6
[ "Fundamentals", "Mathematics", "Algorithms", "Data Structures" ]
https://www.codewars.com/kata/55e61967663140aafb0001d6
5 kyu
## Task You are given an array of positive integers. While the array has more than one element you can choose two elements and replace them with their sum or product. Your task is to find the maximum possible number that can remain in the array after multiple such operations. ## Example For `arr = [1, 3, 2]`, the result should be `9`. in order to maximize the answer the first operation will be `1 + 2` (the array changes into `[3, 3]`) and the next `3 * 3` (the array changes into `[9]`), so the final result is 9. ## Input/Output - `[input]` integer array arr array of positive integers - `[output]` an integer maximum possible leftover
games
import math from collections import Counter def sum_or_product(arr): if len(arr) == 1: return arr[0] cs = Counter(arr) while cs[1]: cs[1] -= 1 m = int(cs[2] > 1) + \ 1 if cs[1] > 0 else min(k for k in cs . keys() if k > 1) cs[m] -= 1 cs[m + 1] += 1 return math . prod(x * * p for x, p in cs . items() if p > 0)
Simple Fun #118: Sum Or Product
589d581680458f695200008e
[ "Puzzles" ]
https://www.codewars.com/kata/589d581680458f695200008e
5 kyu
## Story Eight men fell in love with a woman at the same time. Oh~~ A lucky woman and eight unfortunate men ;-). The 8 men are ready to fight a duel of life and death. ``` The names of eight men: [ "Asda Btry","Csrt Dks","Gjhgj Hewr","Kewrwe Lhgj", "Osdf Psde","Mretb Njhk","Isdf Jjhkhj","Eyui Ferd" ] ``` The duel takes place in a room, with a round table in it. The desktop of the table can be rotated. The table is set with eight guns, filled with bullets. Each man has his own pistol, with his initials engraved on it. They put the eight pistols in a random order around the table and sit down in random order too (imagine or assume that their eyes are covered with cloth.). ``` Asda Btry Csrt Dks \ / CD AB Eyui Ferd -- KL MN -- Gjhgj Hewr Isdf Jjhkhj -- OP IJ -- Kewrwe Lhgj EF GH / \ Mretb Njhk Osdf Psde ``` When they remove the cloth from the eyes, the duel begins. If the gun in front of a man is his own, he can pick it up and kill his neighbors on either side of him. If no one gets their gun, they will turn the table clockwise. On the first round, they rotate it 45 degrees, on the second round 90 degrees, and so on, increasing by 45 degrees each time, until someone gets his gun. Note that they all shoot at the same time ! Therefore it is possible for them to be shot from multiple directions in some rounds. Also, the men who already died in the previous rounds are lying on the floor : each duelist shoots his nearest living neighbors. ``` Turn 45 degrees: Asda Btry Csrt Dks \ / KL CD Eyui Ferd -- OP AB -- Gjhgj Hewr Isdf Jjhkhj -- EF MN -- Kewrwe Lhgj GH IJ / \ Mretb Njhk Osdf Psde Csrt Dks gets his gun, "PONG!PONG!PONG!!!" ``` After a burst of gunfire, two men died(Asda Btry and Gjhgj Hewr). ``` Asda Btry(died) Csrt Dks \ / KL CD Eyui Ferd -- OP AB -- Gjhgj Hewr(died) Isdf Jjhkhj -- EF MN -- Kewrwe Lhgj GH IJ / \ Mretb Njhk Osdf Psde ``` The duel will continue until less than than 2 men are alive... ``` Turn 90 degrees: Asda Btry(died) Csrt Dks \ / EF OP Eyui Ferd -- GH KL -- Gjhgj Hewr(died) Isdf Jjhkhj -- IJ CD -- Kewrwe Lhgj MN AB / \ Mretb Njhk Osdf Psde Isdf Jjhkhj and Mretb Njhk get their guns, "PONG!PONG!PONG!!!" ``` After a burst of gunfire, four men died (Eyui Ferd, Isdf Jjhkhj, Mretb Njhkand and Osdf Psde). ``` Asda Btry(died) Csrt Dks \ / EF OP Eyui Ferd(died) -- GH KL -- Gjhgj Hewr(died) Isdf Jjhkhj(died) -- IJ CD -- Kewrwe Lhgj MN AB / \ Mretb Njhk(died) Osdf Psde(died) ``` The duel will continue until there are less than 2 men alive... ``` Turn 135 degrees: Asda Btry(died) Csrt Dks \ / MN IJ Eyui Ferd(died) -- AB GH -- Gjhgj Hewr(died) Isdf Jjhkhj(died) -- CD EF -- Kewrwe Lhgj KL OP / \ Mretb Njhk(died) Osdf Psde(died) Gjhgj Hewr and Osdf Psde get their guns, Unfortunately, they are already dead ;-) Turn 180 degrees: Asda Btry(died) Csrt Dks \ / OP KL Eyui Ferd(died) -- EF CD -- Gjhgj Hewr(died) Isdf Jjhkhj(died) -- GH AB -- Kewrwe Lhgj IJ MN / \ Mretb Njhk(died) Osdf Psde(died) Turn 225 degrees: Asda Btry(died) Csrt Dks \ / AB MN Eyui Ferd(died) -- CD IJ -- Gjhgj Hewr(died) Isdf Jjhkhj(died) -- KL GH -- Kewrwe Lhgj OP EF / \ Mretb Njhk(died) Osdf Psde(died) Turn 270 degrees: Asda Btry(died) Csrt Dks \ / IJ GH Eyui Ferd(died) -- MN EF -- Gjhgj Hewr(died) Isdf Jjhkhj(died) -- AB OP -- Kewrwe Lhgj CD KL / \ Mretb Njhk(died) Osdf Psde(died) Turn 315 degrees: Asda Btry(died) Csrt Dks \ / GH EF Eyui Ferd(died) -- IJ OP -- Gjhgj Hewr(died) Isdf Jjhkhj(died) -- MN KL -- Kewrwe Lhgj AB CD / \ Mretb Njhk(died) Osdf Psde(died) Kewrwe Lhgj gets his gun, "PONG!PONG!PONG!!!" ``` After a burst of gunfire, Csrt Dks died. Kewrwe Lhgj is the final winner, he got the beloved girl ;-) ## Task Complete function `duel()` that accepts 2 arguments: `names` An array containing the names of the eight men as they are disposed at the beginning of the duel. `guns` An array of the men's pistols as they are diposed at the beginning of the duel. Each gun is represented by his owner's initials. The result should be the winner's name as a string. If no one survived, return an empty string. ## Example ``` // The example in the story: names = [ "Asda Btry","Csrt Dks","Eyui Ferd","Gjhgj Hewr", "Isdf Jjhkhj","Kewrwe Lhgj","Mretb Njhk","Osdf Psde" ] guns = ["CD", "AB","MN","IJ","GH","EF","OP","KL"] duel(names,guns) === "Kewrwe Lhgj" ```
games
from itertools import accumulate from operator import add def duel(people, guns): p = [first_name[0] + last_name[0] for first_name, last_name in map(str . split, people)] initials = {initial: full_name for initial, full_name in zip(p, people)} matrix = [(man, [(i + (guns . index(man) - k) % 8) % 8 for i in accumulate(range(16), add)]) for k, man in enumerate(p)] turn = 0 while (len_r := len(matrix)) > 1: for i, v in enumerate(list(zip(* [t[1] for t in matrix]))[turn]): if not v: matrix[(i - 1) % len_r] = 0 matrix[(i + 1) % len_r] = 0 matrix = list(filter(bool, matrix)) turn += 1 return initials . get(matrix[0][0]) if matrix else ''
T.T.T.53: Fighting for love! Knights of the round
57c3a4431170a30b4e00017f
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/57c3a4431170a30b4e00017f
6 kyu
Quite recently it happened to me to join some recruitment interview, where my first task was to write own implementation of built-in split function. It's quite simple, is it not? However, there were the following conditions: * the function **cannot** use, in any way, the original `split` or `rsplit` functions, * the new function **must** be a generator, * it should behave as the built-in `split`, so it will be tested that way -- think of `split()` and `split('')` *This Kata will control if the new function is a generator and if it's not using the built-in split method, so you may try to hack it, but let me know if with success, or if something would go wrong!* Enjoy!
reference
import re def my_very_own_split(string, delimiter=None): if delimiter == '': raise ValueError('empty delimiter') if delimiter == None: delimiter = '\s+' else: delimiter = re . escape(delimiter) pos = 0 for m in re . finditer(delimiter, string): yield string[pos: m . start()] pos = m . end() yield string[pos:]
My Very Own Python's Split Function
55e0467217adf9c3690000f9
[ "Strings" ]
https://www.codewars.com/kata/55e0467217adf9c3690000f9
5 kyu
Math geeks and computer nerds love to anthropomorphize numbers and assign emotions and personalities to them. Thus there is defined the concept of a "happy" number. A happy number is defined as an integer in which the following sequence ends with the number 1. * Start with the number itself. * Calculate the sum of the square of each individual digit. * If the sum is equal to 1, then the number is happy. If the sum is not equal to 1, then repeat steps 1 and 2. A number is considered unhappy once the same number occurs multiple times in a sequence because this means there is a loop and it will never reach 1. For example, the number 7 is a "happy" number: 7<sup>2</sup> = 49 --> 4<sup>2</sup> + 9<sup>2</sup> = 97 --> 9<sup>2</sup> + 7<sup>2</sup> = 130 --> 1<sup>2</sup> + 3<sup>2</sup> + 0<sup>2</sup> = 10 --> 1<sup>2</sup> + 0<sup>2</sup> = 1 Once the sequence reaches the number 1, it will stay there forever since 1<sup>2</sup> = 1 On the other hand, the number 6 is not a happy number as the sequence that is generated is the following: 6, 36, 45, 41, 17, 50, 25, 29, 85, 89, 145, 42, 20, 4, 16, 37, 58, 89 Once the same number occurs twice in the sequence, the sequence is guaranteed to go on infinitely, never hitting the number 1, since it repeat this cycle. Your task is to write a program which will print a list of all happy numbers between 1 and x (both inclusive), where: ```javascript 2 <= x <= 10000 ``` ```python 2 <= x <= 5000 ``` ___ Disclaimer: This Kata is an adaptation of a HW assignment I had for McGill University's COMP 208 (Computers in Engineering) class. ___ If you're up for a challenge, you may want to try a [performance version of this kata](https://www.codewars.com/kata/happy-numbers-performance-edition) by FArekkusu.
algorithms
def is_happy(n): seen = set() while n not in seen: seen . add(n) n = sum(int(d) * * 2 for d in str(n)) return n == 1 def happy_numbers(n): return [x for x in range(1, n + 1) if is_happy(x)]
Happy Numbers
59d53c3039c23b404200007e
[ "Recursion", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/59d53c3039c23b404200007e
6 kyu
## Story There are four warriors, they need to go through a dark tunnel. Tunnel is very narrow, every time only can let two warriors through, and there are lot of dangerous traps. Fortunately, they have a lamp that can illuminate the tunnel to avoid being trapped by the trap. In order to pass this tunnel, they need five steps: 1. Two people go through the tunnel with the lamp 2. And then one people come back with the lamp 3. And then two people go through the tunnel with the lamp 4. And then one people come back with the lamp 5. And then two people go through the tunnel with the lamp Each warrior has his own walking speed, we need to calculate the shortest time they have to cross the tunnel. For example: Four warriors is `a,b,c,d`. Their speed are `[3,4,5,6]`. It means they need 3 minutes, 4 minutes, 5 minutes and 6 minutes to cross the tunnel. The shortest crossing time should be 21 minutes, the method is as follows: ``` a and b go through the tunnel ---> Spend 4 minutes (Time spent should be calculated by the person who is slow) a come back ---> Spend 3 minutes a and c go through the tunnel ---> Spend 5 minutes a come back ---> Spend 3 minutes a and d go through the tunnel ---> Spend 6 minutes ``` Do you have any other better way? ## Task Complete function `shortestTime()` that accepts 1 argument: `speed` that are the spent time of four warriors. Returns the shortest time that all warriors go through the tunnel. **Note: The method in example above is not always the best way.** ## Example ```javascript shortestTime([3,4,5,6]) === 21 shortestTime([3,7,10,18]) === 41 shortestTime([5,5,6,7]) === 27 shortestTime([5,6,30,40]) === 63 ```
games
def shortest_time(speed): a, b, c, d = sorted(speed) return a + b + d + min(2 * b, a + c)
T.T.T.51: Four warriors and a lamp
57bff92049324c0fd00012fd
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/57bff92049324c0fd00012fd
6 kyu
## Description In this kata, the problem is: Give you a range of number, Calculate the sum of the each digits. For example: ``` range:1-10 all numbers in the range is:12345678910 the sum of each digits is:1+2+3+4+5+6+7+8+9+1+0=46 range:1-20 all numbers in the range is:1234567891011121314151617181920 the sum of each digits is: 1+2+3+4+5+6+7+8+9+1+0+1+1+1+2+1+3+1+4+1+5+1+6+1+7+1+8+1+9+2+0=102 ``` ~~~if:javascript # Task Complete function `sumOfDigits()` that accepts two arguments `from` and `to`. This is a range of a number sequence(`from < to`). Please return the sum of all digits between `from` and `to` (both included). You should find a better algorithm, because the range may be very large(`1 <= from < to <= 10^8`) ;-) ~~~ ~~~if:python # Task Complete function `sum_of_digits()` that accepts two arguments `a` and `b`. This is a range of a number sequence (`a <= b`). Please return the sum of all digits between `a` and `b` (both included). You should find a better algorithm, because the range may be very large(`0 <= a <= b <= 2^1000`) ;-) ~~~ ## Examples ``` sumOfDigits(1,10) === 46 sumOfDigits(1,20) === 102 sumOfDigits(1,100) === 901 sumOfDigits(1,1000) === 13501 ``` ## Hint You might be confused by a very large range . Here is an example of the calculation of 1 to 100: ``` sumOfDigits(1,100) solve process: Divide these numbers into 51 groups (1,98) (2,97) (3,96) (4 95)....(48,51) (49,50) --- 1-49th group 99 ---50th group 100 ---51th group We can find that the value of 1 to 50 groups all are 18 So the whole calculation should be: 18 * 50 + (1+0+0) = 900 + 1 = 901 ``` 1 to 10, 1 to 100, 1 to 1000... can calculate by this way. But you should think about irregular situations, such as: 2 to 100 , 1 to 20, 34 to 101... Good luck ;-)
games
def sum_of_digits(a, b): def f(n): d, m, s = 0, 1, 0 while n: n, r = divmod(n, 10) s += r * 9 * d * 10 * * d / / 2 + r * (r - 1) / / 2 * 10 * * d + r * m m += r * 10 * * d d += 1 return s return f(b) - f(max(a - 1, 0))
T.T.T.38: The sum of each digits
57b1f617b69bfc08cf00042a
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/57b1f617b69bfc08cf00042a
5 kyu
> ## Previous [Cartesian neighbors](https://www.codewars.com/kata/cartesian-neighbors) kata In previous kata we have been searching for all the neighboring points in a Cartesian coordinate system. As we know each point in a coordinate system has eight neighboring points when we search it by range equal to 1, but now we will change range by third argument of our function (range is always greater than zero). For example if range ```= 2```, count of neighboring points ```= 24```. In this kata grid step is the same (```= 1```). It is necessary to write a function that returns array of ```unique``` distances between given point and all neighboring points. You can round up the distance to ```10``` decimal places (as shown in the example). Distances inside list don't have to been sorted (any order is valid). For Example: ```java cartesianNeighborsDistance(3, 2, 1) -> {1.4142135624, 1.0} cartesianNeighborsDistance(0, 0, 2) -> {1.0, 1.4142135624, 2.0, 2.2360679775, 2.8284271247} ``` ```cpp cartesianNeighborsDistance(3, 2, 1) -> {1.4142135624, 1.0} cartesianNeighborsDistance(0, 0, 2) -> {1.0, 1.4142135624, 2.0, 2.2360679775, 2.8284271247} ``` ```c // please remember the length of the array in this variable int array_size = 0; cartesianNeighborsDistance(3, 2, 1, &array_size) -> {1.4142135624, 1.0} cartesianNeighborsDistance(0, 0, 2, &array_size) -> {1.0, 1.4142135624, 2.0, 2.2360679775, 2.8284271247} ``` ```csharp cartesianNeighborsDistance(3, 2, 1) -> {1.4142135624, 1.0} cartesianNeighborsDistance(0, 0, 2) -> {1.0, 1.4142135624, 2.0, 2.2360679775, 2.8284271247} ``` ```go CartesianNeighborsDistance(3, 2, 1) -> {1.4142135624, 1.0} CartesianNeighborsDistance(0, 0, 2) -> {1.0, 1.4142135624, 2.0, 2.2360679775, 2.8284271247} ``` ```javascript cartesianNeighborsDistance(3, 2, 1) -> [1.4142135624, 1.0] cartesianNeighborsDistance(0, 0, 2) -> [1.0, 1.4142135624, 2.0, 2.2360679775, 2.8284271247] ``` ```typescript cartesianNeighborsDistance(3, 2, 1) -> [1.4142135624, 1.0] cartesianNeighborsDistance(0, 0, 2) -> [1.0, 1.4142135624, 2.0, 2.2360679775, 2.8284271247] ``` ```python cartesian_neighbors_distance(3, 2, 1) -> [1.4142135624, 1.0] cartesian_neighbors_distance(0, 0, 2) -> [1.0, 1.4142135624, 2.0, 2.2360679775, 2.8284271247] ```
reference
def cartesian_neighbors_distance(x, y, r): return {(m * m + n * n) * * 0.5 for m in range(1, r + 1) for n in range(m + 1)}
Cartesian neighbors distance
59cd39a7a25c8c117d00020c
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/59cd39a7a25c8c117d00020c
6 kyu
This is the second part of this kata series. First part is [here](https://www.codewars.com/kata/simple-assembler-interpreter/). We want to create an interpreter of assembler which will support the following instructions: - ```mov x, y``` - copy y (either an integer or the value of a register) into register x. - ```inc x``` - increase the content of register x by one. - ```dec x``` - decrease the content of register x by one. - ```add x, y``` - add the content of the register x with y (either an integer or the value of a register) and stores the result in x (i.e. register[x] += y). - ```sub x, y``` - subtract y (either an integer or the value of a register) from the register x and stores the result in x (i.e. register[x] -= y). - ```mul x, y``` - same with multiply (i.e. register[x] *= y). - ```div x, y``` - same with integer division (i.e. register[x] /= y). - ```label:``` - define a label position (`label = identifier + ":"`, an identifier being a string that does not match any other command). Jump commands and `call` are aimed to these labels positions in the program. - ```jmp lbl``` - jumps to the label `lbl`. - ```cmp x, y``` - compares x (either an integer or the value of a register) and y (either an integer or the value of a register). The result is used in the conditional jumps (`jne`, `je`, `jge`, `jg`, `jle` and `jl`) - ```jne lbl``` - jump to the label `lbl` if the values of the previous ```cmp``` command were not equal. - ```je lbl``` - jump to the label `lbl` if the values of the previous ```cmp``` command were equal. - ```jge lbl``` - jump to the label `lbl` if x was greater or equal than y in the previous ```cmp``` command. - ```jg lbl``` - jump to the label `lbl` if x was greater than y in the previous ```cmp``` command. - ```jle lbl``` - jump to the label `lbl` if x was less or equal than y in the previous ```cmp``` command. - ```jl lbl``` - jump to the label `lbl` if x was less than y in the previous ```cmp``` command. - ```call lbl``` - call to the subroutine identified by `lbl`. When a ```ret``` is found in a subroutine, the instruction pointer should return to the instruction next to this ```call``` command. - ```ret``` - when a ```ret``` is found in a subroutine, the instruction pointer should return to the instruction that called the current function. - ```msg 'Register: ', x``` - this instruction stores the output of the program. It may contain text strings (delimited by single quotes) and registers. The number of arguments isn't limited and will vary, depending on the program. - ```end``` - this instruction indicates that the program ends correctly, so the stored output is returned (if the program terminates without this instruction it should return the default output: see below). - ```; comment``` - comments should not be taken in consideration during the execution of the program. <br> ## Output format: The normal output format is a string (returned with the `end` command). For Scala and Rust programming languages it should be incapsulated into Option. If the program does finish itself without using an `end` instruction, the default return value is: ```python -1 (as an integer) ``` ```java null ``` ```csharp null ``` ```ruby -1 (as an integer) ``` ```cpp "-1" (as a string) ``` ```scala None ``` ```rust None ``` ```haskell Nothing ``` ```cobol result = '-1' ``` <br> ## Input format: The function/method will take as input a multiline string of instructions, delimited with EOL characters. Please, note that the instructions may also have indentation for readability purposes. For example: ```python program = """ ; My first program mov a, 5 inc a call function msg '(5+1)/2 = ', a ; output message end function: div a, 2 ret """ assembler_interpreter(program) ``` ```java program = "\n; My first program\nmov a, 5\ninc a\ncall function\nmsg '(5+1)/2 = ', a ; output message\nend\n\nfunction:\n div a, 2\n ret\n" AssemblerInterpreter.interpret(program); // Which is equivalent to (keep in mind that empty lines are not displayed in the console on CW, so you actually won't see the separation before "function:"...): ; My first program mov a, 5 inc a call function msg '(5+1)/2 = ', a ; output message end function: div a, 2 ret ``` ```csharp program = "\n; My first program\nmov a, 5\ninc a\ncall function\nmsg '(5+1)/2 = ', a ; output message\nend\n\nfunction:\n div a, 2\n ret\n" AssemblerInterpreter.Interpret(program); // Which is equivalent to (keep in mind that empty lines are not displayed in the console on CW, so you actually won't see the separation before "function:"...): ; My first program mov a, 5 inc a call function msg '(5+1)/2 = ', a ; output message end function: div a, 2 ret ``` ```ruby program = " ; My first program mov a, 5 inc a call function msg '(5+1)/2 = ', a ; output message end function: div a, 2 ret " assembler_interpreter(program) ``` ```cpp program = R"( ; My first program mov a, 5 inc a call function msg '(5+1)/2 = ', a ; output message end function: div a, 2 ret)"; assembler_interpreter(program); ``` ```scala val program = "\n; My first program\nmov a, 5\ninc a\ncall function\nmsg '(5+1)/2 = ', a ; output message\nend\n\nfunction:\n div a, 2\n ret\n" AssemblerInterpreter.interpret(program); // Which is equivalent to (keep in mind that empty lines are not displayed in the console on CW, so you actually won't see the separation before "function:"...): ; My first program mov a, 5 inc a call function msg '(5+1)/2 = ', a ; output message end function: div a, 2 ret ``` ```rust let program = "\n; My first program\nmov a, 5\ninc a\ncall function\nmsg '(5+1)/2 = ', a ; output message\nend\n\nfunction:\n div a, 2\n ret\n"; AssemblerInterpreter::interpret(program); // Which is equivalent to (keep in mind that empty lines are not displayed in the console on CW, so you actually won't see the separation before "function:"...): ; My first program mov a, 5 inc a call function msg '(5+1)/2 = ', a ; output message end function: div a, 2 ret ``` ```haskell program = "\n; My first program\nmov a, 5\ninc a\ncall function\nmsg '(5+1)/2 = ', a ; output message\nend\n\nfunction:\n div a, 2\n ret\n" interpret program ``` ```cobol * COBOL has no symbol for EOL literal, if you display the program string * to the console, you will see something similar to this: "; My first program mov a, 5 inc a call function msg '(5+1)/2 = ', a ; output message end function: div a, 2 ret" * EOL character (line feed) is ascii character 10 (`function char(11)` in COBOL) ``` The above code would set register ```a``` to 5, increase its value by 1, calls the subroutine function, divide its value by 2, returns to the first call instruction, prepares the output of the program and then returns it with the ```end``` instruction. In this case, the output would be ```(5+1)/2 = 3```.
refactoring
from operator import add, sub, mul, floordiv as div, lt, le, eq, ne, ge, gt import re TOKENIZER = re . compile(r"('.*?'|-?\w+)[:,]?\s*") SKIP_COMMENTS = re . compile("\s*;") SPLIT_PROG = re . compile(r'\n\s*') CMP_FUNCS = {'jmp': lambda x, y: True, 'jne': ne, 'je': eq, 'jge': ge, 'jg': gt, 'jle': le, 'jl': lt} MATH_FUNCS = {'add', 'sub', 'mul', 'div', 'inc', 'dec'} MATH_DCT = {'inc': 'add', 'dec': 'sub'} JUMPS_CMD = set(CMP_FUNCS . keys()) | {'call'} ALL_CMDS = {'ret', 'end', 'mov', 'cmp', 'msg'} | JUMPS_CMD def assembler_interpreter(program): def tokenize(s): return TOKENIZER . findall(SKIP_COMMENTS . split(s)[0]) def updateCmp(x, y): return {k: op(reg . get( x, 0), reg[y] if y . isalpha() else int(y)) for k, op in CMP_FUNCS . items()} def moveTo(cmdJump, lbl): return jumps_lbl[lbl] if cmpDct[cmdJump] else p def updateReg(op, x, y='1', val=None): reg[x] = op( reg[x] if val is None else val, reg[y] if y . isalpha() else int(y)) p, reg, output, callStackP = 0, {}, '', [] inst = [cmd for cmd in map(tokenize, SPLIT_PROG . split(program)) if cmd] jumps_lbl = {cmd[0]: i for i, cmd in enumerate( inst) if cmd[0] not in ALL_CMDS} cmpDct = updateCmp('0', '0') while 0 <= p < len(inst): cmd, xyl = inst[p][0], inst[p][1:] if cmd == 'mov': updateReg(add, xyl[0], xyl[1], 0) elif cmd == 'cmp': cmpDct = updateCmp(xyl[0], xyl[1]) elif cmd in MATH_FUNCS: updateReg(eval(MATH_DCT . get(cmd, cmd)), * xyl) elif cmd in CMP_FUNCS: p = moveTo(cmd, xyl[0]) elif cmd == 'call': callStackP . append(p) p = moveTo('jmp', xyl[0]) elif cmd == 'ret': p = callStackP . pop() elif cmd == 'end': return output elif cmd == 'msg': output += '' . join(s[1: - 1] if s not in reg else str(reg[s]) for s in inst[p][1:]) print(output) p += 1 return - 1
Assembler interpreter (part II)
58e61f3d8ff24f774400002c
[ "Interpreters", "Refactoring" ]
https://www.codewars.com/kata/58e61f3d8ff24f774400002c
2 kyu
### Story You have a list of domain names from a log file, indicating the number of times the computer accessed those sites. However, the list shows subdomains too, but you want to see only the main sites and the total number of accesses. For example `6.clients-channel.google.com` and `apis.google.com` should be counted together as `google.com`. ### Task Complete the function that takes two arguments: * `domains` is a list of domain names, showing the number of access requests to each domain, as you copied it from the logs * and the optional `min_hits` which defines what is the minimum number of accesses in order to appear on the output list. If this is not given, consider it `0`. Return a string ready to be printed, showing the sites with the total number of accesses, in a decreasing order. *Output requirements:* * the output should show the sites with the total number of accesses in parentheses, * sites should have only 2 levels (e.g. `ebay.com`), except for `.co.xx` and `.com.xx` type domains, which should have 3 levels (e.g. `amazon.co.jp`), * the list should be sorted in decreasing order of access, * if two sites have the same number of accesses, sort them alphabetically, * entries should be separated by newlines (`\n`) ### Example ```python domains_list = '''\ *.amazon.co.uk 89 *.doubleclick.net 139 *.fbcdn.net 212 *.in-addr.arpa 384 *.l.google.com 317 1.client-channel.google.com 110 6.client-channel.google.com 45 a.root-servers.net 1059 apis.google.com 43 clients4.google.com 71 clients6.google.com 81 connect.facebook.net 68 edge-mqtt.facebook.com 56 graph.facebook.com 150 mail.google.com 128 mqtt-mini.facebook.com 47 ssl.google-analytics.com 398 star-mini.c10r.facebook.com 46 staticxx.facebook.com 48 www.facebook.com 178 www.google.com 162 www.google-analytics.com 127 www.googleapis.com 87''' count_domains(domains_list, 500) = '''\ root-servers.net (1059) google.com (957) facebook.com (525) google-analytics.com (525)''' ``` --- ### My other katas If you enjoyed this kata then please try [my other katas](https://www.codewars.com/collections/katas-created-by-anter69)! :-) #### *Translations are welcome!*
algorithms
import re from collections import defaultdict PATTERN = re . compile(r'([^.\n]+(\.com?)?\.\w*)\s+(\d+)') def count_domains(domains, min_hits=0): d_dct = defaultdict(int) for k, _, v in PATTERN . findall(domains): d_dct[k] += int(v) sortedAndFilteredItems = sorted([it for it in d_dct . items( ) if it[1] >= min_hits], key=lambda tup: (- tup[1], tup[0])) return '\n' . join("{} ({})" . format(k, v) for k, v in sortedAndFilteredItems)
Count the Domain Names
595120ac5afb2e5c1d000001
[ "Algorithms" ]
https://www.codewars.com/kata/595120ac5afb2e5c1d000001
5 kyu
I will give you an integer (N) and a string. Break the string up into as many substrings of N as you can without spaces. If there are leftover characters, include those as well. ```javascript Example: N = 5; String = "This is an example string"; Return value: Thisi sanex ample strin g Return value as a string: 'Thisi'+'\n'+'sanex'+'\n'+'ample'+'\n'+'strin'+'\n'+'g' ``` ```csharp Example: n = 5; str = "This is an example string"; Return value: Thisi sanex ample strin g Return value as a string: "Thisi"+"\n"+"sanex"+"\n"+"ample"+"\n"+"strin"+"\n"+"g" ``` ```python Example: n = 5; st = "This is an example string"; Return value: Thisi sanex ample strin g Return value as a string: 'Thisi'+'\n'+'sanex'+'\n'+'ample'+'\n'+'strin'+'\n'+'g' ``` ```ruby Example: n = 5; st = "This is an example string"; return value: Thisi sanex ample strin g return value as a string: "Thisi"+"\n"+"sanex"+"\n"+"ample"+"\n"+"strin"+"\n"+"g" ```
reference
def string_breakers(n, st): s = st . replace(' ', '') return '\n' . join(s[i: i + n] for i in range(0, len(s), n))
String Breakers
59d398bb86a6fdf100000031
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/59d398bb86a6fdf100000031
6 kyu
Each composed integer may have a prime factorization. If n is the integer, it will be: <a href="http://imgur.com/M5n0WCg"><img src="http://i.imgur.com/M5n0WCg.png?1" title="source: imgur.com" /></a> and k1, k2, k3....., kn are the exponents corresponding to each prime in the factorization. The radical of n, Rad(n), will be the product of all the prime factors of the number, (without the exponents), so: Rad(n) = p1 . p2 . p3 .....pn Let's see an example for a number, if n = 172800 its prime factorization will be n = 2^8 . 3^3 . 5^2, Rad(172800) = 2 . 3 . 5 = 30 Many numbers, smaller than 172800, may have a radical considerably higher than 30, for example: Rad(9305) = 5 . 1861 = 9305 Primes are a particular case, the value of its radical coincides with the value of the prime itself Rad(31) = 31 Rad(57) = 57 To number 1 it's assigned, Rad(1) = 1 Let's see the comparison between numbers and radicals for the first 10 numbers ```python n Prime Descomposition Prime Factors Radical(n) 1 1 2 2 2 2 3 3 3 3 4 2, 2 2 2 5 5 5 5 6 2, 3 2, 3 6 7 7 7 7 8 2, 2, 2 2 2 9 3, 3 3 3 10 2, 5 2, 5 10 ``` The list above may be sorted by the value of the radicals and the order changes having another sequence. We add a new column that gives the ordinal number of different values ```python k- Term n Radical(n) 1 1 1 2 2 2 3 4 2 4 8 2 5 3 3 6 9 3 7 5 5 8 6 6 9 7 7 10 10 10 ``` We have some numbers that have the same value for its radical, the smaller numbers are selected to go first. For example, n = 2, 4, 8 have Radical(n) = 2, these numbers should be ordered by their own value. Create a function hash_radSeq() that receives two arguments: - nMax is the upper bound such that all values of n are in the interval (1, nMax) (1 <= n <= nMax) - the number k, which is the ordinal number of a certain term in a sequence sorted by the values of the radicals - the function should ouput the value of n, for the corresponding ordinal number k (k-th), in a sequence sorted bby the values of Rad(n) Let's see some examples: ```python hash_radSeq(10, 4) ------> 8 hash_radSeq(10, 6) ------> 9 hash_radSeq(10, 9) ------> 7 ``` If we increase of the number of nMax to 20, the sequence changes ```python hash_radSeq(20, 4) ------> 8 hash_radSeq(20, 6) ------> 3 hash_radSeq(20, 9) ------> 6 ``` (Your code will be tested for values of nMax up to 60000 and values of k up to 11000, so try to think in some data structure, useful for fast hashing) Happy coding!!
reference
def hash_radSeq(n, k): rads = [0] + [1] * n for i in range(2, n + 1): if rads[i] == 1: for j in range(i, n + 1, i): rads[j] *= i return sorted((r, i) for i, r in enumerate(rads))[k][1]
A Challenging Sequence.
55e84ce709a1e37e420000df
[ "Algorithms", "Data Structures", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/55e84ce709a1e37e420000df
5 kyu
<strong>Introduction</strong> <a href="https://en.wikipedia.org/wiki/Brainfuck">Brainfuck</a> is one of the most well-known esoteric programming languages. But it can be hard to understand any code longer that 5 characters. In this kata you have to solve that problem. <strong>Description</strong> In this kata you have to write a function which will do 3 tasks: <ol> <li>Optimize the given Brainfuck code.</li> <li>Check it for mistakes.</li> <li>Translate the given Brainfuck programming code into <a href="https://en.wikipedia.org/wiki/C_(programming_language)">C</a> programming code.</li> </ol> More formally about each of the tasks: <ol> <li> Your function has to remove from the source code all useless command sequences such as: <code>'+-', '<>', '[]'</code>. Also it must erase all characters except <code>+-<>,.[]</code>. <pre>Example: <code>"++--+." -> "+." "[][+++]" -> "[+++]" "<>><" -> ""</code></pre> </li> <li> If the source code contains unpaired braces, your function should return <code>"Error!"</code> string. </li> <li> Your function must generate a string of the C programming code as follows: <br> <br> <ol> <li> Sequences of the X commands <code>+</code> or <code>-</code> must be replaced by <code>\*p += X;\n</code> or <code>\*p -= X;\n</code>. <pre>Example: <code>"++++++++++" -> "\*p += 10;\n" "------" -> "\*p -= 6;\n" </code></pre> </li> <li> Sequences of the Y commands <code>></code> or <code><</code> must be replaced by <code>p += Y;\n</code> or <code>p -= Y;\n</code>. <pre>Example: <code>">>>>>>>>>>" -> "p += 10;\n" "<<<<<<" -> "p -= 6;\n" </code></pre> </li> <li> <code>.</code> command must be replaced by <code>putchar(\*p);\n</code>. <pre>Example: <code>".." -> "putchar(\*p);\nputchar(\*p);\n" </code></pre> </li> <li> <code>,</code> command must be replaced by <code>\*p = getchar();\n</code>. <pre>Example: <code>"," -> "\*p = getchar();\n" </code></pre> </li> <li> <code>[</code> command must be replaced by <code>if (\*p) do {\n</code>. <code>]</code> command must be replaced by <code>} while (\*p);\n</code>. <pre>Example: <code>"[>>]" -> if (\*p) do {\n p += 2;\n } while (\*p);\n </code></pre> </li> <li> Each command in the code block must be shifted 2 spaces to the right accordingly to the previous code block. <pre>Example: <code>"[>>[<<]]" -> if (\*p) do {\n p += 2;\n if (\*p) do {\n p -= 2;\n } while (\*p);\n } while (\*p);\n </code></pre> </li> </ol> </li> </ol> <strong>Examples</strong> <pre> <code>Input: +++++[>++++.<-] Output: *p += 5; if (*p) do { p += 1; *p += 4; putchar(*p); p -= 1; *p -= 1; } while (*p); </code></pre>
reference
import re def brainfuck_to_c(source): # remove comments source = re . sub('[^+-<>,.\[\]]', '', source) # remove redundant code before = '' while source != before: before = source source = re . sub('\+-|-\+|<>|><|\[\]', '', source) # check braces status braces = re . sub('[^\[\]]', '', source) while braces . count('[]'): braces = braces . replace('[]', '') if braces: return 'Error!' # split code into commands commands = re . findall('\++|-+|>+|<+|[.,\[\]]', source) # translate to C output = [] indent = 0 for cmd in commands: if cmd[0] in '+-<>': line = ('%sp %s= %s;\n' % ('*' if cmd[0] in '+-' else '', '+' if cmd[0] in '+>' else '-', len(cmd))) elif cmd == '.': line = 'putchar(*p);\n' elif cmd == ',': line = '*p = getchar();\n' elif cmd == '[': line = 'if (*p) do {\n' elif cmd == ']': line = '} while (*p);\n' indent -= 1 output . append(' ' * indent + line) if cmd == '[': indent += 1 return '' . join(output)
Brainfuck Translator
58924f2ca8c628f21a0001a1
[ "Esoteric Languages", "Strings" ]
https://www.codewars.com/kata/58924f2ca8c628f21a0001a1
4 kyu
In this Kata you will be playing <a href="https://en.wikipedia.org/wiki/Clock_Patience">Clock Patience</a> which is a single-player card game of chance requiring zero skill. ## Input * ```cards``` a shuffled deck of 52 playing cards represented as a string array * card values are ```A```,```2```,```3```,```4```,```5```,```6```,```7```,```8```,```9```,```10```,```J```,```Q```,```K``` (suits are not relevant) ## Process Within the Kata method you will need to: * <span style='color:orange'>**"Deal"**</span> the cards face down one at a time into clock positions * First card at 1 o'clock position, 2nd at 2 o'clock... 12th at 12 o'clock, 13th card in the centre * Repeat 4 times. * When all cards are dealt there will be 13 piles of 4 cards each * See <a href="http://www.wikihow.com/Play-Clock-Patience">here</a> for the general idea (but use this Kata's dealing rules) * <span style='color:orange'>**"Play"**</span> the game according to these RULES * Start by turning over the top card in the clock centre * Place that card face up at the clock position associated with its card-value: * ```A``` at 1 o'clock * ```2``` at 2 o'clock * ```3``` at 3 o'clock * ... * ```Q``` at 12 o'clock * ```K``` in the centre * Next turn over the top card of the pile at this new clock position * REPEAT until no more moves are possible * This happens only when the 4th King (`K`) is revealed * See <a href="http://www.wikihow.com/Play-Clock-Patience">here</a> for clarification of these rules # Kata Task Return the number of cards still remaining face down when the game ends (a winning game would return ```0```)
algorithms
def patience(cards): clock, h = [cards[i:: 13] for i in range(13)], 13 - 1 while len(clock[h]): h = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']. index(clock[h]. pop()) return sum(len(h) for h in clock)
Clock Patience
58e8f020fd89eaa1cf0000c2
[ "Algorithms" ]
https://www.codewars.com/kata/58e8f020fd89eaa1cf0000c2
6 kyu
### Description [Do you know Collatz conjecture? Click here, You can read some details..](https://en.wikipedia.org/wiki/Collatz_conjecture) Given the following algorithm (Collatz conjecture): ``` If number x is even, x = x / 2 else if x is odd, x = x * 3 + 1 ``` Find all the possible numbers(x) which resolve to a specified number (y) when the algorithm is applied a specified number of times (n). Sort the results in ascending order. For example: Find all the possible numbers which resolve to 1 (y = 1) after 5 applications of the algorithm (n = 5). (in accordance with the rules of the Collatz conjecture) ``` reversalCollatz(5,1) === [4,5,32] Because: 4 -> 2 -> 1 -> 4 -> 2 -> 1 5 -> 16 -> 8 -> 4 -> 2 -> 1 32 -> 16 -> 8 -> 4 -> 2 -> 1 ``` ### More Examples ``` reversalCollatz(5,1) === [4,5,32] reversalCollatz(3,12) === [48] reversalCollatz(4,7) === [9,56] ```
games
def reversal_collatz(step, y): bag = {y} for _ in range(step): bag = {z for x in bag for z in [2 * x] + [(x - 1) / / 3] * (x % 6 == 4)} return sorted(bag)
T.T.T.37: Reversal of Collatz
57b1d750b69bfcf231000204
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/57b1d750b69bfcf231000204
6 kyu
Convert a number to a binary coded decimal (BCD). You can assume input will always be an integer. If it is a negative number then simply place a minus sign in front of the output string. Output will be a string with each digit of the input represented as 4 bits (0 padded) with a space between each set of 4 bits. Ex. ```python n = 10 -> "0001 0000" n = -10 -> "-0001 0000" ```
algorithms
def to_bcd(n): return '-' * (n < 0) + ' ' . join(bin(x)[2:]. zfill(4) for x in map(int, str(abs(n))))
Binary Coded Decimal
5521d84b95c172461d0000a4
[ "Algorithms" ]
https://www.codewars.com/kata/5521d84b95c172461d0000a4
6 kyu
In Western music, a major chord (major third) starts at a root note and adds the note 4 semitones and 7 semitones above it. A minor chord (minor third) starts at a root note and adds the note 3 semitones and 7 semitones above it. Given a root note `root`, please return an array of the major chord and the minor chord for that root. The notes are C, C#, D, D#, E, F, F#, G, G#, A, A#, B –– you are given this as a constant --- For a music theory kata from a different point of view (figuring out whether a given set of notes is a major chord or minor chord or neither), try [this kata](https://www.codewars.com/kata/number-01-music-theory-minor-slash-major-chords) from aniametz.
reference
notes = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"] def chords(root): index = notes . index(root) major = [notes[index], notes[(index + 4) % 12], notes[(index + 7) % 12]] minor = [notes[index], notes[(index + 3) % 12], notes[(index + 7) % 12]] return [major, minor]
Chords
59d2fc6c23dacca182000068
[ "Fundamentals" ]
https://www.codewars.com/kata/59d2fc6c23dacca182000068
7 kyu
Given a string as input, move all of its vowels to the end of the string, in the same order as they were before. Vowels are (in this kata): `a, e, i, o, u` Note: all provided input strings are lowercase. ## Examples ```python "day" ==> "dya" "apple" ==> "pplae" ```
reference
def move_vowels(s): return '' . join(sorted(s, key=lambda k: k in 'aeiou'))
Move all vowels
56bf3287b5106eb10f000899
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/56bf3287b5106eb10f000899
7 kyu
In his publication *Liber Abaci* Leonardo Bonacci, aka Fibonacci, posed a problem involving a population of idealized rabbits. These rabbits bred at a fixed rate, matured over the course of one month, had unlimited resources, and were immortal. Create a function that determines the number of pairs of mature rabbits after `n` months, beginning with one **immature** pair of these idealized rabbits that produce `b` pairs of offspring at the end of each month. To illustrate the problem, consider the following example: n = 5 months b = 3 births -> 19 mature rabbit pairs Month|Immature pairs|Mature pairs :---:|:------------:|:----------: 0 | 1 | 0 1 | 0 | 1 2 | 3 | 1 3 | 3 | 4 4 | 12 | 7 5 | 21 | 19 ~~~if:lambdacalc #### Encodings purity: `LetRec` numEncoding: `Scott` ~~~ #### Hint Any Fibonacci number can be computed using the following equation: `F(n) = F(n-1) + F(n-2)`
algorithms
def fib_rabbits(n, b): x, y = 0, 1 for i in range(n): x, y = y, y + b * x return x
Fibonacci Rabbits
5559e4e4bbb3925164000125
[ "Algorithms" ]
https://www.codewars.com/kata/5559e4e4bbb3925164000125
6 kyu
# Introduction Take a list of `n` numbers `a1, a2, a3, ..., aN` to start with. **Arithmetic mean** (or average) is the sum of these numbers divided by `n`. **Geometric mean** (or average) is the product of these numbers taken to the `n`th root. ### Example List of numbers: `1, 3, 9, 27, 81` - `n = 5` - Arithmetic mean = `(1 + 3 + 9 + 27 + 81) / 5 = 121 / 5 = 24.2` - Geometric mean = `(1 * 3 * 9 * 27 * 81) ^ (1/5) = 59049 ^ (1/5) = 9` # Task You will be given a list of numbers and their arithmetic mean. **However, the list is missing one number.** Using this information, you must figure out and return the geometric mean of the FULL LIST, including the number that's missing.
algorithms
from functools import reduce from operator import mul def geo_mean(nums, mean): nums . append(mean * (len(nums) + 1) - sum(nums)) return reduce(mul, nums) * * (1 / len(nums))
Mean Means
57c6b44f58da9ea6c20003da
[ "Mathematics", "Algorithms", "Algebra" ]
https://www.codewars.com/kata/57c6b44f58da9ea6c20003da
7 kyu
Your task is to write a function, which takes two arguments and returns a sequence. First argument is a sequence of values, second is multiplier. The function should filter all non-numeric values and multiply the rest by given multiplier.
algorithms
def multiply_and_filter(seq, multiplier): return [num * multiplier for num in seq if type(num) in (int, float)]
Multiply array values and filter non-numeric
55ed875819ae85ca8b00005c
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/55ed875819ae85ca8b00005c
7 kyu
Check that a number is a valid number that has been given to 2 decimal places. The number passed to the function will be given as a string. If the number satisfies the criteria below, the function should return true, else it should return false. Please check the criteria for a valid number: optional + or - symbol in front optional digits before a decimal point (digits are characters ranging from '0' to '9') a decimal point exactly two digits after the point nothing else _______________________ Examples of valid and non-valid numbers List of valid numbers: [ "0.00" "3.90" "1000.00" ".00" "-2.55" "+2.10" "-.55"] List of non-valid numbers: ["hellow 11.99" "11.9" "11" "11." ".9"]
reference
import re def valid_number(input_str): return re . match(r""" [+-]? # optional +/- sign \d* # optional digits \. # decimal point \d\d # two digits $ # end of string """, input_str, re . VERBOSE) is not None
Valid number to 2 decimal places
55f9064161541a9e01000001
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/55f9064161541a9e01000001
7 kyu
A very passive-aggressive co-worker of yours was just fired. While he was gathering his things, he quickly inserted a bug into your system which renamed everything to what looks like jibberish. He left two notes on his desk, one reads: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" while the other reads: "Uif usjdl up uijt lbub jt tjnqmf kvtu sfqmbdf fwfsz mfuufs xjui uif mfuufs uibu dpnft cfgpsf ju". Rather than spending hours trying to find the bug itself, you decide to try and decode it. If the input is not a string, your function must return "Input is not a string". Your function must be able to handle capital and lower case letters. You will not need to worry about punctuation.
games
alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' correct = 'ZABCDEFGHIJKLMNOPQRSTUVWXYzabcdefghijklmnopqrstuvwxy' def one_down(txt): return "Input is not a string" if type(txt) != str else txt . translate(str . maketrans(alpha, correct))
One down
56419475931903e9d1000087
[ "Strings", "Algorithms", "Cryptography", "Puzzles" ]
https://www.codewars.com/kata/56419475931903e9d1000087
6 kyu
Oh no! You have stumbled upon a mysterious signal consisting of beeps of various lengths, and it is of utmost importance that you find out the secret message hidden in the beeps. There are long and short beeps, the longer ones roughly three times as long as the shorter ones. Hmm... that sounds familiar. That's right: your job is to implement a decoder for the Morse alphabet. Rather than dealing with actual beeps, we will use a common string encoding of Morse. A long beep is represened by a dash (`-`) and a short beep by a dot (`.`). A series of long and short beeps make up a letter, and letters are separated by spaces (` `). Words are separated by double spaces. You should implement the International Morse Alphabet. You need to support letters a-z and digits 0-9 as follows: a .- h .... o --- u ..- 1 .---- 6 -.... b -... i .. p .--. v ...- 2 ..--- 7 --... c -.-. j .--- q --.- w .-- 3 ...-- 8 ---.. d -.. k -.- r .-. x -..- 4 ....- 9 ----. e . l .-.. s ... y -.-- 5 ..... 0 ----- f ..-. m -- t - z --.. g --. n -. ## Examples .... . .-.. .-.. --- .-- --- .-. .-.. -.. → "hello world" .---- ... - .- -. -.. ..--- -. -.. → "1st and 2nd" ```if:python A dictionnary `TOME` is preloaded for you, with the information above to convert morse code to letters. ``` ```if:javascrip An object `TOME` is preloaded for you, with the information above to convert morse code to letters. ``` ```if:ruby A Hashmap `$dict` is preloaded for you, with the information above to convert morse code to letters. ```
algorithms
def decode(s): return '' . join(TOME . get(w, ' ') for w in s . split(' ')) if s else ''
Decode Morse
54b0306c56f22d0bf9000ffb
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/54b0306c56f22d0bf9000ffb
6 kyu
Write a function that takes a string and returns an array of the repeated characters (letters, numbers, whitespace) in the string. If a charater is repeated more than once, only show it once in the result array. Characters should be shown **by the order of their first repetition**. Note that this may be different from the order of first appearance of the character. Characters are case sensitive. For F# return a "char list" ## Examples: ```javascript remember("apple") => returns ["p"] remember("apPle") => returns [] // no repeats, "p" != "P" remember("pippi") => returns ["p","i"] // show "p" only once remember('Pippi') => returns ["p","i"] // "p" is repeated first ``` ```python remember("apple") => returns ["p"] remember("apPle") => returns [] # no repeats, "p" != "P" remember("pippi") => returns ["p","i"] # show "p" only once remember('Pippi') => returns ["p","i"] # "p" is repeated first ``` ```ruby remember("apple") => returns ["p"] remember("apPle") => returns [] # no repeats, "p" != "P" remember("pippi") => returns ["p","i"] # show "p" only once remember('Pippi') => returns ["p","i"] # "p" is repeated first ``` ```csharp Remember("apple") => returns ['p'] Remember("apPle") => returns [] # no repeats, 'p' != 'P' Remember("pippi") => returns ['p','i'] # show 'p' only once Remember('Pippi') => returns ['p','i'] # 'p' is repeated first ``` ```fsharp _rem "apple" => returns ['p'] # _rem returns a char list not a List<char> _rem "apPle" => returns [] # no repeats, 'p' != 'P' _rem "pippi" => returns ['p','i'] # show 'p' only once _rem "Pippi" => returns ['p','i'] # 'p' is repeated first ```
algorithms
def remember(str_): seen = set() res = [] for i in str_: res . append(i) if i in seen and i not in res else seen . add(i) return res
Remember
55a243393fb3e87021000198
[ "Logic", "Strings", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/55a243393fb3e87021000198
6 kyu
In this kata you must take an input string, reverse the order of the words, and reverse the order of the letters within the words. But, as a bonus, every test input will end with a punctuation mark (! ? .) and the output should be returned with the mark at the end. A few examples should help clarify: ```python esrever("hello world.") == "dlrow olleh." esrever("Much l33t?") == "t33l hcuM?" esrever("tacocat!") == "tacocat!" ``` Quick Note: A string will always be passed in (though it may be empty) so no need for error-checking other types.
reference
def esrever(s): return s[: - 1][:: - 1] + s[- 1] if s else ''
esrever esreveR!
57e0206335e198f82b00001d
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/57e0206335e198f82b00001d
7 kyu
Array Exchange and Reversing It's time for some array exchange! The objective is simple: exchange the elements of two arrays in-place in a way that their new content is also reversed. ```ruby # before my_array = ['a', 'b', 'c'] other_array = [1, 2, 3] my_array.exchange_with!(other_array) # after my_array == [3, 2, 1] other_array == ['c', 'b', 'a'] ``` ```python # before my_list = ['a', 'b', 'c'] other_list = [1, 2, 3] exchange_with(my_list, other_list) # after my_list == [3, 2, 1] other_list == ['c', 'b', 'a'] ``` ```javascript // before const myArray = ['a', 'b', 'c']; const otherArray = [1, 2, 3]; exchangeWith(myArray, otherArray); // after myArray => [3, 2, 1] otherArray => ['c', 'b', 'a'] ```
reference
def exchange_with(a, b): a[:], b[:] = b[:: - 1], a[:: - 1]
Array Exchange
5353212e5ee40d4694001114
[ "Arrays", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/5353212e5ee40d4694001114
6 kyu
# Your task should you chose to accept... Build a deck of playing cards by generating 52 strings representing cards. There are no jokers. Each card string will have the format of: ``` "ace of hearts" "ace of spades" "ace of diamonds" "ace of clubs" ``` And will consist of the following ranks: ``` ace two three four five six seven eight nine ten jack queen king ``` They do not need to be in order. ## Additional constraints ~~~if:ruby Ruby: * You must use at least one `flat_map` in your solution * At most 3 lines ~~~ ~~~if:csharp For C# constraints are: * You must at least use one `Select()` in your solution * Less than 8 lines ~~~ ~~~if:fsharp * You must at least use one `map` in your solution * 1 line only! ~~~ ~~~if:python * 1 line only! ~~~ ~~~if:javascript * 1 line only! * `buildDeck` is a variable holding your deck. It is not a function. ~~~
reference
def deck_of_cards(): return [card + " of " + suit for card in ["ace", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king"] for suit in ["hearts", "spades", "diamonds", "clubs"]]
A functional deck of cards....
535742c7e727388cdc000297
[ "Functional Programming", "Fundamentals" ]
https://www.codewars.com/kata/535742c7e727388cdc000297
6 kyu
The Menger Sponge is a three-dimensional fractal, first described by Karl Menger in 1926. ![Mengers Sponge (Level 0-3)](http://i.imgur.com/V6Rb4Za.jpg) ###### _An illustration of the iterative construction of a Menger sponge_ A method of constructing a Menger Sponge can be visualized as follows: 1. Start from a cube (first part of image). 2. Scale down the cube so that side length is 1/3 of its original, and make 20 copies of it. 3. Place the copies so that they measure the same size as the original cube but without its central parts (next part of image) 4. Repeat the process from step 2 for the new smaller cubes from the previous step. 5. In each iteration (e.g. repeating the last three steps), the effect will be that parts of the cube will be removed, they'll never be added. Menger sponge will always consist of parts will never be removed, regardless of how many iterations you do. ___ An alternative explanation: 1. Start from a cube (first part of image). 2. Devide each cube into 27 equal sized cubes. 3. Remove the middle-cube and the six cubes on each side of the group of 27 cubes (second part of image). 4. Repeat the process from step 2 for the smaller cubes (third and fourth part of image). ## Task In this kata you will create a function that takes non negative integers (from 0 to n) and return the amount of cubes that the Menger Sponge would have in that specific iteration. ## Example ```text For n = 0, the ouptut should be 1; For n = 1, the output should be 20; For n = 2, the output should be 400; For n = 3, the output should be 8000; for n = 4, the output should be 160000; For n = 5, the output should be 3200000; For n = 6, the output should be 64000000. ``` Happy coding!
algorithms
def calc_ms(n): return 20 * * n
Count cubes in a Menger Sponge
59d28768a25c8c51a6000057
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/59d28768a25c8c51a6000057
7 kyu
##### _This kata is inspired by [davazp's one](https://www.codewars.com/kata/break-the-pieces)_ <hr> ## Context So, here we go again: You are given an ASCII diagram, containing minus signs `"-"`, plus signs `"+"`, vertical bars `"|"` and whitespaces `" " `. Your task is to write a function which will break the diagram in the minimal pieces it is made of. For example, if the input of your function is the diagram on the left below, the expected answer will be the list of strings representing the three individual shapes on the right (note how the biggest shape lost a `"+"` sign in the extraction) : ``` Input: Expected: +------------+ +------------+ | | | | +------+ +-----+ | | | | | | | | | | | | | | | | +------+-----+ +------------+ +------+ +-----+ | | | | | | +------+-----+ ``` If you encounter imbricated pieces, both outer and inner shapes have to be returned. For example: ``` Input: Expected: +------------+ +------------+ | | | | | +--+ | | +--+ | | | | | | | | | | | | | | | | | +--+ | +--+ | | +--+ | | | | | | | | | +------------+ +------------+ +--+ ``` <hr> ## _So... What's new!?_ What is new in this "evilized" version is that you'll have to manage the extraction of shapes without inner whitespaces. For example, the input below should lead to the following list of strings: ``` Input: Expected: +------------+ +------------+ | | | | +------+ +----+ ++ | | | | | | | | || | | | | | | | | || +------++----+ +------------+ +------+ +----+ ++ | || | | || | +------++----+ ``` From there, you'll have two approaches...: * The "easy" (better) one... * ... or the hard one: if you stumble frequently going through the fixed tests, might be you didn't made the right move and you're on this path. It's doable that way either, but it is way harder than the other one (1 or 2 kyu ranks higher! But if you like challenges, you can try that really evilized way... ;) ) <hr> ## TASK You have to find all the individual pieces contained in the original diagram. Note that you are only searching for the smallest possible ones. You may find below some important indications about what you will have to deal with: * The pieces should not have any spaces on their right (ie. no trailing spaces). * However, they could have leading spaces if the figure is not a rectangle, as shown below: ``` +---+ | | +---+ | | | +-------+ ``` * It is not allowed to use more leading spaces than necessary. It is to say, the first character of at least one of the lines has to be different from a space. * Only explicitly closed pieces have to be considered (meaning, in the diagram above, there is one and only one piece). * The borders of each shape have to contain only the meaningful plus signs `"+"` (those in corners or at the intersections of several straight lines). * Keep an eye on the performances. You won't have to make your code unreadable to pass the tests, but be clever with what you choose to implement. * After all of that, you still will have to pass the random tests... _Note:_ In the display, to make it easier to see where whitespaces are or not, the spaces characters will be replaced with dots: ``` +---+ ....+---+ +---+ +---+ | | ....|...| | | |...|.. <- there are spaces here, on the right +---+ | => +---+...| | +---+ => |...+---+ | | |.......| | | |.......| +-------+ +-------+ +-------+ +-------+ ``` <br> <hr> ## Input * The diagrams are given as ordinary multiline strings of various lengths. ## Output * A list of multilines strings (_see the example tests_). * The order of the individual shapes in the list does not matter. <br> <hr> ### Final notes... * If you're following the "hard path", this kata might make you crazy... * Tests design: about 80 fixed tests (each of them doubled) and the random ones with shapes up to around 80x80 characters (100 for python and ruby, 250 for Java). If your solution times out, do not hesitate to do a second try before to do any modification to your code.
games
USE_BREAK_DISPLAY = True def v(c): return {(c[0] + 1, c[1]), (c[0] - 1, c[1])} def h(c): return {(c[0], c[1] + 1), (c[0], c[1] - 1)} def neig(c): return {(c[0] + 1, c[1]), (c[0] - 1, c[1]), (c[0], c[1] + 1), (c[0], c[1] - 1)} def neig2(c): return {(c[0] + i, c[1] + j) for i in {1, - 1, 0} for j in {1, - 1, 0}} def break_evil_pieces(shape): if not shape . strip(): return [] (a, b, shape) = interpolate(shape) S = {(i, j) for i in range(a) for j in range(b) if shape[i][j] == ' '} regions = [] while S: R = set({S . pop()}) R_ = R while R_: R_ = {j for i in R_ for j in neig(i) & S} - R R . update(R_) S = S - R boundary = {j for i in R for j in neig2(i)} - R min_i = min(i for i, j in boundary) max_i = max(i for i, j in boundary) + 1 min_j = min(j for i, j in boundary) max_j = max(j for i, j in boundary) + 1 if min_i < 0 or min_j < 0 or max_i > a or max_j > b: continue region = [list(row[min_j: max_j]) for row in shape[min_i: max_i]] for i in range(len(region)): for j in range(len(region[i])): if region[i][j] != ' ' and (i + min_i, j + min_j) not in boundary: region[i][j] = ' ' elif region[i][j] == '+': c = (i + min_i, j + min_j) if not (h(c) & boundary and v(c) & boundary): region[i][j] = '-' if h(c) & boundary else '|' regions . append('\n' . join( '' . join(row[:: 2]). rstrip() for row in region[:: 2])) return regions def interpolate(s): shape = s . split('\n') while not shape[0]. strip(): shape = shape[1:] while not shape[- 1]. strip(): shape = shape[: - 1] a = len(shape) b = max(len(shape[i]) for i in range(a)) for i in range(a): shape[i] += ' ' * (b - len(shape[i])) newshape = [[]] * (2 * a - 1) for i in range(2 * a - 1): newshape[i] = [' '] * (2 * b - 1) if i % 2: for j in range(b): if shape[i / / 2][j] in '|+' and shape[i / / 2 + 1][j] in '|+': newshape[i][2 * j] = '|' else: for j in range(2 * b - 1): if j % 2: if shape[i / / 2][j / / 2] in '-+' and shape[i / / 2][j / / 2 + 1] in '-+': newshape[i][j] = '-' else: newshape[i][j] = shape[i / / 2][j / / 2] return (2 * a - 1, 2 * b - 1, newshape)
Break the pieces (Evilized Edition)
591f3a2a6368b6658800020e
[ "Games", "Algorithms", "Puzzles" ]
https://www.codewars.com/kata/591f3a2a6368b6658800020e
1 kyu
## Check Digits Some numbers are more important to get right during data entry than others: a common example is product codes. To reduce the possibility of mistakes, product codes can be crafted in such a way that simple errors are detected. This is done by calculating a single-digit value based on the product number, and then appending that digit to the product number to arrive at the product code. When the product code is checked, the check digit value is stripped off and recalculated. If the supplied value does not match the recalculated value, the product code is rejected. A simple scheme for generating self-check digits, described here, is called Modulus 11 Self-Check. ## Calculation method Each digit in the product number is assigned a multiplication factor. The factors are assigned ***from right to left***, starting at `2` and counting up. For numbers longer than six digits, the factors restart at `2` after `7` is reached. The product of each digit and its factor is calculated, and the products summed. For example: ``` digit : 1 6 7 7 0 3 6 2 5 factor : 4 3 2 7 6 5 4 3 2 --- --- --- --- --- --- --- --- --- 4 + 18 + 14 + 49 + 0 + 15 + 24 + 6 + 10 = 140 ``` Then the sum of the products is divided by the prime number `11`. The remainder is inspected, and: * if the remainder is `0`, the check digit is also `0` * if the remainder is `1`, the check digit is replaced by an uppercase `X` * for all others, the remainder is subtracted from `11` The result is the **check digit**. ## Your task Your task is to implement this algorithm and return the input number with the correct check digit appended. ## Examples ``` input: "036532" product sum = 2*2 + 3*3 + 5*4 + 6*5 + 3*6 + 0*7 = 81 remainder = 81 mod 11 = 4 check digit = 11 - 4 = 7 output: "0365327" ```
algorithms
from itertools import cycle def add_check_digit(number): fact = cycle([2, 3, 4, 5, 6, 7]) r = sum(int(c) * next(fact) for c in number[:: - 1]) % 11 return number + ('0' if not r else 'X' if r == 1 else str(11 - r))
Modulus 11 - Check Digit
568d1ee43ee6afb3ad00001d
[ "Algorithms" ]
https://www.codewars.com/kata/568d1ee43ee6afb3ad00001d
6 kyu
_This is the performance verison of [KenKamau](https://www.codewars.com/users/KenKamau)'s kata: "__[Unique digit sequence](https://www.codewars.com/kata/599688d0e2800dda4e0001b0)__". If you did not complete it yet, you should begin there._ <hr> <br> <h1>Sequence detail:</h1> Consider a serie that has the following sequence: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 22, 11, 20, ... There is nothing special between numbers 0 and 10. The number 10 has digits 1 and 0. The smallest number before or after 10 that does not have 1 or 0 and is not already in the series is 22. Similarly, the smallest number before or after 22 that has not yet appeared in the series and that has no 2 is 11. Again the smallest number before and after 11 that has not appeared in the series and that has no 1 is 20, and so on. Once a number appers in the series, it cannot appear again. The order of the generated numbers might be quite erratic. You can see below the generated values (vertical axis) against the input values (horizontal axis) on different ranges: <img src="http://www.escalade-alsace.com/photos/Freddy/UniqueDigitSeq.png"> As you can surely feel it by seeing these graphes, for numbers above 10000, things become quite messy about performances... <br> <h1>Context:</h1> Your boss has strange habits. One might rather say, really odd delirious ones... He actually likes to play with some numbers with no reason. His last bad idea was to institute some kind of ""control"" over the references of the stored items, labelling those using the sequence above, in order. Well, not so bad as what he asked to you for this morning... Now he has the idea of using some Stock Exchange data to determine what number in the sequence he will use to determine... Well actually he lost you at this part... So weird. But he's the boss, right...? :/ The problem is that those data can output big numbers and that generating the sequence is quite time consuming in these cases. Moreover, the input values are random: you do not know the number of calls the function will recieve each time it's used and there is no known upperbond to the input value. And of course, he wants that you use the minimum amount of time possible to get all of those results, meaning you are not allowed to do extra calculations. Just what is needed. Damn boss... <br> <h1>Task:</h1> Optimize whatever you can in `find_num(n)` with (almost) whatever trick you want to generate the wanted numbers with this constraints: * No extra computations: never calculate useless outputs. That will be checked! * Your function will have to handle inputs over the 10000 critical limit (up to 18000. The reference solution does that in 8,6s). Take in consideration that the naive algorithm (classical good solutions to the original kata version) times out around 11500 when the full sequence is generated with one unique call. Bad algorithms could even times out at 1500-2000 numbers. * Your implementation has to handle inputs in random order * Inputs range: `0 <= n <= 18000` (codewars limitation) * Number of calls of the function: a ___LOT___ ! (several thausends) Since this is an optimization problem, you'll have to do these optimizations. What is forbidden: * hardcoding the full sequence * precompute the sequence or a part if it (meaning: the first test has to be launched less than 100 ms after you clicked the "attempt" button) <br> <h1>Control over the executions of the tests:</h1> Since an optimization kata is all about timing out a lot, and that timing out doesn't provide you any information on what's going on and if you are far away from the goal or not, I added a constant `N_LIMIT = 18000` in the background. You can change its value in your code and the executions will be stopped when your code reach this limit. This way, you'll be able to scan the performances of your function. Still, there may be some executions that could slip through this and time out with special values of `N_LIMIT`, but just try another value if you encounter the case. <br> <h1>Particularity of the tests protocol:</h1> Codewars's tests having a time limit there is, as a matter of fact, an upper bound to the values of `n`. So you might be tempted to memoize the full sequence up to 18000 in a way or another and be done with it. That will be forbidden by the tests for two reasons: 1) The task/context being what it is, the idea is that one could run the program sometimes only with small inputs (they are random!), so "your boss" doesn't want you to compute the whole range if it is not needed, and sometimes with big numbers showing up so you would have to dig far deeper in the sequence. This way, memoization with an upperlimit is not acceptable. This behaviour will be checked. 2) The idea is to be able to compute the number with any input. That cannot be done on codewars. But you'll be forced to struggle with that anyway. ;) <br><br><br> Final notes: * This is designed to be a computationnal task, don't search for mathematical stuff with complicate relations between consecutive numbers in the sequence (I don't even know if it is possible, but if you find a complete mathematical solution, go ahead!). * Not tested but if you want to try the challenge: my best code can generate up to approximately 20100 numbers in one shot on codewars (it takes 11.7-11.9s). If you want to try it, define `CHALLENGE = True` at the beginning of your code. That will deactivate all the tests and lunch a one shot sequence of 20100 numbers. Of course, a final assertion will make fail the execution after that, to avoid some kind of cheating... (note: `N_LIMIT` is inactive if `CHALLENGE = True`) * While creating the kata, I had to dig further in the structure of the sequence and about the performance tests of various implementations. If you're interested in that, you can go read the comment under [my solution](https://www.codewars.com/kata/reviews/599965d1a48343a01d000075/groups/599965d121b8c8ac910005d7). <hr> <br> _This is an optimization problem. It may/will be hard on you. Be persistent!_ ;)
refactoring
from itertools import combinations, count from string import digits def digitalize(n): return frozenset(str(n)) seq, used = [0], {0} def filter_gen(forbidden_digits): for n in count(): if not (n in used or digitalize(n) & forbidden_digits): yield n gens = {c: filter_gen(c) for r in range(1, len(digits)) for c in map(frozenset, combinations(digits, r))} def find_num(n): x = seq[- 1] for i in range(len(seq), n + 1): x = next(gens[digitalize(x)]) seq . append(x) used . add(x) return seq[n]
Unique digit sequence II - Optimization problem
599846fbc2bd3a62a4000031
[ "Memoization", "Refactoring", "Algorithms" ]
https://www.codewars.com/kata/599846fbc2bd3a62a4000031
3 kyu
### Task Your goal is to find two numbers(`>= 0`), the greatest common divisor of which is `divisor` and the number of iterations taken by Euclid's algorithm is `iterations`. ### Euclid's GCD ```cs BigInteger FindGCD(BigInteger a, BigInteger b) { // Swapping `a` and `b` if (a < b) { var tmp = a; a = b; b = tmp; } while (b > 0) { // An iteration of calculation BigInteger c = a % b; a = b; b = c; } // `a` is now the greatest common divisor return a; } ``` ```python def gcd(a: int, b: int) -> int: # Swapping `a` and `b` if a < b: a, b = b, a while b > 0: # An iteration of calculation a, b = b, a % b return a ``` ```ruby def gcd(a, b) # Swapping `a` and `b` if a < b a, b = b, a end while b > 0 # An iteration of calculation a, b = b, a % b end return a ``` ### Restrictions Your program should work for: ``` 0 < divisor < 1000 0 <= iterations <= 50'000 ```
algorithms
def find_initial_numbers(divisor, iterations): if not iterations: return divisor, 0 a, b = divisor, divisor for _ in range(iterations): a, b = a + b, a return a, b
Reversing Euclid's GCD. Parameters out of results
58cd7f6914e656400100005a
[ "Algorithms" ]
https://www.codewars.com/kata/58cd7f6914e656400100005a
6 kyu
If we alternate the vowels and consonants in the string `"have"`, we get the following list, arranged alphabetically: `['ahev', 'aveh', 'ehav', 'evah', 'have', 'heva', 'vahe', 'veha']`. These are the only possibilities in which vowels and consonants are alternated. The first element, `ahev`, is alphabetically lowest. Given a string: * alternate the vowels and consonants and return the lexicographically lowest element in the list * If any two or more vowels or consonants must follow each other, return `"failed"` * if the number of vowels and consonants are equal, the first letter of the result must be a vowel. Examples: ```Haskell solve("codewars") = "failed". However you alternate vowels and consonants, two consonants must follow each other solve("oruder") = "edorur" solve("orudere") = "ederoru". This is the only option that allows you to alternate vowels & consonants. ``` ```if c: In C, return an allocated string even if the response is "failed". ``` Vowels will be any of "aeiou". Input will be a lowercase string, no spaces. See test cases for more examples. Good luck! If you like this Kata, please try: [Consonant value](https://www.codewars.com/kata/59c633e7dcc4053512000073) [Alternate capitalization](https://www.codewars.com/kata/59cfc000aeb2844d16000075)
algorithms
def solve(s): vowels = sorted(c for c in s if c in "aeiou") consonants = sorted(c for c in s if c not in "aeiou") part1, part2 = sorted((vowels, consonants), key=len, reverse=True) part2 . append('') if len(part1) > len(part2): return "failed" return "" . join(a + b for a, b in zip(part1, part2))
Vowel-consonant lexicon
59cf8bed1a68b75ffb000026
[ "Strings", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/59cf8bed1a68b75ffb000026
6 kyu
Given a string, capitalize the letters that occupy even indexes and odd indexes separately, and return as shown below. Index `0` will be considered even. For example, `capitalize("abcdef") = ['AbCdEf', 'aBcDeF']`. See test cases for more examples. The input will be a lowercase string with no spaces. Good luck! If you like this Kata, please try: [Indexed capitalization](https://www.codewars.com/kata/59cfc09a86a6fdf6df0000f1) [Even-odd disparity](https://www.codewars.com/kata/59c62f1bdcc40560a2000060)
reference
def capitalize(s): s = '' . join(c if i % 2 else c . upper() for i, c in enumerate(s)) return [s, s . swapcase()]
Alternate capitalization
59cfc000aeb2844d16000075
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/59cfc000aeb2844d16000075
7 kyu
Given a string and an array of integers representing indices, capitalize all letters at the given indices. For example: * `capitalize("abcdef",[1,2,5]) = "aBCdeF"` * `capitalize("abcdef",[1,2,5,100]) = "aBCdeF"`. There is no index 100. The input will be a lowercase string with no spaces and an array of digits. Good luck! Be sure to also try: [Alternate capitalization](https://www.codewars.com/kata/59cfc000aeb2844d16000075) [String array revisal](https://www.codewars.com/kata/59f08f89a5e129c543000069)
reference
def capitalize(s, ind): ind = set(ind) return '' . join(c . upper() if i in ind else c for i, c in enumerate(s))
Indexed capitalization
59cfc09a86a6fdf6df0000f1
[ "Fundamentals" ]
https://www.codewars.com/kata/59cfc09a86a6fdf6df0000f1
7 kyu
It involves implementing a program that sums the digits of a non-negative integer. For example, the sum of 3433 digits is 13. ```if:javascript Digits can be a number, a string, or undefined. In case of `undefined` return an empty string `''`. ``` ```if:python Digits can be a number, a string, or `None`. In case of `None` return an empty string `''`. ``` To give you a little more excitement, the program will not only write the result of the sum, but also write all the sums used: 3 + 4 + 3 + 3 = 13.
reference
def sum_of_digits(digits): d = str(digits) return "" if digits is None else f' { " + " . join ( x for x in d )} = { sum ( map ( int , d ))} '
Sum of digits
59cf805aaeb28438fe00001c
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/59cf805aaeb28438fe00001c
7 kyu
Define a function that generates medial values between two coordinates and returns them in an array from start to target. For example, if the starting point is `[1,1]` and the target point is `[3,2]` then the shortest route from start to target would be `[[1,1], [2,2], [3,2]]`. The route should go only through integral coordinates. Note: you should move diagonally until the path from your current position to the target can be represented as a fully horizontal/vertical line. ## Examples: ```ruby tick_toward([5,5],[5,7]) #=> [[5,5],[5,6],[5,7]] tick_toward([3,2],[4,5]) #=> [[3,2],[4,3],[4,4],[4,5]] tick_toward([5,1],[5,-2]) #=> [[5,1],[5,0],[5,-1],[5,-2]] ``` ```javascript tickToward([5,5],[5,7]) // => [[5,5],[5,6],[5,7]] tickToward([3,2],[4,5]) // => [[3,2],[4,3],[4,4],[4,5]] tickToward([5,1],[5,-2]) // => [[5,1],[5,0],[5,-1],[5,-2]] ``` ```python tick_toward((5,5), (5,7)) == [(5,5), (5,6), (5,7)] tick_toward((3,2), (4,5)) == [(3,2), (4,3), (4,4), (4,5)] tick_toward((5,1), (5,-2)) == [(5,1), (5,0), (5,-1), (5,-2)] ``` ```c tick_toward({5, 5}, {5, 7}) == {{5, 5}, {5, 6}, {5, 7}} tick_toward({3, 2}, {4, 5}) == {{3, 2}, {4, 3}, {4, 4}, {4, 5}} tick_toward({5, 1}, {5, -2}) == {{5, 1}, {5, 0}, {5, -1}, {5, -2}} ``` ```if:python Note: tuples will be used for representing coordinates in Python. ``` ```if:c Notes for C language: 1) point structures `{x, y}` will be used for coordinates 2) assign the length of return array to `*output_len` ```
reference
def tick_toward(start, target): (x, y), (tx, ty), path = start, target, [start] while (x, y) != target: x = x + (1 if x < tx else - 1 if tx < x else 0) y = y + (1 if y < ty else - 1 if ty < y else 0) path . append((x, y)) return path
Tick Toward
54bd06539f075cece0000feb
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/54bd06539f075cece0000feb
6 kyu
You're given a mystery `puzzlebox` object. Examine it to make the tests pass and solve this kata.
games
def answer(puzzlebox): return 42
Thinkful - Object Drills: Puzzlebox
587f0871f297a6df780000cd
[ "Puzzles" ]
https://www.codewars.com/kata/587f0871f297a6df780000cd
6 kyu
You are given a list of directions in the form of a list: goal = ["N", "S", "E", "W"] Pretend that each direction counts for 1 step in that particular direction. Your task is to create a function called directions, that will return a reduced list that will get you to the same point.The order of directions must be returned as N then S then E then W. If you get back to beginning, return an empty array.
reference
def directions(goal): y = goal . count("N") - goal . count("S") x = goal . count("E") - goal . count("W") return ["N"] * y + ["S"] * (- y) + ["E"] * x + ["W"] * (- x)
Shorter Path
56a14f18005af7002f00003f
[ "Fundamentals" ]
https://www.codewars.com/kata/56a14f18005af7002f00003f
6 kyu
<h3 style='color:#ffffaa'>Task:</h3> <p style='color:#ffff00'>Make a function that converts a word to pig latin. The rules of pig latin are:</p> ``` If the word has more than 3 letters: 1. Take the first letter of a word and move it to the end 2. Add -ay to the word Otherwise leave the word alone. ``` Example: `hello` = `ellohay`
reference
def pig_latin(word): return word[1:] + word[0] + 'ay' if len(word) > 3 else word
Pig Atinlay
58702c0ca44cfc50dc000245
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/58702c0ca44cfc50dc000245
7 kyu
You're putting together contact information for all the users of your website to ship them a small gift. You queried your database and got back a list of users, where each user is another list with up to two items: a string representing the user's name and their shipping zip code. Example data might look like: ```python [["Grae Drake", 98110], ["Bethany Kok"], ["Alex Nussbacher", 94101], ["Darrell Silver", 11201]] ``` Notice that one of the users above has a name but _doesn't_ have a zip code. Write a function `user_contacts()` that takes a two-dimensional list like the one above and returns a dictionary with an item for each user where the key is the user's name and the value is the user's zip code. If your data doesn't include a zip code then the value should be `None`. For example, using the input above, `user_contacts()` would return this dictionary: ```python { "Grae Drake": 98110, "Bethany Kok": None, "Alex Nussbacher": 94101, "Darrell Silver": 11201, } ``` You don't have to worry about leading zeros in zip codes.
reference
def user_contacts(data): return {contact[0]: contact[1] if len(contact) > 1 else None for contact in data}
Thinkful - Dictionary Drills: User contacts
586f61bdfd53c6cce50004ee
[ "Fundamentals" ]
https://www.codewars.com/kata/586f61bdfd53c6cce50004ee
7 kyu
You're running an online business and a big part of your day is fulfilling orders. As your volume picks up that's been taking more of your time, and unfortunately lately you've been running into situations where you take an order but can't fulfill it. You've decided to write a function `fillable()` that takes three arguments: a dictionary `stock` representing all the merchandise you have in stock, a string `merch` representing the thing your customer wants to buy, and an integer `n` representing the number of units of merch they would like to buy. Your function should return `True` if you have the merchandise in stock to complete the sale, otherwise it should return `False`. Valid data will always be passed in and `n` will always be >= 1.
reference
def fillable(stock, merch, n): return stock . get(merch, 0) >= n
Thinkful - Dictionary drills: Order filler
586ee462d0982081bf001f07
[ "Fundamentals" ]
https://www.codewars.com/kata/586ee462d0982081bf001f07
8 kyu
The goal of this Kata is to remind/show you, how Z-algorithm works and test your implementation. For a string str[0..n-1], Z array is of same length as string. An element Z[i] of Z array stores length of the longest substring starting from str[i] which is also a prefix of str[0..n-1]. The first entry of Z array is meaning less as complete string is always prefix of itself. Example: Index: 0 1 2 3 4 5 6 7 8 9 10 11 Text: "a a b c a a b x a a a z" Z values: [11, 1, 0, 0, 3, 1, 0, 0, 2, 2, 1, 0] Your task will be to implement Z algorithm in your code and return Z-array. For empty string algorithm should return []. Input: string str Output: Z array for ex.: print zfunc('ababcaba') [8, 0, 2, 0, 0, 3, 0, 1] P.S. Note, that an important part of this kata is that you have to use efficient way to get Z-array (O(n)) --- because Kata has time test case. Good luck.
algorithms
def prefix1(a, b): cnt = 0 for i, j in zip(a, b): if i == j: cnt += 1 else: return cnt return cnt def prefix2(a, b, num): for i in range(num, - 1, - 1): if b . startswith(a[: i]): return i def zfunc(str_): z = [] k = len(str_) for i in range(len(str_)): z . append(prefix2(str_[i:], str_[: k - i], k - i)) # z.append(prefix1(str_[i:], str_[: k - i])) #poor timing return z
Z-algorithm
56d30dadc554829d55000578
[ "Algorithms" ]
https://www.codewars.com/kata/56d30dadc554829d55000578
5 kyu
We know the formula to find the solutions of an equation of second degree with only one variable: <a href="http://imgur.com/jXO5HA9"><img src="http://i.imgur.com/jXO5HA9.jpg?1" title="source: imgur.com" /></a> We need the function ```sec_deg_solver()/secDegSolver()```, that accepts three arguments, ```a```, ```b``` and ```c```, the coefficients of the above equation. The outputs of the function may vary depending on the values of coefficients a, b and c, according to the following situations. (used values as examples only): ``` - If a is equal 0: - If b and c are not 0. It will return: "It is a first degree equation. Solution: 0.5512345" - If a, b and c are 0. It will return: "The equation is indeterminate" - If a and b are 0, and c is not 0. It will return: "Impossible situation. Wrong entries" - If a and c are 0 and b is not 0: It will return: "It is a first degree equation. Solution: 0.0" ``` ``` - If a is not 0: - If Δ < 0 (see image above). It will return: "There are no real solutions" - If Δ = 0. It will return: "It has one double solution: 1.4142135624" - If Δ > 0. It will return: "Two solutions: 1,7320508076, 2.0" (solutions should be sorted) ``` The results should be expressed up to 10 decimals rounded result Let's see some cases: ```python a = 0 b = 2 c = -4 sec_deg_solver(a, b, c) == It is a first degree equation. Solution: 2.0 a = 10 b = 2 c = -4 sec_deg_solver(a, b, c) == Two solutions: -0.7403124237, 0.5403124237 a = 1.5 b = 2 c = 4 sec_deg_solver(a, b, c) == There are no real solutions a = 1 b = -2 c = 1 sec_deg_solver(a, b, c) == It has one double solution: 1.0 a = 0 b = 0 c = 0 sec_deg_solver(a, b, c) == The equation is indeterminate ``` ```ruby a = 0 b = 2 c = -4 sec_deg_solver(a, b, c) == It is a first degree equation. Solution: 2.0 a = 10 b = 2 c = -4 sec_deg_solver(a, b, c) == Two solutions: -0.7403124237, 0.5403124237 a = 1.5 b = 2 c = 4 sec_deg_solver(a, b, c) == There are no real solutions a = 1 b = -2 c = 1 sec_deg_solver(a, b, c) == It has one double solution: 1.0 a = 0 b = 0 c = 0 sec_deg_solver(a, b, c) == The equation is indeterminate ``` ```javascript a = 0 b = 2 c = -4 secDegSolver(a, b, c) == It is a first degree equation. Solution: 2 a = 10 b = 2 c = -4 secDegSolver(a, b, c) == Two solutions: -0.7403124237, 0.5403124237 a = 1.5 b = 2 c = 4 secDegSolver(a, b, c) == There are no real solutions a = 1 b = -2 c = 1 secDegSolver(a, b, c) == It has one double solution: 1 a = 0 b = 0 c = 0 secDegSolver(a, b, c) == The equation is indeterminate a = 0 b = 0 c = 4 secDegSolver(a, b, c) == "Impossible situation. Wrong entries" ``` (Be aware that the result has a string format and -0.0 is not 0.0) **Note on having two solutions:** input them sorted numerically; in the JavaScript version, not to put any extra difficulty on this one, sort them with a simple `.sort()` (which will sort them lexicographically). Happy coding!!
reference
from math import sqrt MSG = { # a == 0 0: "It is a first degree equation. Solution: {}", # b != 0 and c != 0 1: "The equation is indeterminate", # b == 0 and c == 0 2: "Impossible situation. Wrong entries", # b == 0 and c != 0 3: "It is a first degree equation. Solution: 0.0", # b != 0 and c == 0 # a != 0 4: "There are no real solutions", # Δ < 0 5: "It has one double solution: {}", # Δ == 0 6: "Two solutions: {}, {}" # Δ > 0 } def sec_deg_solver(a, b, c): if a: delta = b * b - 4 * a * c if delta < 0: msg = MSG[4] elif delta > 0: roots = round((- b - sqrt(delta)) / (2 * a), 10), round((- b + sqrt(delta)) / (2 * a), 10) msg = MSG[6]. format(* sorted(roots)) else: root = round(- b / (2 * a), 10) msg = MSG[5]. format(root) else: if b: if c: root = round(- c / b, 10) msg = MSG[0]. format(root) else: msg = MSG[3] else: if c: msg = MSG[2] else: msg = MSG[1] return msg
One Variable Second Degree Equation Solver
560ae2027dc9033b5e0000c2
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/560ae2027dc9033b5e0000c2
6 kyu
Given an array of numbers, return the difference between the largest and smallest values. For example: `[23, 3, 19, 21, 16]` should return `20` (i.e., `23 - 3`). `[1, 434, 555, 34, 112]` should return `554` (i.e., `555 - 1`). The array will contain a minimum of two elements. Input data range guarantees that `max-min` will cause no integer overflow.
algorithms
def between_extremes(numbers): return max(numbers) - min(numbers)
Between Extremes
56d19b2ac05aed1a20000430
[ "Algorithms", "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/56d19b2ac05aed1a20000430
7 kyu
How sexy is your name? Write a program that calculates how sexy one's name is according to the criteria below. There is a preloaded dictionary of letter scores called `SCORES`(Python & JavaScript) / `$SCORES` (Ruby). Add up the letters (case-insensitive) in your name to get your sexy score. Ignore other characters. ```python SCORES = {'A': 100, 'B': 14, 'C': 9, 'D': 28, 'E': 145, 'F': 12, 'G': 3, 'H': 10, 'I': 200, 'J': 100, 'K': 114, 'L': 100, 'M': 25, 'N': 450, 'O': 80, 'P': 2, 'Q': 12, 'R': 400, 'S': 113, 'T': 405, 'U': 11, 'V': 10, 'W': 10, 'X': 3, 'Y': 210, 'Z': 23} ``` ```javascript SCORES = {'A': 100, 'B': 14, 'C': 9, 'D': 28, 'E': 145, 'F': 12, 'G': 3, 'H': 10, 'I': 200, 'J': 100, 'K': 114, 'L': 100, 'M': 25, 'N': 450, 'O': 80, 'P': 2, 'Q': 12, 'R': 400, 'S': 113, 'T': 405, 'U': 11, 'V': 10, 'W': 10, 'X': 3, 'Y': 210, 'Z': 23} ``` ```ruby $SCORES = {'A'=> 100, 'B'=> 14, 'C'=> 9, 'D'=> 28, 'E'=> 145, 'F'=> 12, 'G'=> 3, 'H'=> 10, 'I'=> 200, 'J'=> 100, 'K'=> 114, 'L'=> 100, 'M'=> 25, 'N'=> 450, 'O'=> 80, 'P'=> 2, 'Q'=> 12, 'R'=> 400, 'S'=> 113, 'T'=> 405, 'U'=> 11, 'V'=> 10, 'W'=> 10, 'X'=> 3, 'Y'=> 210, 'Z'=> 23} ``` The program must return how sexy one's name is according to the "Sexy score ranking" chart. score <= 60: 'NOT TOO SEXY' 61 <= score <= 300: 'PRETTY SEXY' 301 <= score <= 599: 'VERY SEXY' score >= 600: 'THE ULTIMATE SEXIEST'
reference
def sexy_name(name): name_score = sum(SCORES . get(a, 0) for a in name . upper()) if name_score >= 600: return 'THE ULTIMATE SEXIEST' elif name_score >= 301: return 'VERY SEXY' elif name_score >= 61: return 'PRETTY SEXY' return 'NOT TOO SEXY'
How sexy is your name?
571b2ee08d8c9c0d160014ec
[ "Fundamentals" ]
https://www.codewars.com/kata/571b2ee08d8c9c0d160014ec
7 kyu
The Monty Hall problem is a probability puzzle base on the American TV show "Let's Make A Deal". In this show, you would be presented with 3 doors: One with a prize behind it, and two without (represented with goats). After choosing a door, the host would open one of the other two doors which didn't include a prize, and having been shown a false door, however the math proves that you significantly increase your chances, from 1/3 to 2/3 by switching.ask the participant if he or she wanted to switch to the third door. Most wouldn't. One would think you have a fifty-fifty chance of winning after Further information about this puzzle can be found on https://en.wikipedia.org/wiki/Monty_Hall_problem. In this program you are given an array of people who have all guessed on a door from 1-3, as well as given the door which includes the price. You need to make every person switch to the other door, and increase their chances of winning. Return the win percentage (as a rounded int) of all participants.
reference
def monty_hall(door, guesses): return round(100.0 * (len(guesses) - guesses . count(door)) / len(guesses))
Monty Hall Problem
54f9cba3c417224c63000872
[ "Fundamentals" ]
https://www.codewars.com/kata/54f9cba3c417224c63000872
7 kyu
As a member of the editorial board of the prestigous scientific Journal _Proceedings of the National Academy of Sciences_, you've decided to go back and review how well old articles you've published stand up to modern publication best practices. Specifically, you'd like to re-evaluate old findings in light of recent literature about ["researcher degrees of freedom"](http://journals.sagepub.com/doi/full/10.1177/0956797611417632). You want to categorize all the old articles into three groups: "Fine", "Needs review" and "Pants on fire". In order to categorize them you've enlisted an army of unpaid grad students to review and give you two data points from each study: (1) the p-value behind the paper's primary conclusions, and (2) the number of recommended author requirements to limit researcher degrees of freedom the authors satisfied: * Authors must decide the rule for terminating data collection before data collection begins and report this rule in the article. * Authors must collect at least 20 observations per cell or else provide a compelling cost-of-data-collection justification. * Authors must list all variables collected in a study. * Authors must report all experimental conditions, including failed manipulations. * If observations are eliminated, authors must also report what the statistical results are if those observations are included. * If an analysis includes a covariate, authors must report the statistical results of the analysis without the covariate. Your army of tenure-hungry grad students will give you the p-value as a float between `1.0` and `0.0` exclusive, and the number of author requirements satisfied as an integer from `0` through `6` inclusive. You've decided to write a function, `categorize_study()` to automatically categorize each study based on these two inputs using the completely scientifically legitimate "bs-factor". The bs-factor for a particular paper is calculated as follows: * bs-factor when the authors satisfy all six requirements is 1 * bs-factor when the authors satisfy only five requirements is 2 * bs-factor when the authors satisfy only four requirements is 4 * bs-factor when the authors satisfy only three requirements is 8... Your function should multiply the p-value by the bs-factor and use that product to return one of the following strings: * product is less than 0.05: "Fine" * product is 0.05 to 0.15: "Needs review" * product is 0.15 or higher: "Pants on fire" You've also decided that all studies meeting _none_ of the author requirements that would have been categorized as "Fine" should instead be categorized as "Needs review". For example: `categorize_study(0.01, 3)` should return `"Needs review"` because the p-value times the bs-factor is `0.08`. `categorize_study(0.04, 6)` should return `"Fine"` because the p-value times the bs-factor is only `0.04`. `categorize_study(0.0001, 0)` should return `"Needs review"` even though the p-value times the bs-factor is only `0.0064`. `categorize_study(0.012, 0)` should return `"Pants on fire"` because the p-value times the bs-factor is `0.768`.
reference
def categorize_study(p_value, requirements): study_value = p_value * (2 * * (6 - requirements)) if study_value < 0.05 and requirements != 0: return "Fine" elif study_value < 0.05 and requirements == 0: return "Needs review" elif study_value > 0.05 and study_value < 0.15: return "Needs review" else: return "Pants on fire"
Thinkful - Logic Drills: Hacking p-hackers
5864af6739c5ab26e80000bf
[ "Fundamentals" ]
https://www.codewars.com/kata/5864af6739c5ab26e80000bf
7 kyu
Old Greg likes to count his 31 fish on just one hand. To do this he holds his right hand up, palm facing toward him, fist closed and then counts in binary using his fingers. First he sticks his thumb out which makes 1, then just his index finger which makes 10 (decimal 2), then Index and thumb which makes 11 (decimal 3), then just his middle finger which makes 100 (decimal 4) and so on up to all five fingers out which makes 11111 (decimal 31). Incidentally this is why when Old Greg is annoyed with you he says: Just let me count to 4 in binary (a joke only for IT people I think!). You need to create a function: binaryFingers into which will be passed a string of 1s and 0s, it should return an array showing which of Old Greg's digits which are up, left to right, as Old Greg sees them: so: BinaryFingers.GetFingers("101") should return {"Middle", "Thumb"} BinaryFingers.GetFingers("11111") should return {"Pinkie", "Ring", "Middle", "Index", "Thumb"} You can be sure that the input parameter string will never contain more than 5 digits (although this wouldn't work for Old Greg's friend Lucky Bob who has six fingers and can count to 63). An empty string should return an empty array.
games
def binary_fingers(s): return [["Pinkie", "Ring", "Middle", "Index", "Thumb"][i] for i, d in enumerate(s . zfill(5)) if int(d)]
Old Greg's Binary Fingers
565f1bd8f97d3e59c400014a
[ "Puzzles" ]
https://www.codewars.com/kata/565f1bd8f97d3e59c400014a
7 kyu
You're playing a game with a friend involving a bag of marbles. In the bag are ten marbles: * 1 smooth red marble * 4 bumpy red marbles * 2 bumpy yellow marbles * 1 smooth yellow marble * 1 bumpy green marble * 1 smooth green marble You can see that the probability of picking a smooth red marble from the bag is `1 / 10` or `0.10` and the probability of picking a bumpy yellow marble is `2 / 10` or `0.20`. The game works like this: your friend puts her hand in the bag, chooses a marble (without looking at it) and tells you whether it's bumpy or smooth. Then you have to guess which color it is before she pulls it out and reveals whether you're correct or not. You know that the information about whether the marble is bumpy or smooth changes the probability of what color it is, and you want some help with your guesses. Write a function `color_probability()` that takes two arguments: a color (`'red'`, `'yellow'`, or `'green'`) and a texture (`'bumpy'` or `'smooth'`) and returns the probability as a decimal fraction accurate to two places. The probability should be a string and should discard any digits after the 100ths place. For example, `2 / 3` or `0.6666666666666666` would become the string `'0.66'`. Note this is different from rounding. As a complete example, `color_probability('red', 'bumpy')` should return the string `'0.57'`.
reference
def color_probability(color, texture): marbles = {"smooth": {"red": 1, "yellow": 1, "green": 1, "total": 3}, "bumpy": {"red": 4, "yellow": 2, "green": 1, "total": 7}} return "{}" . format(marbles[texture][color] / marbles[texture]["total"])[: 4]
Thinkful - Logic Drills: Red and bumpy
5864cdc483f7e6df980001c8
[ "Fundamentals" ]
https://www.codewars.com/kata/5864cdc483f7e6df980001c8
6 kyu
In your class, you have started lessons about [arithmetic progression](https://en.wikipedia.org/wiki/Arithmetic_progression). Since you are also a programmer, you have decided to write a function that will return the first `n` elements of the sequence with the given common difference `d` and first element `a`. Note that the difference may be zero! The result should be a string of numbers, separated by comma and space. ## Example ```python # first element: 1, difference: 2, how many: 5 arithmetic_sequence_elements(1, 2, 5) == "1, 3, 5, 7, 9" ``` ~~~if:fortran *NOTE: In Fortran, your returned string is* **not** *permitted to contain redundant leading/trailing whitespace.* ~~~ ~~~if:c Note: The returned string will be free'd if non-NULL. ~~~
reference
def arithmetic_sequence_elements(a, r, n): return ", " . join((str(a + r * i) for i in range(n)))
Arithmetic progression
55caf1fd8063ddfa8e000018
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/55caf1fd8063ddfa8e000018
7 kyu
Given two numbers `m` and `n`, such that `0 ≤ m ≤ n` : - convert all numbers from `m` to `n` (inclusive) to binary - sum them as if they were in base 10 - convert the result to binary - return as a string ## Example ```javascript 1, 4 --> 1111010 because: 1 // 1 in binary is 1 + 10 // 2 in binary is 10 + 11 // 3 in binary is 11 + 100 // 4 in binary is 100 ----- 122 // 122 in binary is 1111010 ```
reference
def binary_pyramid(m, n): return bin(sum(int(bin(i)[2:]) for i in range(m, n + 1)))[2:]
Binary Pyramid 101
5596700a386158e3aa000011
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5596700a386158e3aa000011
7 kyu
# Task You are given a string `s`. Your task is to count the number of each letter (A-Z), and make a vertical histogram as result. Look at the following examples to understand the rules. # Example For `s = "XXY YY ZZZ123ZZZ AAA BB C"`, the output should be: ``` * * * * * * * * * * * * * * * * * A B C X Y Z ``` # Rules - You just need to count the uppercase letters. Any other character will be ignored. - Using `*` to represent the number of characters. - The order of output is form A to Z. Characters that do not appear in the string are ignored. - To beautify the histogram, there is a space between every pair of columns. - There are no extra spaces at the end of each row. Also, use "\n" to separate rows. - Happy Coding `^_^`
reference
from collections import Counter def verticalHistogramOf(s): def buildLine(h): return ' ' . join(h and ' *' [cnts[k] >= h] or k for k in keys). rstrip() cnts = Counter(filter(str . isupper, s)) keys = sorted(cnts) m = max(cnts . values(), default=0) return '\n' . join(map(buildLine, reversed(range(m + 1))))
Simple Fun #358: Vertical Histogram Of Letters
59cf0ba5d751dffef300001f
[ "Fundamentals" ]
https://www.codewars.com/kata/59cf0ba5d751dffef300001f
5 kyu
Attention Agent. The White House is currently developing a mobile app that it can use to issue instructions to its undercover agents. Part of the functionality of this app is to have messages that can be read only once, and are then destroyed. As our best undercover developer, we need you to implement a `SecureList` class that will deliver this functionality. Behaviour different to the traditional list is outlined below: ~~~if:python - Accessing an item at any index should delete the item at that index eg: ```python messages=SecureList([1,2,3,4]) print(messages[1]) # prints 2 print(messages) # prints [1,3,4] ``` ```java SecureList secureList = new SecureList(new int[]{1, 2, 3, 4}); System.out.println(secureList.get(1)); // prints 2 System.out.println(secureList); // prints [1,3,4] ``` - Printing the whole list should clear the whole list eg: ```python messages=SecureList([1,2,3,4]) print(messages) # prints [1,2,3,4] print(messages) # prints [] ``` - Viewing the representation of the list should also clear the list eg: ```python messages=SecureList([1,2,3,4]) print("my messages are: %r."%messages) # prints "my messages are: [1,2,3,4]. print(messages) # prints [] ``` ~~~ ~~~if:java - Accessing an item at any index should delete the item at that index eg: ```java SecureList secureList = new SecureList(new int[]{1, 2, 3, 4}); System.out.println(secureList.get(1)); // prints 2 System.out.println(secureList); // prints [1,3,4] ``` - Printing the whole list should clear the whole list eg: ```java SecureList secureList = new SecureList(new int[]{1, 2, 3, 4}); System.out.println(secureList); // prints [1,2,3,4] System.out.println(secureList); // prints [] ``` ~~~ ```if:python To complete this kata you need to be able to define a class that implements `__getitem__()`, `__str__()`, `__repr__()`, and possibly `__len__()`. ``` ```if:java To complete this kata you need to be able to define a class that implements `get(int index)`, `toString()`, and possibly `size()`. ``` Good luck Agent.
reference
class SecureList (list): def __getitem__(self, key): ret = list(self)[key] del self[key] return ret def __repr__(self): ret = list(self). __repr__() del self[:] return ret def __str__(self): ret = list(self). __str__() del self[:] return ret
Only-Readable-Once list
53f17f5b59c3fcd589000390
[ "Lists" ]
https://www.codewars.com/kata/53f17f5b59c3fcd589000390
5 kyu
One suggestion to build a satisfactory password is to start with a memorable phrase or sentence and make a password by extracting the first letter of each word. Even better is to replace some of those letters with numbers (e.g., the letter `O` can be replaced with the number `0`): * instead of including `i` or `I` put the number `1` in the password; * instead of including `o` or `O` put the number `0` in the password; * instead of including `s` or `S` put the number `5` in the password. ## Examples: ``` "Give me liberty or give me death" --> "Gml0gmd" "Keep Calm and Carry On" --> "KCaC0" ```
reference
SWAP = {'i': '1', 'I': '1', 'o': '0', 'O': '0', 's': '5', 'S': '5'} def make_password(phrase): return '' . join(SWAP . get(a[0], a[0]) for a in phrase . split())
Password maker
5637b03c6be7e01d99000046
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/5637b03c6be7e01d99000046
7 kyu
The prime number sequence starts with: `2,3,5,7,11,13,17,19...`. Notice that `2` is in position `one`. `3` occupies position `two`, which is a prime-numbered position. Similarly, `5`, `11` and `17` also occupy prime-numbered positions. We shall call primes such as `3,5,11,17` dominant primes because they occupy prime-numbered positions in the prime number sequence. Let's call this `listA`. As you can see from listA, for the prime range `range(0,10)`, there are `only two` dominant primes (`3` and `5`) and the sum of these primes is: `3 + 5 = 8`. Similarly, as shown in listA, in the `range (6,20)`, the dominant primes in this range are `11` and `17`, with a sum of `28`. Given a `range (a,b)`, what is the sum of dominant primes within that range? Note that `a <= range <= b` and `b` will not exceed `500000`. Good luck! If you like this Kata, you will enjoy: [Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3) [Sum of prime-indexed elements](https://www.codewars.com/kata/59f38b033640ce9fc700015b) [Divisor harmony](https://www.codewars.com/kata/59bf97cd4f98a8b1cd00007e)
reference
n = 500000 sieve, PRIMES = [0] * (n / / 2 + 1), [0, 2] for i in range(3, n + 1, 2): if not sieve[i / / 2]: PRIMES . append(i) for j in range(i * * 2, n + 1, i * 2): sieve[j / / 2] = 1 DOMINANTS = [] for p in PRIMES: if p >= len(PRIMES): break DOMINANTS . append(PRIMES[p]) def solve(a, b): return sum(p for p in DOMINANTS if a <= p <= b)
Dominant primes
59ce11ea9f0cbc8a390000ed
[ "Fundamentals" ]
https://www.codewars.com/kata/59ce11ea9f0cbc8a390000ed
6 kyu
# Problem In China,there is an ancient mathematical book, called "The Mathematical Classic of Sun Zi"(《孙子算经》). In the book, there is a classic math problem: “今有物不知其数,三三数之剩二,五五数之剩三,七七数之剩二,问物几何?” Ahh, Sorry. I forgot that you don't know Chinese. Let's translate it to English: There is a unkown positive integer `n`. We know: `n % 3 = 2`, and `n % 5 = 3`, and `n % 7 = 2`. What's the minimum possible positive integer `n`? The correct answer is `23`. # Task You are given three non-negative integers `x,y,z`. They represent the remainders of the unknown positive integer `n` divided by 3,5,7. That is: `n % 3 = x, n % 5 = y, n % 7 = z` Your task is to find the minimum possible positive integer `n` and return it. # Example For `x = 2, y = 3, z = 2`, the output should be `23` `23 % 3 = 2, 23 % 5 = 3, 23 % 7 = 2` For `x = 1, y = 2, z = 3`, the output should be `52` `52 % 3 = 1, 52 % 5 = 2, 52 % 7 = 3` For `x = 1, y = 3, z = 5`, the output should be `103` `103 % 3 = 1, 103 % 5 = 3, 103 % 7 = 5` For `x = 0, y = 0, z = 0`, the output should be `105` For `x = 1, y = 1, z = 1`, the output should be `1` # Note - `0 <= x < 3, 0 <= y < 5, 0 <= z < 7` - Happy Coding `^_^`
algorithms
def find_unknown_number(x, y, z): return (x * 70 + y * 21 + z * 15) % 105 or 105
Algorithm Fun: Find The Unknown Number - Part I
59cdb2b3a25c8c6d56000005
[ "Algorithms" ]
https://www.codewars.com/kata/59cdb2b3a25c8c6d56000005
7 kyu
### Buddy pairs You know what divisors of a number are. The divisors of a positive integer `n` are said to be `proper` when you consider only the divisors other than `n` itself. In the following description, divisors will mean `proper` divisors. For example for `100` they are `1, 2, 4, 5, 10, 20, 25, and 50`. Let `s(n)` be the `sum` of these proper divisors of `n`. Call `buddy` two positive integers such that the `sum` of the proper divisors of each number is one more than the other number: `(n, m)` are a pair of `buddy` if `s(m) = n + 1` and `s(n) = m + 1` For example 48 & 75 is such a pair: * Divisors of 48 are: 1, 2, 3, 4, 6, 8, 12, 16, 24 --> sum: 76 = 75 + 1 * Divisors of 75 are: 1, 3, 5, 15, 25 --> sum: 49 = 48 + 1 #### Task Given two positive integers `start` and `limit`, the function `buddy(start, limit)` should return the **first** pair `(n m)` of `buddy pairs` such that `n` (positive integer) is between `start` (inclusive) and `limit` (inclusive); `m` can be greater than `limit` and has to be **greater** than `n` If there is no `buddy pair` satisfying the conditions, then return `"Nothing"` or (for **Go** lang) `nil` or (for **Dart**) `null`; (for **Lua**, **Pascal**, **Perl**, **D**) `[-1, -1]`; (for **Erlang** {-1, -1}). #### Examples (depending on the languages) ``` buddy(10, 50) returns [48, 75] buddy(48, 50) returns [48, 75] or buddy(10, 50) returns "(48 75)" buddy(48, 50) returns "(48 75)" ``` #### Notes - for C: The returned string will be free'd. - See more examples in "Sample Tests:" of your language.
reference
def div_sum(n): divs = set() for x in range(2, int(n * * 0.5) + 1): if n % x == 0: divs . add(x) divs . add(n / / x) return sum(divs) def buddy(start, limit): for n in range(start, limit + 1): buddy = div_sum(n) if buddy > n and div_sum(buddy) == n: return [n, buddy] return "Nothing"
Buddy Pairs
59ccf051dcc4050f7800008f
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/59ccf051dcc4050f7800008f
5 kyu
Transpose means is to interchange rows and columns of a two-dimensional array matrix. [A<sup>T</sup>]<sub>ij</sub>=[A]<sub>ji</sub> ie: Formally, the i th row, j th column element of AT is the j th row, i th column element of A: <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Matrix_transpose.gif/200px-Matrix_transpose.gif"/> Example : ``` [[1,2,3],[4,5,6]].transpose() //should return [[1,4],[2,5],[3,6]] ``` Write a prototype transpose to array in JS or add a .transpose method in Ruby or create a transpose function in Python so that any matrix of order ixj 2-D array returns transposed Matrix of jxi . Link: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype" target="_blank"> To understand array prototype </a><br>
reference
def transpose(arr): return [list(i) for i in zip(* arr)]
Transpose of a Matrix
559656796d8fb52e17000003
[ "Linear Algebra", "Matrix", "Data Structures", "Mathematics", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/559656796d8fb52e17000003
6 kyu
Julie is x years older than her brother, and she is also y times as old as him. Given x and y calculate Julie's age using the function age(x, y). For example: ```javascript Age(6, 3) // returns 9 ``` ```coffeescript age 6, 3 # returns 9 ``` ```python age(6, 3) #returns 9 ``` Note also that x can be negative, and y can be a decimal. ```javascript Age(-15, 0.25) // returns 5 ``` ```coffeescript age -15, 0.25 # returns 5 ``` ```python age(-15, 0.25) #returns 5 ``` That is, Julie is 15 years younger and 0.25 times the age of her brother. Do not concern yourself with the imperfections inherent in dividing by floating point numbers, as your answer will be rounded. Also, for the sake of simplicity, Julie is never the same age as her brother.
algorithms
def age(x, y): return (x * y) / (y - 1)
Calculate Julie's Age
558445a88826e1376b000011
[ "Algebra", "Algorithms" ]
https://www.codewars.com/kata/558445a88826e1376b000011
7 kyu
Given a string, return true if the first instance of "x" in the string is immediately followed by the string "xx". ``` "abraxxxas" → true "xoxotrololololololoxxx" → false "softX kitty, warm kitty, xxxxx" → true "softx kitty, warm kitty, xxxxx" → false ``` Note : - capital X's do not count as an occurrence of "x". - if there are no "x"'s then return false
reference
def triple_x(s: str) - > bool: return 0 <= s . find("x") == s . find("xxx")
L2: Triple X
568dc69683322417eb00002c
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/568dc69683322417eb00002c
7 kyu
# Escape the room You are creating an "Escape the room" game. The first step is to create a hash table called `rooms` that contains all of the rooms of the game. There should be at least 3 rooms inside it, each being a hash table with at least three properties (e.g. `name`, `description`, `completed`).
reference
rooms = {"Room_1": {"Guest_Name": "Hardik", "Room_Number": "69", "Hotel": "Royal Inn"}, "Room_2": {"Guest_Name": "Hridhik", "Room_Number": "369", "Hotel": "Sandesh The Prince"}, "Room_3": {"Guest_Name": "Pratham", "Room_Number": "96", "Hotel": "The Quorum"}, "Room_4": {"Guest_Name": "Ruturaj", "Room_Number": "14", "Hotel": "Radisson Blu"}}
Grasshopper - Create the rooms
56a29b237e9e997ff2000048
[ "Fundamentals" ]
https://www.codewars.com/kata/56a29b237e9e997ff2000048
8 kyu