description
stringlengths
38
154k
category
stringclasses
5 values
solutions
stringlengths
13
289k
name
stringlengths
3
179
id
stringlengths
24
24
tags
listlengths
0
13
url
stringlengths
54
54
rank_name
stringclasses
8 values
We have an integer```n```, with a certain number of digits```k```, `$d_1d_2\dots d_k$`. We have a function, ```f()``` that produces a certain number ```n'```from ```n```, such that,```f(n) ---> n'``` ```math f(n) = \pm d_1^{|d_1-d_2|} \pm d_2^{|d_2-d_3|} \pm \dots \pm d_{k-1}^{|d_{k-1}-d_k|} + d_k ``` If the difference is such that, `$d_{k-1}-d_k \gt 0$` , the operator will be ```-``` and on the other hand if the difference is such that: `$d_{k-1}-d_k \leq 0$`, the operator will be ```+```. Let's see an example with the number ```186599```. ```math f(186599)=1^{|1-8|}-8^{|8-6|}-6^{|6-5|}+5^{|5-9|}+9^{|9-9|}+9=1-64-6+625+1+1=566 ``` The number ```100``` is the first integer in having the value of the above function equals to ```0```, in other way ```f(100) = 0```. ```math f(100) = -1^{|1-0|} + 0^{|0-0|}+0 = -1^1+0^0+0=-1+1+0=0 ``` (Yes, we consider here that 0<sup>0</sup> is equals to 1, following the output that give most programming languages) The first terms of this special sequence of numbers are: ``` 100, 101, 110, 121, 132, 143, 154, 165,... ``` The function ```prev_next()``` (in javascript: ```prevNext()```)will receive a certain integer ```n``` and will output the highest possible number of this sequence under ```n``` and the smallest possible number of this sequence higher than ```n```. For example ```python prev_next(150) == [143, 154] ``` If a number is part of this sequence will output three values, istself and the next previous and next one: ```python prev_next(154) == [143, 154, 165] ``` If there are no numbers below the given number, the function will output the next number of the sequence. ```python prev_next(99) == [100] prev_next(100) == [100, 101] ``` Features of the random tests: ``` Numbers of tests = 100 n, such that, 100 ≤ n < 1000000 ``` Enjoy it!
reference
def f(n): d = list(map(int, str(n))) return sum((- 1) * * (a > b) * a * * abs(a - b) for a, b in zip(d, d[1:])) + n % 10 seq = [n for n in range(1, 1000101) if not f(n)] from bisect import bisect_left def prev_next(n): idx = bisect_left(seq, n) return seq[max(0, idx - 1): idx + 1 + (seq[idx] == n)]
Map and Filter to Get a Special Sequence of Integers
58224b5334c53a4294000b5a
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic", "Strings" ]
https://www.codewars.com/kata/58224b5334c53a4294000b5a
5 kyu
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said # Description: Given a string `str` consisting of some number of "(" and ")" characters, your task is to find the longest substring in `str` such that all "(" in the substring are closed by a matching ")". The result is the length of that substring. For example: ``` "()()(" => 4 Because "()()" is the longest substring, which has a length of 4 ``` # Note: - All inputs are valid. - If no such substring found, return 0. - Please pay attention to the performance of code. ;-) - In the performance test(100000 brackets str x 100 testcases), the time consuming of each test case should be within 35ms. This means, your code should run as fast as a rocket ;-) # Some Examples ``` "" => 0 "()" => 2 "()(" => 2 "()()" => 4 "()()(" => 4 "(()())" => 6 "(()(())" => 6 "())(()))" => 4 "))((" => 0 ```
games
def find_longest(s): stack, m = [- 1], 0 for i, j in enumerate(s): if j == '(': stack . append(i) else: stack . pop() if stack: m = max(m, i - stack[- 1]) else: stack . append(i) return m
The longest bracket substring in the string
584c3e45710dca21be000088
[ "Puzzles", "Performance", "Algorithms" ]
https://www.codewars.com/kata/584c3e45710dca21be000088
5 kyu
<a href="https://imgur.com/ta6gv1i"><img src="https://i.imgur.com/ta6gv1i.png?1" title="source: imgur.com" /></a> # Kata Task You are given a ``grid``, which always includes exactly two end-points indicated by `X` You simply need to return true/false if you can detect a **one and only one** "valid" line joining those points. A line can have the following characters : * `-` = left / right * `|` = up / down * `+` = corner ## Rules for valid lines * The most basic kind of valid line is when the end-points are already adjacent ``` X X ``` ``` XX ``` * The corner character (`+`) must be used for all corners (but **only** for corners). * If you find yourself at a corner then you **must** turn. * It must be possible to follow the line with no ambiguity (lookahead of just **one** step, and never treading on the same spot twice). * The line may take any path between the two points. * Sometimes a line may be valid in one direction but not the other. Such a line is still considered valid. * Every line "character" found in the grid must be part of the line. If extras are found then the line is not valid. # Examples ## Good lines <table border="2"> <tr> <td width="20%"> <pre style='font-size:20px;line-height:22px'> X---------X </pre> <td width="20%"> <pre style='font-size:20px;line-height:22px'> X | | X </pre> <td width="20%"> <pre style='font-size:20px;line-height:22px'> +--------+ X--+ +--+ | X </pre> <td width="20%"> <pre style='font-size:20px;line-height:22px'> +-------------+ | | X--+ X------+ </pre> <td width="20%"> <pre style='font-size:20px;line-height:22px'> +-------+ | +<span style='background:green'>+</span>+---+ X--+ +-+ X </pre> </table> ## Bad lines <table border="2"> <tr> <td width="20%"> <pre style='font-size:20px;line-height:22px'> X-----<span style='background:red'>|</span>----X </pre> <td width="20%"> <pre style='font-size:20px;line-height:22px'> X | <span style='background:red'>+</span> X </pre> <td width="20%"> <pre style='font-size:20px;line-height:22px'> <span style='background:red'>|</span>--------+ X--- <span style='background:red'>-</span>--+ | X </pre> <td width="20%"> <pre style='font-size:20px;line-height:22px'> +------<span style='background:red'> </span> | <span style='background:red'> </span> X--+ X </pre> <td width="20%"> <pre style='font-size:20px;line-height:22px'> +------+ | | X-----<span style='background:red'>+</span>------+ | X </pre> </table> # Hint Imagine yourself walking a path where you can only see your very next step. Can you know which step you must take, or not?
algorithms
def line(grid): g = {(r, c): v for r, row in enumerate(grid) for c, v in enumerate(row) if v . strip()} ends = [k for k in g if g[k] == 'X'] if len(ends) != 2: return False for start, finish in [ends, ends[:: - 1]]: path = [start] while path[- 1] != finish: r, c = path[- 1] d, V, H = g[path[- 1]], [(r + 1, c), (r - 1, c)], [(r, c - 1), (r, c + 1)] moves = {'+': V if len(path) > 1 and path[- 1][0] == path[- 2][0] else H, '|': V, '-': H, 'X': H + V}[d] possibles = {p for p in moves if p in g and p not in path and ( d == '+' or (p[0] == r and g[p] != '|') or (p[1] == c and g[p] != '-'))} if len(possibles) != 1: break path . append(possibles . pop()) if len(g) == len(path): return True return False
Line Safari - Is that a line?
59c5d0b0a25c8c99ca000237
[ "Algorithms" ]
https://www.codewars.com/kata/59c5d0b0a25c8c99ca000237
3 kyu
In this Kata you are a builder and you are assigned a job of building a wall with a specific size (God knows why...). Create a function called `build_a_wall` (or `buildAWall` in JavaScript) that takes `x` and `y` as integer arguments (which represent the number of rows of bricks for the wall and the number of bricks in each row respectively) and outputs the wall as a string with the following symbols: `■■` => One full brick (2 of `■`) `■` => Half a brick `|` => Mortar (between bricks on same row) There has to be a `|` between every two bricks on the same row. For more stability each row's bricks cannot be aligned vertically with the bricks of the row above it or below it meaning at every 2 rows you will have to make the furthest brick on both sides of the row at the size of half a brick (`■`) while the first row from the bottom will only consist of full bricks. Starting from the top, every new row is to be represented with `\n` except from the bottom row. See the examples for a better understanding. If one or both of the arguments aren't valid (less than 1, isn't integer, isn't given...etc) return `None` in Python or `null` in JavaScript. If the number of bricks required to build the wall is greater than 10000 return `"Naah, too much...here's my resignation."` Examples, based on Python: ``` build_a_wall(5,5) => '■■|■■|■■|■■|■■\n■|■■|■■|■■|■■|■\n■■|■■|■■|■■|■■\n■|■■|■■|■■|■■|■\n■■|■■|■■|■■|■■' build_a_wall(10,7) => '■|■■|■■|■■|■■|■■|■■|■\n■■|■■|■■|■■|■■|■■|■■\n■|■■|■■|■■|■■|■■|■■|■\n■■|■■|■■|■■|■■|■■|■■\n■|■■|■■|■■|■■|■■|■■|■\n■■|■■|■■|■■|■■|■■|■■\n■|■■|■■|■■|■■|■■|■■|■\n■■|■■|■■|■■|■■|■■|■■\n■|■■|■■|■■|■■|■■|■■|■\n■■|■■|■■|■■|■■|■■|■■' build_a_wall("eight",[3]) => None } }> Invalid input build_a_wall(12,-4) => None } build_a_wall(123,987) => "Naah, too much...here's my resignation." 123 * 987 = 121401 > 10000 ``` BTW this is my first Kata so I hope I did well. ^_^
reference
def generateBricks(isCut, y): return "{0}|{1}|{0}" . format("■" * (1 + isCut), '|' . join("■■" for _ in range(y - 1 - isCut))) def build_a_wall(* args): if len(args) != 2 or any(type(z) != int or z <= 0 for z in args): return None x, y = args return ("Naah, too much...here\'s my resignation." if x * y > 10000 else '\n' . join(generateBricks((x - nr) % 2, y) for nr in range(x)))
The Mysterious Wall
5939b753942a2700860000df
[ "Fundamentals", "Algorithms", "Strings", "ASCII Art" ]
https://www.codewars.com/kata/5939b753942a2700860000df
6 kyu
In this Kata, you will be given two integers `n` and `k` and your task is to remove `k-digits` from `n` and return the lowest number possible, without changing the order of the digits in `n`. Return the result as a string. Let's take an example of `solve(123056,4)`. We need to remove `4` digits from `123056` and return the lowest possible number. The best digits to remove are `(1,2,3,6)` so that the remaining digits are `'05'`. Therefore, `solve(123056,4) = '05'`. Note also that the order of the numbers in `n` does not change: `solve(1284569,2) = '12456',` because we have removed `8` and `9`. More examples in the test cases. Good luck!
algorithms
from itertools import combinations def solve(n, k): return '' . join(min(combinations(str(n), len(str(n)) - k)))
Integer reduction
59fd6d2332b8b9955200005f
[ "Algorithms" ]
https://www.codewars.com/kata/59fd6d2332b8b9955200005f
6 kyu
To increase the odds of the old fashioned game ([Rock, Paper, Scissors](https://en.wikipedia.org/wiki/Rock_paper_scissors)) Sam Kass and Karen Bryla reinvented the game with 5 different items instead of 3: [*Rock, Paper, Scissor, Lizard, Spock*](http://www.samkass.com/theories/RPSSL.html). It was later also featured in the sitcom *"The Big Bang Theory"*. ### Game Rules ![](https://i.imgur.com/BWDszrL.jpg) ### Examples ``` "rock", "spock" --> "Player 2 won!" because Spock vaporizes rock "scissor", "lizard" --> "Player 1 won!" because scissor decapitates lizard "scissor", "Scissor" --> "Draw!" because they are the same "foo", "Bar" --> "Oh, Unknown Thing" because they are not valid ```
reference
N = ["scissor", "paper", "rock", "lizard", "spock"] O = [[0, 1, 2, 1, 2], [2, 0, 1, 2, 1], [1, 2, 0, 1, 2], [2, 1, 2, 0, 1], [1, 2, 1, 2, 0]] def result(p1, p2): try: i1, i2 = N . index(p1 . lower()), N . index(p2 . lower()) except: return "Oh, Unknown Thing" r = O[i1][i2] return f"Player { r } won!" if r else "Draw!"
Rock, Paper, Scissor, Lizard, Spock Game
569651a2d6a620b72e000059
[ "Games", "Fundamentals" ]
https://www.codewars.com/kata/569651a2d6a620b72e000059
6 kyu
You get an array of different numbers to sum up. But there is one problem, those numbers all have different bases. For example: ```javascript You get an array of numbers with their base as an input: [["101",16],["7640",8],["1",9]] ``` ```python You get an array of numbers with their base as an input: [["101",16],["7640",8],["1",9]] ``` ```java You get an array of BasedNumbers as an input: public class BasedNumbers{ String number; int base; } [{number:"101", base:16}, {number:"7640", base:8}, {number:"1", base:9}] ``` The output should be the sum as an integer value with a base of 10, so according to the example this would be: 4258 ```javascript A few more examples: [["101",2], ["10",8]] --> 13 [["ABC",16], ["11",2]] --> 2751 ``` ```python A few more examples: [["101",2], ["10",8]] --> 13 [["ABC",16], ["11",2]] --> 2751 ``` ```java A few more examples: [{number:"101", base:2}, {number:"10", base:8}] --> 13 [{number:"ABC", base:16}, {number:"11", base:2}] --> 2751 ``` Bases can be between 2 and 36 (2<=base<=36)
reference
def sum_it_up(a): return sum(int(n, b) for n, b in a)
Sum Array with different bases
5a005f4fba2a14897f000086
[ "Binary", "Arrays", "Lists", "Fundamentals" ]
https://www.codewars.com/kata/5a005f4fba2a14897f000086
7 kyu
Given an array of strings, sort the array into order of weight from light to heavy. Weight units are grams(G), kilo-grams(KG) and tonnes(T). Arrays will always contain correct and positive values aswell as uppercase letters.
reference
def arrange(arr): def normalized(weight): if weight . endswith("T"): return int(weight[: - 1]) * 10 * * 6 if weight . endswith("KG"): return int(weight[: - 2]) * 10 * * 3 if weight . endswith("G"): return int(weight[: - 1]) return sorted(arr, key=normalized)
Order of weight
59ff4709ba2a14501500003a
[ "Strings", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/59ff4709ba2a14501500003a
7 kyu
## Sixteen circles Sixteen circles with radius `r` are placed as shown in the picture. `r` is an integer and `≥ 1`. <center> <img alt="circles" src="https://i.imgur.com/1JuavE1.png"></center> Find the radius of the shaded circle in the centre, rounded to two decimal places.
games
import math def sixteen_circles(r): # coordinates a, b, c, d. Assuming the center (0, 0), x = radius of the center circle # then a = (0, x+r), b = (x+r, 0) # c=(2r*cos(30degree), x+r+2r*sin(30degree)) # d = (x+r+2r*cos(60d), 2r*sin(60d)) # the distance between c and d should be 2r # (x+r+2rcos(60d) - 2rcos(30d))**2 + (x+r+2rsinc(30d) - 2rsin(60d))**2 = 4r**2 # So we got a quadratic ax^2 + bx + c = 0 a = 2 b = 2 * (r + 2 * r * math . cos(math . radians(60)) - 2 * r * math . cos(math . radians(30))) + \ 2 * (r + 2 * r * math . sin(math . radians(30)) - 2 * r * math . sin(math . radians(60))) c = - (2 * r) * * 2 + (r + 2 * r * math . cos(math . radians(60)) - 2 * r * math . cos(math . radians(30))) * * 2 + (r + 2 * r * math . sin(math . radians(30)) - 2 * r * math . sin(math . radians(60))) * * 2 # two roots x1 = round((- b + (b * * 2 - 4 * a * c) * * 0.5) / (2 * a), 2) x2 = round((- b - (b * * 2 - 4 * a * c) * * 0.5) / (2 * a), 2) if x1 <= 0 and x2 <= 0: return None else: return max(x1, x2)
Sixteen circles
589896b99c70093f3e00005b
[ "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/589896b99c70093f3e00005b
6 kyu
## Problem `John` and `Tom` are students of `Myjinxin`. In the classroom, `Myjinxin` often gives 10 judgment questions, let the students write the answer. `o` represents right and `x` represents wrong. i.e. If the students think that the 10 judgments are all right, his answer will be `"oooooooooo"`. Tom always answers questions earlier than John. Then, the teacher gives Tom a score, each subject worth 10 points. i.e. If Tom's answer is `"oooooooooo"` and the correct answer is `"ooxxxxxxxx"`, Tom got 20 points. John didn't know what the correct answer was. He has his own answer. John looked at Tom's answer and Tom's score, and he wanted to know what the minimum possible score and the maximum possible score he could get.. ## Task You are given three arguments: - `answerOfTom`: Tom's answer. It's a string of length 10, contains only `o` or `x`. - `scoreOfTom`: Tom's score. an integer that can be 0,10,20,...,100. - `answerOfJohn`: John's answer. It's a string of length 10, contains only `o` or `x`. Your result should be a 2-elements integer array/tuple: `<minimum possible score of John>, <maximum possible score of John>` Still not understand the task? Look at the following example ;-) ## Examples For `answerOfTom="oooooooooo", scoreOfTom=20, answerOfJohn="oooooooooo"` the output should be `20,20` In this case, John's answer is same as Tom's, so his scores can only be `20`. --- For `answerOfTom="oooooooooo", scoreOfTom=20, answerOfJohn="xxxxxxxxxx"` the output should be `80,80` In this case, John's answer is just the opposite of Tom's, so his scores can only be `80`. --- For `answerOfTom="oooooooooo", scoreOfTom=20, answerOfJohn="oooooxxxxx"` the output should be `30,70` In this case, Tom's score is `20`. It means two questions Tom answered correctly. Let's think about some situations: If the first question and second question Tom answered correctly, the whole correct answer may be `"ooxxxxxxxx"`, John will get `70` points; If the last question and second last question Tom answered correctly, the whole correct answer may be `"xxxxxxxxoo"`, John will get `30` points; If the 5th question and 6th question Tom answered correctly, the whole correct answer may be `"xxxxooxxxx"`, John will get `50` points; ...and other situations... So, John can get at least `30` points, at most `70` points. ## Note - Happy Coding `^_^`
reference
def possible_scores(answer_of_tom, score_of_tom, answer_of_john): """The minimum score for John is when every possible difference from Tom's answer is one that Tom got right. The maximum score for John is when every difference from Tom's answer is one that Tom got wrong. """ num_differences = sum(t != j for t, j in zip( answer_of_tom, answer_of_john)) tom_right = score_of_tom / / 10 tom_wrong = len(answer_of_tom) - tom_right # John worst case john_right = abs(tom_right - num_differences) min_score = 10 * john_right # John best case john_wrong = abs(tom_wrong - num_differences) max_score = 10 * (len(answer_of_john) - john_wrong) return min_score, max_score
Simple Fun #373: The Possible Scores
59ffd493ba2a14d16f0000d9
[ "Fundamentals" ]
https://www.codewars.com/kata/59ffd493ba2a14d16f0000d9
6 kyu
# Task Make a custom esolang interpreter for the language Stick. Stick is a simple, stack-based esoteric programming language with only 7 commands. # Commands * `^`: Pop the stack. * `!`: Add new element to stack with the value of 0. * `+`: Increment element. 255+1=0. * `-`: Decrement element. 0-1=255. * `*`: Add ascii value of **top** element to the output stream. * `[`: Skip past **next** `]` if element value is 0. * `]`: Jump back to the command after **previous** `[` if element value is nonzero. # Syntax and other info * You don't need to add support for nested brackets. * Non-command characters should be ignored. * Code will always have all brackets closed. * Note the highlighted **next** and **previous** in the commands reference. * Program begins with the top element having the value of 0 and being the only element in the stack. * Program ends when command executor reaches the end. # Examples ## Hello, World! ```python '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*!+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*!++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*!++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*!+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*!++++++++++++++++++++++++++++++++++++++++++++*!++++++++++++++++++++++++++++++++*!+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*!+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*!++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*!++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*!++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*!+++++++++++++++++++++++++++++++++*!' ``` # Notes * Feel free to comment in the discourse area. * Swift versions must throw an error (conforming to the Error Protocol) when abnormal conditions occur. * Javascript versions should throw when abnormal conditions occur (like the stack being empty).
reference
def interpreter(tape): ptr, stack, output = 0, [0], [] while ptr < len(tape): command = tape[ptr] if command == '^': stack . pop() elif command == '!': stack . append(0) elif command == '+': stack[- 1] = (stack[- 1] + 1) % 256 elif command == '-': stack[- 1] = (stack[- 1] - 1) % 256 elif command == '*': output . append(chr(stack[- 1])) elif command == '[' and stack[- 1] == 0: ptr = tape . find(']', ptr) elif command == ']' and stack[- 1] != 0: ptr = tape . rfind('[', ptr) ptr += 1 return '' . join(output)
Esolang: Stick
58855acc9e1de22dff0000ef
[ "Esoteric Languages", "Stacks" ]
https://www.codewars.com/kata/58855acc9e1de22dff0000ef
5 kyu
In this kata you're expected to sort an array of 32-bit integers in ascending order of the number of **on** bits they have. E.g Given the array **[7, 6, 15, 8]** - 7 has **3 on** bits (000...0**111**) - 6 has **2 on** bits (000...0**11**0) - 15 has **4 on** bits (000...**1111**) - 8 has **1 on** bit (000...**1**000) So the array in sorted order would be **[8, 6, 7, 15]**. In cases where two numbers have the same number of bits, compare their real values instead. E.g between 10 **(...1010)** and 12 **(...1100)**, they both have the same number of **on** bits '**2**' but the integer 10 is less than 12 so it comes first in sorted order. Your task is to write a function that takes an array of integers and sort them as described above. ```if-not:haskell Note: your solution has to sort the array __in place__. ``` Example: [3, 8, 3, 6, 5, 7, 9, 1] => [1, 8, 3, 3, 5, 6, 9, 7]
reference
def sort_by_bit(arr): # they wanted to modify the input arr . sort(key=lambda x: (bin(x). count('1'), x)) return arr
Sorting by bits
59fa8e2646d8433ee200003f
[ "Logic", "Arrays", "Algorithms", "Data Structures", "Fundamentals", "Bits", "Binary", "Sorting" ]
https://www.codewars.com/kata/59fa8e2646d8433ee200003f
6 kyu
Given a matrix, find the cross (row and column) with the largest sum of elements. Return the sum. ```javascript [[1, 2, 3], [4, 5, 6], [7, 8, 9]] largest cross is the last column, [3,6,9], with the last row, [7,8,9]. Sum of elements is 3 + 6 + 7 + 8 + 9 = 33 therefore largestCrossSum(matrix) = 33 ``` ```csharp new int[][] { new int[] {1, 2, 3}, new int[] {4, 5, 6}, new int[] {7, 8, 9} }; // Largest cross is the last column, {3, 6, 9}, with the last row, {7, 8, 9}. // Sum of elements is 3 + 6 + 7 + 8 + 9 = 33, therefore Kata.LargestCrossSum(matrix) = 33 ``` ```python [[1, 2, 3], [4, 5, 6], [7, 8, 9]] largest cross is the last column, [3,6,9], with the last row, [7,8,9]. Sum of elements is 3 + 6 + 7 + 8 + 9 = 33 therefore largest_cross_sum(matrix) = 33 ``` NOTE: the shared element of the column and row should only be counted once. The matrix may not be square. All elements will be positive integers.
reference
def largest_cross_sum(arr): h, w = range(len(arr)), range(len(arr[0])) rows = [sum(row) for row in arr] cols = [sum(col) for col in zip(* arr)] return max(rows[j] + cols[i] - arr[j][i] for j in h for i in w)
Largest Cross Sum
59fc9e7ec374cbbb8a0000a7
[ "Fundamentals" ]
https://www.codewars.com/kata/59fc9e7ec374cbbb8a0000a7
6 kyu
This calculator takes values that could be written in a browsers route path as a single string. It then returns the result as a number (or an error message). Route paths use the '/' symbol so this can't be in our calculator. Instead we are using the '$' symbol as our divide operator. You will be passed a string of any length containing numbers and operators: * '+' = add * '-' = subtract * '*' = multiply * '$' = divide Your task is to break the string down and calculate the expression using this order of operations. (division => multiplication => subtraction => addition) If you are given an invalid input (i.e. any character except `.0123456789+-*$`) you should return the error message:`'400: Bad request'` ### Remember: 1. The number of operations isn't limited 1. Order of operations is imperative 1. No `eval` or equivalent functions 1. convert the number to `floats`, not to integers **Examples:** ```javascript calculate('1+1') => '2' calculate('10$2') => '5' calculate('1.5*3') => '4.5' calculate('5+5+5+5') => '20' calculate('1000$2.5$5+5-5+6$6') =>'81' calculate('10-9p') => '400: Bad request' ``` ```typescript calculate('1+1') => '2' calculate('10$2') => '5' calculate('1.5*3') => '4.5' calculate('5+5+5+5') => '20' calculate('1000$2.5$5+5-5+6$6') =>'81' calculate('10-9p') => '400: Bad request' ``` ```python calculate('1+1') => '2' calculate('10$2') => '5' calculate('1.5*3') => '4.5' calculate('5+5+5+5') => '20' calculate('1000$2.5$5+5-5+6$6') =>'81' calculate('10-9p') => '400: Bad request' ``` ### Further Notes - Parameters outside of this challenge: - Brackets e.g. 10*(1+2) - Square root, log, % or any other operators - Unary minus (10*-1) - Bad mathematical input (10**$10 or 5+5$) - You may have to deal with floats If enjoy this and want something harder please see http://www.codewars.com/kata/evaluate-mathematical-expression/ for making a much more complicated calculator. This is a good kata leading up to that.
algorithms
def tokenize(expression): result = [] curr = '' for chr in expression: if chr . isdigit() or chr == '.': curr += chr elif chr in '$*-+': result . extend([float(curr), chr]) curr = '' else: raise ValueError('invalid input') if curr: result . append(float(curr)) return result def calculate(expression): ops = { '+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y: x * y, '$': lambda x, y: x / y, } try: l = tokenize(expression) except ValueError: return '400: Bad request' for op in '$*-+': while op in l: i = l . index(op) l = l[: i - 1] + [ops[op](l[i - 1], l[i + 1])] + l[i + 2:] return l[0]
Route Calculator
581bc0629ad9ff9873000316
[ "Algorithms" ]
https://www.codewars.com/kata/581bc0629ad9ff9873000316
4 kyu
The new football league season is coming and the Football Association need some help resetting the league standings. Normally the initial league standing is done in alphabetical order (from A to Z) but this year the FA have decided to freshen it up. It has been decided that team who finished first last season will begin the next season in first place. Regardless of what letter their club begins with. e.g. if Manchester City were in first place last year, they will begin the season in position one. All other teams should be in alphabetical order. The teams will be fed in as an object ({}). The key will be will be their position from last season and the value is the club's name e.g. Arsenal. The output should be an object ({}) with the key as the club's starting position for the new season and the value should be club's name e.g. Arsenal. For example. If in the previous season the standings were: 1:'Leeds United' 2:'Liverpool' 3:'Manchester City' 4:'Coventry' 5:'Arsenal' Then the new season standings should 1:'Leeds United' (first last season) 2:'Arsenal' (alphabetical) 3:'Coventry' (alphabetical) 4:'Liverpool' (alphabetical) 5:'Manchester City' (alphabetical)
algorithms
def premier_league_standings(teams): dct = {1: teams[1]} dct . update({i: t for i, t in enumerate( sorted(set(teams . values()) - {teams[1]}), 2)}) return dct
New season, new league
58de08d376f875dbb40000f1
[ "Algorithms" ]
https://www.codewars.com/kata/58de08d376f875dbb40000f1
7 kyu
In this Kata, we are going to see how a Hash (or Map or dict) can be used to keep track of characters in a string. Consider two strings `"aabcdefg"` and `"fbd"`. How many characters do we have to remove from the first string to get the second string? Although not the only way to solve this, we could create a Hash of counts for each string and see which character counts are different. That should get us close to the answer. I will leave the rest to you. For this example, `solve("aabcdefg","fbd") = 5`. Also, `solve("xyz","yxxz") = 0`, because we cannot get second string from the first since the second string is longer. More examples in the test cases. Good luck!
reference
from collections import Counter def solve(a, b): return 0 if Counter(b) - Counter(a) else len(a) - len(b)
String reduction
59fab1f0c9fc0e7cd4000072
[ "Fundamentals" ]
https://www.codewars.com/kata/59fab1f0c9fc0e7cd4000072
6 kyu
In this Kata, you will be given a string that has lowercase letters and numbers. Your task is to compare the number groupings and return the largest number. Numbers will not have leading zeros. For example, `solve("gh12cdy695m1") = 695`, because this is the largest of all number groupings. Good luck! Please also try [Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7)
algorithms
import re def solve(s): return max(map(int, re . findall(r"(\d+)", s)))
Numbers in strings
59dd2c38f703c4ae5e000014
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/59dd2c38f703c4ae5e000014
7 kyu
In this Kata, you will be given two numbers, n and k and your task will be to return the k-digit array that sums to n and has the maximum possible GCD. For example, given `n = 12, k = 3`, there are a number of possible `3-digit` arrays that sum to `12`, such as `[1,2,9], [2,3,7], [2,4,6], ...` and so on. Of all the possibilities, the one with the highest GCD is `[2,4,6]`. Therefore, `solve(12,3) = [2,4,6]`. Note also that digits cannot be repeated within the sub-array, so `[1,1,10]` is not a possibility. Lastly, if there is no such array, return an empty array. More examples in the test cases. Good luck!
algorithms
def solve(n, k): maxGcd = 2 * n / / (k * (k + 1)) for gcd in range(maxGcd, 0, - 1): last = n - gcd * k * (k - 1) / / 2 if not last % gcd: return [gcd * x if x != k else last for x in range(1, k + 1)] return []
Constrained GCD
59f61aada01431e8c200008d
[ "Arrays", "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/59f61aada01431e8c200008d
5 kyu
&ensp;It is necessary to define who of two players will win the game in the ideal moves of each.<br> &ensp;The NxM board is given, the players' figures are on opposite sides of the board. ``` 4x7 |X.....Y| |X.....Y| |X.....Y| |X.....Y| ``` &ensp;In his turn, the player <u>must</u> move one of his figures forward horizontally to any number of cells, but not further than the enemy figure on this line. ``` |X......Y..| => |.X.....Y..| or |..X....Y..| or ... or |......XY..| ``` &ensp;A player who can't make a move loses. **Example 3х6 game (not ideal):** ``` |X....Y| |X....Y| |X....Y| -------- |...X.Y| |...X.Y| |X....Y| |X....Y| |X....Y| |XY....| -------- -------- |...X.Y| |...X.Y| |..X..Y| |..X.Y.| |XY....| |XY....| -------- -------- |....XY| |....XY| |..X.Y.| |..XY..| |XY....| |XY....| ``` &ensp;Player X can't make a turn => player Y is winner. ``` @param {n,m} n>=1 m>=2 @return {player} 'first' or 'second' ``` **Examples:** ``` (3,7) => 'first' (6,12) => 'second' (2,4) => 'second' ```
games
def game(x, y): return 'second' if y == 2 else 'first' if x % 2 and y % 2 == 0 or x % 2 else 'second'
Simple Game
59831e3575ca6c8aea00003a
[ "Games", "Puzzles", "Logic", "Game Solvers" ]
https://www.codewars.com/kata/59831e3575ca6c8aea00003a
7 kyu
# Task Given a string which represents a valid arithmetic expression, find the index of the character in the given expression corresponding to the arithmetic operation which needs to be computed first. Note that several operations of the same type with equal priority are computed from left to right. # Example For `expr = "(2 + 2) * 2"`, the output should be 3. There are two operations in the expression: `+ and *`. The result of `+` should be computed first, since it is enclosed in parentheses. Thus, the output is the index of the '+' sign, which is `3`. For `expr = "2 + 2 * 2"`, the output should be `6`. There are two operations in the given expression: `+ and *`. Since there are no parentheses, `*` should be computed first as it has higher priority. The answer is the position of '*', which is `6`. # Input/Output - `[input]` string `expr` A string consisting of digits, parentheses, addition and multiplication signs (pluses and asterisks). It is guaranteed that there is at least one arithmetic sign in it. - `[output]` an integer The index of the operation character which needs to be computed first.
games
def first_operation_character(expr): res, lvl = (1, None, None), 0 for i, c in enumerate(expr): match c: case '(': lvl -= 1 case ')': lvl += 1 case '+' | '*': res = min(res, (lvl, c, i)) return res[2]
Challenge Fun #13: First Operation Character
58aa50372223a30e4f000068
[ "Puzzles" ]
https://www.codewars.com/kata/58aa50372223a30e4f000068
5 kyu
An expression is formed by taking the digits 1 to 9 in numerical order and then inserting into each gap between the numbers either a plus sign or a minus sign or neither. Your task is to write a method which takes one parameter and returns the **smallest possible number** of plus and minus signs necessary to form such an expression which equals the input. **Note:** All digits from 1-9 must be used exactly once. If there is no possible expression that evaluates to the input, then return `null/nil/None`. ~~~if:haskell `eval :: String -> Int` is available in `Preloaded` for your convenience. ~~~ There are 50 random tests with upper bound of the input = 1000. ## Examples When the input is 100, you need to return `3`, since that is the minimum number of signs required, because: 123 - 45 - 67 + 89 = 100 (3 operators in total). More examples: ``` 11 --> 5 # 1 + 2 + 34 + 56 + 7 - 89 = 11 100 --> 3 # 123 - 45 - 67 + 89 = 100 766 --> 4 # 1 - 2 + 34 - 56 + 789 = 766 160 --> - # no solution possible ``` Inspired by a [puzzle on BBC Radio 4](https://www.bbc.co.uk/programmes/p057wxwl) (which is unfortunately not available anymore)
games
from itertools import product def operator_insertor(n): result = [] for ops in product(["+", "-", ""], repeat=8): expression = "" . join( a + b for a, b in zip("123456789", list(ops) + [""])) res = eval(expression) if res == n: result . append(len(expression) - 9) return min(result, default=None)
Operator Insertion
596b7f284f232df61e00001b
[ "Puzzles" ]
https://www.codewars.com/kata/596b7f284f232df61e00001b
5 kyu
It's the fourth quater of the Super Bowl and your team is down by 4 points. You're 10 yards away from the endzone, if your team doesn't score a touchdown in the next four plays you lose. On a previous play, you were injured and rushed to the hospital. Your hospital room has no internet, tv, or radio and you don't know the results of the game. You look at your phone and see that on your way to the hospital a text message came in from one of your teamates. It contains an array of the last 4 plays in chronological order. In each play element of the array you will receive the yardage of the play and the type of the play. Have your function let you know if you won or not. # What you know: * Gaining greater than 10 yds from where you started is a touchdown and you win. * Yardage of each play will always be a positive number greater than 0. * There are only four types of plays: "run", "pass", "sack", "turnover". * Type of plays that will gain yardage are: "run", "pass". * Type of plays that will lose yardage are: "sack". * Type of plays that will automatically lose the game are: "turnover". * When a game ending play occurs the remaining (plays) arrays will be empty. * If you win return true, if you lose return false. # Examples: <code> [[8, "pass"],[5, "sack"],[3, "sack"],[5, "run"]] `false` [[12, "pass"],[],[],[]]) `true` [[2, "run"],[5, "pass"],[3, "sack"],[8, "pass"]] `true` [[5, "pass"],[6, "turnover"],[],[]] `false` </code> <h1 style="text-align: center">Good Luck!</h1>
reference
def did_we_win(plays): plays = [p for p in plays if p] return all(p != 'turnover' for y, p in plays) and sum(- y if p == 'sack' else y for y, p in plays) > 10
Did we win the Super Bowl?
59f69fefa0143109e5000019
[ "Games", "Arrays", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/59f69fefa0143109e5000019
7 kyu
<h3>Bit Vectors/Bitmaps</h3> <p>A bitmap is one way of efficiently representing sets of unique integers using single bits.<br> To see how this works, we can represent a set of unique integers between `0` and `< 20` using a vector/array of 20 bits:</p> ``` var set = [3, 14, 2, 11, 16, 4, 6];``` ``` var bitmap = [0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0]; ``` <p>As you can see, with a bitmap, the length of the vector represents the range of unique values in the set (in this case `0-20`), and the `0/1` represents whether or not the current index is equal to a value in the set. <h3>Task:</h3> <p>Your task is to write a function `toBits` that will take in a set of uniqe integers and output a bit vector/bitmap (an array in javascript) using `1`s and `0`s to represent present and non-present values.</p> <p><b>Input:</b><br> The function will be passed a set of unique integers in string form, in a random order, separated by line breaks.<br> Each integer can be expected to have a unique value `>= 0` and `< 5000`.<br> The input will look like this:<br> `let exampleInput = '3\n14\n5\n19\n18\n1\n8\n11\n2...'`</p> <p><b>Output:</b><br> The function will be expected to output a 5000 bit vector (array) of bits, either `0` or `1`, for example:<br> `let exampleOutput = [0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0,...]`</p><br> <p>More in-depth bitmap kata coming very soon, happy coding!</p><br> <p>To learn more about bitmapping and to see the inspiration for making these kata, checkout the book <a href="http://www.wou.edu/~jcm/Spring-P-2015/Programming%20Pearls%20(2nd%20Ed)%20Bentley.pdf">Programming Pearls</a> by Jon Bently. It's a powerful resource for any programmer!</p>
algorithms
def to_bits(s): lst = [0] * 5000 for i in map(int, s . split()): lst[i] = 1 return lst
Basic Bitmapping
59f8dd1132b8b9af150001ea
[ "Bits", "Arrays", "Sets", "Lists", "Algorithms", "Recursion" ]
https://www.codewars.com/kata/59f8dd1132b8b9af150001ea
6 kyu
# Introduction The goal of this kata is to check whether a network of water pipes is leaking anywhere. # Task Create a function which accepts a `map` input and validates if water is leaking anywhere. In case water is leaking return `false`. In case the pipe network is correct -- i.e. there are no leaks anywhere -- return `true`. There can be multiple water sources. All pipes which are directed outside of the `map` are connected to a water source, and you need to check them for leaks. ``` For example, in the map below: ╋━━┓ ┃..┃ ┛..┣ The water sources (marked with +) are: + + ╋━━┓ ┃..┃ + ┛..┣ + + This map shows a correct pipe network. It's not leaking anywhere. ``` A leaking pipeline example : ``` The leak is marked by the arrow pointing to the top left-hand corner of the map: --> ...┏ + ┃..┃ + ┛..┣ + + ``` A leak may involve a pipe pointing to an empty cell in the map, like this: `━━.`. It may also involve a pipe pointing to another pipe that does not point back, like this: `━━┗` There can be also 'old pipes` on the map which are not connected to water sources. You should ignore such pipes. ``` .... .┛┛. .... ``` There are two old pipes not connected to a water source. Water is not leaking, so the function should return `true`. [![Leaking.png](https://i.postimg.cc/cC1WjZ6f/Leaking.png)](https://postimg.cc/vgKCgJrm) # Notes - Check the test cases for more samples ```if:rust - In the argument of the function `check_pipe(pipe_map: &[&str]) -> bool`, each `&str` represents a row. ``` - Unicode UTF-8 characters used for pipes: ``` ┗ - 9495 - BOX DRAWINGS HEAVY UP AND RIGHT ┓ - 9491 - BOX DRAWINGS HEAVY DOWN AND LEFT ┏ - 9487 - BOX DRAWINGS HEAVY DOWN AND RIGHT ┛ - 9499 - BOX DRAWINGS HEAVY UP AND LEFT ━ - 9473 - BOX DRAWINGS HEAVY HORIZONTAL ┃ - 9475 - BOX DRAWINGS HEAVY VERTICAL ┣ - 9507 - BOX DRAWINGS HEAVY VERTICAL AND RIGHT ┫ - 9515 - BOX DRAWINGS HEAVY VERTICAL AND LEFT ┳ - 9523 - BOX DRAWINGS HEAVY DOWN AND HORIZONTAL ┻ - 9531 - BOX DRAWINGS HEAVY UP AND HORIZONTAL ╋ - 9547 - BOX DRAWINGS HEAVY VERTICAL AND HORIZONTAL ```
reference
def check_pipe(pipe_map): def get(y, x): return pipe_map[y][x] if 0 <= y < len( pipe_map) and 0 <= x < len(pipe_map[0]) else None UP, LEFT, DOWN, RIGHT = (- 1, 0), (0, - 1), (1, 0), (0, 1) pipes = { '┗': (UP, RIGHT), '┓': (LEFT, DOWN), '┏': (RIGHT, DOWN), '┛': (UP, LEFT), '━': (LEFT, RIGHT), '┃': (UP, DOWN), '┣': (UP, DOWN, RIGHT), '┫': (UP, DOWN, LEFT), '┳': (LEFT, DOWN, RIGHT), '┻': (LEFT, UP, RIGHT), '╋': (UP, LEFT, RIGHT, DOWN) } ok = set() to_check = {(y, x) for y, r in enumerate(pipe_map) for x, v in enumerate(r) if (y == 0 or y == len(pipe_map) - 1 or x == 0 or x == len(pipe_map[0]) - 1) and get(y, x) != '.' and any(get(y + dy, x + dx) is None for dy, dx in pipes[v]) } while to_check: y, x = to_check . pop() for dy, dx in pipes[get(y, x)]: if (v := get(y + dy, x + dx)) is None: continue if v == '.' or (- dy, - dx) not in pipes[v]: return False ok . add((y, x)) if (y + dy, x + dx) not in ok: to_check . add((y + dy, x + dx)) return True
Fix the pipes - #2 - is it leaking?
59f81fe146d84322ed00001e
[ "Arrays", "Strings" ]
https://www.codewars.com/kata/59f81fe146d84322ed00001e
3 kyu
Lets talk like a monkey. Find out how! Look at the test cases an engineer code to pass them.
reference
def monkey_talk(phrase): return ' ' . join(['ook', 'eek'][w[0]. lower() in 'aeiou'] for w in phrase . split()). capitalize() + '.'
Monkey Talk
59f897ecc374cb9ed90000c2
[ "Fundamentals", "Strings", "Puzzles" ]
https://www.codewars.com/kata/59f897ecc374cb9ed90000c2
6 kyu
# Introduction The goal of the kata is to connect water pipes from the water source to end of the pipe line without leaking anywhere. # Task Create a function which replaces all `x` in the `map` array with one of available pipes : `┗`,`┓`,`┏`,`┛`,`━`,`┃` and returns new map as an output. The water source is located on the left side of the map on `start` position (indexed from 0). The end of pipe is located on the right side of the map on `end` position (indexed from 0). The pipleline can go only from left side of the screen to the right side of the screen. It never returns. Of course it can also go up and down. It's hard to explain in words. This is not allowed: ``` ━━━┓ ┏━━┛ <-- the pipline goes back to left ( => incorrect pipline) ┗━━━ ``` # Correct samples ## Sample 1 ``` The inputs: start = 1 , end = 1 ... map = xxx ... The solution: ... ━━━ ... ``` ## Sample 2: ``` The inputs: start = 0 , end = 0 xxxx map = xxxx xxxx The solution: ┓┏┓┏ ┃┃┃┃ ┗┛┗┛ ``` ## Sample 3: ``` The inputs: start = 2 , end = 2 xxxx map = xxxx xxxx The solution: ┏┓┏┓ ┃┃┃┃ ┛┗┛┗ ``` # Notes - In case of Python return a two-dimensional array of integers: - 0 for . (not a pipe) - UTF-8's integer for specific pipe (the list is below) - Check the test cases for more samples. - The `map` creates always a rectangle. - All inputs are correct. There is no need for any validation - Unicode UTF-8 charcters used for pipes: ``` ┗ - 9495 - BOX DRAWINGS HEAVY UP AND RIGHT ┓ - 9491 - BOX DRAWINGS HEAVY DOWN AND LEFT ┏ - 9487 - BOX DRAWINGS HEAVY DOWN AND RIGHT ┛ - 9499 - BOX DRAWINGS HEAVY UP AND LEFT ━ - 9473 - BOX DRAWINGS HEAVY HORIZONTAL ┃ - 9475 - BOX DRAWINGS HEAVY VERTICAL ```
reference
def connect_pipes(pipes, s, e): zipped = [] for l in map('' . join, zip(* pipes)): s1, s2 = l . find('x'), l . rfind('x') waterline = [0 if c == '.' else 9473 if i == s == s1 == s2 else 9499 if i == s == s2 else 9487 if i == s1 != s else 9491 if i == s == s1 else 9495 if i == s2 != s else 9475 for i, c in enumerate(l)] zipped . append(waterline) if s1 != s2: s = ({s1, s2} - {s}). pop() return list(map(list, zip(* zipped)))
Fix the pipes
59f2e89601601434ae000055
[ "Fundamentals", "Strings", "Arrays" ]
https://www.codewars.com/kata/59f2e89601601434ae000055
5 kyu
I have the `par` value for each hole on a golf course and my stroke `score` on each hole. I have them stored as strings, because I wrote them down on a sheet of paper. Right now, I'm using those strings to calculate my golf score by hand: take the difference between my actual `score` and the `par` of the hole, and add up the results for all 18 holes. For example: * If I took 7 shots on a hole where the par was 5, my score would be: 7 - 5 = 2 * If I got a hole-in-one where the par was 4, my score would be: 1 - 4 = -3. Doing all this math by hand is really hard! Can you help make my life easier? ## Task Overview Complete the function which accepts two strings and calculates the golf score of a game. Both strings will be of length 18, and each character in the string will be a number between 1 and 9 inclusive.
reference
def golf_score_calculator(par, score): return sum(int(b) - int(a) for a, b in zip(par, score))
What's my golf score?
59f7a0a77eb74bf96b00006a
[ "Strings", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/59f7a0a77eb74bf96b00006a
7 kyu
Consider an array that has no prime numbers, and none of its elements has any prime digit. It would start with: `[1,4,6,8,9,10,14,16,18,40,44..]`. `12` and `15` are not in the list because `2` and `5` are primes. You will be given an integer `n` and your task will be return the number at that index in the array. For example: ``` solve(0) = 1 solve(2) = 6 ``` More examples in the test cases. Good luck! If you like Prime Katas, you will enjoy this Kata: [Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3)
algorithms
from gmpy2 import is_prime as ip def solve(n): a = 1 while n > - 1: if not ip(a) and all(i not in '2357' for i in str(a)): n -= 1 a += 1 return a - 1
Life without primes
59f8750ac374cba8f0000033
[ "Algorithms" ]
https://www.codewars.com/kata/59f8750ac374cba8f0000033
6 kyu
A trick I learned in elementary school to determine whether or not a number was divisible by three is to add all of the integers in the number together and to divide the resulting sum by three. If there is no remainder from dividing the sum by three, then the original number is divisible by three as well. Given a series of digits as a string, determine if the number represented by the string is divisible by three. Example: ``` "123" -> true "8409" -> true "100853" -> false "33333333" -> true "7" -> false ``` Try to avoid using the % (modulo) operator.
reference
def divisible_by_three(st): while len(st) != 1: st = str(sum(int(n) for n in st)) return int(st) in [0, 3, 6, 9]
By 3, or not by 3? That is the question . . .
59f7fc109f0e86d705000043
[ "Arrays", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/59f7fc109f0e86d705000043
7 kyu
## Task ~~~if:javascript,python, You are at position `[0, 0]` in maze NxN and you can **only** move in one of the four cardinal directions (i.e. North, East, South, West). Return the minimal number of steps to exit position `[N-1, N-1]` *if* it is possible to reach the exit from the starting position. Otherwise, return `false`. ~~~ ~~~if:cpp,csharp,java, You are at position `[0, 0]` in maze NxN and you can **only** move in one of the four cardinal directions (i.e. North, East, South, West). Return the minimal number of steps to exit position `[N-1, N-1]` *if* it is possible to reach the exit from the starting position. Otherwise, return `-1`. ~~~ ~~~if:julia, You are at position `[1, 1]` in maze NxN and you can **only** move in one of the four cardinal directions (i.e. North, East, South, West). Return the minimal number of steps to exit position `[N, N]` *if* it is possible to reach the exit from the starting position. Otherwise, return `false`. ~~~ ~~~if:rust You are at position `[0, 0]` in maze NxN and you can **only** move in one of the four cardinal directions (i.e. North, East, South, West). Return the minimal number of steps to exit position `[N-1, N-1]` *if* it is possible to reach the exit from the starting position. Otherwise, return `None`. ~~~ Empty positions are marked `.`. Walls are marked `W`. Start and exit positions are guaranteed to be empty in all test cases. ## Path Finder Series: - [#1: can you reach the exit?](https://www.codewars.com/kata/5765870e190b1472ec0022a2) - [#2: shortest path](https://www.codewars.com/kata/57658bfa28ed87ecfa00058a) - [#3: the Alpinist](https://www.codewars.com/kata/576986639772456f6f00030c) - [#4: where are you?](https://www.codewars.com/kata/5a0573c446d8435b8e00009f) - [#5: there's someone here](https://www.codewars.com/kata/5a05969cba2a14e541000129)
algorithms
""" Task You are at position [0, 0] in maze NxN and you can only move in one of the four cardinal directions (i.e. North, East, South, West). Return true if you can reach position [N-1, N-1] or false otherwise. Empty positions are marked .. Walls are marked W. Start and exit positions are empty in all test cases. """ def path_finder(maze): maze_arr = maze_str_to_array(maze) n = len(maze_arr) start, goal = (0, 0), (n - 1, n - 1) return ai_star(maze_arr, start, goal) def bfs(maze_arr, start, goal): """ Implementation of breadth first search algorithm for solving maze problem :param maze_arr: search space :param start: starting node :param goal: goal node :return: True if goal can be reached """ from queue import Queue to_be_expanded = Queue() to_be_expanded . put(start) tree = set() while not to_be_expanded . empty(): node = to_be_expanded . get() if node == goal: return True tree . add(node) neighbors = get_node_neighbors(maze_arr, node) for neighbor in neighbors: if neighbor not in tree: to_be_expanded . put(neighbor) return False def ai_star(maze_arr, start, goal): """ Implementation of A* algorithm for solving maze problem. Heap is used. The value passed to a heap is a tuple containing priority (estimated cost) and cell coordinates. :param maze_arr: search space :param start: starting node :param goal: goal node :return: True if goal can be reached """ from heapq import heappush, heappop to_be_expanded = [] heappush(to_be_expanded, (manhattan_distance(start, goal), 0, 0, start)) tree = set() while to_be_expanded: _, cost, real_cost, node = heappop(to_be_expanded) if node == goal: return real_cost tree . add(node) neighbors = get_node_neighbors(maze_arr, node) for neighbor in neighbors: if neighbor not in tree: heappush(to_be_expanded, (cost + manhattan_distance(neighbor, goal), cost + 0.99, real_cost + 1, neighbor)) return False def manhattan_distance(cell, goal): """ Computes manhattan distance from some cell to the goal. :param cell: cell from where the distance is measured :param goal: goal node :return: absolute integer value of a manhattan distance """ return abs(cell[0] - goal[0]) + abs(cell[1] - goal[1]) def euclidean_distance(cell, goal): """ Computes euclidean distance from some cell to the goal. :param cell: cell from where the distance is measured :param goal: goal node :return: absolute float value of a euclidean distance """ from math import sqrt return sqrt((cell[0] - goal[0]) * * 2 + (cell[1] - goal[1]) * * 2) def maze_str_to_array(maze): """ Function to convert string representation of a maze into multidimensional list. One (1) represents empty field, zero (0) represents a wall (impenetrable field) :param maze: string representation of a maze :return: list representation of a maze. """ return [[1 if char == '.' else 0 for char in row] for row in maze . split('\n')] def get_node_neighbors(maze_arr, parent_node): """ Computes a list of SearchNodes with all valid neighbors (except walls and cells out of board) :param maze_arr: a multidim list containing the maze :param parent_node: a node for with neighbors are calculated :return a list containing all possible neighbors """ n = len(maze_arr) neighbors = [] x_0, y_0 = parent_node for dx, dy in [(- 1, 0), (1, 0), (0, - 1), (0, 1)]: x_1 = x_0 + dx y_1 = y_0 + dy if 0 <= x_1 < n and 0 <= y_1 < n and maze_arr[y_1][x_1] == 1: neighbors . append((x_1, y_1)) return neighbors
Path Finder #2: shortest path
57658bfa28ed87ecfa00058a
[ "Algorithms" ]
https://www.codewars.com/kata/57658bfa28ed87ecfa00058a
4 kyu
Consider the numbers `6969` and `9116`. When you rotate them `180 degrees` (upside down), these numbers remain the same. To clarify, if we write them down on a paper and turn the paper upside down, the numbers will be the same. Try it and see! Some numbers such as `2` or `5` don't yield numbers when rotated. Given a range, return the count of upside down numbers within that range. For example, `solve(0,10) = 3`, because there are only `3` upside down numbers `>= 0 and < 10`. They are `0, 1, 8`. More examples in the test cases. Good luck! If you like this Kata, please try [Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3) [Life without primes](https://www.codewars.com/kata/59f8750ac374cba8f0000033) Please also try the performance version of this kata at [Upside down numbers - Challenge Edition ](https://www.codewars.com/kata/59f98052120be4abfa000304)
algorithms
REV = {'6': '9', '9': '6'} BASE = set("01869") def isReversible(n): s = str(n) return (not (set(s) - BASE) # contains only reversible characters # does not contain 6 or 9 right in the middle (only for odd number of digits) and (not len(s) % 2 or s[len(s) / / 2] not in "69") and all(REV . get(c, c) == s[- 1 - i] for i, c in enumerate(s[: len(s) / / 2]))) # symmetric repartition def solve(a, b): return sum(isReversible(n) for n in range(a, b))
Upside down numbers
59f7597716049833200001eb
[ "Algorithms" ]
https://www.codewars.com/kata/59f7597716049833200001eb
6 kyu
With regular expressions you can find information and even split the found information into parts. This will be a recognition test, although it is important to know how regular expression groups work. The assignment will be to create a regular expression that will match with (dutch) phone numbers. These phone numbers can be written multiple ways: * `0012 34 567890`: is how you would dial a number in another nation using the <a href="https://en.wikipedia.org/wiki/List_of_international_call_prefixes">ITU-recommendation</a> (which is the `00` or `+` prefix. Note that countries do not follow these recommendations, as for Japan: `010`. This will not be tested) * `+12 34 567890`: a more readable shorter version * `034 567890`: is how you would dial a number in the same nation * `567890`: is how you would dial a number in the same area These phone numbers can be split up into a nation code (without prefix), an area code with 2 digits (with the leading `0` if it's at the beginning of the whole number) and the local number with 6 digits. The regular expression should only contain these three caught groups and anything in a format other than shown in the examples above should not result in a match. Especially, consider these additionnal rules: The nation code, area code and local number may never contain a 0 at the start unless it is the prefix for dialing out of the country or it is at the beginning of the area code if there is no country code. Some examples of invalid codes because of this rule:<BR> * `0001 34 567890` * `+01 34 567890` * `+12 04 567890` * `+12 034 567890` * `+12 34 067895` * `034 067895` * `001 567890` * `098765` Good luck. The validation tests will display the number with which it fails, but not the details. Do not hesitate to add your own example tests.
algorithms
first = '(?:(?:\+|00)([1-9][0-9])(?: ))?' second = '(?:((?(1)[1-9][0-9]|0[1-9][0-9]))(?: ))?' third = '([1-9][0-9]{5})' regex_str = r'^{}{}{}$' . format(first, second, third)
Regular Expressions (groups): Splitting phone numbers into their separate parts.
57a492607cb1f315ec0000bb
[ "Regular Expressions", "Parsing", "Algorithms" ]
https://www.codewars.com/kata/57a492607cb1f315ec0000bb
4 kyu
Someone was hacking the score. Each student's record is given as an array The objects in the array are given again as an array of scores for each name and total score. ex> ```javascript var array = [ ["name1", 445, ["B", "A", "A", "C", "A", "A"]], ["name2", 110, ["B", "A", "A", "A"]], ["name3", 200, ["B", "A", "A", "C"]], ["name4", 200, ["A", "A", "A", "A", "A", "A", "A"]] ]; ``` ```python array = [ ["name1", 445, ["B", "A", "A", "C", "A", "A"]], ["name2", 110, ["B", "A", "A", "A"]], ["name3", 200, ["B", "A", "A", "C"]], ["name4", 200, ["A", "A", "A", "A", "A", "A", "A"]] ] ``` The scores for each grade is: - A: 30 points - B: 20 points - C: 10 points - D: 5 points - Everything else: 0 points If there are 5 or more courses and all courses has a grade of B or above, additional 20 points are awarded. After all the calculations, the total score should be capped at 200 points. Returns the name of the hacked name as an array when scoring with this rule. ```javascript var array = [ ["name1", 445, ["B", "A", "A", "C", "A", "A"]], // name1 total point is over 200 => hacked ["name2", 110, ["B", "A", "A", "A"]], // name2 point is right ["name3", 200, ["B", "A", "A", "C"]], // name3 point is 200 but real point is 90 => hacked , ["name4", 200, ["A", "A", "A", "A", "A", "A", "A"]] // name4 point is right ]; return ["name1", "name3"]; ``` ```python array = [ ["name1", 445, ["B", "A", "A", "C", "A", "A"]], # name1 total point is over 200 => hacked ["name2", 110, ["B", "A", "A", "A"]], # name2 point is right ["name3", 200, ["B", "A", "A", "C"]], # name3 point is 200 but real point is 90 => hacked ["name4", 200, ["A", "A", "A", "A", "A", "A", "A"]] # name4 point is right ]; return ["name1", "name3"] ```
games
PTS = {'A': 30, 'B': 20, 'C': 10, 'D': 5} MAX_PTS = 200 HAS_BONUS = set('AB') BONUS_PTS = 20 def find_hack(arr): return [name for name, pts, card in arr if pts != min(MAX_PTS, sum(PTS . get(n, 0) for n in card) + BONUS_PTS * (len(card) > 4 and set(card) <= HAS_BONUS))]
Find Cracker.
59f70440bee845599c000085
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/59f70440bee845599c000085
6 kyu
A little weird green frog speaks in a very strange variation of English: it reverses sentence, omitting all puntuation marks `, ; ( ) - ` except the final exclamation, question or period. We urgently need help with building a proper translator. To simplify the task, we always use lower-case letters. Apostrophes are forbidden as well. Translator should be able to process multiple sentences in one go. Sentences are separated by arbitrary amount of spaces. **Examples** `you should use python.` -> `python use should you.` `look, a fly!` -> `fly a look!` `multisentence is good. is not it?` -> `good is multisentence. it not is?`
reference
import re def frogify(s): return ' ' . join(' ' . join(re . findall(r'[a-z]+', sentence)[:: - 1]) + punct for sentence, punct in re . findall(r'(.*?)([.!?])', s))
Frogificator
59f6d96d27402f9329000081
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/59f6d96d27402f9329000081
6 kyu
Imagine you have a number of jobs to execute. Your workers are not permanently connected to your network, so you have to distribute all your jobs in the beginning. Luckily, you know exactly how long each job is going to take. Let ``` x = [2,3,4,6,8,2] ``` be the amount of time each of your jobs is going to take. Your task is to write a function ```splitlist(x)```, that will return two lists ```a``` and ```b```, such that ```abs(sum(a)-sum(b))``` is minimised. One possible solution to this example would be ``` a=[2, 4, 6] b=[3, 8, 2] ``` with ```abs(sum(a)-sum(b)) == 1```. The order of the elements is not tested, just make sure that you minimise ```abs(sum(a)-sum(b))``` and that ```sorted(a+b)==sorted(x)```. You may assume that ```len(x)<=15``` and ```0<=x[i]<=100```. When done, please continue with [part II](https://www.codewars.com/kata/586e6b54c66d18ff6c0015cd)!
algorithms
def splitlist(lst): target = sum(lst) / / 2 l = len(lst) best = 0 for n in range(2 * * l): bits = bin(n)[2:]. zfill(l) tot = sum((lst[i] for i in range(l) if bits[i] == '1')) if best <= tot <= target: indices = bits best = tot a, b = [], [] for i in range(l): if indices[i] == '1': a . append(lst[i]) else: b . append(lst[i]) return a, b
Splitting the Workload (part I)
587387d169b6fddc16000002
[ "Algorithms" ]
https://www.codewars.com/kata/587387d169b6fddc16000002
5 kyu
This is the second part of a two-part challenge. See [part I](https://www.codewars.com/kata/587387d169b6fddc16000002) if you haven't done so already. The problem is the same, only with longer lists and larger values. Imagine you have a number of jobs to execute. Your workers are not permanently connected to your network, so you have to distribute all your jobs in the beginning. Luckily, you know exactly how long each job is going to take. Let ``` x = [2,3,4,6,8,2] ``` be the amount of time each of your jobs is going to take. Your task is to write a function ```splitlist(x)```, that will return two lists ```a``` and ```b```, such that ```abs(sum(a)-sum(b))``` is minimised. One possible solution to this example would be ``` a=[2, 4, 6] b=[3, 8, 2] ``` with ```abs(sum(a)-sum(b)) == 1```. The order of the elements is not tested, just make sure that you minimise ```abs(sum(a)-sum(b))``` and that ```sorted(a+b)==sorted(x)```. You may assume that ```len(x)<=40``` and ```0<=x[i]<=1000```.
algorithms
def splitlist(l): half = sum(l) / / 2 sums = [(0, [])] for i, n in enumerate(l): sums = sums + [(m + n, a + [i]) for m, a in sums if m + n <= half] if max(s[0] for s in sums) == half: break sums . sort(key=lambda v: abs(v[0] - half)) indices = sums[0][1] return [n for i, n in enumerate(l) if i in indices], [n for i, n in enumerate(l) if i not in indices]
Splitting the Workload (part II)
586e6b54c66d18ff6c0015cd
[ "Algorithms" ]
https://www.codewars.com/kata/586e6b54c66d18ff6c0015cd
4 kyu
## Sum Even Fibonacci Numbers * Write a func named SumEvenFibonacci that takes a parameter of type int and returns a value of type int * Generate all of the Fibonacci numbers starting with 1 and 2 and ending on the highest number before exceeding the parameter's value #### Each new number in the Fibonacci sequence is generated by adding the previous two numbers - by starting with 1 and 2(the input could be smaller), the first 10 numbers will be: ``` 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... ``` * Sum all of the even numbers you generate and return that int #### Example: ``` sumEvenFibonacci(8) // returns 10 by adding the even values 2 and 8 ```
reference
def SumEvenFibonacci(limit): a, b, s = 1, 1, 0 while a <= limit: if not a % 2: s += a a, b = b, a + b return s
Sum Even Fibonacci Numbers
5926624c9b424d10390000bf
[ "Fundamentals" ]
https://www.codewars.com/kata/5926624c9b424d10390000bf
7 kyu
Consider the array `[3,6,9,12]`. If we generate all the combinations with repetition that sum to `12`, we get `5` combinations: `[12], [6,6], [3,9], [3,3,6], [3,3,3,3]`. The length of the sub-arrays (such as `[3,3,3,3]` should be less than or equal to the length of the initial array (`[3,6,9,12]`). Given an array of positive integers and a number `n`, count all combinations with repetition of integers that sum to `n`. For example: ```Haskell find([3,6,9,12],12) = 5. ``` More examples in the test cases. Good luck! If you like this Kata, please try: [Array combinations](https://www.codewars.com/kata/59e66e48fc3c499ec5000103) [Sum of prime-indexed elements](https://www.codewars.com/kata/59f38b033640ce9fc700015b)
reference
from itertools import combinations_with_replacement def find(arr, n): return sum(sum(c) == n for x in range(1, len(arr) + 1) for c in combinations_with_replacement(arr, x))
Sum of integer combinations
59f3178e3640cef6d90000d5
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/59f3178e3640cef6d90000d5
6 kyu
In this Kata, you will be given an integer array and your task is to return the sum of elements occupying prime-numbered indices. ~~~if-not:fortran The first element of the array is at index `0`. ~~~ ~~~if:fortran The first element of an array is at index `1`. ~~~ Good luck! If you like this Kata, try: [Dominant primes](https://www.codewars.com/kata/59ce11ea9f0cbc8a390000ed). It takes this idea a step further. [Consonant value](https://www.codewars.com/kata/59c633e7dcc4053512000073)
reference
def is_prime(n): return n >= 2 and all(n % i for i in range(2, 1 + int(n * * .5))) def total(arr): return sum(n for i, n in enumerate(arr) if is_prime(i))
Sum of prime-indexed elements
59f38b033640ce9fc700015b
[ "Lists", "Fundamentals" ]
https://www.codewars.com/kata/59f38b033640ce9fc700015b
6 kyu
In this Kata, you will implement a function `count` that takes an integer and returns the number of digits in `factorial(n)`. For example, `count(5) = 3`, because `5! = 120`, and `120` has `3` digits. More examples in the test cases. Brute force is not possible. A little research will go a long way, as this is a well known series. Good luck! Please also try:
algorithms
from math import * def count(n): return ceil(lgamma(n + 1) / log(10))
Factorial length
59f34ec5a01431ab7600005a
[ "Algorithms" ]
https://www.codewars.com/kata/59f34ec5a01431ab7600005a
6 kyu
The [half-life](https://en.wikipedia.org/wiki/Half-life) of a radioactive substance is the time it takes (on average) for one-half of its atoms to undergo radioactive decay. # Task Overview Given the initial quantity of a radioactive substance, the quantity remaining after a given period of time, and the period of time, return the half life of that substance. # Usage Examples ```javascript // if quantity halves in 1 time period, half-life = 1 halfLife(10, 5, 1) => 1 // if quantity halves in 2 time periods, half-life = 2 halfLife(8,4,2) => 2 // if quantity is one-quarter after 2 time periods, half-life = 1 halfLife(12,3,2) => 1 ``` ```csharp // if quantity halves in 1 time period, half-life = 1 Kata.HalfLife(10, 5, 1) => 1 // if quantity halves in 2 time periods, half-life = 2 Kata.HalfLife(8,4,2) => 2 // if quantity is one-quarter after 2 time periods, half-life = 1 Kata.HalfLife(12,3,2) => 1 ``` ```if:csharp <h1>Documentation:</h1> <h2>Kata.HalfLife Method (Double, Double, Int32)</h2> Returns the half-life for a substance given the initial quantity, the remaining quantity, and the elasped time. <span style="font-size:20px">Syntax</span> <div style="margin-top:-10px;padding:2px;background-color:Grey;position:relative;left:20px;width:600px;"> <div style="background-color:White;color:Black;border:1px;display:block;padding:10px;padding-left:18px;font-family:Consolas,Courier,monospace;"> <span style="color:Blue;">public</span> <span style="color:Blue;">static</span> <span style="color:Blue;">double</span> HalfLife(</br> <span style="position:relative;left:62px;">double quantityInitial,</span></br>   <span style="position:relative;left:62px;">double quantityRemaining,</span></br> <span style="position:relative;left:62px;">int time</span></br>   ) </div> </div> </br> <div style="position:relative;left:20px;"> <strong>Parameters</strong> </br> <i>quantityInitial</i> </br> <span style="position:relative;left:50px;">Type: <a href="https://msdn.microsoft.com/en-us/library/system.double(v=vs.110).aspx">System.Double</a></span></br> <span style="position:relative;left:50px;">The initial amount of the substance.</span> </br></br> <i>quantityRemaining</i> </br> <span style="position:relative;left:50px;">Type: <a href="https://msdn.microsoft.com/en-us/library/system.double(v=vs.110).aspx">System.Double</a></span></br> <span style="position:relative;left:50px;">The current amount of the substance.</span> </br></br> <i>time</i> </br> <span style="position:relative;left:50px;">Type: <a href="https://msdn.microsoft.com/en-us/library/system.int32(v=vs.110).aspx">System.Int32</a></span></br> <span style="position:relative;left:50px;">The amount of time elapsed.</span> </br></br> <strong>Return Value</strong> </br> <span>Type: <a href="https://msdn.microsoft.com/en-us/library/system.double(v=vs.110).aspx">System.Double</a></span></br> A floating-point number representing the half-life of the substance. </div> ```
reference
from math import log def half_life(N0, N, t): return t / log(N0 / N, 2)
Half Life
59f33b86a01431d5ae000032
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/59f33b86a01431d5ae000032
7 kyu
Given a number of points on a plane, your task is to find two points with the smallest distance between them in linearithmic [O(n log n)](http://en.wikipedia.org/wiki/Time_complexity#Linearithmic_time) time. ### Example ``` 1 2 3 4 5 6 7 8 9 1 2 . A 3 . D 4 . F 5 . C 6 7 . E 8 . B 9 . G ``` For the plane above, the input will be: ```javascript [ [2,2], // A [2,8], // B [5,5], // C [6,3], // D [6,7], // E [7,4], // F [7,9] // G ] => closest pair is: [[6,3],[7,4]] or [[7,4],[6,3]] (both answers are valid) ``` ```java [ [2,2], // A [2,8], // B [5,5], // C [6,3], // D [6,7], // E [7,4], // F [7,9] // G ] => closest pair is: [[6,3],[7,4]] or [[7,4],[6,3]] (both answers are valid) ``` ```python ( (2,2), # A (2,8), # B (5,5), # C (6,3), # D (6,7), # E (7,4), # F (7,9) # G ) => closest pair is: ((6,3),(7,4)) or ((7,4),(6,3)) (both answers are valid. You can return a list of tuples too) ``` The two points that are closest to each other are D and F. Expected answer should be an array with both points in any order. ### Goal The goal is to come up with a function that can find two closest points for any arbitrary array of points, in a linearithmic time. ~~~if:python **Note:** Don't use `math.hypot`, it's too slow... ~~~ ~~~if:javascript ----- _**Note:** for compatibility reasons, your function will be called with one additional parameter, a distance calculation function. However you can completely ignore it, and you do not have to account for it - it's there only to keep compatibility with old solutions._ ~~~ ~~~if:java ----- `Point` class is preloaded for you as: ```java public class Point { public double x, y; public Point() { x = y = 0.0; } public Point(double x, double y) { this.x = x; this.y = y; } @Override public String toString() { return String.format("(%f, %f)", x, y); } @Override public int hashCode() { return Double.hashCode(x) ^ Double.hashCode(y); } @Override public boolean equals(Object obj) { if (obj instanceof Point) { Point other = (Point) obj; return x == other.x && y == other.y; } else { return false; } } } ``` ~~~ ----- More information on [wikipedia](http://en.wikipedia.org/wiki/Closest_pair_of_points_problem).
algorithms
def distance(a, b): return ((b[0] - a[0]) * * 2 + (b[1] - a[1]) * * 2) * * 0.5 def iterative_closest(arr): n = len(arr) mini = ((arr[0], arr[1]), distance(arr[0], arr[1])) for i in range(n - 1): for j in range(i + 1, n): dij = distance(arr[i], arr[j]) if dij < mini[1]: mini = ((arr[i], arr[j]), dij) return mini def recursive_closest(arr): n = len(arr) if n <= 3: # if the array is less than 3 items # use the naive method return iterative_closest(arr) # divide the row into two parts # and search the closest pair of points in each mid = n / / 2 ml, mr = recursive_closest(arr[: mid]), recursive_closest(arr[mid:]) # the closest pair is the one having the minimum # distance in both parts mlr = ml if ml[1] < mr[1] else mr # Now we have to combine the results from # the two parts # find the points that are close to the median point arr1 = [pt for pt in arr if abs(pt[0] - arr[mid][0]) < mlr[1]] arr1 . sort(key=lambda pt: pt[1]) # sort it by Y coordinates # foreach of the points search within the next 7 points # which have the lowest distance n1 = len(arr1) for i in range(n1 - 1): for j in range(1, min(7, n1 - i)): dij = distance(arr1[i], arr1[i + j]) if dij < mlr[1]: mlr = ((arr1[i], arr1[i + j]), dij) return mlr def closest_pair(points): arr = sorted(points) return recursive_closest(arr)[0]
Closest pair of points in linearithmic time
5376b901424ed4f8c20002b7
[ "Algorithms", "Geometry", "Mathematics" ]
https://www.codewars.com/kata/5376b901424ed4f8c20002b7
3 kyu
Bob has a server farm crunching numbers. He has `nodes` servers in his farm. His company has a lot of work to do. The work comes as a number `workload` which indicates how many jobs there are. Bob wants his servers to get an equal number of jobs each. If that is impossible, he wants the first servers to receive more jobs. He also wants the jobs sorted, so that the first server receives the first jobs. The way this works, Bob wants an array indicating which jobs are going to which servers. Can you help him distribute all this work as evenly as possible onto his servers? Example ------- Bob has `2` servers and `4` jobs. The first server should receive job 0 and 1 while the second should receive 2 and 3. ``` distribute(2, 4) # => [[0, 1], [2, 3]] ``` On a different occasion Bob has `3` servers and `3` jobs. Each should get just one. ``` distribute(3, 3) # => [[0], [1], [2]] ``` A couple of days go by and Bob sees a spike in jobs. Now there are `10`, but he hasn't got more than `4` servers available. He boots all of them. This time the first and second should get a job more than the third and fourth. ``` distribute(4, 10) # => [[0, 1, 2], [3, 4, 5], [6, 7], [8, 9]] ``` Input ----- Don't worry about invalid inputs. That is, `nodes > 0` and `workload > 0` and both will always be integers.
algorithms
def distribute(n, w): g, (d, r) = iter(range(w)), divmod(w, n) return [[next(g) for _ in range(d + (i < r))] for i in range(n)]
Distribute server workload
59f22b3cf0a83ff3e3003d8c
[ "Arrays", "Lists", "Algorithms" ]
https://www.codewars.com/kata/59f22b3cf0a83ff3e3003d8c
6 kyu
You are given `num` (up to `15 digits`, `never less than 0`).</br> If the `length of num is even`, return `odd numbers as ints` and `even ones as strings`, based on their `position` in the given number. Strings alternate in type cases: starting in `lowercase` to `uppercase` and so on based on position. If the `length of num is odd`, all the rules are `opposite`. See sample tests. </br> Note: Positions of numbers are `1-based`.</br>
reference
numbers = ("zeroZERO" * 3, "ONEone" * 3, "twoTWO" * 3, "THREEthree" * 3, "fourFOUR" * 3, "FIVEfive" * 3, "sixSIX" * 3, "SEVENseven" * 3, "eightEIGHT" * 3, "NINEnine" * 3) def conv(num): s = str(num) check = ("13579", "02468")[len(s) & 1] return '' . join(d if d in check else numbers[int(d)][: i + 1] for i, d in enumerate(s))
1 Two 3 Four 5!
59f2746e50c8c2b55d000085
[ "Algorithms" ]
https://www.codewars.com/kata/59f2746e50c8c2b55d000085
6 kyu
Given a certain array of positive and negative numbers, give the longest increasing or decreasing combination of at least 3 elements of the array. If our array is ```a = [a[0], a[1], ....a[n-1]]```: i) For the increasing case: there is a combination: ```a[i] < a[j] < a[k]..< a[p]```, such that ```0 ≤ i < j < k < ...< p ≤ n - 1``` For the decreasing case the combination would be: ```a[i] > a[j] > a[k]..> a[p]```, such that ```0 ≤ i < j < k < ...< p ≤ n - 1``` For that task create a function ```longest_comb()``` (Javascript: ```longestComb()``` ) that will receive an array, and a command, one of the two kinds of strings: ```'< <' or '<<'``` (increasing), ```'> >' or '>>'``` (decreasing). ~~~if:python,javascript,ruby Let's see some examples: ```python longest_comb([-1, 3, -34, 18, -55, 60, 118, -64], '< <') == [-1, 3, 18, 60, 118] longest_comb([-1, 3, -34, 18, -55, 60, 118, -64], '> >') == [[-1, -34, -55, -64], [3, -34, -55, -64]] # outputs a 2D array of two combinations # of same length in the order that they appear in the given array from # left to right ``` We may have some cases without any possible combination: ```python longest_comb([-26, 26, -36, 17, 12, 12, -10, -21], "< <") == [] ``` On the other hand we may have cases with many solutions: ```python longest_comb([-22, 40, -45, -43, -1, 7, 43, -56], "> >") == [[-22, -45, -56], [-22, -43, -56], [40, -45, -56], [40, -43, -56], [40, -1, -56], [40, 7, -56]] ``` ~~~ ~~~if:d,rust,go Let's see some examples (input --> output): ``` [-1, 3, -34, 18, -55, 60, 118, -64], "< <" --> [[-1, 3, 18, 60, 118]] [-1, 3, -34, 18, -55, 60, 118, -64], "> >" --> [[-1, -34, -55, -64], [3, -34, -55, -64]] # outputs a 2D array of two combinations # of same length in the order that they appear in the given array from # left to right ``` We may have some cases without any possible combination: ``` [-26, 26, -36, 17, 12, 12, -10, -21], "< <" --> [] ``` On the other hand we may have cases with many solutions: ``` [-22, 40, -45, -43, -1, 7, 43, -56], "> >" -> [[-22, -45, -56], [-22, -43, -56], [40, -45, -56], [40, -43, -56], [40, -1, -56], [40, 7, -56]] ``` ~~~
reference
from itertools import starmap, combinations from operator import lt, gt def longest_comb(arr, command): check = lt if command . startswith('<') else gt for i in range(len(arr), 2, - 1): # if all(map(check, x, x[1:])) In Python 3 result = [list(x) for x in combinations(arr, i) if all(starmap(check, zip(x, x[1:])))] # Also always annoying to return only the first element when we only have one if result: return result[0] if len(result) == 1 else result return []
Find the Longest Increasing or Decreasing Combination in an Array
5715508de1bf8174c1001832
[ "Data Structures", "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/5715508de1bf8174c1001832
5 kyu
Create a function that returns an array containing the first `l` numbers from the `n`th diagonal of [Pascal's triangle](https://en.wikipedia.org/wiki/Pascal's_triangle). `n = 0` should generate the first diagonal of the triangle (the ones). The first number in each diagonal should be `1`. If `l = 0`, return an empty array. Both `n` and `l` will be non-negative integers in all test cases. ~~~if:lambdacalc #### Encodings `Purity: LetRec` `numEncoding: BinaryScott` export `foldr` for your `List` encoding ~~~
algorithms
def generate_diagonal(d, l): result = [1] if l else [] for k in range(1, l): result . append(result[- 1] * (d + k) / / k) return result
Pascal's Diagonals
576b072359b1161a7b000a17
[ "Algorithms" ]
https://www.codewars.com/kata/576b072359b1161a7b000a17
5 kyu
Kate constantly finds herself in some kind of a maze. Help her to find a way out!. For a given maze and Kate's position find if there is a way out. Your function should return True or False. Each maze is defined as a list of strings, where each char stays for a single maze "cell". ' ' (space) can be stepped on, '#' means wall and 'k' stays for Kate's starting position. Note that the maze may not always be square or even rectangular. Kate can move left, up, right or down only. There should be only one Kate in a maze. In any other case you have to throw an exception. Example input ============= ``` ['# ##', '# k#', '####'] ``` Example output ============== True Example input ============= ``` ['####'. '# k#', '####'] ``` Example output ============== False
algorithms
MOVES = {(0, 1), (0, - 1), (1, 0), (- 1, 0)} def has_exit(maze): posSet = {(x, y) for x in range(len(maze)) for y in range(len(maze[x])) if maze[x][y] == 'k'} if len(posSet) != 1: raise ValueError("There shouldn't be more than one kate") seen = set(posSet) while posSet: x, y = posSet . pop() if any(not (0 <= x + dx < len(maze) and 0 <= y + dy < len(maze[x + dx])) for dx, dy in MOVES): return True neighbors = {(x + dx, y + dy) for dx, dy in MOVES if 0 <= x + dx < len(maze) and 0 <= y + dy < len(maze[x + dx]) and maze[x + dx][y + dy] == ' ' and (x + dx, y + dy) not in seen} posSet |= neighbors seen |= neighbors return False
Simple maze
56bb9b7838dd34d7d8001b3c
[ "Queues", "Recursion", "Algorithms" ]
https://www.codewars.com/kata/56bb9b7838dd34d7d8001b3c
4 kyu
The following figure shows a cell grid with 6 cells (2 rows by 3 columns), each cell separated from the others by walls: +--+--+--+ | | | | +--+--+--+ | | | | +--+--+--+ This grid has 6 connectivity components of size 1. We can describe the size and number of connectivity components by the list `[(1, 6)]`, since there are 6 components of size 1. If we tear down a couple of walls, we obtain: +--+--+--+ | | | + +--+--+ | | | | +--+--+--+ , which has two connectivity components of size 2 and two connectivity components of size 1. The size and number of connectivity components is described by the list `[(2, 2), (1, 2)]`. Given the following grid: +--+--+--+ | | | + +--+--+ | | | +--+--+--+ we have the connectivity components described by `[(4, 1), (1, 2)]`. Your job is to define a function `components(grid)` that takes as argument a string representing a grid like in the above pictures and returns a list describing the size and number of the connectivity components. The list should be sorted in descending order by the size of the connectivity components. The grid may have any number of rows and columns. Note: The grid is always rectangular and will have all its outer walls. Only inner walls may be missing. The `+` are considered bearing pillars, and are always present.
algorithms
from collections import deque, Counter def fill(grid, x, y): h, w = len(grid), len(grid[x]) unexplored = deque([(x, y)]) size = 0 while unexplored: x, y = unexplored . popleft() if 0 <= x < h and 0 <= y < w and grid[x][y] == ' ': grid[x][y] = '#' unexplored . extend(((x + 1, y), (x, y + 1), (x - 1, y), (x, y - 1))) size += x % 2 == 1 and y % 3 == 1 return size def components(diagram): grid = [list(line) for line in diagram . split('\n')] cells = ((x, y) for x in range(len(grid)) for y in range(len(grid[x]))) sizes = Counter(fill(grid, x, y) for x, y in cells if grid[x][y] == ' ') return sorted(sizes . items(), reverse=True)
Count Connectivity Components
5856f3ecf37aec45e6000091
[ "Strings", "Algorithms", "Graph Theory" ]
https://www.codewars.com/kata/5856f3ecf37aec45e6000091
3 kyu
###Instructions A time period starting from ```'hh:mm'``` lasting until ```'hh:mm'``` is stored in an array: ``` ['08:14', '11:34'] ``` A set of different time periods is then stored in a 2D Array like so, each in its own sub-array: ``` [['08:14','11:34'], ['08:16','08:18'], ['22:18','01:14'], ['09:30','10:32'], ['04:23','05:11'], ['11:48','13:48'], ['01:12','01:14'], ['01:13','08:15']] ``` Write a function that will take a 2D Array like the above as argument and return a 2D Array of the argument's sub-arrays sorted in ascending order. Take note of the following: * The first time period starts at the earliest time possible ```('00:00'+)```. * The next time period is the one that starts the soonest **after** the prior time period finishes. If several time periods begin at the same hour, pick the first one showing up in the original array. * The next time period can start the same time the last one finishes. This: ``` [['08:14','11:34'], ['08:16','08:18'], ['13:48','01:14'], ['09:30','10:32'], ['04:23','05:11'], ['11:48','13:48'], ['01:12','01:14'], ['01:13','08:15']] ``` Should return: ``` [['01:12','01:14'], ['04:23','05:11'], ['08:14','11:34'], ['11:48','13:48'], ['13:48','01:14'], ['08:16','08:18'], ['09:30','10:32'], ['01:13','08:15']] ```
algorithms
def sort_time(arr): arr, s = sorted(arr, key=lambda t: t[0]), [] while arr: nextTP = next((i for i, t in enumerate( arr) if not s or t[0] >= s[- 1][1]), 0) s . append(arr . pop(nextTP)) return s
Sorting Time
57024825005264fe9200057d
[ "Sorting", "Arrays", "Algorithms", "Date Time" ]
https://www.codewars.com/kata/57024825005264fe9200057d
6 kyu
Create an OR function that takes a list of boolean values and runs OR against all of them, without ( depending on language ) the `or` keyword or the `||` operator,. There will be between `0` and `6` elements ( inclusive ). Return `None`, `nil` or a similar empty value for an empty list.
algorithms
def alt_or(lst): return any(lst) if lst else None
Alternate Logic
58f625e20290fb29c3000056
[ "Algorithms" ]
https://www.codewars.com/kata/58f625e20290fb29c3000056
7 kyu
In computing, there are two primary byte order formats: big-endian and little-endian. Big-endian is used primarily for networking (e.g., IP addresses are transmitted in big-endian) whereas little-endian is used mainly by computers with microprocessors. Here is an example (using 32-bit integers in hex format): Little-Endian: 00 6D F4 C9 = 7,206,089 Big-Endian: C9 F4 6D 00 = 3,388,239,104 Your job is to write a function that switches the byte order of a given integer. The function should take an integer n for the first argument, and the bit-size of the integer for the second argument. The bit size must be a power of 2 greater than or equal to 8. Your function should return a None value if the integer is negative, if the specified bit size is not a power of 2 that is 8 or larger, or if the integer is larger than the specified bit size can handle. In this kata, assume that all integers are unsigned (non-negative) and that all input arguments are integers (no floats, strings, None/nil values, etc.). Remember that you will need to account for padding of null (00) bytes. Hint: bitwise operators are very helpful! :)
algorithms
def switch_endian(n, bits): out = 0 while bits > 7: bits -= 8 out <<= 8 out |= n & 255 n >>= 8 return None if n or bits else out
Endianness Conversion
56f2dd31e40b7042ad001026
[ "Algorithms" ]
https://www.codewars.com/kata/56f2dd31e40b7042ad001026
5 kyu
Four-digit palindromes start with `[1001,1111,1221,1331,1441,1551,1551,...]` and the number at position `2` is `1111`. You will be given two numbers `a` and `b`. Your task is to return the `a-digit` palindrome at position `b` if the palindromes were arranged in increasing order. Therefore, `palin(4,2) = 1111`, because that is the second element of the `4-digit` palindrome series. More examples in the test cases. Good luck! If you like palindrome Katas, please try: [Palindrome integer composition](https://www.codewars.com/kata/599b1a4a3c5292b4cc0000d5) [Life without primes](https://www.codewars.com/kata/59f8750ac374cba8f0000033)
algorithms
def palin(length, pos): left = str(10 * * ((length - 1) / / 2) + (pos - 1)) right = left[:: - 1][length % 2:] return int(left + right)
Fixed length palindromes
59f0ee47a5e12962cb0000bf
[ "Algorithms" ]
https://www.codewars.com/kata/59f0ee47a5e12962cb0000bf
6 kyu
In this Kata, you will be given an array of numbers in which two numbers occur once and the rest occur only twice. Your task will be to return the sum of the numbers that occur only once. For example, `repeats([4,5,7,5,4,8]) = 15` because only the numbers `7` and `8` occur once, and their sum is `15`. Every other number occurs twice. More examples in the test cases. <!-- C# documentation --> ```if:csharp <h1>Documentation:</h1> <h2>Kata.Repeats Method (List&lt;Int32&gt;)</h2> Takes a list where all ints are repeated twice, except two ints, and returns the sum of the ints of a list where those ints only occur once. <span style="font-size:20px">Syntax</span> <div style="margin-top:-10px;padding:2px;background-color:Grey;position:relative;left:20px;width:600px;"> <div style="background-color:White;color:Black;border:1px;display:block;padding:10px;padding-left:18px;font-family:Consolas,Courier,monospace;"> <span style="color:Blue;">public</span> <span style="color:Blue;">static</span> <span style="color:Blue;">int</span> Repeats(</br> <span style="position:relative;left:62px;">List&lt;<span style="color:Blue;">int</span>&gt; source</span></br>   ) </div> </div> </br> <div style="position:relative;left:20px;"> <strong>Parameters</strong> </br> <i>source</i> </br> <span style="position:relative;left:50px;">Type: <a href="https://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx">System.Collections.Generic.List</a>&lt;Int32&gt;</span></br> <span style="position:relative;left:50px;">The list to process.</span> </br></br> <strong>Return Value</strong> </br> <span>Type: <a href="https://msdn.microsoft.com/en-us/library/system.int32(v=vs.110).aspx">System.Int32</a></span></br> The sum of the elements of the list where those elements have no duplicates. </div> ``` <!-- end C# documentation --> Good luck! If you like this Kata, please try: [Sum of prime-indexed elements](https://www.codewars.com/kata/59f38b033640ce9fc700015b) [Sum of integer combinations](https://www.codewars.com/kata/59f3178e3640cef6d90000d5)
algorithms
def repeats(arr): return sum([x for x in arr if arr . count(x) == 1])
Sum of array singles
59f11118a5e129e591000134
[ "Algorithms" ]
https://www.codewars.com/kata/59f11118a5e129e591000134
7 kyu
In this Kata, you will be given an array of strings and your task is to remove all consecutive duplicate letters from each string in the array. For example: * `dup(["abracadabra","allottee","assessee"]) = ["abracadabra","alote","asese"]`. * `dup(["kelless","keenness"]) = ["keles","kenes"]`. Strings will be lowercase only, no spaces. See test cases for more examples. ~~~if:rust For the sake of simplicity you can use the macro 'vec_of_strings!' to create a Vec<String> with an array of string literals. ~~~ Good luck! If you like this Kata, please try: [Alternate capitalization](https://www.codewars.com/kata/59cfc000aeb2844d16000075) [Vowel consonant lexicon](https://www.codewars.com/kata/59cf8bed1a68b75ffb000026)
algorithms
from itertools import groupby def dup(arry): return ["" . join(c for c, grouper in groupby(i)) for i in arry]
String array duplicates
59f08f89a5e129c543000069
[ "Strings", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/59f08f89a5e129c543000069
6 kyu
The number ```1331``` is the first positive perfect cube, higher than ```1```, having all its digits odd (its cubic root is ```11```). The next one is ```3375```. In the interval [-5000, 5000] there are six pure odd digit perfect cubic numbers and are: ```[-3375,-1331, -1, 1, 1331, 3375]``` Give the numbers of this sequence that are in the range ```[a,b] ```(both values inclusive) Examples: ``` python odd_dig_cubic(-5000, 5000) == [-3375,-1331, -1, 1, 1331, 3375] # the output should be sorted. odd_dig_cubic(0, 5000) == [1, 1331, 3375] odd_dig_cubic(-1, 5000) == [-1, 1, 1331, 3375] odd_dig_cubic(-5000, -2) == [-3375,-1331] ``` Features of the random tests for python: ``` number of Tests = 94 minimum value for a = -1e17 maximum value for b = 1e17 ``` You do not have to check the entries, ```a``` and ```b``` always integers and ```a < b``` Working well in Python 2 and Python 3. Translation into Ruby is coming soon.
reference
CUBICS = [1, 1331, 3375, 35937, 59319, 357911, 753571, 5177717, 5359375, 5735339, 9393931, 17373979, 37595375, 37159393753, 99317171591, 175333911173, 397551775977, 1913551573375, 9735913353977, 11997979755957, 17171515157399, 335571975137771, 1331399339931331, 1951953359359375, 7979737131773191, 11751737113715977, 13337513771953951] CUBICS = [- x for x in reversed(CUBICS)] + CUBICS def odd_dig_cubic(a, b): return [x for x in CUBICS if a <= x <= b]
# 2 Sequences: Pure Odd Digit Perfect Cubic (P.O.D.P.C)
59f04228e63f8ceb92000038
[ "Mathematics", "Arrays", "Algorithms", "Logic", "Memoization", "Fundamentals" ]
https://www.codewars.com/kata/59f04228e63f8ceb92000038
6 kyu
Imagine you start on the 5th floor of a building, then travel down to the 2nd floor, then back up to the 8th floor. You have travelled a total of 3 + 6 = 9 floors of distance. Given an array representing a series of floors you must reach by elevator, return an integer representing the total distance travelled for visiting each floor in the array in order. ``` // simple examples elevatorDistance([5,2,8]) = 9 elevatorDistance([1,2,3]) = 2 elevatorDistance([7,1,7,1]) = 18 // if two consecutive floors are the same, //distance travelled between them is 0 elevatorDistance([3,3]) = 0 ``` Array will always contain at least 2 floors. Random tests will contain 2-20 elements in array, and floor values between 0 and 30.
reference
def elevator_distance(array): return sum(abs(a - b) for a, b in zip(array, array[1:]))
Elevator Distance
59f061773e532d0c87000d16
[ "Fundamentals" ]
https://www.codewars.com/kata/59f061773e532d0c87000d16
7 kyu
Odd bits are getting ready for [Bits Battles](https://www.codewars.com/kata/world-bits-war/). Therefore the `n` bits march from right to left along an `8` bits path. Once the most-significant bit reaches the left their march is done. Each step will be saved as an array of `8` integers. Return an array of all the steps. `1 <= n <= 8` NOTE: `n != 0`, because `n` represents the number of `1`s. ## Examples This resembles a simple 8 LED chaser: ``` n = 3 00000111 00001110 00011100 00111000 01110000 11100000 ``` ``` n = 7 01111111 11111110 ```
reference
def bit_march(n: int) - > list: return [[0] * (8 - n - i) + [1] * n + [0] * i for i in range(8 - n + 1)]
Odd March Bits 8 bits
58ee4db3e479611e6f000086
[ "Bits", "Binary", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/58ee4db3e479611e6f000086
7 kyu
Your task is to implement a simple regular expression parser. We will have a parser that outputs the following AST of a regular expression: ```haskell data RegExp = Normal Char -- ^ A character that is not in "()*|." | Any -- ^ Any character | ZeroOrMore RegExp -- ^ Zero or more occurances of the same regexp | Or RegExp RegExp -- ^ A choice between 2 regexps | Str [RegExp] -- ^ A sequence of regexps. ``` ```c RegExp* normal (char); // ^ A character that is not in "()*|." RegExp* any (); // ^ Any character RegExp* zeroOrMore (RegExp *starred); // ^ Zero or more occurances of the same regexp RegExp* or (RegExp* left, RegExp* right); // ^ A choice between 2 regexps RegExp* str (RegExp *first); // ^ A sequence of regexps, first element RegExp* add (RegExp *str, RegExp* next); // ^ A sequence of regexps, additional element ``` ```csharp Reg.Exp normal (char); // ^ A character that is not in "()*|." Reg.Exp any (); // ^ Any character Reg.Exp zeroOrMore (Reg.Exp starred); // ^ Zero or more occurances of the same regexp Reg.Exp or (Reg.Exp left, Reg.Exp right); // ^ A choice between 2 regexps Reg.Exp str (Reg.Exp first); // ^ A sequence of regexps, first element Reg.Exp add (Reg.Exp str, Reg.Exp next); // ^ A sequence of regexps, additional element ``` ```cpp RegExp* normal (char); // ^ A character that is not in "()*|." RegExp* any (); // ^ Any character RegExp* zeroOrMore (RegExp *starred); // ^ Zero or more occurances of the same regexp RegExp* orr (RegExp* left, RegExp* right); // ^ A choice between 2 regexps RegExp* str (RegExp *first); // ^ A sequence of regexps, first element RegExp* add (RegExp *str, RegExp* next); // ^ A sequence of regexps, additional element ``` ```python Normal(c) # ^ A character (string) that is not in "()*|." Any() # ^ Any character ZeroOrMore(regexp) # ^ Zero or more occurances of the same regexp Or(regexp, regexp) # ^ A choice between 2 regexps Str([regexps]) # ^ A sequence of regexps. ``` ```java new Void() // An empty RegExp object, used only // as default output for wrong inputs. new Normal(char c) // A character (string) that is not in "()*|." new Any() // Any character new ZeroOrMore(RegExp regexp) // Zero or more occurances of the same regexp new Or(RegExp r1, RegExp r2) // A choice between 2 regexps new Str(List<RegExp> lstRegexps]) // A sequence of regexps. // All these objects implement the toString(), hashCode() and equals() methods and extend the RegExp abstract class. In addition, you can use the getType() method to obtain a string representing the structure of the object and its children (using Str, Or, Normal, ... dnominations). ``` ```javascript new Normal(c) // A character that is not in "()*|." new Any() // Any character new ZeroOrMore(regexp) // Zero or more occurances of the same regexp new Or(regexp,regexp) // A choice between 2 regexps new Str([regexp]) // A sequence of regexps ``` ```rust enum RegExp { Normal(char), // A character that is not in "()*|." Any, // Any character ZeroOrMore(Box<RegExp>), // Zero or more occurances of the same regexp Or(Box<RegExp>, Box<RegExp>), // A choice between 2 regexps Str(Vec<RegExp>), // A sequence of regexps } ``` As with the usual regular expressions, `Any` is denoted by the `'.'` character, `ZeroOrMore` is denoted by a subsequent `'*'` and `Or` is denoted by `'|'`. Brackets, `(` and `)`, are allowed to group a sequence of regular expressions into the `Str` object. `Or` is not associative, so `"a|(a|a)"` and `"(a|a)|a"` are both valid regular expressions, whereas `"a|a|a"` is not. Operator precedences from highest to lowest are: `*`, sequencing and `|`. Therefore the followings hold: ```haskell "ab*" -> Str [Normal 'a', ZeroOrMore (Normal 'b')] "(ab)*" -> ZeroOrMore (Str [Normal 'a', Normal 'b']) "ab|a" -> Or (Str [Normal 'a',Normal 'b']) (Normal 'a') "a(b|a)" -> Str [Normal 'a',Or (Normal 'b') (Normal 'a')] "a|b*" -> Or (Normal 'a') (ZeroOrMore (Normal 'b')) "(a|b)*" -> ZeroOrMore (Or (Normal 'a') (Normal 'b')) ``` ```c "ab*" -> add (str (normal ('a')), zeroOrMore (normal ('b'))) "(ab)*" -> zeroOrMore (add (str (normal ('a')), normal ('b'))) "ab|a" -> or (add (str (normal ('a')), normal ('b')), normal ('a')) "a(b|a)" -> add (str (normal ('a')), or (normal ('b'), normal ('a'))) "a|b*" -> or (normal ('a'), zeroOrMore (normal ('b'))) "(a|b)*" -> zeroOrMore (or (normal ('a'), normal ('b'))) ``` ```csharp "ab*" -> Reg.add (Reg.str (Reg.normal ('a')), Reg.zeroOrMore (Reg.normal ('b'))) "(ab)*" -> Reg.zeroOrMore (Reg.add (str (Reg.normal ('a')), Reg.normal ('b'))) "ab|a" -> Reg.or (Reg.add (Reg.str (Reg.normal ('a')), Reg.normal ('b')), Reg.normal ('a')) "a(b|a)" -> Reg.add (Reg.str (Reg.normal ('a')), Reg.or (Reg.normal ('b'), Reg.normal ('a'))) "a|b*" -> Reg.or (Reg.normal ('a'), Reg.zeroOrMore (Reg.normal ('b'))) "(a|b)*" -> Reg.zeroOrMore (Reg.or (Reg.normal ('a'), Reg.normal ('b'))) ``` ```cpp "ab*" -> add (str (normal ('a')), zeroOrMore (normal ('b'))) "(ab)*" -> zeroOrMore (add (str (normal ('a')), normal ('b'))) "ab|a" -> orr (add (str (normal ('a')), normal ('b')), normal ('a')) "a(b|a)" -> add (str (normal ('a')), orr (normal ('b'), normal ('a'))) "a|b*" -> orr (normal ('a'), zeroOrMore (normal ('b'))) "(a|b)*" -> zeroOrMore (orr (normal ('a'), normal ('b'))) ``` ```python "ab*" -> Str([Normal ('a'), ZeroOrMore(Normal('b'))]) "(ab)*" -> ZeroOrMore(Str([Normal('a'), Normal('b')])) "ab|a" -> Or(Str([Normal('a'), Normal('b')]), Normal('a')) "a(b|a)" -> Str([Normal('a'), Or(Normal('b'), Normal('a'))]) "a|b*" -> Or(Normal('a'), ZeroOrMore(Normal('b'))) "(a|b)*" -> ZeroOrMore(Or(Normal('a'), Normal('b'))) ``` ```java "ab*" -> new Str ([new Normal ('a'), new ZeroOrMore (new Normal ('b'))]) "(ab)*" -> new ZeroOrMore (new Str ([new Normal ('a'), new Normal ('b')])) "ab|a" -> new Or (new Str ([new Normal ('a'), new Normal ('b')]), new Normal ('a')) "a(b|a)" -> new Str ([new Normal ('a'), new Or (new Normal ('b'), new Normal ('a'))]) "a|b*" -> new Or (new Normal ('a'), new ZeroOrMore (new Normal ('b'))) "(a|b)*" -> new ZeroOrMore (new Or (new Normal ('a'), new Normal ('b'))) ``` ```kotlin "ab*" -> Str ([Normal ('a'), ZeroOrMore (Normal ('b'))]) "(ab)*" -> ZeroOrMore (Str ([Normal ('a'), Normal ('b')])) "ab|a" -> Or (Str ([Normal ('a'), Normal ('b')]), Normal ('a')) "a(b|a)" -> Str ([Normal ('a'), Or (Normal ('b'), Normal ('a'))]) "a|b*" -> Or (Normal ('a'), ZeroOrMore (Normal ('b'))) "(a|b)*" -> ZeroOrMore (Or (Normal ('a'), Normal ('b'))) ``` ```javascript "ab*" -> new Str([ new Normal('a'), new ZeroOrMore(new Normal ('b')) ]) "(ab)*" -> new ZeroOrMore(new Str([ new Normal('a'), new Normal('b') ])) "ab|a" -> new Or( new Str([ new Normal('a'), new Normal('b') ]), new Normal ('a') ) "a(b|a)" -> new Str([ new Normal('a'), new Or( new Normal('b'), new Normal('a') ) ]) "a|b*" -> new Or( new Normal('a'), new ZeroOrMore(new Normal('b')) ) "(a|b)*" -> new ZeroOrMore(new Or( new Normal('a'), new Normal('b') )) ``` ```rust // Box::new() parts are omitted from Or and ZeroOrMore variants for readability "ab*" -> Str(vec![Normal('a'), ZeroOrMore(Normal('b'))]) "(ab)*" -> ZeroOrMore(Str(vec![Normal('a'), Normal('b')])) "ab|a" -> Or(Str(vec![Normal('a'), Normal('b')]), Normal('a')) "a(b|a)" -> Str(vec![Normal('a'), Or(Normal('b'), Normal('a'))]) "a|b*" -> Or(Normal('a'), ZeroOrMore(Normal('b'))) "(a|b)*" -> ZeroOrMore(Or(Normal('a'), Normal('b'))) ``` Some examples: ```haskell "a" -> Normal 'a' "ab" -> Str [ Normal 'a', Normal 'b'] "a.*" -> Str [ Normal 'a', ZeroOrMore Any ] "(a.*)|(bb)" -> Or (Str [Normal a, ZeroOrMore Any]) (Str [Normal 'b', Normal 'b']) ``` ```c "a" -> normal ('a') "ab" -> add (str (normal ('a')), normal ('b')) "a.*" -> add (str (normal ('a')), zeroOrMore (any ())) "(a.*)|(bb)" -> or (add (str (normal ('a')), zeroOrMore (any ())), add (str (normal ('b')), normal (b))) ``` ```csharp "a" -> Reg.normal ('a') "ab" -> Reg.add (Reg.str (Reg.normal ('a')), Reg.normal ('b')) "a.*" -> Reg.add (Reg.str (Reg.normal ('a')), Reg.zeroOrMore (Reg.any ())) "(a.*)|(bb)" -> Reg.or (Reg.add (Reg.str (Reg.normal ('a')), Reg.zeroOrMore (Reg.any ())), Reg.add (Reg.str (Reg.normal ('b')), Reg.normal (b))) ``` ```cpp "a" -> normal ('a') "ab" -> add (str (normal ('a')), normal ('b')) "a.*" -> add (str (normal ('a')), zeroOrMore (any ())) "(a.*)|(bb)" -> orr (add (str (normal ('a')), zeroOrMore (any ())), add (str (normal ('b')), normal (b))) ``` ```python "a" -> Normal('a') "ab" -> Str([Normal('a'), Normal('b')]) "a.*" -> Str([Normal('a'), ZeroOrMore(Any())]) "(a.*)|(bb)" -> Or(Str([Normal('a'), ZeroOrMore(Any())]), Str([Normal('b'), Normal('b')])) ``` ```java "a" -> new Normal('a') "ab" -> new Str([ new Normal('a'), new Normal('b') ]) "a.*" -> new Str([ new Normal('a'), new ZeroOrMore( new Any() ) ]) "(a.*)|(bb)" -> new Or( new Str([ new Normal('a'), new ZeroOrMore( new Any() ) ]), new Str([ new Normal('b'), new Normal('b') ]) ) ``` ```kotlin "a" -> Normal('a') "ab" -> Str([ Normal('a'), Normal('b') ]) "a.*" -> Str([ Normal('a'), ZeroOrMore( Any() ) ]) "(a.*)|(bb)" -> Or( Str([ Normal('a'), ZeroOrMore( Any() ) ]), Str([ Normal('b'), Normal('b') ]) ) ``` ```javascript "a" -> new Normal('a') "ab" -> new Str([ new Normal('a'), new Normal('b') ]) "a.*" -> new Str([ new Normal('a'), new ZeroOrMore(new Any()) ]) "(a.*)|(bb)" -> new Or( new Str([ new Normal('a'), new ZeroOrMore(new Any()) ]) , new Str([ new Normal('b'), new Normal('b') ]) ) ``` ```rust // Box::new() parts are omitted from Or and ZeroOrMore variants for readability "a" -> Normal('a') "ab" -> Str(vec![Normal('a'), Normal('b')]) "a.*" -> Str(vec![Normal('a'), ZeroOrMore(Any)]) "(a.*)|(bb)" -> Or( Str(vec![Normal('a'), ZeroOrMore(Any)]), Str(vec![Normal('b'), Normal('b')]) ) ``` The followings are invalid regexps and the parser should return `Nothing` in Haskell / `0` in C or C++ / `null` in JavaScript or C# / `None` in Python or Rust / `new Void()` in Java/`Void()` in Kotlin: `""`, `")("`, `"*"`, `"a("`, `"()"`, `"a**"`, etc. Feel free to use any parser combinator libraries available on codewars, or implement the parser "from scratch".
algorithms
""" GRAMMAR Root ::= Or Or ::= Str ( '|' Str )? Str ::= ZeroMul+ ZeroMul ::= Term '*'? Term ::= Normal | Any | '(' Or ')' Normal ::= [^()|*.] Any ::= '.' """ def parseRegExp(input): return Parser(input). parse() class InvalidRegex (Exception): pass class Parser (object): def __init__(self, input): self . tokens = list (input) def parse(self): try: ret = self . parse_Or() except InvalidRegex: ret = '' return ret if isinstance(ret, RegExp) and not self . tokens else '' def pop(self): return self . tokens . pop(0) def peek(self): return self . tokens and self . tokens[0] def parse_Or(self): or_ = self . parse_Str() if self . peek() == '|': self . pop() or_ = Or(or_, self . parse_Str()) return or_ def parse_Str(self): seq = [] while self . peek() and self . peek() not in "*)|": ret = self . parse_ZeroMul() seq . append(ret) return ('' if not seq else Str (seq) if len (seq) > 1 else seq[0]) def parse_ZeroMul(self): zm = self . parse_Term() if zm is not None and self . peek() == '*': self . pop() zm = ZeroOrMore(zm) return zm def parse_Term(self): if not self . peek(): raise InvalidRegex() was = self . pop() if was == '(': if not self . peek() or self . peek() == ')': raise InvalidRegex() expr = self . parse_Or() if not self . peek() or self . peek() != ')': raise InvalidRegex() self . pop() elif was == '.': expr = Any() elif was not in "()*|": expr = Normal(was) else: raise ValueError("Wrong code: you shouldn't reach this statment!") return expr
Regular expression parser
5470c635304c127cad000f0d
[ "Parsing", "Functional Programming", "Algorithms" ]
https://www.codewars.com/kata/5470c635304c127cad000f0d
2 kyu
In this Kata, you will be given an array of numbers and a number `n`, and your task will be to determine if `any` array elements, when summed (or taken individually), are divisible by `n`. For example: * `solve([1,3,4,7,6],9) == true`, because `3 + 6` is divisible by `9` * `solve([1,2,3,4,5],10) == true` for similar reasons. * `solve([8,5,3,9],7) == true`, because `7` evenly divides `5 + 9` * but `solve([8,5,3],7) == false`. All numbers in the array will be greater than `0`. More examples in the test cases. Good luck! If you like this Kata, please try: [Simple division](https://www.codewars.com/kata/59ec2d112332430ce9000005) [Divisor harmony](https://www.codewars.com/kata/59bf97cd4f98a8b1cd00007e)
reference
from itertools import combinations def solve(a, n): return any(sum(c) % n == 0 for i in range(len(a)) for c in combinations(a, i + 1))
Sub-array division
59eb64cba954273cd4000099
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/59eb64cba954273cd4000099
6 kyu
## Witamy! You are in Poland and want to order a drink. You need to ask "One beer please": "Jedno piwo poprosze" ``` java Translator.orderingBeers(1) = "Jedno piwo poprosze" ``` But let's say you are really thirsty and want several beers. Then you need to count in Polish. And more difficult, you need to understand the Polish grammar and cases (nominative, genitive, accustative and more). ## The grammar In English, the plural of "beer" is simply "beers", with an "s". In Polish, the plural of "piwo" (nominative singular) is "piw" (genitive plural) or "piwa" (nominative plural). It depends! The rules: * usually the plural is genitive: "piw" * but after the numerals 2, 3, 4, and compound numbers ending with them (e.g. 22, 23, 24), the noun is plural and takes the same case as the numeral, so nominative: "piwa" * and exception to the exception: for 12, 13 and 14, it's the genitive plural again: "piw" (yes, I know, it's crazy!) ## The numbers From 0 to 9: "zero", "jeden", "dwa", "trzy", "cztery", "piec", "szesc" , "siedem", "osiem", "dziewiec" From 10 to 19 it's nearly the same, with "-ascie" at the end: "dziesiec", "jedenascie", "dwanascie", "trzynascie", "czternascie", "pietnascie", "szesnascie", "siedemnascie", "osiemnascie", "dziewietnascie" Tens from 10 to 90 are nearly the same, with "-ziesci" or "ziesiat" at the end: "dziesiec", "dwadziescia", "trzydziesci", "czterdziesci", "piecdziesiat", "szescdziesiat", "siedemdziesiat", "osiemdziesiat", "dziewiecdziesiat" Compound numbers are constructed similarly to English: tens + units. For example, 22 is "dwadziescia dwa". "One" could be male ("Jeden"), female ("Jedna") or neuter ("Jedno"), which is the case for "beer" (piwo). But all other numbers are invariant, even if ending with "jeden". Ah, and by the way, if you don't want to drink alcohol (so no beers are ordered), ask for mineral water instead: "Woda mineralna". Note: if the number of beers is outside your (limited) Polish knowledge (0-99), raise an error! --- More about the crazy polish grammar: https://en.wikipedia.org/wiki/Polish_grammar
algorithms
def ordering_beers(beers): assert 0 <= beers < 100 units = ["", "jeden", "dwa", "trzy", "cztery", "piec", "szesc", "siedem", "osiem", "dziewiec", "dziesiec", "jedenascie", "dwanascie", "trzynascie", "czternascie", "pietnascie", "szesnascie", "siedemnascie", "osiemnascie", "dziewietnascie"] tens = ["", "", "dwadziescia", "trzydziesci", "czterdziesci", "piecdziesiat", "szescdziesiat", "siedemdziesiat", "osiemdziesiat", "dziewiecdziesiat"] if beers == 0: order = "Woda mineralna" elif beers == 1: order = "Jedno piwo" elif beers < 20: order = units[beers] + " piw" else: order = tens[beers / / 10] + " " * bool(beers % 10) + units[beers % 10] + " piw" if beers % 10 in [2, 3, 4] and beers not in [12, 13, 14]: order += "a" return order . capitalize() + " poprosze"
Ordering Beers in Poland
54f4e56e00ecc43c6d000220
[ "Algorithms" ]
https://www.codewars.com/kata/54f4e56e00ecc43c6d000220
5 kyu
Given an **unsorted** array of 3 positive integers ```[ n1, n2, n3 ]```, determine if it is possible to form a [Pythagorean Triple](https://en.wikipedia.org/wiki/Pythagorean_triple) using those 3 integers. A [Pythagorean Triple](https://en.wikipedia.org/wiki/Pythagorean_triple) consists of arranging 3 integers, such that: **a<sup>2</sup> + b<sup>2</sup> = c<sup>2</sup>** ### Examples [5, 3, 4] : it **is possible** to form a Pythagorean Triple using these 3 integers: 3<sup>2</sup> + 4<sup>2</sup> = 5<sup>2</sup> [3, 4, 5] : it **is possible** to form a Pythagorean Triple using these 3 integers: 3<sup>2</sup> + 4<sup>2</sup> = 5<sup>2</sup> [13, 12, 5] : it **is possible** to form a Pythagorean Triple using these 3 integers: 5<sup>2</sup> + 12<sup>2</sup> = 13<sup>2</sup> [100, 3, 999] : it **is NOT possible** to form a Pythagorean Triple using these 3 integers - no matter how you arrange them, you will never find a way to satisfy the equation a<sup>2</sup> + b<sup>2</sup> = c<sup>2</sup> ### Return Values - For Python: return `True` or `False` - For JavaScript: return `true` or `false` - Other languages: return `1` or `0` or refer to Sample Tests.
reference
def pythagorean_triple(integers): a, b, c = sorted(integers) return a * a + b * b == c * c
Pythagorean Triple
5951d30ce99cf2467e000013
[ "Algebra", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5951d30ce99cf2467e000013
8 kyu
A [Power Law](https://en.wikipedia.org/wiki/Power_law) distribution occurs whenever "a relative change in one quantity results in a proportional relative change in the other quantity." For example, if *y* = 120 when *x* = 1 and *y* = 60 when *x* = 2 (i.e. *y* halves whenever *x* doubles) then when *x* = 4, *y* = 30 and when *x* = 8, *y* = 15. Therefore, if I give you any pair of co-ordinates (x1,y1) and (x2,y2) in a power law distribution, you can plot the entire rest of the distribution and tell me the value of *y* for any other value of *x*. Given a pair of co-ordinates (x1,y1) and (x2,y2) and another x co-ordinate *x3*, return the value of *y3* ``` powerLaw(x1y1, x2y2, x3) e.g. powerLaw([1,120], [2,60], 4) - when x = 1, y = 120 - when x = 2, y = 60 - therefore whenever x doubles, y halves - therefore when x = 4, y = 60 * 0.5 - therfore solution = 30 ``` (x1,y1) and (x2,y2) will be given as arrays. Answer should be to the nearest integer, but random tests will give you leeway of 1% of the reference solution to account for possible discrepancies from different methods.
reference
from math import log def power_law(p1, p2, x3): (x1, y1), (x2, y2) = p1, p2 x1 += 1e-9 y1 += 1e-9 return round(y1 * (y2 / y1) * * log(x3 / x1, x2 / x1))
Power Laws
59b6ae2e5227dd0fbc000005
[ "Fundamentals" ]
https://www.codewars.com/kata/59b6ae2e5227dd0fbc000005
6 kyu
It's 9 time! I want to count from 1 to n. How many times will I use a '9'? 9, 19, 91.. will contribute one '9' each, 99, 199, 919.. wil contribute two '9's each...etc **Note:** `n` will always be a positive integer. ### Examples (input -> output) ``` 8 -> 0 9 -> 1 10 -> 1 98 -> 18 100 -> 20 ```
algorithms
def count_nines(n): num = 0 l = len(str(n)) i = l while i > 0: k = 10 * * i m = 10 * * (i - 1) num += n / / k * (i * m) n = n % k if n >= k - m: num += n % m + 1 i -= 1 return int(num)
count '9's from 1 to n
55143152820d22cdf00001bb
[ "Puzzles", "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/55143152820d22cdf00001bb
5 kyu
A rectangle is can be defined by two factors: height and width. Its area is defined as the multiplication of the two: height * width. Its perimeter is the sum of its four edges: height + height + width + width. It is possible to create rectangles of the same area but different perimeters. For example, given an area of 45, the possible heights, widths and resultant perimeters would be: (1, 45) = 92 (9, 5) = 28 (15, 3) = 36 Note that (6, 7.5) has an area of 45 too, but is discarded in this kata because its width is non integral. The task is to write a function that, given an area as a positive integer, returns the smallest perimeter possible of a rectangle with integral side lengths. ### Input range: ~~~if-not:cpp 1 <= area <= 5 x 10 ^ 10 ~~~ ~~~if:cpp 1 <= area <= 982451653 ~~~
algorithms
from math import sqrt def minimum_perimeter(area): a, b = 0, area while a <= sqrt(area): a += 1 if a * b == area: p = 2 * (a + b) if not area % (a + 1): b = area / (a + 1) return p
Minimum Perimeter of a Rectangle
5826f54cc60c7e5266000baf
[ "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/5826f54cc60c7e5266000baf
7 kyu
Assume you are creating a webshop and you would like to help the user in the search. You have products with brands, prices and name. You have the history of opened products (the most recently opened being the first item). Your task is to create a list of brands ordered by popularity, if two brands have the same popularity level then choose the one which was opened last from the two and second the other one. Product popularity is calculated from the history. If a product is more times in the history than it is more popular. Your function will have one parameter which will be always an array/list of object. example product: { name: "Phone", price: 25, brand: "Fake brand" }
algorithms
from collections import Counter def sorted_brands(history): brands = [x['brand'] for x in history] counter = Counter(brands) return sorted(set(brands), key=lambda x: (- counter[x], brands . index(x)))
Personalized brand list
57cb12aa40e3020bb4001d2e
[ "Algorithms" ]
https://www.codewars.com/kata/57cb12aa40e3020bb4001d2e
6 kyu
Just another day in the world of Minecraft, Steve is working on his new project -- building a beacon pyramid in front of his house. ![Beacon pyramid](http://www.minecraft101.net/reference/images/beacon_pyramid_thb.jpg) Steve has already obtained the beacon (the glass wrapped blue thingy on the top), he just needs to build the pyramid. Each level of the pyramid is built using one of the following four kinds of block: gold, diamond, emerald, and iron. Since these four kinds of blocks are relatively hard to collect, Steve needs to know exactly how many of each kind is required to build a pyramid of level N. Assume that the top level of the pyramid uses gold blocks, the second level uses diamond blocks, the third level uses emerald blocks, the fourth level uses iron blocks, and the fifth level uses gold blocks, etc. (if you are a Minecraft player, you know it's not neccessary the right way to build the pyramid. Let's just assume it is for the sake of this kata ;-)) Implement a function that takes one argument which is the number of levels of the pyramid, and returns an object of the form: `{total: 9, gold: 9, diamond: 0, emerald: 0, iron: 0}`. --- To all the Minecraft players out there: feel free to expand this series or let me know if you have any ideas related to Minecraft that can be turned into codewars puzzles. Some ideas I have that might potentially be turned into katas: * distance traveled in real world vs. in Nether * shortest path problems related to mining diamonds/gold/goodies that appears in different levels under ground * growth of animal population from breeding * redstone stuff?! If you do end up expanding this series, please send me a link of your kata so I can check it out and include a link to your kata here :-) * [Minecraft Series #2: Minimum amount of fuel needed to get some iron ingots](https://www.codewars.com/kata/minecraft-series-number-2-minimum-amount-of-fuel-needed-to-get-some-iron-ingots/ruby) * [Minecraft Series #3: Lava is amazing! ](https://www.codewars.com/kata/583a23d40cf946ec380002c2) * [Minecraft Series #4: Lava is amazing, however...](https://www.codewars.com/kata/583a6b0b171f3a3c3f0003e3)
algorithms
def blocks_to_collect(level): answer = { 'total': sum([(i + 3 + i) * * 2 for i in range(level)]), 'gold': sum([(i + 3 + i) * * 2 for i in range(0, level, 4)]), 'diamond': sum([(i + 3 + i) * * 2 for i in range(1, level, 4)]), 'emerald': sum([(i + 3 + i) * * 2 for i in range(2, level, 4)]), 'iron': sum([(i + 3 + i) * * 2 for i in range(3, level, 4)]), } return answer
[Minecraft Series #1] Steve wants to build a beacon pyramid
5839cd780426f5d0ec00009a
[ "Algorithms" ]
https://www.codewars.com/kata/5839cd780426f5d0ec00009a
6 kyu
German mathematician Christian Goldbach (1690-1764) [conjectured](https://en.wikipedia.org/wiki/Goldbach%27s_conjecture) that every even number greater than 2 can be represented by the sum of two prime numbers. For example, `10` can be represented as `3+7` or `5+5`. Your job is to make the function return a list containing all unique possible representations of `n` in an increasing order if `n` is an even integer; if `n` is odd, return an empty list. Hence, the first addend must always be less than or equal to the second to avoid duplicates. Constraints : `2 < n < 32000` and `n` is even ## Examples ``` 26 --> ['3+23', '7+19', '13+13'] 100 --> ['3+97', '11+89', '17+83', '29+71', '41+59', '47+53'] 7 --> [] ```
algorithms
from gmpy2 import is_prime, next_prime from functools import lru_cache is_p = lru_cache(maxsize=None)(is_prime) next_p = lru_cache(maxsize=None)(next_prime) def gen(n): prime, limit = 2, n >> 1 while prime <= limit: yield prime, n - prime prime = next_p(prime) def goldbach_partitions(n): return [] if n & 1 else [f" { p } + { q } " for p, q in gen(n) if is_p(q)]
Goldbach’s Conjecture
578dec07deaed9b17d0001b8
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/578dec07deaed9b17d0001b8
6 kyu
In this Kata, you will be given two numbers, `a` and `b`, and your task is to determine if the first number `a` is divisible by `all` the prime factors of the second number `b`. For example: `solve(15,12) = False` because `15` is not divisible by all the prime factors of `12` (which include`2`). See test cases for more examples. Good luck! If you like this Kata, please try: [Sub-array division](https://www.codewars.com/kata/59eb64cba954273cd4000099) [Divisor harmony](https://www.codewars.com/kata/59bf97cd4f98a8b1cd00007e)
reference
import fractions def solve(a, b): c = fractions . gcd(a, b) while c > 1: b / /= c c = fractions . gcd(a, b) return b == 1
Simple division
59ec2d112332430ce9000005
[ "Fundamentals" ]
https://www.codewars.com/kata/59ec2d112332430ce9000005
6 kyu
The triangular numbers, ```Tn```, may be obtained by this formula: ``` T(n) = n * (n + 1) / 2 ``` We select, for example, the first ```5 (n terms)``` consecutive terms of this sequence. They will be: ```1, 3, 6, 10 and 15``` Now we want to obtain, again for example, the first ```8 (m terms)``` consecutive multiples to all of these five triangular numbers. The least common multiple of them will be, ```30```, so the first eight multiple terms (for the sequence of the above five triangular numbers) will be: ```30, 60, 90, 120, 150, 180, 210 and 240``` Finally the sum of all these multiples will be: ```30 + 60 + 90 + 120 + 150 + 180 + 210 + 240 = 1080``` We want the function ```sum_mult_triangnum()``` that may calculate this sum with different values of n and m terms. Let's see some cases: ```python n = 5 m = 8 sum_mult_triangnum(n, m) = 1080 ``` ```ruby n = 5 m = 8 sum_mult_triangnum(n, m) = 1080 ``` Another case: ```python n = 7 m = 10 sum_mult_triangnum(n, m) = 23100 ``` ```ruby n = 7 m = 10 sum_mult_triangnum(n, m) = 23100 ``` The values of ```n``` and ```m``` will be always integer values higher than ```2```. Enjoy it!!
reference
import math def sum_mult_triangnum(n, m): LCM = math . lcm(* [int(i * (i + 1) / 2) for i in range(1, n + 1)]) return sum(i * LCM for i in range(1, m + 1))
Get the Sum of Multiples of Triangular Numbers
566afbfc8595f2e751000040
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/566afbfc8595f2e751000040
6 kyu
In this example you need to implement a function that sort a list of integers based on it's binary representation. The rules are simple: 1. sort the list based on the amount of 1's in the binary representation of each number. 2. if two numbers have the same amount of 1's, the shorter string goes first. (ex: "11" goes before "101" when sorting 3 and 5 respectively) 3. if the strings have the same length, lower decimal number goes first. (ex: 21 = "10101" and 25 = "11001", then 21 goes first as is lower) Examples: - Input: **[1,15,5,7,3]** - ( in binary strings is: `["1", "1111", "101", "111", "11"]`) - Output: **[15, 7, 3, 5, 1]** - (and after _sortByBinaryOnes_ is: `["1111", "111", "11", "101", "1"]`)
algorithms
def sortByBinaryOnes(a): return sorted(a, key=lambda k: (- bin(k). count('1'), k))
Sort by binary ones
59eb28fb0a2bffafbb0000d6
[ "Arrays", "Lists", "Algorithms", "Sorting", "Binary", "Bits" ]
https://www.codewars.com/kata/59eb28fb0a2bffafbb0000d6
7 kyu
Make your strings more nerdy: Replace all 'a'/'A' with 4, 'e'/'E' with 3 and 'l' with 1 e.g. "Fundamentals" --> "Fund4m3nt41s" <!-- C# documentation --> ```if:csharp <h1>Documentation:</h1> <h2>Kata.Nerdify Method (String)</h2> Nerdifies a string. Returns a copy of the original string with 'a'/'A' characters replaced with '4', 'e'/'E' characters replaced with '3', and 'l' characters replaced with '1'. <span style="font-size:20px">Syntax</span> <div style="margin-top:-10px;padding:1px;background-color:Grey;position:relative;left:20px;width:600px;"> <div style="background-color:White;color:Black;border:1px;display:block;padding:10px;padding-left:18px;font-family:Consolas,Courier,monospace;"> <span style="color:Blue;">public</span> <span style="color:Blue;">static</span> <span style="color:Blue;">string</span> Nerdify(</br> <span style="position:relative;left:62px;">string str</span></br>   ) </div> </div> </br> <div style="position:relative;left:20px;"> <strong>Parameters</strong> </br> <i>str</i> </br> <span style="position:relative;left:50px;">Type: <a href="https://msdn.microsoft.com/en-us/library/system.string(v=vs.110).aspx">System.String</a></span></br> <span style="position:relative;left:50px;">The string to be nerdified.</span> </br></br> <strong>Return Value</strong> </br> <span>Type: <a href="https://msdn.microsoft.com/en-us/library/system.string(v=vs.110).aspx">System.String</a></span></br> The nerdified string. </div> </br></br> <span style="font-size:20px">Exceptions</span> </br></br> <div style="position:relative;left:20px;"> <table style="width:350px;border: 1px solid grey;"> <th style="background-color:#ABABAB;color:#424242;font-weight:bolder;font-size:17px;border: 1px solid grey;">Exception</th> <th style="background-color:#ABABAB;color:#424242;font-weight:bolder;font-size:17px;border: 1px solid grey;">Condition</th> <tr style="background-color:White;color:Black;"> <td style="border: 1px solid grey;"><a href="color:https://msdn.microsoft.com/en-us/library/system.argumentnullexception(v=vs.110).aspx" style="color:#3390B1;">ArgumentNullException</a></td> <td style="border: 1px solid grey;"><i>str</i> is <b>null</b>.</td> </tr> </table> </div> ``` <!-- end C# documentation -->
reference
def nerdify(txt): return txt . translate(str . maketrans("aAeEl", "44331"))
Ch4113ng3
59e9f404fc3c49ab24000112
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/59e9f404fc3c49ab24000112
7 kyu
# Fourier transformations are hard. Fouriest transformations are harder. [<img src="http://smbc-comics.com/comics/20130201.gif">](http://smbc-comics.com/comic/2013-02-01) This Kata is based on the SMBC Comic on fourier transformations (2874). (click on the comic to go to the website) A fourier transformation on a number is one that converts the number to a base in which it has more `4`s ( `10` in base `6` is `14`, which has `1` four as opposed to none, hence, fourier in base `6` ). A number's fouriest transformation converts it to the base in which it has the most `4`s. For example: `35353` is the fouriest in base `6`: `431401`. This kata requires you to create a method `fouriest` that takes a number and makes it the fouriest, telling us in which base this happened, as follows: ```ruby fouriest(number) -> "#{number} is the fouriest (#{fouriest_representation}) in base #{base}" ``` ```haskell fouriest number -> ( ${fouriestRepresentation}, #{base} ) ``` ```javascript fouriest number -> [ ${fouriestRepresentation}, #{base} ] ``` ```python fouriest(number) -> "{number} is the fouriest ({fouriest_representation}) in base {base}" ``` ## Important notes * For this kata we don't care about digits greater than `9` ( only `0` to `9` ), so we will represent all digits greater than `9` as `'x'`: `10` in base `11` is `'x'`, `119` in base `20` is `'5x'`, `118` in base `20` is also `'5x'` * When a number has several fouriest representations, we want the one with the LOWEST base ```if:haskell,javascript * Numbers below `9` will not be tested ``` ```if:javascript * The native BigInt is used as input: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt">link</a> ``` ## Examples ```ruby "30 is the fouriest (42) in base 7" "15 is the fouriest (14) in base 11" ``` ```haskell 30 -> ("42",7) 15 -> ("14",11) ``` ```javascript "30" -> ["42",7] "15" -> ["14",11] ``` ```python "30 is the fouriest (42) in base 7" "15 is the fouriest (14) in base 11" ```
algorithms
def transform(num, base): digits = [] while num > 0: num, remainder = divmod(num, base) digits . append(remainder if remainder < 10 else "x") return digits def fouriest(i): max_fours, base, best = 0, 5, [None, None] while i >= base * * (max_fours): digits = transform(i, base) if digits . count(4) > max_fours: max_fours = digits . count(4) best = base, "" . join(map(str, digits[:: - 1])) base += 1 base, transformed = best return "%s is the fouriest (%s) in base %s" % (i, transformed, base)
Fouriest transformation
59e1254d0863c7808d0000ef
[ "Algorithms" ]
https://www.codewars.com/kata/59e1254d0863c7808d0000ef
5 kyu
Based on the well known ['Eight Queens' problem](https://en.wikipedia.org/wiki/Eight_queens_puzzle). #### Summary Your challenge is to place N queens on a chess board such that none of the queens are attacking each other. #### Details A standard 8x8 chess board has its rows (aka ranks) labelled 1-8 from bottom to top, and its columns (aka files) labelled a-h from left to right. Any square can be denoted by a combination of letter and number. For example, the top left square is a8. A queen may attack any square on its rank or file. It may also attack any square diagonally. In this kata, chessboard may have any size from 1 to 10. Columns are marked with letters a-j, and rows with single digit from 1 to 0 (first row is marked with 1, ninth row is marked with 9, and tenth row is marked with 0, so `a1` denotes bottom left field of the chessboard, and `j0` - top right field on a 10x10 board). You will be given the position of one queen on the board (e.g. `'c3'`). Your challenge is to compute the position of the remaining queens and return the full solution (including the original input) as a comma-separated string (e.g. `'d8,a7,e6,h5,b4,g3,c2,f1'`). Fields do not have to be sorted in any particular way, but you have to adhere to above format (lowercase letters, no spaces, fields separated with commas). Note that there may be multiple valid solutions for a given starting position. Your function only needs to produce (any) one of these. All given starting positions produce valid solutions. If you wish to write more tests, the validity of a solution may be checked using preloaded function (see sample tests). Hint: check the wiki article for the various algorithms that are applicable to this problem. ---- Next steps: - [N queens problem (with no mandatory queen position)](https://www.codewars.com/kata/52cdc1b015db27c484000031) - [N queens problem (with one mandatory queen position) - challenge version](https://www.codewars.com/kata/5985ea20695be6079e000003)
games
def queens(fixQ, S): def areClashing(i, x): j, y = qs[i], qs[x] return j == y or abs(i - x) == abs(j - y) def dfs(i=0): if i == iQ: return dfs(i + 1) if i == len(qs): return 1 for y in range(S): qs[i] = y if (not any(areClashing(i, ii) for ii in range(i)) and (iQ < i or not areClashing(i, iQ)) and dfs(i + 1)): return 1 iQ, yQ = ord(fixQ[0]) - 97, (int(fixQ[1]) or 10) - 1 qs = [yQ if i == iQ else 0 for i in range(S)] dfs() return ',' . join(f" { chr ( x + 97 ) }{ str ( y + 1 )[ - 1 ] } " for x, y in enumerate(qs))
N queens puzzle (with one mandatory queen position)
561bed6a31daa8df7400000e
[ "Algorithms", "Combinatorics", "Puzzles" ]
https://www.codewars.com/kata/561bed6a31daa8df7400000e
4 kyu
You live in a communal house. Each night, one room's residents are required to clean the dayroom. Your task is to make a random rota for the entire week. Write a function that takes a list/array of the current occupied rooms in the house, and returns a list of 7 random rooms. If the number of occupied rooms is equal to or bigger than 7, duplicates are not allowed. If the number is less than 7, duplicates are allowed. Examples: ``` rota(["One", "Two", "Three", "Four", "Five", "Six", "Seven"]) ``` Would output ``` [ 'Three', 'Six', 'Four', 'Five', 'Two', 'One', 'Seven' ] ``` And `rota(["One", "Two", "Three"])` would output ``` [ 'One', 'Three', 'Two', 'One', 'Two', 'Three', 'One' ] ```
reference
import random def rota(rooms): if len(rooms) >= 7: return random . sample(rooms, 7) return [random . choice(rooms) for i in range(7)]
Create a House Cleaning Rota
56c89644b2f1981874000046
[ "Fundamentals" ]
https://www.codewars.com/kata/56c89644b2f1981874000046
6 kyu
Seven is a hungry number and its favourite food is number 9. Whenever it spots 9 through the hoops of 8, it eats it! Well, not anymore, because you are going to help the 9 by locating that particular sequence (7,8,9) in an array of digits and tell 7 to come after 9 instead. Seven "ate" nine, no more! (If 9 is not in danger, just return the same array)
reference
import re def hungry_seven(arr): ss, s = '', '' . join(map(str, arr)) while ss != s: ss, s = s, re . sub(r'(7+)(89)', r'\2\1', s) return list(map(int, s))
Seven "ate" nine!
59e61c577905df540000016b
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/59e61c577905df540000016b
6 kyu
The pizza store wants to know how long each order will take. They know: - Prepping a pizza takes 3 mins - Cook a pizza takes 10 mins - Every salad takes 3 mins to make - Every appetizer takes 5 mins to make - There are 2 pizza ovens - 5 pizzas can fit in a oven - Prepping for a pizza must be done before it can be put in the oven - There are two pizza chefs and one chef for appitizers and salads combined - The two pizza chefs can work on the same pizza Write a function, order, which will tell the company how much time the order will take. See example tests for details.
games
from math import ceil def order(pizzas, salads, appetizers): tp = 3 * pizzas / 2 + 10 * math . ceil(pizzas / 10) ts = 3 * salads + 5 * appetizers return max(tp, ts)
How long each order will take
59e255c07997cb248500008c
[ "Puzzles" ]
https://www.codewars.com/kata/59e255c07997cb248500008c
6 kyu
<img src="http://bestanimations.com/Science/Gears/loadinggears/loading-gears-animation-6-4.gif"/> # Kata Task You are given a list of cogs in a <a href ="https://en.wikipedia.org/wiki/Gear_train">gear train</a> Each element represents the number of teeth of that cog e.g. `[100, 50, 25]` means * 1st cog has 100 teeth * 2nd cog has 50 teeth * 3rd cog has 25 teeth If the ``nth`` cog rotates clockwise at 1 RPM what is the RPM of the cogs at each end of the gear train? **Notes** * no two cogs share the same shaft * return an array whose two elements are RPM of the first and last cogs respectively * use negative numbers for anti-clockwise rotation * for convenience `n` is zero-based * For C and NASM coders, the returned array will be `free`'d. --- Series: * <a href=https://www.codewars.com/kata/cogs>Cogs</a> * Cogs 2
reference
def cog_RPM(cogs, n): return [ cogs[n] / cogs[0] * (- 1 if n % 2 else 1), cogs[n] / cogs[- 1] * (1 if (len(cogs) - n) % 2 else - 1), ]
Cogs 2
59e72bdcfc3c4974190000d9
[ "Fundamentals" ]
https://www.codewars.com/kata/59e72bdcfc3c4974190000d9
7 kyu
Take a look at this [pirate game](https://youtu.be/Mc6VA7Q1vXQ). Give Amaro an array to confirm his logic for the next time, when the number of pirates changes. Keep in mind that each time the pirates find a treasure, the amount of gold equals to the ```number of pirates * 20```. **Example:** If number of pirates is 2, including Amaro, then array = ```[40, 0]```, So he can keep all of the gold to himself. If number of pirates is 3, including Amaro, then array = ```[59, 0, 1]```, and 59 gold is his for the taking. If number of pirates is 4, including Amaro, then array = ```[79, 0, 1, 0]```, and 79 gold is his to take. If number of pirates is 5, including Amaro, then array = ```[98, 0, 1, 0, 1]```, and 98 gold is his for the taking. ...
reference
def amaro_plan(pirate_num): return [1 + 39 * pirate_num / / 2, * (c % 2 for c in range(pirate_num - 1))]
Pirate Code
59e77930233243a7b7000026
[ "Puzzles", "Games", "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/59e77930233243a7b7000026
7 kyu
Background ---------- In another dimension, there exist two immortal brothers: Solomon and Goromon. As sworn loyal subjects to the time elemental, Chronixus, both Solomon and Goromon were granted the power to create temporal folds. By sliding through these temporal folds, one can gain entry to parallel dimensions where time moves relatively faster or slower. Goromon grew dissatisfied and one day betrayed Chronixus by stealing the Temporal Crystal, an artifact used to maintain the time continuum. Chronixus summoned Solomon and gave him the task of tracking down Goromon and retrieving the Temporal Crystal. Using a map given to Solomon by Chronixus, you must find Goromon's precise location. Mission Details --------------- The map is represented as a 2D array. See the example below: ```javascript let mapExample = [[1,3,5],[2,0,10],[-3,1,4],[4,2,4],[1,1,5],[-3,0,12],[2,1,12],[-2,2,6]]; ``` ```haskell mapExample = [(1,3,5),(2,0,10),(-3,1,4),(4,2,4),(1,1,5),(-3,0,12),(2,1,12),(-2,2,6)] ``` ```go mapExample := [][3]int{{1,3,5},{2,0,10},{-3,1,4},{4,2,4},{1,1,5},{-3,0,12},{2,1,12},{-2,2,6}} ``` ```python map_example = [[1,3,5],[2,0,10],[-3,1,4],[4,2,4],[1,1,5],[-3,0,12],[2,1,12],[-2,2,6]] ``` ```elixir map_example = [{1,3,5},{2,0,10},{-3,1,4},{4,2,4},{1,1,5},{-3,0,12},{2,1,12},{-2,2,6}] ``` ```csharp var map_example = new int[][]{new[]{1,3,5},new[]{2,0,10},new[]{-3,1,4},new[]{4,2,4},new[]{1,1,5},new[]{-3,0,12},new[]{2,1,12},new[]{-2,2,6}}; ``` ```c int map_example[8][3] = {{1,3,5},{2,0,10},{-3,1,4},{4,2,4},{1,1,5},{-3,0,12},{2,1,12},{-2,2,6}}; ``` ```kotlin // In Kotlin, the input is of type Array<Triple<Int,Int,Int>> val mapExample = arrayOf(Triple(1,3,5),Triple(2,0,10),Triple(-3,1,4),Triple(4,2,4),Triple(1,1,5),Triple(-3,0,12),Triple(2,1,12),Triple(-2,2,6)) ``` ```rust // In Rust, the input is of type Vec<(i32, i32, i32)> let map_example = vec![(1,3,5),(2,0,10),(-3,1,4),(4,2,4),(1,1,5),(-3,0,12),(2,1,12),(-2,2,6)]; ``` ```julia mapexample = [1 3 5; 2 0 10; -3 1 4; 4 2 4; 1 1 5; -3 0 12; 2 1 12; -2 2 6] ``` Here are what the values of each subarray represent: - **Time Dilation:** With each additional layer of time dilation entered, time slows by a factor of `2`. At layer `0`, time passes normally. At layer `1`, time passes at half the rate of layer `0`. At layer `2`, time passes at half the rate of layer `1`, and therefore one quarter the rate of layer `0`. - **Directions** are as follow: `0 = North, 1 = East, 2 = South, 3 = West` - **Distance Traveled:** This represents the distance traveled relative to the current time dilation layer. See below: ``` The following are equivalent distances (all equal a Standard Distance of 100): Layer: 0, Distance: 100 Layer: 1, Distance: 50 Layer: 2, Distance: 25 ``` For the `mapExample` above: ``` mapExample[0] -> [1,3,5] 1 represents the level shift of time dilation 3 represents the direction 5 represents the distance traveled relative to the current time dilation layer Solomon's new location becomes [-10,0] mapExample[1] -> [2,0,10] At this point, Solomon has shifted 2 layers deeper. He is now at time dilation layer 3. Solomon moves North a Standard Distance of 80. Solomon's new location becomes [-10,80] mapExample[2] -> [-3,1,4] At this point, Solomon has shifted out 3 layers. He is now at time dilation layer 0. Solomon moves East a Standard Distance of 4. Solomon's new location becomes [-6,80] ``` Your function should return Goromon's `[x,y]` coordinates. For `mapExample`, the correct output is `[346,40]`. Additional Technical Details ---------------------------- - Inputs are always valid. - Solomon begins his quest at time dilation level `0`, at `[x,y]` coordinates `[0,0]`. - Time dilation level at any point will always be `0` or greater. - Standard Distance is the distance at time dilation level `0`. - For given distance `d` for each value in the array: `d >= 0`. - Do not mutate the input **Note from the author:** I made up this story for the purpose of this kata. Any similarities to any fictitious persons or events are purely coincidental. If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored).
reference
def solomons_quest(arr): pos, lvl = [0, 0], 0 for dilat, dir, dist in arr: lvl += dilat pos[dir in [0, 2]] += dist * 2 * * lvl * (- 1) * * (dir in [2, 3]) return pos
Solomon's Quest for the Temporal Crystal
59d7c910f703c460a2000034
[ "Fundamentals" ]
https://www.codewars.com/kata/59d7c910f703c460a2000034
6 kyu
## Description Give you the number of year and month, make a monthly calendar board. ## Task Complete function `calendar()` that accepts two arguments `year` and `month`. Returns a calendar board of this month. Note: The first line is centered(see following example). ## Rules & Examples An example of `calendar(2016,8)` The first line show the Year and Month. The format should be centered. The second line show Sunday to Saturday, each one shorted to three uppercase chars, separated by spaces. The following line is days of this month. The first digit of day should under the second char of the week title. ``` 2016 August SUN MON TUE WED THU FRI SAT 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ``` An example of `calendar(2016,2)` ``` 2016 February <----- This line should be centered. SUN MON TUE WED THU FRI SAT pad 7 spaces on the left 1 2 3 4 5 6 Don't need to pad on the right 7 8 9 10 11 12 13 If it can not be symmetrical 14 15 16 17 18 19 20 The left side can be 1 space 21 22 23 24 25 26 27 less than the right side. 28 29 <----- Don't forget the leap year ```
games
from calendar import TextCalendar, month_name class MyTextCalender (TextCalendar): def formatmonthname(self, theyear, themonth, width, _=True): return f" { f' { theyear } { month_name [ themonth ]} ' : ^ { width }} " def formatweekheader(self, _): return "SUN MON TUE WED THU FRI SAT" def formatday(self, day, _, width): return (f" { day : < 2 } " if day else ''). center(width) def calendar(year, month): return MyTextCalender(6). formatmonth(year, month, w=3). rstrip('\n')
T.T.T.56: Make a monthly calendar board
57c671eaf8392d75b9000033
[ "Puzzles", "Games", "ASCII Art" ]
https://www.codewars.com/kata/57c671eaf8392d75b9000033
5 kyu
## Description Given a string representing an integer, return a string with every sequence of ascending or descending digits reversed. Examples: ``` 123456 ---> 654321 // ascending sequence 123456 654321 ---> 123456 // descending sequence 654321 135246 ---> 531642 // ascending sequence 135, ascending sequence 246 642531 ---> 246135 // descending sequence 642, descending sequence 531 ``` Such sequences are not required to be strictly ascending / descending: ``` 12333 ---> 33321 // ascending sequence 12333 66654 ---> 45666 // descending sequence 66654 133555224466 ---> 555331664422 // ascending sequence 133555, ascending sequence 224466 ``` If a digit (or several of the same consecutive digits) is at the junction part of ascending and descending sequence, it should belong to the left part of the junction: ``` 12321 ---> 32112 digit 3 may be part of an ascending order(123) It can also be a part of a descending order(321) 135642 ---> 653124 digit 6 may be part of an ascending order(1356) It can also be a part of a descending order(642) 13555432 ---> 55531234 consecutive digits 555 may be part of an ascending order(13555) It can also be a part of a descending order(555432) ``` If the number is a negative number, the symbol `-` does not reverse: ``` -123 ---> -321 -123321 ---> -332112 ``` After reverse, if the digit 0 is in the first place (ignoring the sign), it should be removed: ``` 420135 ---> 024531 ---> 24531 -520025 ---> -002552 ---> -2552 ``` ## Task Complete function `reverseNumber()` that accepts a arguments `n`(given by string format). Returns the number that reverse in accordance with the rules(string format).
games
def reverse_number(n): sub, var, s = '', 0, '-' * (n[0] == '-') for c in n . strip('-'): if len(sub) < 2: sub += c if len(sub) == 2: var = (sub[1] > sub[0]) - (sub[1] < sub[0]) continue new_var = (c > sub[- 1]) - (c < sub[- 1]) if var in (- 1, 1) and var == - new_var: s += sub[:: - 1] sub = '' sub += c if new_var in (- 1, 1): var = new_var return str(int(s + sub[:: - 1]))
T.T.T.57: Reverse a number
57c786e858da9e5ed20000ea
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/57c786e858da9e5ed20000ea
5 kyu
## Description You find a treasure map that record the location of the hidden treasure: ``` [ ["X" ,"W3","E2","S3","S4"], ["S1","E1","N1","S2","W1"], ["S2","E1","N2","S1","N3"], ["N1","X" ,"S2","E1","W4"], ["X" ,"E3","X" ,"N2","W4"] ] ``` `"X"` is the place where the treasure is likely to be buried. But there are more than one `"X"`, Which is the right place? We need to know the correct way to read the map: We always start from the center of the map(You can assume that the width and height of the map are odd). `N,S,E,W` means `North, South, East and West`. Like most maps: ``` North | West --+-- East | South ``` The number that behind N,S,W,E is how many step that we should move. In the map above, the center of map is `"N2"`, so we need move to North with 2 step, and then we got a code `"E2"`, so we move to East with 2 step, and so on.. ``` "N2"-->"E2"-->"S4"-->"W4"-->"X" ``` Ok, after some moves, we got the `"X"`, we need return the `array index` of this `"X"` ```javascript [4,0] ``` ```python (4, 0) ``` Sometimes, the treasure map is fake. It does not record the correct information of the treasure, and we should return `null`/`None`. For example: ``` [ ["X" ,"W3","E2","S3","S4"], ["S1","E1","N1","S2","W1"], ["S2","E1","N4","S1","N3"], ["N1","X" ,"S2","E1","W4"], ["X" ,"E3","X" ,"N2","W4"] ] The code at center("N4") is invalid. ``` Or like this: ``` [ ["X" ,"W3","E2","S3","S2"], ["S1","E1","N1","S2","W1"], ["S2","E1","N2","S1","W2"], ["N1","X" ,"S2","E1","W4"], ["X" ,"E3","X" ,"N2","E4"] ] Path "N2"-->"E2"-->"S2"-->"W2" into an infinite loop ``` ## Task ```if:javascript Complete function `findX` that accepts an argument `m`. Returns the result in accordance with the rules above. ``` ```if:python Complete function `find_x` that accepts an argument `treasure_map`. Returns the result in accordance with the rules above. ```
games
DIRS = dict(zip('NSEW', ((- 1, 0), (1, 0), (0, 1), (0, - 1)))) def find_x(bd): X, Y = len(bd), bd and len(bd[0]) x, y = X >> 1, Y >> 1 bd = list(map(list, bd)) while 0 <= x < X and 0 <= y < Y and (d := bd[x][y]) != 'Z': if d == 'X': return x, y bd[x][y] = 'Z' (dx, dy), n = DIRS[d[0]], int(d[1:]) x, y = x + n * dx, y + n * dy
#8: Treasure Map
57d63b45ec1670518c000259
[ "Puzzles" ]
https://www.codewars.com/kata/57d63b45ec1670518c000259
6 kyu
My third kata, write a function `check_generator` that examines the status of a Python generator expression `gen` and returns `'Created'`, `'Started'` or `'Finished'`. For example: `gen = (i for i in range(1))` >>> returns `'Created'` (the generator has been initiated) `gen = (i for i in range(1)); next(gen, None)` >>> returns `'Started'` (the generator has yielded a value) `gen = (i for i in range(1)); next(gen, None); next(gen, None)` >>> returns `'Finished'` (the generator has been exhuasted) For an introduction to Python generators, read: https://wiki.python.org/moin/Generators. Please do vote and rank the kata, and provide any feedback. Hint: you can solve this if you know the right module to use.
reference
def check_generator(gen): if gen . gi_frame is None: return "Finished" if gen . gi_frame . f_lasti == - 1: return "Created" return "Started"
Check the status of the generator expression
585e6eb2eec14124ea000120
[ "Fundamentals" ]
https://www.codewars.com/kata/585e6eb2eec14124ea000120
5 kyu
# Task In a black and white image we can use `1` instead of black pixels and `0` instead of white pixels. For compression image file we can reserve pixels by consecutive pixels who have the same color. Your task is to determine how much of black and white pixels is in each row sorted by place of those. # Example: For `height=2,width=100 and compressed=[40,120,40,0]` The result should be `[[40,60],[0,60,40,0]]` Sum of compressed array always divisible by width and height of image. Pixels available is in Compressed array in this order: `[Black,White,Black,White,Black,White,...]` ![](http://s3.picofile.com/file/8194350650/Compressed_Image_1_.png) For `height=2,width=100 and compressed=[0, 180, 20, 0]` The result should be `[[0,100],[0,80,20,0]]` ![](http://s6.picofile.com/file/8194348868/Compressed_Image.png) # Input/Output - `[input]` integer `height` Height of image - `[input]` integer `width` Width of image - `[input]` integer array `compressed` Consecutive pixels - `[output]` 2D integer array The black and white pixels in each row.
games
from enum import Enum class Colors (Enum): White = 0 Black = 1 class Entry: @ staticmethod def parse(amount, index): return Entry(amount, Colors((index % 2) ^ 1)) def __init__(self, amount, color): self . amount = amount self . color = color def take(self, amount): amount = min(amount, self . amount) self . amount -= amount return amount def is_empty(self): return not self . amount def __repr__(self): return f"( { self . amount } , { self . color } )" class Bag: @ staticmethod def parse(compressed): return Bag([Entry . parse(e, i) for i, e in enumerate(compressed)][:: - 1]) def __init__(self, data): self . data = data def take(self, amount, color): if self . is_empty(): return 0 current = self . peek() if color != current . color: return 0 amount = current . take(amount) if current . is_empty(): self . data . pop() return amount def peek(self): return 0 if self . is_empty() else self . data[- 1] def is_empty(self): return not len(self . data) def __repr__(self): return repr(self . peek()) def black_and_white(height, width, compressed): bag, res = Bag . parse(compressed), [] while not bag . is_empty(): row, remaining = [], width while remaining: amount_black = bag . take(remaining, Colors . Black) row . append(amount_black) remaining -= amount_black amount_white = bag . take(remaining, Colors . White) row . append(amount_white) remaining -= amount_white res . append(row) return res
Simple Fun #139: Black And White
58a6a56942fd72afdd000161
[ "Puzzles" ]
https://www.codewars.com/kata/58a6a56942fd72afdd000161
5 kyu
In this Kata, you will be given an array of arrays and your task will be to return the number of unique arrays that can be formed by picking exactly one element from each subarray. For example: `solve([[1,2],[4],[5,6]]) = 4`, because it results in only `4` possibilites. They are `[1,4,5],[1,4,6],[2,4,5],[2,4,6]`. ```if:r In R, we will use a list data structure. So the argument for `solve` is a list of numeric vectors. ~~~ solve(list(c(1, 2), 4, c(5, 6))) [1] 4 ~~~ ``` Make sure that you don't count duplicates; for example `solve([[1,2],[4,4],[5,6,6]]) = 4`, since the extra outcomes are just duplicates. See test cases for more examples. Good luck! If you like this Kata, please try: [Sum of integer combinations](https://www.codewars.com/kata/59f3178e3640cef6d90000d5) [Sum of array singles](https://www.codewars.com/kata/59f11118a5e129e591000134)
reference
def solve(arr): x = 1 for a in arr: x *= len(set(a)) return x
Array combinations
59e66e48fc3c499ec5000103
[ "Fundamentals" ]
https://www.codewars.com/kata/59e66e48fc3c499ec5000103
6 kyu
# Letterss of Natac In a game I just made up that doesn’t have anything to do with any other game that you may or may not have played, you collect resources on each turn and then use those resources to build settlements, roads, and cities or buy a development. Other kata about this game can be found [here](https://www.codewars.com/collections/59e6938afc3c49005900011f). ## Task This kata asks you to implement the function `build_or_buy(hand)` , which takes as input a `hand`, the resources you have (a string of letters representing the resources you have), and returns a list of the unique game objects you can build or buy given your hand. There are five different resources, `'b'`, `'w'`, `'g'`, `'s'`, and `'o'`. Game objects and the resources required to build or buy them are as follows: 1. `'road'`: `bw` 2. `'settlement'`: `bwsg` 3. `'city'`: `ooogg` 4. `'development'`: `osg` ## Examples ```python build_or_buy("bwoo") => ['road'] build_or_buy("bwsg") => ['road', 'settlement'] or ['settlement', 'road'] build_or_buy("") => [] build_or_buy("ogogoogogo") => ['city'] ``` ## Notes: 1. Don't mutate the hand 2. The order of the returned list doesn't matter 3. You do not have to test for whether a hand is valid. 4. The list will be interpreted to mean 'you can build any of these objects,' not 'you can build all these objects in one play'. See example 2 above, even though there is only one `'b'` and one `'w'` in `hand`, both `Road()` and `Settlement()` are in the list. 5. A hand can be empty. In the event a hand is empty, you can't build or buy anything, so return an empty list, see example 3 above. 6. Hand are between 0 and 39 in length.
reference
def build_or_buy(hand): d = {'bw': 'road', 'bwsg': 'settlement', 'ooogg': 'city', 'osg': 'development'} res = [] for r, build in d . items(): if all(hand . count(i) >= r . count(i) for i in set(r)): res . append(build) return res
Letterss of natac: build or buy
59e6aec2b2c32c9d8b000184
[ "Fundamentals" ]
https://www.codewars.com/kata/59e6aec2b2c32c9d8b000184
7 kyu
You are tasked with implementing a representation of [complex numbers](https://en.wikipedia.org/wiki/Complex_number). Starting with the basics, we only require to be able to: - Extract the real and imaginary parts of a complex number - Add two complex numbers - Multiply two complex numbers Since complex numbers are, in fact, numbers, addition and multiplication should be implemented by overloading the operators + and * if your language supports it.
reference
class Complex (complex): @ property def imaginary(self): return super(). imag def __add__(self, other): return Complex(complex(self) + other) def __mul__(self, other): return Complex(complex(self) * other)
Representing complex numbers
59e5fe367905df7f5c000072
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/59e5fe367905df7f5c000072
7 kyu
Take an input string and return a string that is made up of the number of occurences of each english letter in the input followed by that letter, sorted alphabetically. The output string shouldn't contain chars missing from input (chars with 0 occurence); leave them out. An empty string, or one with no letters, should return an empty string. Notes: * the input will always be valid; * treat letters as **case-insensitive** ## Examples ``` "This is a test sentence." ==> "1a1c4e1h2i2n4s4t" "" ==> "" "555" ==> "" ```
reference
from collections import Counter def string_letter_count(s): cnt = Counter(c for c in s . lower() if c . isalpha()) return '' . join(str(n) + c for c, n in sorted(cnt . items()))
String Letter Counting
59e19a747905df23cb000024
[ "Strings", "Sorting", "Fundamentals" ]
https://www.codewars.com/kata/59e19a747905df23cb000024
6 kyu
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said # Description: Complete function `findSequences`. It accepts a positive integer `n`. Your task is to find such integer sequences: <span style="background:#000000"><font size=4>Continuous positive integer and their sum value equals to n </font></span> ``` For example, n = 15 valid integer sequences: [1,2,3,4,5] (1+2+3+4+5==15) [4,5,6] (4+5+6==15) [7,8] (7+8==15) ``` The result should be an array `[sequence 1,sequence 2...sequence n]`, sorted by ascending order of the length of sequences; If no result found, return []. # Some examples: ``` findSequences(3) === [[1,2]] findSequences(15) === [[7,8],[4,5,6],[1,2,3,4,5]] findSequences(20) === [[2, 3, 4, 5, 6]] findSequences(100) === [[18, 19, 20, 21, 22], [9, 10, 11, 12, 13, 14, 15, 16]] findSequences(1) === [] ```
algorithms
from math import isqrt def find_sequences(n: int) - > list[list[int]]: seq = [] for k in range(2, isqrt(2 * n) + 1): s = n - k * (k - 1) / / 2 if s % k == 0: x = s / / k seq . append(list(range(x, x + k))) return seq
Find the integer sequences
582aad136755daf91a000021
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/582aad136755daf91a000021
6 kyu
No Story No Description Only by Thinking and Testing Look at result of testcase, guess the code! # #Series:<br> <a href="http://www.codewars.com/kata/56d904db9963e9cf5000037d">01:A and B?</a><br> <a href="http://www.codewars.com/kata/56d9292cc11bcc3629000533">02:Incomplete string</a><br> <a href="http://www.codewars.com/kata/56d931ecc443d475d5000003">03:True or False</a><br> <a href="http://www.codewars.com/kata/56d93f249c844788bc000002">04:Something capitalized</a><br> <a href="http://www.codewars.com/kata/56d949281b5fdc7666000004">05:Uniq or not Uniq</a> <br> <a href="http://www.codewars.com/kata/56d98b555492513acf00077d">06:Spatiotemporal index</a><br> <a href="http://www.codewars.com/kata/56d9b46113f38864b8000c5a">07:Math of Primary School</a><br> <a href="http://www.codewars.com/kata/56d9c274c550b4a5c2000d92">08:Math of Middle school</a><br> <a href="http://www.codewars.com/kata/56d9cfd3f3928b4edd000021">09:From nothingness To nothingness</a><br> <a href="http://www.codewars.com/kata/56dae2913cb6f5d428000f77">10:Not perfect? Throw away!</a> <br> <a href="http://www.codewars.com/kata/56db19703cb6f5ec3e001393">11:Welcome to take the bus</a><br> <a href="http://www.codewars.com/kata/56dc41173e5dd65179001167">12:A happy day will come</a><br> <a href="http://www.codewars.com/kata/56dc5a773e5dd6dcf7001356">13:Sum of 15(Hetu Luosliu)</a><br> <a href="http://www.codewars.com/kata/56dd3dd94c9055a413000b22">14:Nebula or Vortex</a><br> <a href="http://www.codewars.com/kata/56dd927e4c9055f8470013a5">15:Sport Star</a><br> <a href="http://www.codewars.com/kata/56de38c1c54a9248dd0006e4">16:Falsetto Rap Concert</a><br> <a href="http://www.codewars.com/kata/56de4d58301c1156170008ff">17:Wind whispers</a><br> <a href="http://www.codewars.com/kata/56de82fb9905a1c3e6000b52">18:Mobile phone simulator</a><br> <a href="http://www.codewars.com/kata/56dfce76b832927775000027">19:Join but not join</a><br> <a href="http://www.codewars.com/kata/56dfd5dfd28ffd52c6000bb7">20:I hate big and small</a><br> <a href="http://www.codewars.com/kata/56e0e065ef93568edb000731">21:I want to become diabetic ;-)</a><br> <a href="http://www.codewars.com/kata/56e0f1dc09eb083b07000028">22:How many blocks?</a><br> <a href="http://www.codewars.com/kata/56e1161fef93568228000aad">23:Operator hidden in a string</a><br> <a href="http://www.codewars.com/kata/56e127d4ef93568228000be2">24:Substring Magic</a><br> <a href="http://www.codewars.com/kata/56eccc08b9d9274c300019b9">25:Report about something</a><br> <a href="http://www.codewars.com/kata/56ee0448588cbb60740013b9">26:Retention and discard I</a><br> <a href="http://www.codewars.com/kata/56eee006ff32e1b5b0000c32">27:Retention and discard II</a><br> <a href="http://www.codewars.com/kata/56eff1e64794404a720002d2">28:How many "word"?</a><br> <a href="http://www.codewars.com/kata/56f167455b913928a8000c49">29:Hail and Waterfall</a><br> <a href="http://www.codewars.com/kata/56f214580cd8bc66a5001a0f">30:Love Forever</a><br> <a href="http://www.codewars.com/kata/56f25b17e40b7014170002bd">31:Digital swimming pool</a><br> <a href="http://www.codewars.com/kata/56f4202199b3861b880013e0">32:Archery contest</a><br> <a href="http://www.codewars.com/kata/56f606236b88de2103000267">33:The repair of parchment</a><br> <a href="http://www.codewars.com/kata/56f6b4369400f51c8e000d64">34:Who are you?</a><br> <a href="http://www.codewars.com/kata/56f7eb14f749ba513b0009c3">35:Safe position</a><br> <br> # #Special recommendation Another series, innovative and interesting, medium difficulty. People who like to challenge, can try these kata: <a href="http://www.codewars.com/kata/56c85eebfd8fc02551000281">Play Tetris : Shape anastomosis</a><br> <a href="http://www.codewars.com/kata/56cd5d09aa4ac772e3000323">Play FlappyBird : Advance Bravely</a><br>
games
from itertools import zip_longest as zip def collatz(n): seq = [n % 10] while n > 1: n = 3 * n + 1 if n % 2 else n / / 2 seq . append(n % 10 if n > 1 else ".") return map(str, seq) def test_it(arr): return "\n" . join("|" . join(a) for a in zip(* map(collatz, arr), fillvalue="."))
Thinking & Testing : Hail and Waterfall
56f167455b913928a8000c49
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/56f167455b913928a8000c49
6 kyu
An array of different positive integers is given. We should create a code that gives us the number (or the numbers) that has (or have) the highest number of divisors among other data. The function ```proc_arrInt()```, (Javascript: ```procArrInt()```) will receive an array of unsorted integers and should output a list with the following results: ```python [(1), (2), (3)] (1) - Total amount of numbers received (2) - Total prime numbers received (3) - a list [(a), (b)] (a)- The highest amount of divisors that a certain number (or numbers) of the given array have (b)- A sorted list with the numbers that have the largest amount of divisors. The list may have only one number ``` ## Examples ```python arr1 = [66, 36, 49, 40, 73, 12, 77, 78, 76, 8, 50, 20, 85, 22, 24, 68, 26, 59, 92, 93, 30] proc_arrInt(arr1) ------> [21, 2, [9, [36]] # 21 integers in the array # 2 primes: 73 and 97 # 36 is the number that has the highest amount of divisors: # 1, 2, 3, 4, 6, 9, 12, 18, 36 (9 divisors, including 1 and 36) ``` Another case: ```python arr2 = [267, 273, 271, 145, 275, 150, 487, 169, 428, 50, 314, 444, 445, 67, 458, 211, 58, 95, 357, 486, 359, 491, 108, 493, 247, 379] proc_arrInt(arr2) ------> [26, 7, [12, [108, 150, 444, 486]]] # 26 integers in the array # 7 primes: 271, 487, 67, 211, 359, 491, 379 # 108, 150, 444 and 486 have the highest amount of divisors: # 108: [1, 2, 3, 4, 6, 9, 12, 18, 27, 36, 54, 108] (12 divisors) # 150: [1, 2, 3, 5, 6, 10, 15, 25, 30, 50, 75, 150] (12 divisors) # 444: [1, 2, 3, 4, 6, 12, 37, 74, 111, 148, 222, 444] (12 divisors) # 486: [1, 2, 3, 6, 9, 18, 27, 54, 81, 162, 243, 486] (12 divisors) ``` Happy coding!!
reference
def divisors(n): return sum(2 if i != n / / i else 1 for i in range(1, int(n * * 0.5) + 1) if n % i == 0) def proc_arrInt(arr): n_divs = {i: divisors(i) for i in arr} max_div = max(n_divs . values()) return [len(arr), sum(divisors(i) == 2 for i in arr), [max_div, sorted([i for i, v in n_divs . items() if v == max_div])]]
Numbers with The Highest Amount of Divisors
55ef57064cb8418a3f000061
[ "Fundamentals", "Algorithms", "Data Structures", "Mathematics", "Arrays" ]
https://www.codewars.com/kata/55ef57064cb8418a3f000061
5 kyu
Let's take an integer number, ``` start``` and let's do the iterative process described below: - we take its digits and raise each of them to a certain power, ```n```, and add all those values up. (result = ```r1```) - we repeat the same process with the value ```r1``` and so on, ```k``` times. Let's do it with ```start = 420, n = 3, k = 5``` ``` 420 ---> 72 (= 4³ + 2³ + 0³) ---> 351 (= 7³ + 2³) ---> 153 ---> 153 ----> 153 ``` We can observe that it took ```3``` steps to reach a cyclical pattern ```[153]```(```h = 3```). The length of this cyclical pattern is ```1```, ```patt_len```. The last term of our k operations is 153, ```last_term``` Now, ```start = 420, n = 4, k = 30``` ``` 420 ---> 272 ---> 2433 ---> 434 ---> 593 ---> 7267 ---> 6114 ---> 1554 ---> 1507 ---> 3027 ---> 2498 ---> 10929 ---> 13139 ---> 6725 ---> 4338 ---> 4514 ---> 1138 ---> 4179 ---> 9219 ---> 13139 ---> 6725 ---> 4338 ---> 4514 ---> 1138 ---> 4179 ---> 9219 ---> 13139 ---> 6725 ---> 4338 ---> 4514 ---> 1138 ---> 4179 ---> 9219...... ``` In this example we can observe that the cyclical pattern (```cyc_patt_arr```) is ```[13139, 6725, 4338, 4514, 1138, 4179, 9219]``` with a length of ```7```, (```patt_len = 7```), and it took ```12``` steps (```h = 12```) to reach the cyclical pattern. The last term after doing ```30``` operations is ```1138``` Make the function ```sum_pow_dig_seq()```, that receives the arguments in the order shown below with the corresponding output: ```python sum_pow_dig_seq(start, n, k) ---> [h, cyc_patt_arr, patt_len, last_term] ``` ```haskell sumPowDigSeq start n k ---> (h, cyc_patt_arr, patt_len, last_term) ``` For our given examples, ```python sum_pow_dig_seq(420, 3, 5) == [3, [153], 1, 153] sum_pow_dig_seq(420, 4, 30) == [12, [13139, 6725, 4338, 4514, 1138, 4179, 9219], 7, 1138] ``` ```haskell sumPowDigSeq 420 3 5 == (3, [153], 1, 153) sumPowDigSeq 420 4 30 == (12, [13139, 6725, 4338, 4514, 1138, 4179, 9219], 7, 1138) ``` Constraints for tests: ``` 500 ≤ start ≤ 8000 2 ≤ n ≤ 9 100 * n ≤ k ≤ 200 * n ``` Do your best!
reference
def sum_pow_dig_seq(num, exp, k): seq = [] for step in range(k): seq . append(num) num = sum(int(dig) * * exp for dig in str(num)) if num in seq: cycle_start = seq . index(num) cycle = seq[cycle_start:] last_term = cycle[(k - cycle_start) % len(cycle)] return [cycle_start, cycle, len(cycle), last_term] return [0, [], 0, num]
Sequence of Power Digits Sum
572f32ed3bd44719f8000a54
[ "Algorithms", "Recursion", "Data Structures", "Mathematics" ]
https://www.codewars.com/kata/572f32ed3bd44719f8000a54
5 kyu
You will be given the prime factors of a number as an array. E.g: ```[2,2,2,3,3,5,5,13]``` You need to find the number, n, to which that prime factorization belongs. It will be: ``` n = 2³.3².5².13 = 23400 ``` Then, generate the divisors of this number. Your function ```get_num() or getNum()``` will receive an array with potentially unordered prime factors and should output: an array with the found integer n at index 0, the amount of total divisors (both prime and compound numbers) at index 1, followed the smallest factor (index 2, and the biggest one (last element) We will see the example given above with the only difference that the array of the prime factors is unordered. The list of divisors for that number (23400) is: ``` 2, 3, 4, 5, 6, 8, 9, 10, 12, 13, 15, 18, 20, 24, 25, 26, 30, 36, 39, 40, 45, 50, 52, 60, 65, 72, 75, 78, 90, 100, 104, 117, 120, 130, 150, 156, 180, 195, 200, 225, 234, 260, 300, 312, 325, 360, 390, 450, 468, 520, 585, 600, 650, 780, 900, 936, 975, 1170, 1300, 1560, 1800, 1950, 2340, 2600, 2925, 3900, 4680, 5850, 7800, 11700 (not considering the integer 23400 itself) ``` There is a total amount of ```71``` divisors. The smallest divisor is ```2``` and the highest ```11700```. So the expected output will be: ``` get_num([2,13,2,5,2,5,3,3]) == [23400, 71, 2, 11700] ``` Enjoy!
reference
def get_num(arr): c, n, r = 1, 1, {} arr . sort() for a in arr: n *= a r[a] = r[a] + 1 if a in r else 1 for a in r: c *= r[a] + 1 return [n, c - 1, arr[0], n / / arr[0]]
Following the Paths of Numbers Through Prime Factorization
58f301633f5066830c000092
[ "Mathematics", "Data Structures", "Fundamentals" ]
https://www.codewars.com/kata/58f301633f5066830c000092
5 kyu
## Task The prisoners from previous challenges love playing chess so they make extra plan C in communcation , it goes as follows. They distribute the 26 letters on the standard 8 x 8 chess board as shown below : <div> <img src="http://i.imgur.com/Sbdzpaa.jpg"> <img src="http://i.imgur.com/zO5VwkV.png"> </div> Then they assign every letter to its location on the board as described below: <br> <br> <div style="background-color: white"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/SCD_algebraic_notation.svg/242px-SCD_algebraic_notation.svg.png"></div> <br> So character `v` would correspond to a1 and `u` would be b1, etc.. NOTE: during the encryption words are separated by space ## Example For: `msg = "hi"`, the result should be: `"e5e4"` For: `msg = "play again"`, the result should be: `"g1f2d3c2 d3e6d3e4h2"` ## Input/Output - `[input]` string `msg` message input. - `[output]` a string encrypted message.
games
D = {r: c + str(i) for l, c in zip(['vw', 'ux', 'ty', 'szabcde', 'rkjihgf', 'ql', 'pm', 'on'], 'abcdefgh') for i, r in enumerate(l, 1)} def chess_encryption(s): return '' . join(D . get(c, c) for c in s)
Chess Fun #10: Chess Encryption
58a3f0662f949eba5c00004f
[ "Puzzles" ]
https://www.codewars.com/kata/58a3f0662f949eba5c00004f
6 kyu
Johnny is working as an intern for a publishing company, and was tasked with cleaning up old code. He is working on a program that determines how many digits are in all of the page numbers in a book with pages from 1 to n (inclusive). For example, a book with 4 pages has 4 digits (one for each page), while a 12 page book has 15 (9 for 1-9, plus 2 each for 10, 11, 12). Johnny's boss, looking to futureproof, demanded that the new program be able to handle books up to 400,000,000,000,000,000 pages.
refactoring
def page_digits(pages): total = 0 start = 0 tens = 10 while pages > start: total += pages - start start = tens - 1 tens *= 10 return total
Paginating a huge book
55905b7597175ffc1a00005a
[ "Performance", "Refactoring" ]
https://www.codewars.com/kata/55905b7597175ffc1a00005a
5 kyu
### Background In the world of investment banking, when the quantities bought and sold are so large that pricing is significant at less then the smallest available unit of 'real' currency. This is why you'll often see things quoted with a pair of buy-sell prices for a single producty that are less than a cent. Once of the niceties of trading this way is a format to display these extra small fractions. By convention, some products will be quoted not to decimal places, but to pre-agreed fractions. For example, if a product is quoted to the 16th of a cent you might see a price displayed like this: `109.28/7` which means $109.28 <sup>7</sup>/<sub>16</sub> Internally within these systems the price will still be in cents and fractions of a cent like so: `10928.4375`. ### Kata In this kata you must write a class to convert between internal and display values. When constructed the class is supplied with the fractional denominator to be used in the conversion, if none is supplied, use `16` as a default. **Note:** You can assume that all inputs are valid for conversion. Further, all denominators will be a power of two so no need to worry about floating point approximations.
reference
class PriceDisplayFraction (object): def __init__(self, denominator=16): self . d = denominator def to_display(self, cents): return "{}/{}" . format(int(cents) / 100, int((cents % 1) * self . d)) def to_internal(self, display): cents, num = map(int, display . replace('.', ''). split('/')) return cents + num / self . d
Fractions of a currency' smallest value
55c4a2a2586d8706be0000d0
[ "Fundamentals" ]
https://www.codewars.com/kata/55c4a2a2586d8706be0000d0
6 kyu
We are interested in obtaining some different features of given arrays. For that purpose we will define a ```class Array``` that will have the following methods: - ```num_elements```, will give the total of elements of the array. - ```num_values```, will give the total amount of different values of the array. - ```start_end```, will output a list with the first and last element of the array, like ```[first, last]```. - ```range_```, will output a list with the minimum and maximum value of the array, like ```[min_value, max_value]```. - ```largest_increas_subseq```, will output the largest subsequence (length >= 3) of **contiguous elements that are in increasing order**. like ```[array[i], array[i + 1], array[i + 2], ...., array[i + k]]``` and ```array[i] < array[i + 1] < array[i + 3] < ......< array[i + k]```. In case of length less than three, or no increasing pair at all, this method will output the string: ```No increasing subsequence``` - ```largest_decreas_subseq```, will output the largest subsequence (length >= 3) of **contiguous elements that are in decreasing order**. like ```[array[i], array[i + 1], array[i + 2], ...., array[i + k]]``` and ```array[i] > array[i + 1] > array[i + 3] > ......> array[i + k]```. In case of length less than three, or no decreasing pair at all, this method will output the string: "No decreasing subsequence" - ```__str__```, will join the results of all the methods of the class and will output an ordered dictionary, having the same order as we present the methods. Let's see an example: ```python arr = [345, 32, 45, 12, 45, 47, 49, 55, 90, 104, 20, 30, 34] c = Array(arr) c.num_elements() == 13 c.num_values() == 12 c.start_end() == [345, 34] c.range_() == [12, 345] c.largest_increas_subseq() == [12, 45, 47, 49, 55, 90, 104] c.largest_decreas_subseq() == "No decreasing subsequence" # [345, 32], [45,12] length less than 3 c.__str__() == OrderedDict([('1.number of elements', 13), ('2.number of different values', 12), ('3.first and last terms', [345, 34]), ('4.range of values', [12, 345]), ('5.increas subseq', [12, 45, 47, 49, 55, 90, 104]), ('6.decreas subseq', 'No decreasing subsequence')]) ``` Let's see a case of an array that have both, increasing and decreasing subsequences in contiguous elements. ```python arr = [345, 288, 250, 215,187, 156, 32, 32, 45, 12, 45, 47, 49, 55, 90, 104, 20, 30, 34] c.__str__() == OrderedDict([('1.number of elements', 19), ('2.number of different values', 17), ('3.first and last terms', [345, 34]), ('4.range of values', [12, 345]), ('5.increas subseq', [12, 45, 47, 49, 55, 90, 104]), ('6.decreas subseq', [345, 288, 250, 215, 187, 156, 32])]) ``` If the result of an increasing or decreasing subsequences is that we have more than one list (of same length, obviously), it will be output only the sequence that occurs first in the array. Assumptions: All the array will have positive integer values, without wrong entries. Your code will be evaluated mostly by the output of the ```__str__``` method. The object of the output should be expressed as an ordered dictionary in string format as it is pointed out in your initial solution box. Enjoy it and happy coding!!
reference
from collections import OrderedDict class Array (object): def __init__(self, arr=[]): self . arr = arr self . num_elements = lambda: len(self . arr) self . num_values = lambda: len(set(self . arr)) self . start_end = lambda: [self . arr[0], self . arr[- 1]] self . range_ = lambda: [min(self . arr), max(self . arr)] inc, dec, maxinc, maxdec = [], [], [], [] for item in self . arr: if len(inc) == 0 or inc[- 1] < item: inc += [item] else: inc = [item] if len(inc) > len(maxinc): maxinc = inc if len(dec) == 0 or dec[- 1] > item: dec += [item] else: dec = [item] if len(dec) > len(maxdec): maxdec = dec self . largest_increas_subseq = lambda: maxinc if len( maxinc) > 2 else "No increasing subsequence" self . largest_decreas_subseq = lambda: maxdec if len( maxdec) > 2 else "No decreasing subsequence" # one-liner ineffficient versions just for the lolZ # self.largest_increas_subseq=lambda: (lambda a: a[0] if a and len(a[0])>2 else "No increasing subsequence")(sorted(filter(lambda a: len(a)>=3 and all(x<a[y+1] for y,x in enumerate(a[:-1])), [self.arr[x:y+1] for x in xrange(len(self.arr)-2) for y in xrange(2,len(self.arr))]), key=len, reverse=True)) # self.largest_decreas_subseq=lambda: (lambda a: a[0] if a and len(a[0])>2 else "No decreasing subsequence")(sorted(filter(lambda a: len(a)>=3 and all(x>a[y+1] for y,x in enumerate(a[:-1])), [self.arr[x:y+1] for x in xrange(len(self.arr)-2) for y in xrange(2,len(self.arr))]), key=len, reverse=True)) self . __str__ = lambda: str(OrderedDict([('1.number of elements', self . num_elements()), ('2.number of different values', self . num_values()), ('3.first and last terms', self . start_end( )), ('4.range of values', self . range_()), ('5.increas subseq', self . largest_increas_subseq()), ('6.decreas subseq', self . largest_decreas_subseq())]))
Features of a Given Array
569ff2622f71816610000048
[ "Fundamentals", "Data Structures", "Algorithms", "Sorting", "Mathematics", "Logic", "Object-oriented Programming" ]
https://www.codewars.com/kata/569ff2622f71816610000048
5 kyu
Run Length Encoding is used to compress data. RLE works like this: characters = "AAAALOTOOOOFTEEEEXXXXXXT" then the encoding will store AAAA = A4 and L1 So all together: ``` python encode("AAAALOTOOOOFTEEEEXXXXXXT") == "A4L1O1T1O4F1T1E4X6T1" # or encode("HELLO WORLD") == "H1E1L2O1 1W1O1R1L1D1" # or encode("FOO+BAR") == "F1O2+1B1A1R1" ``` as you can see, its not always as efficient, but with some specific data it works!
algorithms
from itertools import groupby def encode(s): return '' . join(k + str(sum(1 for _ in g)) for k, g in groupby(s))
Compress/Encode a Message with RLE (Run Length Encoding)
57d6c3fb950d84fcfb0015c8
[ "Algorithms" ]
https://www.codewars.com/kata/57d6c3fb950d84fcfb0015c8
6 kyu
<h2>Sort the Vowels!</h2> In this kata, we want to sort the vowels in a special format. <h3>Task</h3> Write a function which takes a input string <code>s</code> and return a string in the following way: <pre> <code> C| R| |O n| D| d| "CODEWARS" => |E "Rnd Te5T" => | W| T| |A |e R| 5| S| T| </code> </pre> Notes: <ul> <li>List all the Vowels on the right side of <code>|</code></li> <li>List every character except Vowels on the left side of <code>|</code></li> <li>for the purpose of this kata, the vowels are : <code>a e i o u</code></li> <li>Return every character in its original case</li> <li>Each line is seperated with <code>\n</code></li> <li>Invalid input <code>( undefined / null / integer )</code> should return an empty string</li> </ul>
reference
def sort_vowels(s): try: return '\n' . join('|' + i if i . lower() in 'aioue' else i + '|' for i in s) except: return ''
Sort the Vowels!
59e49b2afc3c494d5d00002a
[ "Fundamentals", "Algorithms", "Strings" ]
https://www.codewars.com/kata/59e49b2afc3c494d5d00002a
7 kyu
Think in all the primes that: if ```p``` is prime and ```p < n``` , all these following numbers ``` (p + 2) ``` , ``` (p + h) ``` and ```(p + 2h)``` are all primes, being ``` h ``` an even number such that: ``` 2 <= h <= hMax ``` Your function, ```give_max_h()``` , will receive 2 arguments ``` n ``` and ```hMax``` . It should find for which value or values of ``` h ``` , we encounter the maximum amount of primes that satisfy the above constraint, testing for all possible even values from ``` 2 to hMax ``` included. So, ```give_max_h(n, hMax)``` should ouput a list of lists with the following structure: a) if you find a unique solution: ``` [[h0, max amount of primes]]``` being ``` h0 ``` such that ``` 2 <= h0 <= hMax``` and is the value that has the highest amount of collected primes b) if you have more than one solution, suposse ``` 2 ``` , you found two values of h: ```h0``` , ```h1 ``` such that : ```2 <= ho < h1 <= hmax ``` ```[[h0, max_amount_of_primes], [h1, max_amount_of_primes]]``` (lists should be sorted by the value of h) Let's see some cases: For Python and Ruby: ``` Case 1 give_max_h(30, 8) ------> [[6, 3]] ``` For Javascript: ``` Case 1 giveMax_h(30, 8) ------> [[6, 3]] ``` we have 4 different sets of steps to test [2, 2, 4], [2, 4, 8], [2, 6, 12] and [2, 8, 16] ///so that we select primes p in the range (2, 30) that fulfill: ```p, p + 2, p + 2 and p + 4``` all primes --- > only with prime 3 (1 prime) ```p, p + 2, p + 4 and p + 8``` all primes ----> only with prime 3 (1 prime) ```p, p + 2, p + 6 and p + 12``` all primes -----> passed by primes 5, 11, 17 (3 primes) ```p, p + 2, p + 8 and p + 16``` all primes -----> only with prime 3 (1 prime) So h is 6 with 3 found primes (max amount of primes) ([6, 3])/// Case 2) For Python and Ruby ``` give_max_h(100, 10) -----> [[6, 4]] # with h = 6 we found the highest amount of primes (4) : 5, 11, 17, 41 ``` For Javascript ``` giveMax_h(100, 10) -----> [[6, 4]] ``` Case 3) For Python and Ruby ``` give_max_h(1000, 100) -----> [[30, 13], [42, 13]] # we have two values of h that #procuded the highest amount of primes (13) ``` For Javascript ``` giveMax_h(1000, 100) -----> [[30, 13], [42, 13]] ``` ``` ///h = 30 produced the primes 11, 29, 41, 71, 107, 137, 197, 419, 431, 461, 617, 827, 881 h = 42 produced the primes 5, 17, 29, 107, 149, 197, 227, 269, 347, 419, 599, 617, 659 /// ``` Happy coding!! (Advise: You will need a fast prime generator. Do not use primality tests, otherwise the runtimes would exceed our allowed 6000 ms to complete tests) (To investigate beyond this kata: Do we have a convergence for the value of h, no matter the values of n and hMax are?)
reference
from gmpy2 import next_prime as np, is_prime as ip def give_max_h(n, k): a, h, d, p, v = 2, 2, [[0, 0]], [], 0 while a < n: p, a = p + [a], np(a) while h <= k: v = sum(ip(i + 2) and ip(i + h) and ip(i + (2 * h)) for i in p) d, h, v = d + [[h, v]] if v == d[0][1] else [[h, v] ] if v > d[0][1] else d, h + 2, 0 return d
Primes with Two, Even and Double Even Jumps
55df9798b87f0f87d100019a
[ "Fundamentals", "Algorithms", "Mathematics", "Data Structures" ]
https://www.codewars.com/kata/55df9798b87f0f87d100019a
5 kyu