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
The challenge is to efficiently find the largest [pronic number](https://en.wikipedia.org/wiki/Pronic_number) less than the method's input. The initial solution passes the sample tests, but fails for larger numbers used in the acceptance tests. Your algorithm should be fast as the acceptance tests will run 10,000 randomly selected numbers. Are you up to the challenge?
reference
def next_smaller_pronic(n): k = int((- 1 + (1 + 4 * n) * * .5) / 2 - 10 * * - 5) return k * (k + 1)
Next smaller pronic
5a90f6d457c5624ecc000012
[ "Mathematics", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/5a90f6d457c5624ecc000012
6 kyu
In this Kata, you will be given a string and your task is to determine if that string can be a palindrome if we rotate one or more characters to the left. ```Haskell solve("4455") = true, because after 1 rotation, we get "5445" which is a palindrome solve("zazcbaabc") = true, because after 3 rotations, we get "abczazcba", a palindrome ``` More examples in test cases. Input will be strings of lowercase letters or numbers only. Good luck!
algorithms
def solve(s): return any(s[i + 1:] + s[: i + 1] == s[i:: - 1] + s[: i: - 1] for i in range(len(s)))
Simple rotated palindromes
5a8fbe73373c2e904700008c
[ "Algorithms" ]
https://www.codewars.com/kata/5a8fbe73373c2e904700008c
7 kyu
> [Learn about Sandpile numbers from Numberphile!](https://www.youtube.com/watch?v=1MtEUErz7Gg) Let's learn about a new type of number: the Sandpile. ## What are Sandpiles? A sandpile is a grid of piles of sand ranging from `0` to some max integer value. For simplicity's sake, we'll look at a `3x3` grid containing `0`, `1`, `2`, or `3` grains of sand. An example of this sort of sandpile might look like this: ``` 1 3 0 . ∴ 1 2 1 = . : . 3 2 2 ∴ : : ``` This means that in row one, column one, there's `1` grain of sand, then `3` grains, then `0`, etc. ## Sandpile Math I mentioned that Sandpiles are a form of number, and as numbers, they support a single operation: addition. To add two sandpiles, simply add the number of grains of sand within each cell with the matching cell in the second value: ``` 1 3 0 2 0 2 (1+2) (3+0) (0+2) 3 3 2 1 2 1 + 2 1 0 = (1+2) (2+1) (1+0) = 3 3 1 3 2 2 0 0 1 (3+0) (2+0) (2+1) 3 2 3 ``` ## Toppling Piles You probably already have wondered, what happens if the number of grains goes above our max value of `3`? The answer is, that pile topples over. If the pile is in the middle, it dumps one grain of sand to each neighbor, keeping whatever is left over. If it's on the edge, it loses one grain to each direct neighbor _and also loses_ one grain for any edges that are on the side, which just disappear. This means that, no matter what, the over-sized cell loses `4` grains of sand, while any neighboring cells gain `1` grain of sand. This repeats until we've reached a state or equilibrium, like so: ``` * * 1 3 0 3 0 2 4 3 2 * 0 5 2 2 1 3 2 1 3 1 2 1 + 2 3 0 = 3 5 1 => 5 1 2 => * 1 3 2 => 2 3 2 => 3 2 2 0 0 1 3 2 3 3 3 3 4 3 3 * 0 4 3 * * 2 1 3 2 2 3 2 2 4 2 3 0 * => 2 4 2 => 3 0 4 => 3 1 0 * => 3 1 1 1 0 4 1 2 0 * 1 2 1 1 2 1 * * ``` So the final sum looks like this. ``` 1 3 0 3 0 2 2 3 0 1 2 1 + 2 3 0 = 3 1 1 3 2 2 0 0 1 1 2 1 ``` That's a lot of work, and fairly error-prone. (Trust me!) ## The Challenge We want to create a class, `Sandpile`, that simulates the `3x3`, max `3` sandpile. This class should have the following properties: - The constructor optionally takes a string, which is 3 groups of 3 integers (`0-9`), separated by a newline. If any of the values of the integers are over `3`, then immediately topple each pile until the Sandpile is at rest. If no argument is provided, initialize the piles with all zeros. - There should be a `toString` method, which prints the sandpile the same way as the constructor. This will be used to validate your results. - There should be an `add` method, which takes another Sandpile as an argument. This method returns a _new_ Sandpile, with the sum of the previous Sandpiles. - Sandpiles are immutable after creation - To let you focus on the fun part of this challenge, you don't have to worry about validation: - The input to the contructor will either be nothing or a string that matches `/[0-9]{3}\n[0-9]{3}\n[0-9]{3}/` - The `add` function will only ever receive another `Sandpile` instance. ## Thinking Ahead While working on this, think about what might be involved in a more generic Sandpile class, which could have a grid of any dimension, or allow for different numbers of grains before toppling over. If you like this Kata, I'll look at an extended version tackling the dynamic sandpile.
algorithms
class Sandpile: def __init__(self, piles: str = "000\n000\n000"): self . piles = Sandpile . _to_list(piles) self . _topple() def __str__(self): return Sandpile . _to_str(self . piles) def add(self, sandpile): return Sandpile(Sandpile . _to_str([[p1 + p2 for p1, p2 in zip(r1, r2)] for r1, r2 in zip(self . piles, sandpile . piles)])) @ staticmethod def _to_list(piles): return [[* map(int, row)] for row in piles . splitlines()] @ staticmethod def _to_str(piles): return '\n' . join('' . join(map(str, row)) for row in piles) def _topple(self): check = True while check: check = False for i, row in enumerate(self . piles): for j, x in enumerate(row): if x >= 4: check = True self . piles[i][j] -= 4 for k, l in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)): if 0 <= k < 3 and 0 <= l < 3: self . piles[k][l] += 1
Playing with Sandpiles
58c5fca35722de3493000081
[ "Algorithms" ]
https://www.codewars.com/kata/58c5fca35722de3493000081
5 kyu
We all know how to handle exceptions in Python. Just use: try: num = float(input()) except ValueError: print("That's not a number!") else: print(num) Code such as this def factorial(x, n = 1): if x == 0: raise ValueError(n) factorial(x - 1, n * x) relies on ridiculous exception misuse, but you can't change it because that would require a complete refactor. Code such as this try: return int(input("Input a number: ") except ValueError: return 4 # random number relies on reasonable exception use - almost all of the Python documentation examples are written in this way. What if you are using a faulty implementation of Embedded Python that doesn't implement the `try` statement? Where `sys.excepthook` is a hard-coded, unoverrideable value? Where even `__file__` is not defined? How do you use basic functions like `list.index`? Your task is to write a function that can handle exceptions raised in a program or function _without_ using `try` or `except`. Somehow. The first argument of your function `handle` will be a `lambda` requiring no parameters. You will call this function and handle any exceptions raised. The second argument will be a callable `success`: def success(func, val): pass The third argument will be a callable `failure`: def failure(func, exc): pass Subsequent arguments will be exceptions. If instances of these exceptions are raised, you must call the handler and no error message must be printed to `stderr`. If the exception raised is not provided as an argument, it should appear as though the exception was never caught. Pass the return value of `func` to `success` unless it raises an exception. If it raises an exception that `isinstance` of an exception class passed to `handle`, call `failure` with an instance of the raised exception. Don't worry about the little things like dealing with the extra arguments to exceptions or maintaining the call stack. Whoever writes code like _that_ deserves the extra work. ## What does "catching an exception" mean? It means: * The exception will not be printed to `stderr`. * Code can continue to be executed. * The `failure` callable knows what the exception was.
reference
def handle(func, success, failure, * exceptions): class manager: def __enter__(self): pass def __exit__(self, type, value, traceback): if isinstance(value, exceptions): failure(func, value) return True return not value with manager(): success(func, func())
Bad Exception Handling
5950eec3a100d72be100003f
[ "Fundamentals" ]
https://www.codewars.com/kata/5950eec3a100d72be100003f
4 kyu
RSA is a widely used public-key cryptosystem. Like other public-key encryption systems, RSA takes in data and encrypts it using a publicly available key. The private key is then used to decrypt the data. It is useful for sending data to servers because anyone can encrypt their own data, but only the server containing the private key can decrypt it. The driving force behind the difficulty in breaking an RSA encryption is the complexity of prime factorization of very large numbers. In this kata, you will implement an RSA object that can encrypt and decrypt data. For the sake of simplity, we will just use numbers instead of string/text data. Here is the basic outline of how RSA works (see [this link](https://en.wikipedia.org/wiki/RSA_(cryptosystem)) for more details): 1. Pick 2 prime numbers called `p` and `q` 2. Compute the modulus `n = p * q` 3. Compute the totient of `n`, which can be found by the formula `phi(n) = (p - 1) * (q - 1)` 4. Pick a positive integer `e` that is coprime to the totient (see [here](https://en.wikipedia.org/wiki/Coprime_integers) for an explanation of coprimes) - this will be the exponent used in the public key 5. Compute the modular multiplicative inverse of 'e (mod phi(n))' - this will be the exponent d used in the private key - (for details on modular multiplicative inverses, click [here](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse)) 6. To encrypt a number `m` into a ciphered number `c`, use the following formula: `c = m**e (mod n)` 7. To decrypt a number `c` back into the original number `m`, use the following formula: `m = c**d (mod n)` **Note**: Since `e` is generally a much smaller number than `d`, encryption is much quicker than decryption. In real practice (and in this kata), you will need to implement an optimized decryption method, as the formula given above will probably take too long for some of the more difficult test cases. Your task is to create a class that when initialized with some `p`, `q`, and `e`, will be able to encrypt and decrypt numbers using the RSA algorithm. You may assume that the test cases will only test valid inputs.
algorithms
class RSA: def __init__(self, p, q, e): phi = (p - 1) * (q - 1) self . n = p * q self . e = e self . d = pow(e, - 1, phi) def encrypt(self, m): return pow(m, self . e, self . n) def decrypt(self, c): return pow(c, self . d, self . n)
Simple RSA Implementation
56f1e42f0cd8bc1e6e001713
[ "Cryptography", "Algorithms", "Number Theory" ]
https://www.codewars.com/kata/56f1e42f0cd8bc1e6e001713
5 kyu
<p>You and a group of explorers have found a legendary ziggurat hidden in an obscure jungle. According to legend, the ancient structure houses portals to other worlds.</p> <p>The outer west wall of the ziggurat consists of a series of entrance doors. When an explorer enters through a door, they sit in a mobile cart that moves in a straight path until it reaches a "switch" or hits a wall.</p> <p>A <span style="color:#8df">switch</span> re-routes the cart either left or right, depending on the state of the switch and the cart's movement direction.</p> <p>Interdimensional portals line the entire north, east, and south walls inside the ziggurat. If a cart hits one of these walls, the occupying explorer exits through the portal before them. If a cart ends at the west wall, the explorer exits through a door and returns back outside.</p> <p>The expedition leader has assigned to you the task of keeping track of the exit points of each explorer. You are given an artifact that provides you with a map of the ziggurat's inner chamber.</p> <h2 style='color:#f88'>Switch Mechanics</h2> <div style="width:310px;height:260px;background:#000;padding:5px"><img src="https://i.imgur.com/RHPCVqC.png"></div> <p>Above is a representation of a switch. It exists in one of two states <code>A</code> or <code>B</code>.</p> <ul> <li>If a switch is in the <code>A</code> state and and a cart enters by moving: <ul> <li><b>west</b>, they are routed north</li> <li><b>east</b>, they are routed south</li> <li><b>south</b>, they are routed east</li> <li><b>north</b>, they are routed west</li> </ul></li> <li>If the switch were in the <code>B</code> state, the cart would be routed in the orthogonal direction opposite to that for the <code>A</code> state.</li> <li>Immediately after a cart passes through a switch, the switch changes state by rotating 90 degrees.</li> </ul> <h2 style='color:#f88'>Cart Pathing</h2> <img src="https://i.imgur.com/UChfJkG.png"> <p>Above left is an example ziggurat with four switches in their initial states. The <code>S</code> in the green arrow represents the initial position of the explorer who enters the structure through door <code>1</code>.<br/> The switches at <code>[1,1]</code>, <code>[1,4]</code>, and <code>[4,1]</code> begin in state <code>A</code>, while the switch at <code>[4,4]</code> begins in state <code>B</code>.</p> <ul> <li>The left image shows the path followed by the cart (in sequence, denoted by the white dashed arrows labeled <code>1</code>, <code>2</code>, and <code>3</code>). First it travels through the switch at <code>[1,1]</code>, then <code>[4,1]</code>, and then <code>[4,4]</code>.</li> <li>The right image shows the remainder of the cart's path, up to the explorer's exit (marked by the red arrow).<br/>By step <code>4</code> (after exiting the switch at <code>[1,4]</code>), the state of all four switches have changed, as shown above.</li> <li>The end state for the switch at <code>[1,4]</code> is <code>B</code>, while the rest end in state <code>A</code>.</li> <li>If the next explorer in sequence were also to enter through door <code>1</code>, they would exit through the portal at <code>[5,4]</code>.</li> </ul> <h2 style='color:#f88'>Input</h2> <p>Your function will receive two arguments:</p> <ul> <li>An <code>n</code> x <code>n</code> matrix representing the layout of the ziggurat interior.</li> <li>An array/list of the doors (rows) entered by each explorer in sequence. Assume each following explorer enters immediately after the preceding explorer has exited.</li> </ul> <h2 style='color:#f88'>Output</h2> <p>Your function should return an array of the exit points of explorers who exit through portals and <code>null</code>/<code>None</code> for those who return back outside.</p> <h2 style='color:#f88'>Test Example</h2> ```javascript let artifact = [ ' ', ' A A ', ' ', ' ', ' A B ', ' ']; let explorers = [1,1,0,3,4,4,2,5,1,4]; rideOfFortune(artifact,explorers); //[null,[5,4],[0,5],[3,5],[0,4],[5,1],[2,5],[5,5],null,[5,1]] ``` ```python artifact = [ ' ', ' A A ', ' ', ' ', ' A B ', ' '] explorers = [1,1,0,3,4,4,2,5,1,4] ride_of_fortune(artifact,explorers) #[None,[5,4],[0,5],[3,5],[0,4],[5,1],[2,5],[5,5],None,[5,1]] ``` ```go artifact := []string{ " ", " A A ", " ", " ", " A B ", " ", } explorers := []int{1,1,0,3,4,4,2,5,1,4} RideOfFortune(artifact,explorers) // [[-1 -1] [5 4] [0 5] [3 5] [0 4] [5 1] [2 5] [5 5] [-1 -1] [5 1]] ``` ```csharp string[] artifact = { " ", " A A ", " ", " ", " A B ", " " }; int[] explorers = {1,1,0,3,4,4,2,5,1,4}; Ziggurat.RideOfFortune(artifact,explorers); // {{-1,-1}, {5,4}, {0,5}, {3,5}, {0,}] ,{5,1}, {2,5}, {5,5}, {-1,-1}, {5,1}} ``` ```java String[] artifact = { " ", " A A ", " ", " ", " A B ", " "}; int[] explorers = {1,1,0,3,4,4,2,5,1,4}; List<Point> sol = Ziggurat.ride_of_fortune(artifact,explorers) // [null,(5,4),(0,5),(3,5),(0,4),(5,1),(2,5),(5,5),null,(5,1)] ``` ```kotlin val artifact = arrayOf( " ", " A A ", " ", " ", " A B ", " " ) val explorers = intArrayOf(1,1,0,3,4,4,2,5,1,4) val solution = arrayOfNulls(null,Pair(5,4),Pair(0,5),Pair(3,5),Pair(0,4),Pair(5,1),Pair(2,5),Pair(5,5),null,Pair(5,1)) Ziggurat.rideOfFortune(artifact,explorers)// should be equivalent to solution ``` ```rust let artifact = [ " ", " A A ", " ", " ", " A B ", " " ]; let explorers = [1,1,0,3,4,4,2,5,1,4]; let solution = vec![None, Some((5,4)), Some((0,5)), Some((3,5)), Some((0,4)), Some((5,1)), Some((2,5)), Some((5,5)), None, Some((5,1))]; ziggurat::ride_of_fortune(&artifact,&explorers)// should be equivalent to solution ``` <h2 style='color:#f88'>Technical Constraints</h2> - Ziggurat size `n` range: `40 >= n >= 6` - Final Test Suite: `15` fixed tests, `100` random tests - JavaScript: prototypes have been frozen and `require` has been disabled - Inputs will always be valid If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored).
algorithms
class Ziggurate: board = [] exit_gates = [] def __init__(self, x): self . x = x self . y = 0 self . axis_flag = 1 self . direction = 1 self . exit = None def travers_ziggurate(self): while self . is_exit(len(self . board), self . x, self . y): field = self . board[self . x][self . y] if field is not None: self . pass_switcher(field) Ziggurate . shift_switcher(self . x, self . y) self . exit = [self . x, self . y] if self . y + \ self . direction * self . axis_flag >= 0 else None self . x += self . direction * (1 - self . axis_flag) self . y += self . direction * self . axis_flag Ziggurate . add_exit_gate(self . exit) return self . exit def pass_switcher(self, state): """Set direction of explorer's movement (forward/backward).""" self . axis_flag = 0 if self . axis_flag else 1 self . direction = - self . direction if state == 'B' else self . direction @ staticmethod def is_exit(n, x, y): """Check if explorer reaches exit gate.""" return True if (0 <= x < n) and (0 <= y < n) else False @ classmethod def shift_switcher(cls, x, y): """Change state of switcher ('A'/'B').""" item = cls . board[x][y] cls . board[x][y] = 'A' if item == 'B' else 'B' return cls . board @ classmethod def set_board(cls, board): cls . board = [ [column if column != ' ' else None for column in raw] for raw in board ] return cls . board @ classmethod def add_exit_gate(cls, exit_gate): cls . exit_gates . append(exit_gate) def ride_of_fortune(artifact, explorers): Ziggurate . set_board(artifact) return [ Ziggurate(explorer_gate). travers_ziggurate() for explorer_gate in explorers ]
Ziggurat Ride of Fortune
5a8cacb2d5261f53ec0031f3
[ "Arrays", "Performance", "Algorithms" ]
https://www.codewars.com/kata/5a8cacb2d5261f53ec0031f3
5 kyu
Given the number pledged for a year, current value and name of the month, return string that gives information about the challenge status: - ahead of schedule - behind schedule - on track - challenge is completed Examples: `(12, 1, "February")` - should return `"You are on track."` `(12, 1, "March")` - should return `"You are 1 behind schedule."` `(12, 5, "March")` - should return `"You are 3 ahead of schedule."` `(12, 12, "September")` - should return `"Challenge is completed."` Details: - you do not need to do any prechecks (input will always be a natural number and correct name of the month) - months should be as even as possible (i.e. for 100 items: January, February, March and April - 9, other months 8) - count only the item for completed months (i.e. for March check the values from January and February) and it means that for January you should always return `"You are on track."`.
reference
MONTH = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] def check_challenge(pledged, current, month): d, p = divmod(pledged, 12) plg = [d + 1] * p + [d] * (12 - p) diff = current - sum(plg[: MONTH . index(month)]) return ('Challenge is completed.' if current >= pledged else 'You are on track.' if diff == 0 or month == 'January' else 'You are {} ahead of schedule!' . format(diff) if diff > 0 else 'You are {} behind schedule.' . format(- diff))
Progress of a challenge
584acd331b8b758fe700000d
[ "Fundamentals" ]
https://www.codewars.com/kata/584acd331b8b758fe700000d
6 kyu
# Convergents of e The square root of `$2$` can be written as an infinite continued fraction. ```math \displaystyle{\sqrt{2} = 1 + \dfrac{1}{2 + \dfrac{1}{2 + \dfrac{1}{2 + \dfrac{1}{2 + ...}}}}} ``` The infinite continued fraction can be written, `$\sqrt{2} = [1; (2)]$`, `$(2)$` indicates that `$2$` repeats ad infinitum. In a similar way, `$\sqrt{23} = [4;(1,3,1,8)]$`. It turns out that the sequence of partial values of continued fractions for square roots provide the best rational approximations. Let us consider the convergents for `$\sqrt{2}$`. ```math 1 + \dfrac{1}{2} = \dfrac{3}{2}\\[10pt] 1 + \dfrac{1}{2 + \dfrac{1}{2}} = \dfrac{7}{5}\\[10pt] 1 + \dfrac{1}{2 + \dfrac{1}{2 + \dfrac{1}{2}}} = \dfrac{17}{12}\\[10pt] 1 + \dfrac{1}{2 + \dfrac{1}{2 + \dfrac{1}{2 + \dfrac{1}{2}}}} = \dfrac{41}{29} ``` Hence the sequence of the first ten convergents for `$\sqrt{2}$` are: `$1, \dfrac{3}{2}, \dfrac{7}{5}, \dfrac{17}{12}, \dfrac{41}{29}, \dfrac{99}{70}, \dfrac{239}{169}, \dfrac{577}{408}, \dfrac{1393}{985}, \dfrac{3363}{2378}, ...$` What is most surprising is that the important mathematical constant, `$e = [2; 1, 2, 1, 1, 4, 1, 1, 6, 1, ... , 1, 2k, 1, ...]$` The first ten terms in the sequence of convergents for e are: `$2, 3, \dfrac{8}{3}, \dfrac{11}{4}, \dfrac{19}{7}, \dfrac{87}{32}, \dfrac{106}{39}, \dfrac{193}{71}, \dfrac{1264}{465}, \dfrac{1457}{536}, ...$` The sum of digits in the numerator of the `$10$`th convergent is `$1+4+5+7=17$`. Find the sum of digits in the numerator of the mth convergent of the continued fraction for e. - Powered by [Project Euler](https://projecteuler.net/problem=65)
reference
e = [1, 2] for n in range(1, 10 * * 4): for f in 1, 2 * n, 1: e . append(f * e[- 1] + e[- 2]) def convergents_of_e(n): return sum(map(int, str(e[n])))
Convergents of e
5a8d63930025e92f4c000086
[ "Fundamentals" ]
https://www.codewars.com/kata/5a8d63930025e92f4c000086
5 kyu
You are given a matrix of `m rows` and `n columns` having integer numbers, positive an negative ones. You have to rearrenge it in order to have `all the rows sorted from left to right` and `all the columns sorted from top to bottom.` E.g.: Case 1: Square Matrix 3x3 ``` matrix1 = [[7, 1, 4], [3, 2, 8], [6, -1, -6]] res1 = [[-6, -1, 6], [1, 3, 7], [2, 4, 8]] # having the required order ``` Case 2: Square Matrix 5x5 ``` matrix2 = [[7, 1, 4, 2, -55], [8, 2, -33, 1, 9], [5, 61, -9, 3, 8], [2, -12, 9, 51, 6], [4, 7, 2, 2, 1]] res2 = [[-55, 1, 2, 4, 7], [-33, 1, 2, 4, 7], [-12, 2, 2, 8, 9], [ -9, 2, 5, 8, 51], [ 1, 3, 6, 9, 61]] # having the required order ``` Case 3: Rectangle Matrix 5x3 ``` matrix3 = [[7, 1, 4, 37, 28], [3, 2, 8, 12, -8], [6, -1, -6, 7, 55]] res3 = [[-8, -1, 3, 7, 12], [-6, 2, 6, 8, 37], [ 1, 4, 7, 28, 55]] # having the required order ``` You will not be given a matrix with all the same elements Features of the random tests for matrices mxn: ``` number of tests = 100 10 ≤ m ≤ 100 10 ≤ n ≤ 100 -10000 ≤ m[i,j] ≤ 10000 ``` Enjoy it! Only available for Python 2 by the moment. Note: there are often different valid solutions. Use the algorithm you prefer, all that matters is that your answer fulfills the order requirement.
reference
def order(matrix): matrix = [sorted(row) for row in matrix] matrix = [sorted(row) for row in zip(* matrix)] return list(zip(* matrix))
#5 Matrices: Sort The Matrix
590363d57e16c9b3c0000014
[ "Algorithms", "Matrix", "Sorting", "Data Structures", "Fundamentals" ]
https://www.codewars.com/kata/590363d57e16c9b3c0000014
6 kyu
In this kata, you will sort elements in an array by decreasing frequency of elements. If two elements have the same frequency, sort them by increasing value. ```haskell solve([2,3,5,3,7,9,5,3,7]) = [3,3,3,5,5,7,7,2,9] -- We sort by highest frequency to lowest frequency. -- If two elements have same frequency, we sort by increasing value. ``` ```cpp solve({2,3,5,3,7,9,5,3,7}) == {3,3,3,5,5,7,7,2,9} // We sort by highest frequency to lowest frequency. // If two elements have same frequency, we sort by increasing value. ``` ```java Solution.sortByFrequency(new int[]{2, 3, 5, 3, 7, 9, 5, 3, 7}); // Returns {3, 3, 3, 5, 5, 7, 7, 2, 9} // We sort by highest frequency to lowest frequency. // If two elements have same frequency, we sort by increasing value. ``` More examples in test cases. ~~~if:lambdacalc ### Encodings purity: `LetRec` numEncoding: `BinaryScott` export constructors `nil, cons` and deconstructor `foldl` for your `List` encoding ~~~ Good luck! Please also try [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2)
algorithms
from collections import Counter def solve(a): c = Counter(a) return sorted(a, key=lambda k: (- c[k], k))
Simple frequency sort
5a8d2bf60025e9163c0000bc
[ "Algorithms", "Sorting", "Arrays" ]
https://www.codewars.com/kata/5a8d2bf60025e9163c0000bc
6 kyu
In this Kata, you will be given a string and two indexes (`a` and `b`). Your task is to reverse the portion of that string between those two indices inclusive. ~~~if-not:fortran ``` solve("codewars",1,5) = "cawedors" -- elements at index 1 to 5 inclusive are "odewa". So we reverse them. solve("cODEWArs", 1,5) = "cAWEDOrs" -- to help visualize. ``` ~~~ ~~~if:fortran ``` solve("codewars",2,6) = "cawedors" -- elements at indices 2 to 6 inclusive are "odewa". So we reverse them. solve("cODEWArs", 2,6) = "cAWEDOrs" -- to help visualize. ``` ~~~ Input will be lowercase and uppercase letters only. The first index `a` will always be lower that than the string length; the second index `b` can be greater than the string length. More examples in the test cases. Good luck! Please also try: [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2) [Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7) ~~~if:fortran *NOTE: You may assume that all input strings will* **not** *contain any (redundant) trailing whitespace. In return, your returned string is* **not** *permitted to contain any (redundant) trailing whitespace.* ~~~
algorithms
def solve(s, a, b): return s[: a] + s[a: b + 1][:: - 1] + s[b + 1:]
Simple string reversal II
5a8d1c82373c2e099d0000ac
[ "Algorithms" ]
https://www.codewars.com/kata/5a8d1c82373c2e099d0000ac
7 kyu
We have to find the longest substring of identical characters in a very long string. Let's see an example: ``` s1 = "1111aa994bbbb1111AAAAAFF?<mmMaaaaaaaaaaaaaaaaaaaaaaaaabf" ``` The longest substring in ```s1``` is ```"aaaaaaaaaaaaaaaaaaaaaaaaa"``` having a length of ```25```, made of character, "a", with its corresponding ascii code equals to ```"97"```, and having its starting index ```29``` and the ending one ```53```. We express the results using an array in the following order: ```["97", 25, [29,53]]``` The symbols ```'!"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~'``` that a string may have will be considered as noise, so they cannot be a solution even though the substring, made of one of them, is the longest of all. In other words, the allowed characters may be the uppercase or lower letters of the English alphabet or the decimal digits (```'0123456789'```) Let's see an example to show what happens if we have non alphanumeric symbols. ```s2 = "1111aa994bbbb1111AAAAAFF????????????????????????????"``` The longest substring is ```"AAAAA"``` so the result for it is: ``` ['65', 5, [17, 21]] ``` If there are two or more substrings with the maximum length value, it will be chosen the one that starts first, from left to right. Make an agile code that may output an array like the one shown above when it receives a huge string. Features of the random tests: ``` number of tests = 210 length of the strings up to a bit more than: 10.000.000 (python and javascript) 6.000.000 (ruby) ```
reference
import re def find_longest_substr(s): m = max(re . finditer(r'([A-Za-z0-9])\1*', s), key=lambda m: m . end() - m . start()) return [str(ord(m . group(1))), m . end() - m . start(), [m . start(), m . end() - 1]]
#1 Strings: Find The Longest Substring and Required Data.
59167d51c63c18af32000055
[ "Fundamentals", "Strings", "Algorithms" ]
https://www.codewars.com/kata/59167d51c63c18af32000055
6 kyu
**Principal Diagonal** -- The principal diagonal in a matrix identifies those elements of the matrix running from North-West to South-East. **Secondary Diagonal** -- the secondary diagonal of a matrix identifies those elements of the matrix running from North-East to South-West. For example: ``` matrix: [1, 2, 3] [4, 5, 6] [7, 8, 9] principal diagonal: [1, 5, 9] secondary diagonal: [3, 5, 7] ``` ## Task Your task is to find which diagonal is "larger": which diagonal has a bigger sum of their elements. * If the principal diagonal is larger, return `"Principal Diagonal win!"` * If the secondary diagonal is larger, return `"Secondary Diagonal win!"` * If they are equal, return `"Draw!"` **Note:** You will always receive matrices of the same dimension.
reference
def diagonal(m): P = sum(m[i][i] for i in range(len(m))) S = sum(m[i][- i - 1] for i in range(len(m))) if P > S: return "Principal Diagonal win!" elif S > P : return "Secondary Diagonal win!" else : return 'Draw!'
Principal Diagonal | VS | Secondary Diagonal
5a8c1b06fd5777d4c00000dd
[ "Fundamentals", "Matrix", "Algorithms" ]
https://www.codewars.com/kata/5a8c1b06fd5777d4c00000dd
7 kyu
# Definition A **_Tidy number_** *is a number whose* **_digits are in non-decreasing order_**. ___ # Task **_Given_** a number, **_Find if it is Tidy or not_** . ____ # Warm-up (Highly recommended) # [Playing With Numbers Series](https://www.codewars.com/collections/playing-with-numbers) ___ # Notes * **_Number_** *passed is always* **_Positive_** . * **_Return_** *the result as* a **_Boolean_** ~~~if:prolog * Since prolog doesn't have booleans, return value should be 1 for (True) or 0 for (false) ~~~ ___ # Input >> Output Examples ``` tidyNumber (12) ==> return (true) ``` ## **_Explanation_**: **_The number's digits_** `{ 1 , 2 }` are *in non-Decreasing Order* (i.e) *1 <= 2* . ____ ``` tidyNumber (32) ==> return (false) ``` ## **_Explanation_**: **_The Number's Digits_** `{ 3, 2}` are **_not in non-Decreasing Order_** (i.e) *3 > 2* . ___ ``` tidyNumber (1024) ==> return (false) ``` ## **_Explanation_**: **_The Number's Digits_** `{1 , 0, 2, 4}` are **_not in non-Decreasing Order_** as *0 <= 1* . ___ ``` tidyNumber (13579) ==> return (true) ``` ## **_Explanation_**: **_The number's digits_** `{1 , 3, 5, 7, 9}` are *in non-Decreasing Order* . ____ ``` tidyNumber (2335) ==> return (true) ``` ## **_Explanation_**: **_The number's digits_** `{2 , 3, 3, 5}` are *in non-Decreasing Order* , **_Note_** *3 <= 3* ___ ___ ___ # [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) # [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored) ___ ## ALL translations are welcomed ## Enjoy Learning !! # Zizou
reference
def tidyNumber(n): s = list(str(n)) return s == sorted(s)
Tidy Number (Special Numbers Series #9)
5a87449ab1710171300000fd
[ "Fundamentals", "Arrays", "Strings" ]
https://www.codewars.com/kata/5a87449ab1710171300000fd
7 kyu
# Introduction and Warm-up (Highly recommended) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) ___ # Definition An **_element is leader_** *if it is greater than The Sum all the elements to its right side*. ____ # Task **_Given_** an *array/list [] of integers* , **_Find_** *all the **_LEADERS_** in the array*. ___ # Notes * **_Array/list_** size is *at least 3* . * **_Array/list's numbers_** Will be **_mixture of positives , negatives and zeros_** * **_Repetition_** of numbers in *the array/list could occur*. * **_Returned Array/list_** *should store the leading numbers **_in the same order_** in the original array/list* . ___ # Input >> Output Examples ``` arrayLeaders ({1, 2, 3, 4, 0}) ==> return {4} ``` ## **_Explanation_**: * `4` *is greater than the sum all the elements to its right side* * **_Note_** : **_The last element_** `0` *is equal to right sum of its elements (abstract zero)*. ____ ``` arrayLeaders ({16, 17, 4, 3, 5, 2}) ==> return {17, 5, 2} ``` ## **_Explanation_**: * `17` *is greater than the sum all the elements to its right side* * `5` *is greater than the sum all the elements to its right side* * **_Note_** : **_The last element_** `2` *is greater than the sum of its right elements (abstract zero)*. ___ ``` arrayLeaders ({5, 2, -1}) ==> return {5, 2} ``` ## **_Explanation_**: * `5` *is greater than the sum all the elements to its right side* * `2` *is greater than the sum all the elements to its right side* * **_Note_** : **_The last element_** `-1` *is less than the sum of its right elements (abstract zero)*. ___ ``` arrayLeaders ({0, -1, -29, 3, 2}) ==> return {0, -1, 3, 2} ``` ## **_Explanation_**: * `0` *is greater than the sum all the elements to its right side* * `-1` *is greater than the sum all the elements to its right side* * `3` *is greater than the sum all the elements to its right side* * **_Note_** : **_The last element_** `2` *is greater than the sum of its right elements (abstract zero)*. ___ ___ ___ # [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) # [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored) ___ ## ALL translations are welcomed ## Enjoy Learning !! # Zizou
reference
def array_leaders(numbers): return [n for (i, n) in enumerate(numbers) if n > sum(numbers[(i + 1):])]
Array Leaders (Array Series #3)
5a651865fd56cb55760000e0
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5a651865fd56cb55760000e0
7 kyu
## Task You're given two non-negative numbers `(0 <= x,y)`. The goal is to create a function named `simple_sum` which return their sum. ## Restrictions The restrictions can be summurized as 'bit and logical operations are allowed'. Here comphrensive description. You're code __mustn't__ contain: ``` 1. `import`, `getattr`, `exec`, `eval`, `sum` # with next point produce short solutions, 2. `int` class methods names # but here is another idea. 3. `__loader__`, `vars`, `__dict__` # even more of them. 4. `if`, `in`, `is` # they start with `i` :) 5. `+`, `-`, `*`, `/`, `//`, `%` # arithmetic operations 6. `==`, `!=`, `<`, `>`, `<=`, `>=` # comparisions ``` ## Note **Inspired by [suic](https://www.codewars.com/users/553bfb4e8234ef15340000b9)'s katas** **Please assess the difficulty of the kata when you finish it :)**
reference
def simple_sum(x, y): while x: x, y = ((x & y) << 1), (x ^ y) return y
Simple Sum (with restrictions)
584c692db32364474000000a
[ "Puzzles", "Restricted" ]
https://www.codewars.com/kata/584c692db32364474000000a
6 kyu
Several officials, managers and even athletes of your national football league have been charged with corruption allegations. The upcoming season is at stake. With only a few days to go, the season's pairings have not yet been established. In search for trustworthy individuals you were assigned this important task. Implement a function 'schedule' that takes a list of teams and returns a list containing a season's pairings, such that the following criteria are met: * the number of teams must be even. * every team competes on every matchday * every team competes against all other teams exactly once. * the difference between home and away games is exactly 1 for all teams, i.e. every team either has one home match more than it has away matches or vice versa. The function takes a single argument of the form: ```python ["team a", "team b", ..] ``` The function's return value has the following structure: ```python [[("team a", "team b"), ..], ..] ``` where a is the home team and b the contender. The inner list represents a single day and contains all pairings for that day. The outer list contains all days of the season. A valid example for a league of four teams would be: ```python >>> schedule(['a', 'b', 'c', 'd']) [[('d', 'a'), ('c', 'b')], [('b', 'a'), ('d', 'c')], [('a', 'c'), ('b', 'd')]] ``` Of the many valid solutions, you may return any. Invalid input should raise an exception.
algorithms
def schedule(teams): if len(teams) % 2: raise ValueError season = [] for _ in range(len(teams) - 1): season . append([(teams[i], teams[- 1 - i]) if i or len(season) % 2 else (teams[- 1 - i], teams[i]) for i in range(len(teams) / / 2)]) teams = [teams[0], teams[- 1]] + teams[1: - 1] return season
Football Season
584d9a8fd2d637cccf00017a
[ "Combinatorics", "Permutations", "Algorithms" ]
https://www.codewars.com/kata/584d9a8fd2d637cccf00017a
5 kyu
This is a question from codingbat Given an integer n greater than or equal to 0, create and return an array with the following pattern: squareUp(3) => [0, 0, 1, 0, 2, 1, 3, 2, 1] squareUp(2) => [0, 1, 2, 1] squareUp(4) => [0, 0, 0, 1, 0, 0, 2, 1, 0, 3, 2, 1, 4, 3, 2, 1] ~~~if-not:bf 0 <= `n` <= 1000. ~~~ ~~~if:bf 0 <= `n` <= 255 ~~~ # Check out my other kata! <a title="Matrix Diagonal Sort OMG" href="https://www.codewars.com/kata/5ab1f8d38d28f67410000090">Matrix Diagonal Sort OMG</a> <a title="String -> N iterations -> String" href="https://www.codewars.com/kata/5ae43ed6252e666a6b0000a4">String -> N iterations -> String</a> <a title="String -> X iterations -> String" href="https://www.codewars.com/kata/5ae64f28d2ee274164000118">String -> X iterations -> String</a> <a title="ANTISTRING" href="https://www.codewars.com/kata/5ab349e01aaf060cd0000069">ANTISTRING</a> <a title="Array - squareUp b!" href="https://www.codewars.com/kata/5a8bcd980025e99381000099">Array - squareUp b!</a> <a title="Matrix - squareUp b!" href="https://www.codewars.com/kata/5a972f30ba1bb5a2590000a0">Matrix - squareUp b!</a> <a title="Infinitely Nested Radical Expressions" href="https://www.codewars.com/kata/5af2b240d2ee2764420000a2">Infinitely Nested Radical Expressions</a> <a title="pipi Numbers!" href="https://www.codewars.com/kata/5af27e3ed2ee278c2c0000e2">pipi Numbers!</a>
games
def square_up(n): return [j if j <= i else 0 for i in range(1, n + 1) for j in range(n, 0, - 1)]
Array - squareUp b!
5a8bcd980025e99381000099
[ "Mathematics", "Arrays" ]
https://www.codewars.com/kata/5a8bcd980025e99381000099
7 kyu
In this challenge, you will be creating a go board that users can play a game of go on. An understanding of the rules of go should be sufficient enough to complete this kata. The main goals for this kata: - Creating a go board to a specific size. - Placing go stones on the board. (White and Black alternating). - Capturing stones and removing them from the board. - Catching invalid moves (throw an `IllegalArgumentException` in Java). - Placing Handicap stones. Scoring is not covered in this kata. # Details ### Creating a board Outputting the board after it has been created should return an array of arrays filled with dots (representing empty spaces). ```javascript let game = new Go(9); game.board; ``` ```coffeescript game = new Go 9 game.board ``` ```python game = Go(9) game.board ``` ```java Go game = new Go(9); char[][] board = game.getBoard(); ``` ##### output ``` . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ``` ### Placing stones on board When given valid coordinates (one or several arguments, see example tests) the program should place either a white stone `o` or a black stone `x` in the correct position. _Note that the letter I is omitted from possible coordinates_. ```javascript game.move('7A'); game.move('1A'); game.board; ``` ```coffeescript game.move '7A' game.move '1A' game.board ``` ```python game.move('7A') game.move('1A') game.board ``` ```java game.move("7A"); game.move("1A"); char[][] board = game.getBoard(); ``` ##### output ``` A B C D E F G H J 9 . . . . . . . . . 8 . . . . . . . . . 7 x . . . . . . . . 6 . . . . . . . . . 5 . . . . . . . . . 4 . . . . . . . . . 3 . . . . . . . . . 2 . . . . . . . . . 1 o . . . . . . . . ``` ### Capturing ##### liberties As a side note, to understand capturing you need to understand the concept of liberties. They are the spaces surounding a stone/stones that are not out of bounds and are not occupied by the opponents stones. Take a look at these examples. ``` Black has 4 liberties Group of black has 5 liberties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . o . . . . . . . o . . . . . . . 1 . . . . . . . . 1 o . . . . . . 2 x 4 . . . . . . 2 x x o . . . . . . 3 . . . . . . . . 3 x 5 . . . . . . . . . . . . . . . . 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ``` When a group of white or black stones has no more liberties the group should be removed from the board. Take this board for example. ``` . x o o o o o . . . x o o o o o x . . . x o o o x . . . . . x o o x . . . . x . x x . . . . . . . . . . o . . . x . . . . . . . . . x . . o . . . . . . . . . . . ``` Calling `game.move('9H');` will remove the white stones from the board. ``` . x . . . . . x . . x . . . . . x . . . x . . . x . . . . . x . . x . . . . x . x x . . . . . . . . . . o . . . x . . . . . . . . . x . . o . . . . . . . . . . . ``` ##### Self-capturing Placing a white stone on the 1 below would be an illegal move. ``` . x o o o o o 1 x . x o o o o o x . . . x o o o x . . . . . x o o x . . . . x . x x . . . . . . . . . . o . . . x . . . . . . . . . x . . o . . . . . . . . . . . ``` ### Invalid moves - Simple Ko Rule should be implemented (One may not play in such a way as to recreate the board position following one's previous move). - Self-capturing (suicide) is illegal. - Cannot play out of bounds. - Cannot place a stone on another stone. ### KO Rule To further explain the KO rule, take a look at these go boards. ``` . . o . o x . . . . . o x . x . . . . . o . o x . . . . . . o x . . . . . . . o x . . . . . . . o x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Move 1 Move 2 Move 3 (Illegal) ``` These moves could loop over and over again. That is why move 3 is illegal according to simple KO rule, because it recreates the same board as the board after the previous move by white (move 1). _Note :_ If any illegal move is attempted, an error should be thrown and the board rolled back to the previous board before the illegal move. That player will have another chance to place their stone. ### Handicap stones Handicap stones are used to make a game more fair when two players of different ranks play. The order of handicap stones (least to greatest). ``` 9x9 13x13 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 . . . 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 . . 8 . . 1 . . . . . . . 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 . . . 3 . . . . . 6 . . 5 . . 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 . . 9 . . 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19x19 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 . . . . . 8 . . . . . 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 . . . . . 5 . . . . . 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 . . . . . 9 . . . . . 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ``` This next example should place 3 handicap stones on a 19x19 board in the correct order mentioned above. ```javascript let game = new Go(19); game.handicapStones(3); ``` ```coffeescript game = new Go 19 game.handicapStones 3 ``` ```python game = Go(19) game.handicap_stones(3) ``` ```java Go game = new Go(19); game.handicapStones(3); ``` ### Invalid handicap usage - Handicap stones can only be placed on 9x9, 13x13 and 19x19 boards. Throw an error otherwise. - A player cannot place down handicap stones after the first move has been made or handicap stones have already been placed. Throw an error if this happens. - Placing too many handicap stones for a given board should throw an error. ### Breakdown of a turn For clarity, let's go over the general flow of each turn throughout the game. - After a player makes a move, all opponent stones without liberties should be captured and removed from the board. - Check to make sure a move is valid before proceeding. A player should not be able to make a move that will result in the loss of their stones due to lack of liberties (Suicide). The board also shouldn't be identical to the one after the previous move made by the same player (KO Rule). - Rollback and let the player try again if a move is illegal. # Additional functionality ### size Given this new game. ```javascript let game = new Go(9,6); ``` ```coffeescript game = new Go 9,6 ``` ```python game = Go(9,6) ``` ```java Go game = new Go(9,6); ``` When `game.size` (`game.getSize()` in java) is called, it should return a mapping `{"height": 9, "width": 6}`. ### rollback User should be able to rollback a set amount of turns on the go board. ### get position User should be able to get status of a particular position on the board (x, o, or .). ```javascript game.getPosition("1A") // x, o , or . ``` ```coffeescript game.getPosition '1A' # x, o , or . ``` ```python game.get_position("1A") # x, o, or . ``` ### turn Get the current turn color. ```javascript game.turn // "black" game.pass() game.turn // "white" ``` ```coffeescript game.turn # 'black' game.pass() game.turn # 'white' ``` ```python game.turn # "black" game.pass_turn() game.turn # "white" ``` ```java game.getTurn(); // "black" game.passTurn(); game.getTurn(); // "white" ``` ### reset Resetting the board should clear all of the stones from it and set the turn to `"black"`. ### pass User should be able to pass their turn. _Note :_ Passing should count as a turn, so rollbacks need to account for this. # Language Specifics `Python` - Methods are in snake case (`function_name`). - Creating a game does not need `new`. - The `pass` method is `pass_turn`. `JavaScript`, `Coffeescript` & `Java` - Methods are in camel case (`functionName`).
algorithms
from copy import deepcopy class Go: MOVES = [(1, 0), (- 1, 0), (0, 1), (0, - 1)] SYMBOLS = "xo" HANDICAP = {(9, 9): ['7G', '3C', '3G', '7C', '5E'], (13, 13): ['10K', '4D', '4K', '10D', '7G', '7D', '7K', '10G', '4G'], (19, 19): ['16Q', '4D', '4Q', '16D', '10K', '10D', '10Q', '16K', '4K']} def __init__(self, * args): if not all(0 < v < 26 for v in args): raise ValueError("This is sooooo wrong... :p") args = args * 2 self . lenX, self . lenY = args[: 2][:] self . pos = {str(i) + chr(65 + j + (j >= 8)): (args[0] - i, j) for i in range(1, args[0] + 1) for j in range(args[1])} self . p, self . archive, self . board, self . hasHandi = self . initializer( * args) @ property def size(self): return {z: v for z, v in zip( ["height", "width"], (self . lenX, self . lenY))} @ property def turn(self): return "white" if self . p else "black" def initializer(self, * args): return 0, [], [['.'] * args[1] for _ in range(args[0])], False def reset(self): self . p, self . archive, self . board, self . hasHandi = self . initializer( self . lenX, self . lenY) # raise an exception if invalid position def get_position( self, pos): x, y = self . pos[pos] return self . board[x][y] def updatePlayer(self): self . p ^= 1 def pass_turn(self): self . archive . append(deepcopy(self . board)) self . updatePlayer() def rollback(self, n=1): for _ in range(n): self . board = self . archive . pop() self . updatePlayer() def rollInvalidMove_Raise(self, msg): self . rollback() self . updatePlayer() # Restore current player if invalid move raise ValueError(msg) def handicap_stones(self, n): if self . hasHandi or self . archive or self . p: raise ValueError("No, I wont...") self . hasHandi = True # raise an exception if invalid size of the board pos = iter(self . HANDICAP[(self . lenX, self . lenY)]) for _ in range(n): # raise an exception of too many number of handicap stones asked for x, y = self . pos[next(pos)] self . board[x][y] = self . SYMBOLS[self . p] def move(self, * moves): for m in moves: self . archive . append(deepcopy(self . board)) # Archive for rollback x, y = self . pos . get(m, (- 1, - 1)) if (x, y) == (- 1, - 1) or self . board[x][y] != '.': self . rollInvalidMove_Raise(["Reproduction of stones does not work... (at {})" . format(m), "Play in the board, damn you!!"][(x, y) == (- 1, - 1)]) # Retrieve player and opponent symbols player, opp = self . SYMBOLS[::(- 1) * * (2 * * self . p ^ 1)] self . board[x][y] = player # Update the board around = [(x + dx, y + dy) for dx, dy in self . MOVES if 0 <= x + dx < self . lenX and 0 <= y + dy < self . lenY and self . board[x + dx][y + dy] != '.'] # {"x": list of tuples [(set of (x,y), liberty count), ...], "o": ...} grpsAround = {player: [], opp: []} for a, b in around + [(x, y)]: # Extract all the groups (opponent AND player) around the concerned position: (sets of positions, liberties count), as many lists of tuples that there are groups of stones c = self . board[a][b] # Update the groups and lib value only if the current seed position is not already in a previously found group if not any((a, b) in neighGrp for neighGrp in grpsAround[c]): grpsAround[c]. append(self . floodLib(a, b, c)) isSuicidal = grpsAround[player][0][1] == 0 isCapturing = any(lib == 0 for _, lib in grpsAround[opp]) if isSuicidal and not isCapturing: # Forbid self-capturing (suicide) self . rollInvalidMove_Raise("You definitely have suicidal tendances") for grp, lib in grpsAround[opp]: if lib == 0: # Handle captures of opponent's stones for a, b in grp: self . board[a][b] = '.' # Remove opponent's stone # Check for KO rule if len(grp) == 1 and len(self . archive) > 2 and self . board == self . archive[- 2]: self . rollInvalidMove_Raise("You're knocked out! Again!") self . updatePlayer() # Change the current player def floodLib(self, x, y, c): # Floof-fill the board, retrieving all the pieces of the same group and counting its liberties at the same time pos = (x, y) seens, q, grp, lib = {pos}, {pos}, {pos}, 0 while q: x, y = q . pop() for dx, dy in self . MOVES: a, b = pos = x + dx, y + dy if 0 <= a < self . lenX and 0 <= b < self . lenY and pos not in seens: if self . board[a][b] == '.': lib += 1 elif self . board[a][b] == c: grp . add(pos) q . add(pos) seens . add(pos) return grp, lib
Game of Go
59de9f8ff703c4891900005c
[ "Games", "Performance", "Algorithms" ]
https://www.codewars.com/kata/59de9f8ff703c4891900005c
2 kyu
Make the 2D list by the sequential integers started by the ```head``` number. See the example test cases for the expected output. ``` Note: -10**20 < the head number <10**20 1 <= the number of rows <= 1000 0 <= the number of columms <= 1000 ```
reference
def make_2d_list(head, row, col): return [[head + c + r * col for c in range(col)] for r in range(row)]
2D list by the sequential integers
5a8897d4ba1bb5f266000057
[ "Fundamentals" ]
https://www.codewars.com/kata/5a8897d4ba1bb5f266000057
7 kyu
You will be given a list with the coefficients of a polynomial. Look the following order in both: ``` P(x) = 6x³ + 3x² + 5x -4 coefficients = [ 6, 3, 5, -4] ``` Your task is to express the polynomial like a string with its value for a certain determinate x: ```python [6, 3, 5, -4], 4 returns "For 6*x^3 + 3*x^2 + 5*x - 4 with x = 4 the value is 448" ``` If we have some coefficients equals to ```0```, its corresponding term will not be seen. ```python [2, 0, 5, -6, 4, 0], 2 returns "For 2*x^5 + 5*x^3 - 6*x^2 + 4*x with x = 2 the value is 88" ``` An interesting case will be when the first coefficient is equal to ```-1``` ```python [-1, -6, 28, 79], 35 returns "For -x^3 - 6*x^2 + 28*x + 79 with x = 35 the value is -49166" ``` The following answer will be considered incorrect: ```python "For -1x^3 - 6*x^2 + 28*x + 79 with x = 35 the value is -49166" ``` You will not receive an empty list and the values for the varible ```x``` will be valid for all the cases. Happy coding ^-^ !!
reference
import re def calc_poly(coefs, x): coefs = coefs[:: - 1] res = sum(x * * i * c for i, c in enumerate(coefs)) poly = ' + ' . join(["{}*x^{}" . format(c, i) for i, c in enumerate(coefs) if c][:: - 1]) poly = re . sub(r'\*x\^0|\^1\b|\b1\*(?!x\^0)', '', poly). replace("+ -", "- ") return "For {} with x = {} the value is {}" . format(poly, x, res)
Polynomials II: Coefficients In a List
5694b4f9a01ae685c400002f
[ "Fundamentals", "Mathematics", "Strings", "Logic" ]
https://www.codewars.com/kata/5694b4f9a01ae685c400002f
6 kyu
## Emotional Sort ( ︶︿︶) You'll have a function called "**sortEmotions**" that will return an array of **emotions** sorted. It has two parameters, the first parameter called "**arr**" will expect an array of **emotions** where an **emotion** will be one of the following: - **:D** -> Super Happy - **:)** -> Happy - **:|** -> Normal - **:(** -> Sad - **T\_T** -> Super Sad Example of the array:``[ 'T_T', ':D', ':|', ':)', ':(' ]`` And the second parameter is called "**order**", if this parameter is **true** then the order of the emotions will be descending (from **Super Happy** to **Super Sad**) if it's **false** then it will be ascending (from **Super Sad** to **Super Happy**) Example if **order** is true with the above array: ``[ ':D', ':)', ':|', ':(', 'T_T' ]`` - Super Happy -> Happy -> Normal -> Sad -> Super Sad If **order** is false: ``[ 'T_T', ':(', ':|', ':)', ':D' ]`` - Super Sad -> Sad -> Normal -> Happy -> Super Happy Example: ``` arr = [':D', ':|', ':)', ':(', ':D'] sortEmotions(arr, true) // [ ':D', ':D', ':)', ':|', ':(' ] sortEmotions(arr, false) // [ ':(', ':|', ':)', ':D', ':D' ] ``` **More in test cases!** Notes: - The array could be empty, in that case return the same empty array ¯\\\_( ツ )\_/¯ - All **emotions** will be valid ## Enjoy! (づ。◕‿‿◕。)づ
reference
def sort_emotions(arr, order): return sorted(arr, key=[':D', ':)', ':|', ':(', 'T_T']. index, reverse=not order)
Emotional Sort ( ︶︿︶)
5a86073fb17101e453000258
[ "Arrays", "Fundamentals", "Sorting" ]
https://www.codewars.com/kata/5a86073fb17101e453000258
6 kyu
### Please also check out other katas in [Domino Tiling series](https://www.codewars.com/collections/5d19554d13dba80026a74ff5)! --- # Task A domino is a rectangular block with `2` units wide and `1` unit high. A domino can be placed on a grid in two ways: horizontal or vertical. ``` ## or # # ``` You have infinitely many dominoes, and you want to fill a board that is `2*N` units wide and `5` units high: ``` <--- 2N ---> ################ ################ ################ ################ ################ ``` The task is to find **the number of ways** you can fill the given grid with dominoes. Since the answer will be very large, please give your answer **modulo 12345787**. # Examples ```javascript fiveBy2N(1) == 8 fiveBy2N(2) == 95 fiveBy2N(3) == 1183 fiveBy2N(5) == 185921 fiveBy2N(10) == 8228892 fiveBy2N(20) == 9942990 fiveBy2N(50) == 2308182 fiveBy2N(100) == 334896 fiveBy2N(1000) == 6032838 fiveBy2N(10000) == 2392948 ``` ```python five_by_2n(1) == 8 five_by_2n(2) == 95 five_by_2n(3) == 1183 five_by_2n(5) == 185921 five_by_2n(10) == 8228892 five_by_2n(20) == 9942990 five_by_2n(50) == 2308182 five_by_2n(100) == 334896 five_by_2n(1000) == 6032838 five_by_2n(10000) == 2392948 ``` # Constraints `1 <= N <= 10000` All inputs are valid integers. # Hint The reference solution uses eleven mutual recurrence equations.
games
import numpy as np def five_by_2n(n): x = np . array([[1, 1, 1, 1, 1, 1, 1, 1], [1, 2, 1, 1, 1, 2, 2, 1], [1, 1, 2, 1, 1, 1, 2, 1], [1, 1, 1, 2, 1, 1, 2, 1], [ 1, 1, 1, 1, 2, 1, 2, 2], [1, 2, 1, 1, 2, 1, 6, 1], [1, 2, 1, 1, 2, 1, 6, 1], [1, 2, 1, 1, 2, 1, 6, 1]]) y = np . array([1, 1, 1, 1, 1, 1, 1, 1]) z = y for i in range(n - 1): z = np . mod(x @ z, 12345787 * y) return z . T @ y % 12345787
Domino Tiling - 5 x 2N Board
5a77f76bfd5777c6c300001c
[ "Puzzles", "Mathematics", "Logic", "Dynamic Programming" ]
https://www.codewars.com/kata/5a77f76bfd5777c6c300001c
4 kyu
# Disclaimer This kata is an insane step-up from [myjinxin's Four Warriors and a Lamp](https://www.codewars.com/kata/t-dot-t-t-dot-51-four-warriors-and-a-lamp), so I recommend to solve it first before trying this one. (You'll also get a better understanding of the story, though it doesn't matter very much in solving the kata.) # Problem Description The story continues. After the great success of the Four Warriors, a whole army of `n` warriors have reached the entrance of the dreaded tunnel, which is still narrow and full of traps. Now the `n` warriors want to pass the tunnel, but the same rules apply: * At most two warriors can pass the tunnel at once. * There is still one lamp (probably due to stupid leader :P), so one person has to come back carrying the lamp before other people can pass the tunnel. * Each warrior has his own walking speed, which is given as the time to pass the tunnel in minutes. * The walking speed of two people is the slower one. Your task is to find the shortest possible time for the warriors to pass the tunnel, given the passing times of the warriors `times`. # Examples Four warriors `a, b, c, d` with speed `[3, 4, 5, 6]` will take 21 minutes: ``` a and b go through the tunnel ---> Spend 4 minutes a come back ---> Spend 3 minutes a and c go through the tunnel ---> Spend 5 minutes a come back ---> Spend 3 minutes a and d go through the tunnel ---> Spend 6 minutes ``` More examples: ```javascript shortestTime([10]) == 10 shortestTime([10, 11]) == 11 shortestTime([5, 10, 15]) == 30 shortestTime([3, 4, 5, 6]) == 21 shortestTime([5, 5, 6, 7]) == 27 shortestTime([3, 7, 10, 18]) == 41 shortestTime([5, 6, 30, 40]) == 63 shortestTime([1, 2, 4, 8, 16]) == 28 shortestTime([4, 5, 6, 7, 8, 9]) == 49 shortestTime([1, 7, 8, 9, 10, 11, 13, 14, 15, 16]) == 109 ``` ```python shortest_time([10]) == 10 shortest_time([10, 11]) == 11 shortest_time([5, 10, 15]) == 30 shortest_time([3, 4, 5, 6]) == 21 shortest_time([5, 5, 6, 7]) == 27 shortest_time([3, 7, 10, 18]) == 41 shortest_time([5, 6, 30, 40]) == 63 shortest_time([1, 2, 4, 8, 16]) == 28 shortest_time([4, 5, 6, 7, 8, 9]) == 49 shortest_time([1, 7, 8, 9, 10, 11, 13, 14, 15, 16]) == 109 ``` # Constraints * `1 <= length(times) <= 10000` * `1 <= times[i] <= 100` All input values are valid integers.
games
def shortest_time(times): times . sort() cost = 0 while len(times) > 3: t1 = times[0] + 2 * times[1] + times[- 1] t2 = 2 * times[0] + times . pop() + times . pop() cost += min(t1, t2) cost += sum(times) - sum(times[: - 1]) * (len(times) < 3) return cost
(Insane) N Warriors and a Lamp
5a77f725b17101edd5000020
[ "Puzzles", "Performance", "Logic", "Algorithms" ]
https://www.codewars.com/kata/5a77f725b17101edd5000020
5 kyu
*NOTE: It is highly recommended that you complete the first 4 Kata in this Series before attempting this final Kata; otherwise, the description would make little sense.* --- ```if:java <font color="orange"><b><i>For java users:</i></b></font> Each time you encounter an invalid case you 'll have to throw a `RuntimeException`. ``` --- ## RoboScript #5 - The Final Obstacle (Implement RSU) ### Disclaimer The story presented in this Kata Series is purely fictional; any resemblance to actual programming languages, products, organisations or people should be treated as purely coincidental. ### About this Kata Series This Kata Series is based on a fictional story about a computer scientist and engineer who owns a firm that sells a toy robot called MyRobot which can interpret its own (esoteric) programming language called RoboScript. Naturally, this Kata Series deals with the software side of things (I'm afraid Codewars cannot test your ability to build a physical robot!). ### Story Since **RS3** was released into the market which introduced handy pattern definitions on top of command grouping and repetition, its popularity soared within the robotics community, insomuch that other budding robotics firms have pleaded your company to allow them to use the RoboScript programming language in their products. In order to grant them their requests and protect your company at the same time, you decided to apply for a patent which would allow other companies to utilize RoboScript in their own products with certain restrictions and only with an annual fee paid to your company. So far, so good - the patent application was successful and your firm gained an ample amount of revenue in the first year from this patent alone. However, since RoboScript is still a rather small and domain-specific programming language, the restrictions listed on the patent were rather limited. Competing firms soon found a loophole in the wording of the patent which allowed them to develop their own RoboScript-like programming language with minor modifications and improvements which allowed them to legally circumvent your patent. Soon, these robotics firms start overtaking your company in terms of popularity, profitability and size. In order to investigate the main cause of the downfall of your company, a secret survey was sent to thousands of former MyRobot (and hence "official" RoboScript) users. It was revealed in this survey that the main reason for this downfall was due to the **lack of readability** of **RS3** code (and RoboScript code in general), especially as the program becomes very large and complex. After all, it makes perfect sense - who would even bother to try to understand and maintain the following **RS3** code, let alone *much* larger and complex programs? ``` p0FFLFFR((FFFR)2(FFFFFL)3)4qp1FRqp2FP1qp3FP2qp4FP3qP0P1P2P3P4 ``` In a final attempt to save your company from going bankrupt and disappearing from the world of robotics, you decide to address all of the major issues identified in the secret survey head-on by designing the fourth and *final* specification for the RoboScript programming language - **RoboScript Ultimatum (RSU)**. The only thing left for you to do is to properly implement the specification by writing an RSU-compliant code executor - once that is achieved, your company will catapult back into 1st position in global robotics and perhaps even leave a mark in the history of technology ... ### Task #### RoboScript Ultimatum (RSU) - The Official Specification RoboScript Ultimatum (RSU) is a superset of the RS3 specification (which itself is a superset of RS2, RS2 being a superset of RS1). However, it introduces quite a few new (and handy) features. ##### 1. Whitespace and Indentation Support In RSU, whitespace and indentation is supported to improve readability and can appear *anywhere* in the program *in any form* **except within a token itself** (explained in more detail later). For example, the program below is valid: ``` p0 ( F2 L )2 ( F2 R )2 q ( P0 )2 ``` While the following program is **not** valid: ``` p 0 ( F 2L ) 2 ( F 2 R ) 2 q ( P 0 )2 ``` Of course, the code *need not* be neatly indented - it should be valid *so long as* tokens such as `p0`, `F2`, `)2` do not contain any whitespace themselves. ##### 2. Comment Support RSU should support single line comments `(optional code) // ... ` and multiline comments `/* ... */` like in many other programming languages such as JavaScript. All single line comments are terminated by **either of** a newline character `\n` and the **end-of-file (EOF)** (beware of this edge case ;) ) and multiline comments *cannot* be nested. For example, this is a valid program with comments: ``` /* RoboScript Ultimatum (RSU) A simple and comprehensive code example */ // Define a new pattern with identifier n = 0 p0 // The commands below causes the MyRobot to move // in a short snake-like path upwards if executed ( F2 L // Go forwards two steps and then turn left )2 ( F2 R // Go forwards two steps and then turn right )2 q // Execute the snake-like pattern twice to generate // a longer snake-like pattern ( P0 )2 ``` Comments follow the same rules as whitespace and indentation - they can be placed *anywhere* within the program **except within a token itself**, e.g. `F/* ... */37` is **invalid**. Both single-line and multiline comments may be empty, i.e. `/**/` and `//\n` are valid. ##### 3. Pattern Scoping This is much like function and/or block scoping in many other programming languages. While attempts to nest a pattern definition in another pattern yielded undefined behavior in RS3, each pattern will have its own scope in RSU. Furthermore, each pattern will be able to "see" pattern definitions both in its own scope and in any subsequent parent scopes. For example: ``` // The global scope can "see" P1 and P2 p1 // P1 can see P2, P3 and P4 p3 // P3 can see P1, P2 and P4 though invoking // P1 will likely result in infinite recursion F L q p4 // Similar rules apply to P4 as they do in P3 F P3 q F P4 q p2 // P2 can "see" P1 and therefore can invoke P1 if it wishes F3 R q ( P1 P2 )2 // Execute both globally defined patterns twice ``` Furthermore, an RSU program is still **valid** if more than one pattern with the *same* identifier is defined **provided that they all appear in different scopes**. In case of an identifier conflict between two patterns of different scopes, the definition of the pattern in the **innermost** scope takes precedence. For example: ``` p1 p1 F R q F2 P1 // Refers to "inner" (locally defined) P1 so no infinite recursion results q ( F2 P1 // Refers to "outer" (global) P1 since the // global scope can't "see" local P1 )4 /* Equivalent to executing the following raw commands: F F F F F R F F F F F R F F F F F R F F F F F R */ ``` However, pattern *redefinition* in the same scope is **not** allowed and should throw an error at some stage (more details later). ##### Finally ... ... no other character sequences are allowed in an RSU program, such as "stray comments" as in `this is a stray comment not escaped by a double slash or slash followed by asterisk F F F L F F F R F F F L F F F R and lowercase "flr" are not acceptable as commands` or "stray numbers" as in `F 32R 298984`. Also, some edge cases in case you're wondering: 1. Zero postfixes (e.g. `F0`, `L0` and of course `P0`) are allowed (`F0` and `L0` do nothing while `P0` invokes pattern with identifier `n = 0`). 2. Empty pattern definitions / bracketed repeat sequences `p0 /* (empty) */ q`, `()`, `()23` are allowed. 3. Leading zeroes (except for the number `0` itself) should **not** be allowed - these errors should be thrown *during the tokenizing process* (more details later) as a "token" containing a number with leading zeroes is an invalid token. 4. Pattern definitions can contain brackets within them (of course!) but **bracketed sequences must NOT contain any pattern definitions**. Such errors should be detected in the second stage of RSU code processing. 5. Calls to infinitely recursive patterns and/or non-existent patterns within a bracketed sequence that is executed `0` times should *not* throw an error; they should simply be ignored. #### RSU Code Executor - Structure In this Kata, your RSU code executor should be a class `RSUProgram` with a class constructor which accepts a string `source`, the RSU source code to be executed. No error checking is required in this part. *NOTE: All methods described below must be properly implemented and will be tested extensively in the Submit tests - namely,* `getTokens`, `convertToRaw`, `executeRaw` and `execute` (*or the equivalent function/method names in your language,* **according to your language's naming convention(s)**). *If in doubt, you may always refer to the Sample Test Cases to get an idea of what will be tested in the Sumbit tests.* ##### Tokenizer Your class should have an *instance method* `getTokens` which accepts no arguments and returns the tokens present in `source` (argument passed to class constructor) **in order** as an array. The tokenizer should ignore all whitespace characters (except when they prevent a token from being identified, e.g. in `) 2`) and comments and should throw if it encounters one or more invalid tokens in the process. The following tokens are the *only* valid tokens: - Single commands `F`, `L` and `R` - Commands with repeats `Fn`, `Ln` and `Rn` (`n` being a non-negative integer which *may* exceed 1 digit but may *not* contain any leading `0`s) - Opening round brackets `(` - Closing round brackets, with or without a repeat prefix `)` **OR** `)n` (`n` a non-negative integer with the rules described above) - Pattern definition `pn` (`n` a non-negative integer ... ) - End of pattern definition `q` - Pattern invocation `Pn` (`n` a non-negative integer ... ) During the tokenizing process, do *not* perform any form of analysis checking the order of the tokens or whether a particular pattern invoked actually exists, etc. Such errors should be left to later stages. ##### Compiler Your class should have an *instance method* `convertToRaw` which accepts 1 argument `tokens` (an array of tokens, ideally returned from the tokenizer in the previous step) and returns an array of **raw commands** from processing the tokens. "Raw commands" are the most basic commands that can be understood by the robot natively, namely `F`, `L` and `R` (**nothing else**, *not even with prefixes* such as `F2` or `R5`). For example, the following RS3-compliant program from the Story: ``` p0FFLFFR((FFFR)2(FFFFFL)3)4qp1FRqp2FP1qp3FP2qp4FP3qP0P1P2P3P4 ``` ... can be converted into the following "raw commands" *after its tokenized form is passed in to this instance method* (indented for better visualization): ``` [ "F", "F", "L", "F", "F", "R", "F", "F", "F", "R", "F", "F", "F", "R", "F", "F", "F", "F", "F", "L", "F", "F", "F", "F", "F", "L", "F", "F", "F", "F", "F", "L", "F", "F", "F", "R", "F", "F", "F", "R", "F", "F", "F", "F", "F", "L", "F", "F", "F", "F", "F", "L", "F", "F", "F", "F", "F", "L", "F", "F", "F", "R", "F", "F", "F", "R", "F", "F", "F", "F", "F", "L", "F", "F", "F", "F", "F", "L", "F", "F", "F", "F", "F", "L", "F", "F", "F", "R", "F", "F", "F", "R", "F", "F", "F", "F", "F", "L", "F", "F", "F", "F", "F", "L", "F", "F", "F", "F", "F", "L", "F", "R", "F", "F", "R", "F", "F", "F", "R", "F", "F", "F", "F", "R" ] ``` See the "Sample Tests" for more examples. Remember from RS3 that placing a pattern invocation before its definition is valid, e.g. `P0P1P2P3P4p0FFLFFR((FFFR)2(FFFFFL)3)4qp1FRqp2FP1qp3FP2qp4FP3q` should produce the same result as the above program. On the other hand, the following RSU programs are *invalid* and should throw an error at this stage: - Unmatched bracketing and/or pattern definition sequences, e.g. `(p0q` or `p1(q)34` (an obvious syntax error) - **Nesting pattern definitions within bracketed sequences**, e.g. `(p0/* ... */q)`. This should be treated as a *syntax error* and as such, it should not appear *anywhere* within the program, even if it is nested within multiple pattern definitions and never invoked. - Attempting to invoke a non-existent pattern or one that invokes a non-existing pattern definition in its pattern body, etc., *in the global scope* - Attempting to invoke an infinitely recursive pattern *of any form* (including non-recursive patterns which call on infinitely recursive patterns in their pattern body, etc.) *in the global scope*. Extreme cases (e.g. `500` levels of non-infinite recursion) will *not* be tested in the test cases so a sensible recursion limit will do. As for the input token array `tokens`, you may assume that it will always be valid **provided that your tokenizer is working properly ;)** ##### Machine Instruction Executor Now that you've implemented the most challenging part of your `RSUProgram` class, it is time to wind down a little and implement something more straightforward :) Your class should have an *instance method* `executeRaw` which receives an array of raw commands (consisting of only `F`, `L` and/or `R`) returned from your compiler and returns a string representation of the path that the MyRobot walks on the floor. This string representation is identical in format as the ones required in Kata #2 through #4 of this Series. For example, the raw commands (comparable to machine instructions/code in computers) obtained from this program: ``` /* RoboScript Ultimatum (RSU) A simple and comprehensive code example */ // Define a new pattern with identifier n = 0 p0 // The commands below causes the MyRobot to move // in a short snake-like path upwards if executed ( F2 L // Go forwards two steps and then turn left )2 ( F2 R // Go forwards two steps and then turn right )2 q // Execute the snake-like pattern twice to generate // a longer snake-like pattern ( P0 )2 ``` ... should evaluate to the string `"* \r\n* \r\n***\r\n *\r\n***\r\n* \r\n***\r\n *\r\n***"`. Once again, you may assume that the array of raw commands passed in will always be valid **provided that your tokenizer and compiler are both working properly**. *Quick Tip: If you have completed Kata #2 of this Series (Implement the RS1 Specification), you may pass this section by simply copying and pasting your solution to that Kata here and making minor modifications.* #### One-Step Execution Hooray - you have successfully implemented an RSU-compliant code executor! In order to tidy things up a little, define an *instance method* `execute` which accepts no arguments and combines the three previous instance methods in a way such that when this method is invoked (without invoking any other methods before it), it tokenizes, compiles and executes the `source` (from the constructor) in one go and returns the string representation of the MyRobot's path. For example: ```javascript new RSUProgram(`/* RoboScript Ultimatum (RSU) A simple and comprehensive code example */ // Define a new pattern with identifier n = 0 p0 // The commands below causes the MyRobot to move // in a short snake-like path upwards if executed ( F2 L // Go forwards two steps and then turn left )2 ( F2 R // Go forwards two steps and then turn right )2 q // Execute the snake-like pattern twice to generate // a longer snake-like pattern ( P0 )2`).execute(); // => "* \r\n* \r\n***\r\n *\r\n***\r\n* \r\n***\r\n *\r\n***" ``` ```java List<String> lst = Arrays.asList( "/*", " RoboScript Ultimatum (RSU)", " A simple and comprehensive code example", "*/", "// Define a new pattern with identifier n = 0", "p0", " // The commands below causes the MyRobot to move", " // in a short snake-like path upwards if executed", " (", " F2 L // Go forwards two steps and then turn left", " )2 (", " F2 R // Go forwards two steps and then turn right", " )2", "q", "// Execute the snake-like pattern twice to generate", "// a longer snake-like pattern", "(", " P0", ")2"); new RSUProgram(String.join("\n",lst)).execute(); // => "* \r\n* \r\n***\r\n *\r\n***\r\n* \r\n***\r\n *\r\n***" ``` ```python RSUProgram("""/* RoboScript Ultimatum (RSU) A simple and comprehensive code example */ // Define a new pattern with identifier n = 0 p0 // The commands below causes the MyRobot to move // in a short snake-like path upwards if executed ( F2 L // Go forwards two steps and then turn left )2 ( F2 R // Go forwards two steps and then turn right )2 q // Execute the snake-like pattern twice to generate // a longer snake-like pattern ( P0 )2""").execute(); // => "* \r\n* \r\n***\r\n *\r\n***\r\n* \r\n***\r\n *\r\n***" ``` ### Kata in this Series 1. [RoboScript #1 - Implement Syntax Highlighting](https://www.codewars.com/kata/roboscript-number-1-implement-syntax-highlighting) 2. [RoboScript #2 - Implement the RS1 Specification](https://www.codewars.com/kata/roboscript-number-2-implement-the-rs1-specification) 3. [RoboScript #3 - Implement the RS2 Specification](https://www.codewars.com/kata/58738d518ec3b4bf95000192) 4. [RoboScript #4 - RS3 Patterns to the Rescue](https://www.codewars.com/kata/594b898169c1d644f900002e) 5. **RoboScript #5 - The Final Obstacle (Implement RSU)**
algorithms
import re class RSUProgram: ID_PATT_BRA = r'[PpRFL)](?:0|[1-9]\d*)|[RFLq()]' WHITE_COMMENTS = r'\s+|//.*?(?:\n|$)|/\*.*?\*/' TOKENIZER = re . compile(r'|' . join( [WHITE_COMMENTS, ID_PATT_BRA, r'.']), flags=re . DOTALL) VALID_TOKEN = re . compile(ID_PATT_BRA) IS_NOT_TOKEN = re . compile(WHITE_COMMENTS, flags=re . DOTALL) MOVES = ((0, 1), (1, 0), (0, - 1), (- 1, 0)) def __init__(self, prog): self . source = prog def convert_to_raw(self, tokens): return [ c for c, r in self . compileCode(tokens) for _ in range(r)] def execute(self): return self . execute_raw( '', self . compileCode(self . get_tokens())) def compileCode(self, tokens): scope = {'parent': None, 'cmd': ()} return self . applyPatterns(self . parseCode(iter(tokens), scope), scope, 0) def get_tokens(self): tokens = [] for tok in self . TOKENIZER . findall(self . source): if self . IS_NOT_TOKEN . match(tok): continue elif self . VALID_TOKEN . match(tok): tokens . append(tok) elif tok: raise Exception("Invalid expression found: {}" . format(tok)) return tokens def execute_raw(self, cmds, todo=None): pos, seens, iDir = (0, 0), {(0, 0)}, 0 # OVERRIDE todo/cmds TO BYPASS SPECIFICATIONS... for s, r in todo or ((c, 1) for c in cmds): if s == 'F': for _ in range(r): pos = tuple(z + dz for z, dz in zip(pos, self . MOVES[iDir])) seens . add(pos) else: iDir = (iDir + r * (- 1) * * (s == 'L')) % len(self . MOVES) miX, maX = (f(x for x, _ in seens) for f in (min, max)) miY, maY = (f(y for _, y in seens) for f in (min, max)) return '\r\n' . join('' . join('*' if (x, y) in seens else ' ' for y in range(miY, maY + 1)) for x in range(miX, maX + 1)) def parseCode(self, tokIter, scope, inPattern=0): cmds = [[]] for tok in tokIter: cmd, r = tok[0], int(tok[1:] or '1') isRepeat = cmds[- 1] and cmds[- 1][- 1] and cmds[- 1][- 1][0] == cmd if cmd in 'pq' and len(cmds) > 1: raise Exception("pattern definition inside brackets") if cmd == 'p': name = tok . upper() if name in scope: raise Exception("Invalid pattern: cannot define multiple patterns with the same name at the same level: {}\nScope: {}\n\n{}" . format( name, scope, self . source)) else: freshScope = {'parent': scope, 'cmds': ()} scope[name] = freshScope freshScope['cmds'] = self . parseCode(tokIter, freshScope, 1) elif cmd == 'q': if not inPattern: raise Exception('unopened pattern definition') inPattern = 0 break elif cmd == '(': cmds . append([]) elif cmd == ')': lst = cmds . pop() cmds[- 1]. extend(lst * r) elif isRepeat: cmds[- 1][- 1] = (cmd, cmds[- 1][- 1][1] + r) else: cmds[- 1]. append((tok, 1) if cmd == 'P' else (cmd, r)) if inPattern: raise Exception("unclosed pattern definition, last token: " + tok) if len(cmds) > 1: raise Exception("unclosed brackets, last token: " + tok) return cmds[0] def applyPatterns(self, rawCmds, scope, depth): if depth == 20: raise Exception("Stack overflow") lst = [] for c, r in rawCmds: if c[0] != 'P': lst . append((c, r)) else: pattern, nextScope = self . reachPattern(scope, c) lst . extend(self . applyPatterns(pattern, nextScope, depth + 1)) return lst def reachPattern(self, scope, name): calledP = scope . get(name) parent = scope['parent'] if calledP is not None: return calledP['cmds'], calledP if not parent: raise Exception("Unknown pattern: " + name) return self . reachPattern(parent, name)
RoboScript #5 - The Final Obstacle (Implement RSU)
5a12755832b8b956a9000133
[ "Compilers", "Interpreters", "Algorithms" ]
https://www.codewars.com/kata/5a12755832b8b956a9000133
1 kyu
A stick is balanced horizontally on a support. Will it topple over or stay balanced? (This is a physics problem: imagine a real wooden stick balanced horizontally on someone's finger or on a narrow table, for example). The stick is represented as a list, where each entry shows the mass in that part of the stick. The stick is balanced on a support. The "terrain" is represented by a list of 1s and 0s, where the 1s represent the support and the 0s represent empty space. Each index is a coordinate on the x-axis, so e.g. the physical interpretations of some terrains are as follows: ![](https://i.imgur.com/P4MpHZV.png) The stick will only balance if its centre of mass is directly above some part of its support. Return `True` if the stick will balance and `False` if it will topple. Both lists will be of equal length (that is, the stick and the terrain have equal width so that each index of the stick is directly above the corresponding index of the terrain). Every terrain will contain one, and only one, support. ## Examples: ![](https://i.imgur.com/PyMBsAl.png) ``` [2,3,2] [0,1,0] ---> Perfectly balanced, return True [5,1,1] [0,1,0] ---> will topple to the left, return False [3,3,4] [0,1,0] ---> will topple to the right (but only just) [7,1,1,1,1,1,1,1] [0,1,1,0,0,0,0,0] ---> will balance, perfectly, without a doubt [5, 3, 2, 8, 6] [0, 0, 0, 1, 1] ---> will topple to the left ```
reference
from math import ceil def will_it_balance(stick, gnd): gravPt = sum(v * i for i, v in enumerate(stick)) / sum(stick) return gnd[int(gravPt)] == gnd[ceil(gravPt)] == 1
Will it balance?
5a8328fefd57777fa3000072
[ "Fundamentals" ]
https://www.codewars.com/kata/5a8328fefd57777fa3000072
6 kyu
In Spanish, the conjugated verb changes by adding suffixes and according to the person we're talking about. There's something similar in English when we talk about "She", "He"or "It" (3rd person singular): With the verb "run": **He / She / It runS** As you can see, the rule (at least with regular verbs) is to add the suffix "-s" in the 3rd person singular. In Spanish it works the same way but we need to remove the **infinitive suffix** and add a specific suffix to all the others persons (I, You, He/She/It, We, You, They). Verbs in Spanish and the infinitive suffix. -- In Spanish we assume a verb is on its infitive form when it has one of the infinitives suffixes (**AR**, **ER** or **IR**) at the end: - Com**er** -> to eat - Camin**ar** -> to walk - Viv**ir** -> to live ## How to conjugate For conjugating in Spanish, we need to remove the infinitive suffix (**ar**, **er** *or* **ir**) and add the personal suffixes corresponding to the person we're talking to. In this kata we'll conjugate the verbs to its **presente indicativo** (simple present) form. Personal suffixes -- The personal suffixes changes depending of the **Infinitive suffix**. If the infinitive suffix is **AR** the personal suffixes are: - first person singular (Yo / I): -**o** - second person singular (Tú / You): -**as** - third person singular (Él, Ella / He, She): -**a** - first person plural (Nosotros / We): -**amos** - second person plural (Vosotros / You): -**áis** - third person plural (Ellos / They): -**an** If the infinitive suffix is **ER**: - first person singular (Yo / I): -**o** - second person singular (Tú / You): -**es** - third person singular (Él, Ella / He, She): -**e** - first person plural (Nosotros / We): -**emos** - second person plural (Vosotros / You): -**éis** - third person plural (Ellos / They): -**en** If the infinitive suffix is **IR**: - first person singular (Yo / I): -**o** - second person singular (Tú / You): -**es** - third person singular (Él, Ella / He, She): -**e** - first person plural (Nosotros / We): -**imos** - second person plural (Vosotros / You): -**ís** - third person plural (Ellos / They): -**en** ## Conjugating Steps for conjugating: 1. Remove the infinitive suffix (ar, er, ir) 2. And add the personal suffixes - Example: verb **Caminar** (to walk) - Camin**o** (I walk) - Camin**as** (You walk) - Camin**a** (He walks) - Camin**amos** (We walk) - Camin**áis** (You guys walk) - Camin**an** (They walk) - Example: verb **Comer** (to eat): - Com**o** (I eat) - Com**es** (You eat) - Com**e** (He, She eats) - Com**emos** (We eat) - Com**éis** (You guys eat) - Com**en** (They eat) - Example: verb **Vivir** (to live): - Viv**o** (I live) - Viv**es** (You live) - Viv**e** (He, She lives) - Viv**imos** (We live) - Viv**ís** (You guys live) - Viv**en** (They live) ## Your Task You need to write a function called **conjugate** which will return an object with a spanish verb conjugated. The object must look like this: ``` { "comer": [ "como", "comes", "come", "comemos", "coméis", "comen" ] } ``` Where the key is the verb in its original form (infinitive form) and its value will be an array with the conjugations. Another example: ``` { "vivir": [ "vivo", "vives", "vive", "vivimos", "vivís", "viven" ] } ``` ## Notes: 1. The conjugations must be in this order: ``` { verb: [ "first person singular", "second person singular", "third person singular", "first person plural", "second person plural", "third person plural" ] } ``` 2. Don't use `JSON.stringify(obj, null, 2)` because the "presentation" of the object isn't important. 3. 'á' is U+00E1, 'é' is U+00E9, 'í' is U+00ED. 4. Don't use accents in Python or Ruby version. **Buena suerte!** ---
reference
SUFFIXES = {'a': ['o', 'as', 'a', 'amos', 'ais', 'an'], 'e': ['o', 'es', 'e', 'emos', 'eis', 'en'], 'i': ['o', 'es', 'e', 'imos', 'is', 'en']} def conjugate(verb): return {verb: [verb[: - 2] + s for s in SUFFIXES[verb[- 2]]]}
Spanish Conjugator
5a81b78d4a6b344638000183
[ "Strings", "Arrays", "Functional Programming", "Fundamentals" ]
https://www.codewars.com/kata/5a81b78d4a6b344638000183
7 kyu
In [American football](http://en.wikipedia.org/wiki/American_football#Scoring), scoring can occur in several ways. These scores have different values, which leads to scores that jump up based on the way the team has scored. A team can score in one of the following ways: * Scoring a *touchdown*, which gains **6 points**. A touchdown gives the team a chance to add to their score, either by: * Going for a *2-point conversion*, which (as you might guess), earns **2 points**, or * Attempting to kick for an *extra point*, which earns **1 point**. * *Neither of those points are guaranteed!* * Kicking a *field goal*, which is worth **3 points**. * A player being tackled in their own endzone is called a *safety*, and it's worth **2 points**. [More on safeties](https://en.wikipedia.org/wiki/Safety_%28gridiron_football_score%29) We've just come into a game in the middle, and we'd like to know how the current score came to be. Given a current score, return an array containing all the possible ways that a team could have ended up with the current score. The array should contain one or more objects that look like this: ```javascript { td: 2, // touchdowns = 6pts * 2 tp: 1, // 2 point conversions = 2pts * 1 ep: 1, // extra points = 1pts * 1 fg: 1, // field goals = 3pts * 1 s: 0 // safeties = 2pts * 0 } // 18 total points ``` ```coffeescript td: 2 # touchdowns = 6pts * 2 tp: 1 # 2 point conversions = 2pts * 1 ep: 1 # extra points = 1pts * 1 fg: 1 # field goals = 3pts * 1 s: 0 # safeties = 2pts * 0 # 18 total points ``` You will not be provided with scores that cannot be solved, so it's not *necessary* to verify the score, but add it if you want. Some of the provided scores will be rather high (around 150 points) while but even low scores can have dozens of possible combinations, so be prepared! *Remember that 2-point conversions or extra points can **only** happen after a successful touchdown!* ---- To assist in your testing, I've included a function called `checkScores(score, expected)`, which will call the `scoreBreakdowns` function with the provided `score`, compare the resulting set of scores without concern for order, and report a useful error if one occurs. You use it like this: ```javascript checkScores(2, [ { td: 0, tp: 0, ep: 0, fg: 0, s: 1 } ]); ```
algorithms
def score_breakdowns(score): ways = [] for s in range(0, score + 1, 2): for fg in range(0, score - s + 1, 3): for td in range(0, score - s - fg + 1, 6): for tdep in range(0, score - s - fg - td + 1, 7): for tdtp in range(0, score - s - fg - td - tdep + 1, 8): if s + fg + td + tdep + tdtp == score: ways . append(dict(s=s / / 2, fg=fg / / 3, td=td / / 6 + tdep / / 7 + tdtp / / 8, ep=tdep / / 7, tp=tdtp / / 8)) return ways
Touchdown?
52a401f1a65172ce8f00008d
[ "Algorithms" ]
https://www.codewars.com/kata/52a401f1a65172ce8f00008d
4 kyu
A binary tree is a data structure in which every node has at most two children (https://en.wikipedia.org/wiki/Binary_tree). A possible implementation in python of a binary tree is: ```python class Tree(object): def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right ``` A path of a tree is a sequence of consecutive nodes, starting from the root node and ending in a leaf. The amplitude of a path is the biggest difference between two node values in a path. The amplitude of a tree is the biggest amplitude of all paths. An empty tree has the amplitude 0. Consider this tree: ``` 5 / \ 1 2 / \ 3 9 ``` This tree has the paths [5, 1, 3] (amplitude 4), [5, 1, 9] (amplitude 8) and [5, 2] (amplitude 3). Hence, its amplitude is 8. In this Kata you have to write a function which takes the root node of a tree (defined as in the example) as an argument and returns its amplitude.
reference
def tree_amplitude(node, path=[]): if not node: return max(path) - min(path) if path else 0 left = tree_amplitude(node . left, path + [node . data]) right = tree_amplitude(node . right, path + [node . data]) return max(left, right)
Find amplitude of a binary tree
55eab8c5a15df752cc00002b
[ "Fundamentals" ]
https://www.codewars.com/kata/55eab8c5a15df752cc00002b
6 kyu
Given a string with friends to visit in different states: ``` ad3="John Daggett, 341 King Road, Plymouth MA Alice Ford, 22 East Broadway, Richmond VA Sal Carpenter, 73 6th Street, Boston MA" ``` we want to produce a result that sorts the names by state and lists the name of the state followed by the name of each person residing in that state (people's names sorted). When the result is printed we get: ``` Massachusetts .....^John Daggett 341 King Road Plymouth Massachusetts .....^Sal Carpenter 73 6th Street Boston Massachusetts ^Virginia .....^Alice Ford 22 East Broadway Richmond Virginia ``` Spaces not being always well seen, in the above result `^` means a white space. The resulting string (when not printed) will be: ``` "Massachusetts\n..... John Daggett 341 King Road Plymouth Massachusetts\n..... Sal Carpenter 73 6th Street Boston Massachusetts\n Virginia\n..... Alice Ford 22 East Broadway Richmond Virginia" ``` or (the separator is `\n` or `\r\n` depending on the language) ``` "Massachusetts\r\n..... John Daggett 341 King Road Plymouth Massachusetts\r\n..... Sal Carpenter 73 6th Street Boston Massachusetts\r\n Virginia\r\n..... Alice Ford 22 East Broadway Richmond Virginia" ``` #### Notes - There can be a blank last line in the given string of addresses. - The tests only contains CA, MA, OK, PA, VA, AZ, ID, IN for states. - You can see another example in the "Sample tests". #### States For the lazy ones: 'AZ': 'Arizona', 'CA': 'California', 'ID': 'Idaho', 'IN': 'Indiana', 'MA': 'Massachusetts', 'OK': 'Oklahoma', 'PA': 'Pennsylvania', 'VA': 'Virginia'
reference
from collections import defaultdict import re PATTERN = re . compile(r'(.+?), (.+?), (.+?(?= [A-Z]{2})) ([A-Z]{2})') STATES = {"CA": "California", "MA": "Massachusetts", "OK": "Oklahoma", "PA": "Pennsylvania", "VA": "Virginia", "AZ": "Arizona", "ID": "Idaho", "IN": "Indiana"} def by_state(s): dct = defaultdict(list) for name, addrs, city, state in PATTERN . findall(s): dct[STATES[state]]. append("..... {} {} {} {}" . format( name, addrs, city, STATES[state])) return '\r\n ' . join("{}\r\n{}" . format(state, '\r\n' . join(sorted(lst))) for state, lst in sorted(dct . items()))
Address Book by State
59d0ee709f0cbcf65400003b
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/59d0ee709f0cbcf65400003b
6 kyu
Your task in this kata is to write a function which will take a square matrix and a non-negative integer `n` as inputs and return a matrix raised to the power `n`. Be ready to handle big `n`s. Example: ```python A = [[1, 2], [1, 0]] calc(A, 2) = [[3, 2], [1, 2]] ``` ```haskell calc [ [ 1, 2 ], [ 1, 0 ] ] 2 = [ [ 3, 2 ], [ 1, 2 ] ] ``` ```if:python External aiding modules disabled ```
algorithms
def calc(M, n): def mulM(a, b, S=len(M)): return [[sum(a[i][x] * b[x][j] for x in range(S)) for j in range(S)] for i in range(S)] def quick(m, n): if n < 2: return m out = quick(mulM(m, m), n >> 1) if n & 1: out = mulM(out, m) return out return quick(M, n)
Matrix Exponentiation
5791bdba3467db61ff000040
[ "Arrays", "Matrix", "Algorithms", "Logic" ]
https://www.codewars.com/kata/5791bdba3467db61ff000040
6 kyu
Find the longest substring in alphabetical order. Example: the longest alphabetical substring in `"asdfaaaabbbbcttavvfffffdf"` is `"aaaabbbbctt"`. There are tests with strings up to `10 000` characters long so your code will need to be efficient. The input will only consist of lowercase characters and will be at least one letter long. If there are multiple solutions, return the one that appears first. Good luck :)
reference
import re reg = re . compile('a*b*c*d*e*f*g*h*i*j*k*l*m*n*o*p*q*r*s*t*u*v*w*x*y*z*') def longest(s): return max(reg . findall(s), key=len)
Longest alphabetical substring
5a7f58c00025e917f30000f1
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/5a7f58c00025e917f30000f1
6 kyu
Your task is very simple. Given an input string s, case\_sensitive(s), check whether all letters are lowercase or not. Return True/False and a list of all the entries that are not lowercase in order of their appearance in s. For example, case\_sensitive('codewars') returns [True, []], but case\_sensitive('codeWaRs') returns [False, ['W', 'R']]. Goodluck :) Have a look at my other katas! <a href="https://www.codewars.com/kata/5a8059b1fd577709860000f6">Alphabetically ordered </a> <a href="https://www.codewars.com/kata/5a805d8cafa10f8b930005ba">Find Nearest square number </a> <a href="https://www.codewars.com/kata/5a9a70cf5084d74ff90000f7">Not prime numbers </a> <a href="https://www.codewars.com/kata/6402205dca1e64004b22b8de">Find your caterer </a>
reference
def case_sensitive(s): return [s . islower() or not s, [c for c in s if c . isupper()]]
Case-sensitive!
5a805631ba1bb55b0c0000b8
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5a805631ba1bb55b0c0000b8
7 kyu
Your task is very simple. Just write a function that takes an input string of lowercase letters and returns `true`/`false` depending on whether the string is in alphabetical order or not. ### Examples (input -> output) * "kata" -> false ('a' comes after 'k') * "ant" -> true (all characters are in alphabetical order) Good luck :) Check my other katas: <a href="https://www.codewars.com/kata/5a805d8cafa10f8b930005ba">Find Nearest square number </a> <a href="https://www.codewars.com/kata/5a805631ba1bb55b0c0000b8">Case-sensitive! </a> <a href="https://www.codewars.com/kata/5a9a70cf5084d74ff90000f7">Not prime numbers </a> <a href="https://www.codewars.com/kata/6402205dca1e64004b22b8de">Find your caterer </a>
reference
def alphabetic(s): return sorted(s) == list(s)
Alphabetically ordered
5a8059b1fd577709860000f6
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5a8059b1fd577709860000f6
7 kyu
This challenge is an extension of the kata of Codewars: **Missing and Duplicate Number"**, authored by the user **Uraza**. (You may search for it and complete it if you have not done it) In this kata, we have an unsorted sequence of consecutive numbers from ```a``` to ```b```, such that ```a < b``` always (remember ```a```, is the minimum, and ```b``` the maximum value). They were introduced an unknown amount of duplicates in this sequence and we know that there is an only missing value such that all the duplicate values and the missing value are between ```a``` and ```b```, but never coincide with them. Find the missing number with the duplicate numbers (duplicates should be output in a sorted array). Let's see an example: ```arr = [10,9,8,9,6,1,2,4,3,2,5,5,3]``` ```find_dups_miss([10,9,8,9,6,1,2,4,3,2,5,5,3]) == [7,[2,3,5,9]]``` The code should be fast to process long arrays (maximum length aprox. = 1.000.000). The values for the randon tests: ``` 500 <= a <= 50000 a + k <= b and 100 <= k <= 1000000 amount of duplicates variable, according to the length of the array ```
reference
from collections import Counter def find_dups_miss(arr): mi, ma, c = min(arr), max(arr), Counter(arr) duplicates = sorted(n for n in c if c[n] > 1) return [ma * (ma + 1) / / 2 - mi * (mi - 1) / / 2 - sum(c), duplicates]
Unknown amount of duplicates. One missing number.
5a5cdb07fd56cbdd3c00005b
[ "Fundamentals", "Mathematics", "Arrays", "Algorithms", "Sorting", "Performance" ]
https://www.codewars.com/kata/5a5cdb07fd56cbdd3c00005b
6 kyu
You are given a list of items (characters and/or integers). Find if an item reoccurs after a break of its sequence (see explanation below). In other words: are there any items that reoccur in the list, but separated by one or more different items? A sequence is a continuous "repetition" (1 or more occurence) of the same item. For example: ```python [0, 0, 0, 0, 0, 0, 1, 2, 3, 3, 3, 4, 0, 0] sequence of 0s | other sequences | ^ 0 reoccurs! ``` Return `true` if there is such an item, and `false` otherwise. ## Examples ```python [0, 0, 1, 1, 0, 0] ==> True # 0 is re-occuring [0, 0, 'a', 0] ==> True # 0 is re-occuring [0, 0, 1, 1, 2, 2, 1, 1] ==> True # 1 is re-occuring [0, 0, 0] ==> False # no sequence re-occurs [0, 0, 1, 1, 2, 2] ==> False # no sequence re-occurs ``` **Note:** Lists with up to 10<sup>7</sup> items will be tested, so make sure your code is efficient!
reference
from itertools import groupby def is_reoccuring(xs): cs = [k for k, _ in groupby(xs)] return len(cs) != len(set(cs))
Is there a sequence re-occuring in the list
5a7e6bd576c0e2f27d00237a
[ "Arrays", "Lists", "Fundamentals", "Performance" ]
https://www.codewars.com/kata/5a7e6bd576c0e2f27d00237a
6 kyu
# Definition **_Extra perfect number_** *is the number that* **_first_** and **_last_** *bits* are **_set bits_**. ____ # Task **_Given_** *a positive integer* `N` , **_Return_** the **_extra perfect numbers_** *in range from* `1` to `N` . ____ # Warm-up (Highly recommended) # [Playing With Numbers Series](https://www.codewars.com/collections/playing-with-numbers) ___ # Notes * **_Number_** *passed is always* **_Positive_** . * **_Returned array/list_** should *contain the extra perfect numbers in ascending order* **from lowest to highest** ___ # Input >> Output Examples ``` extraPerfect(3) ==> return {1,3} ``` ## **_Explanation_**: # (1)<sub>10</sub> =(1)<sub>2</sub> **First** and **last** bits as **_set bits_**. # (3)<sub>10</sub> = (11)<sub>2</sub> **First** and **last** bits as **_set bits_**. ___ ``` extraPerfect(7) ==> return {1,3,5,7} ``` ## **_Explanation_**: # (5)<sub>10</sub> = (101)<sub>2</sub> **First** and **last** bits as **_set bits_**. # (7)<sub>10</sub> = (111)<sub>2</sub> **First** and **last** bits as **_set bits_**. ___ ___ ___ # [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) # [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored) ___ ## ALL translations are welcomed ## Enjoy Learning !! # Zizou
reference
def extra_perfect(n): return list(range(1, n + 1, 2))
Extra Perfect Numbers (Special Numbers Series #7)
5a662a02e626c54e87000123
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5a662a02e626c54e87000123
7 kyu
The goal of this kata is to write a function `tower(base, height, modulus)` that returns `base ** base ** ... ** base`, with `height` occurrences of `base`, modulo `modulus`. (`**` is the power operator in Python, in case this kata gets translated.) As input constraints, we have: ``` 1 <= base < 1e20 0 <= height < 1e20 1 <= modulus < 1e7 ``` If `modulus == 1`, the returned value should be `0` irrespective of the values of the two other parameters. Otherwise, if `base == 1` or `height == 0`, the output should be 1, and, if `height == 1`, the output should be `base % modulus`. For example, `tower(2, 4, 1000)` should return 536, because: `2 ** 2 ** 2 ** 2 == 2 ** (2 ** (2 ** 2)) == 65536` and `65536 % 1000 == 536`. Note that the power operator is right-associative, meaning that `a ** b ** c` is computed `a ** (b ** c)` and not `(a ** b) ** c`. For example, `2 ** 2 ** 4 == 2 ** 16 == 65536` and `2 ** 2 ** 4 != 4 ** 4 == 256`. Note also that `tower(b, h, m) = pow(b, tower(b, h - 1, m), m)` is _not_ a correct recursive relationship. For example, `tower(13, 3, 31) != pow(13, tower(13, 2, 31), 31)`. However, `tower(13, 3, 31) == pow(13, tower(13, 2, 30), 31)`. There are more examples in the example tests. ### Some number theory Since Codewars is for programmers and not mathematicians, I thought that I would provide a minimum of number theory background to let programmers get started. Given a positive integer `m > 1`, we can form the set of all integers between 1 and `m` that are coprime with `m`. This set can be defined with code as `G = {i for i in range(1, m) if gcd(i, m) == 1}`, where `gcd(a, b)` returns the greatest common divisor of `a` and `b`. The number of elements in this set is sometimes denoted `phi(m)`, sometimes `totient(m)`. For example, let `m = 15`. The prime factors of 15 are 3 and 5. Let's start with the set {1, 2, ..., 15} and remove all the multiples of 3. Every 3rd element is a multiple of 3 and, if they are removed, we are left with `15 * 2 / 3 = 10` elements. Next remove all multiples of 5. Every 5th element is a multiple of 5 and, if they are removed, we are left with `10 * 4 / 5 = 8` elements. So, `totient(15) = 8`. The set of elements that are coprime with 15 is `G = {1, 2, 4, 7, 8, 11, 13, 14}`, and, as can be observed, it contains 8 elements. Now, take any element of `G` and raise it to the first 8 powers modulo 15. For example, the powers of 7 modulo 15 are 7, 4, 13, 1, 7, 4, 13, 1, and the powers of 2 modulo 15 are 2, 4, 8, 1, 2, 4, 8, 1. The powers of any element of `G` have a cycle length that divides `totient(m)` and the cycle always ends with 1. In other words, for any `b` in `G` and `q, r` such that `0 <= q and 0 <= r < totient(m)`, + `b ** (q * totient(m) + r) % m == b ** r % m`. This allows us to reduce large powers to powers that are less than `totient(m)`. What if we choose a number `b` that is not in `G`. For example, let `b = 3`. Then the powers of 3 modulo 15 are 3, 9, 12, 6, 3, 9, 12, 6. The cycle length is still a divisor of `totient(m)`, but the cycle does _not_ end with 1. This implies that for `b` not in `G`, the statement in the above bullet does not hold. However, it can be amended slighly, so that we can still reduce large powers to smaller powers. Good luck with this kata!
refactoring
from math import log def phi(n): r, i = n, 2 while i * i <= n: if n % i == 0: r = r / / i * (i - 1) while n % i == 0: n / /= i i += 1 if n > 1: r = r / / n * (n - 1) return r def _tower(base, h, m): if h < 2 or m == 1: return pow(base, h, m) p = phi(m) return pow(base, p + tower(base, h - 1, p), m) def tower(base, h, m): res = 1 for _ in range(h): if res * log(base) > log(m): return _tower(base, h, m) res = base * * res return res % m
Power tower modulo m
5a08b22b32b8b96f4700001c
[ "Refactoring" ]
https://www.codewars.com/kata/5a08b22b32b8b96f4700001c
2 kyu
# Story Well, here I am stuck in another traffic jam. *<span style='color:orange'>Damn all those courteous people!</span>* Cars are trying to enter the main road from side-streets somewhere ahead of me and people keep letting them cut in. Each time somebody is let in the effect ripples back down the road, so pretty soon I am not moving at all. (Sigh... late again...) <hr/> ## Visually The diagram below shows lots of cars all attempting to go North. * the `a`,`b`,`c`... cars are on the main road with me (`X`) * the `B` cars and `C` cars are merging from side streets <pre style='font-size:15px;line-height:15px'> | a | | b | <span style='color:orange'>↑</span> --------+ c | BBBBBB d | --------+ e | | f | <span style='color:orange'>↑</span> | g | --------+ h | CCCCC i | --------+ j | <span style='color:orange'>↑</span> | k | | l | | m | | <span style='font-weight:bold;background:black;color:green'>X</span> | </pre> This can be represented as * `mainRoad` = `"abcdefghijklmX"` * `sideStreets` = `["","","","BBBBBB","","","","","CCCCC"]` # Kata Task Assume every car on the main road will "give way" to 1 car entering from each side street. Return a string representing the cars (up to and including me) in the order they exit off the top of the diagram. ## Notes * My car is the only `X`, and I am always on the main road * Other cars may be any alpha-numeric character (except `X` of course) * There are no "gaps" between cars * Assume side streets are always on the left (as in the diagram) * The `sideStreets` array length may vary but is never more than the length of the main road * A pre-loaded `Util.display(mainRoad,sideStreets)` method is provided which may help to visualise the data * (Util.Display for C#) ## Example Here are the first few iterations of my example, showing that I am hardly moving at all... <table border="1"> <tr><th>Initial<th>Iter 1<th>Iter 2<th>Iter 3<th>Iter 4<th>Iter 5<th>Iter 6<th>Iter 7</tr> <tr> <td> <pre style='font-size:15px;line-height:15px'> a b c <span style='color:red'>BBBBBB</span>d e f g h <span style='color:orange'>CCCCC</span>i j k l m <span style='font-weight:bold;background:black;color:green'>X</span> </pre> <td> <pre style='font-size:15px;line-height:15px'> b c d <span style='color:red'>BBBBBB</span> e f g h <span style='color:orange'>CCCCC</span>i j k l m <span style='font-weight:bold;background:black;color:green'>X</span> </pre> <td> <pre style='font-size:15px;line-height:15px'> c d <span style='color:red'>B</span> <span style='color:red'>BBBBB</span>e f g h i <span style='color:orange'>CCCCC</span> j k l m <span style='font-weight:bold;background:black;color:green'>X</span> </pre> <td> <pre style='font-size:15px;line-height:15px'> d <span style='color:red'>B</span> e <span style='color:red'>BBBBB</span> f g h i <span style='color:orange'>CCCCC</span> j k l m <span style='font-weight:bold;background:black;color:green'>X</span> </pre> <td> <pre style='font-size:15px;line-height:15px'> <span style='color:red'>B</span> e <span style='color:red'>B</span> <span style='color:red'>BBBB</span>f g h i <span style='color:orange'>C</span> <span style='color:orange'>CCCC</span>j k l m <span style='font-weight:bold;background:black;color:green'>X</span> </pre> <td> <pre style='font-size:15px;line-height:15px'> e <span style='color:red'>B</span> f <span style='color:red'>BBBB</span> g h i <span style='color:orange'>C</span> <span style='color:orange'>CCCC</span>j k l m <span style='font-weight:bold;background:black;color:green'>X</span> </pre> <td> <pre style='font-size:15px;line-height:15px'> <span style='color:red'>B</span> f <span style='color:red'>B</span> <span style='color:red'>BBB</span>g h i <span style='color:orange'>C</span> j <span style='color:orange'>CCCC</span> k l m <span style='font-weight:bold;background:black;color:green'>X</span> </pre> <td> <pre style='font-size:15px;line-height:15px'> f <span style='color:red'>B</span> g <span style='color:red'>BBB</span> h i <span style='color:orange'>C</span> j <span style='color:orange'>CCCC</span> k l m <span style='font-weight:bold;background:black;color:green'>X</span> </pre> </table> <hr> :-) DM
algorithms
def traffic_jam(road, sides): X = road . index("X") main = list(road[: X + 1]) for i in reversed(range(min(X, len(sides)))): tmp = [] for j in range(1, min(len(main) - i - 1, len(sides[i])) + 1): tmp . append(sides[i][- j]) tmp . append(main[i + j]) main[i + 1: i + len(tmp) / / 2 + 1] = tmp return '' . join(main)
Traffic Jam
5a26073ce1ce0e3c01000023
[ "Algorithms" ]
https://www.codewars.com/kata/5a26073ce1ce0e3c01000023
5 kyu
In this kata the function returns an array/list like the one passed to it but with its nth element removed (with `0 <= n <= array/list.length - 1`). The function is already written for you and the basic tests pass, but random tests fail. Your task is to figure out why and fix it. Good luck! ~~~if:javascript Some good reading: [MDN Docs about arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) ~~~ ~~~if:python Some good reading: [Python Docs about lists](https://docs.python.org/3/tutorial/datastructures.html) ~~~ ~~~if:coffeescript Some good reading: [CoffeeScript docs](http://coffeescript.org/) ~~~
refactoring
def remove_nth_element(lst, n): lst_copy = lst . copy() del lst_copy[n] return lst_copy
Working with arrays II (and why your code fails in some katas)
5a7b3d08fd5777bf6a000121
[ "Refactoring", "Arrays" ]
https://www.codewars.com/kata/5a7b3d08fd5777bf6a000121
7 kyu
Convert Decimal Degrees to Degrees, Minutes, Seconds. Remember: 1 degree = 60 minutes; 1 minute = 60 seconds. Input: Positive number. Output: Array [degrees, minutes, seconds]. E.g [30, 25, 25] Trailing zeroes should be omitted in the output. E.g ``` convert (50) //correct output -> [50] //wrong output -> [50, 0, 0] convert(80.5) //correct output -> [ 80, 30 ] //wrong output -> [80, 30, 0] convert(0.0001388888888888889) //correct output -> [ 0, 0, 1 ] //wrong output -> [1] ``` Round the seconds to the nearest integer.
reference
def convert(i): t = round(i * 3600) d, m, s = t / / 3600, t % 3600 / / 60, t % 60 return [d, m, s] if s else [d, m] if m else [d]
Convert Decimal Degrees to Degrees, Minutes, Seconds
590ac6b9be4dff49b0000042
[ "Fundamentals" ]
https://www.codewars.com/kata/590ac6b9be4dff49b0000042
7 kyu
The description is rather long but it tries to explain what a financing plan is. The fixed monthly payment for a fixed rate mortgage is the amount paid by the borrower every month that ensures that the loan is paid off in full with interest at the end of its term. The monthly payment formula is based on the annuity formula. The monthly payment `c` depends upon: - `rate` - the monthly interest rate is expressed as a decimal, not a percentage. The monthly rate is simply the **given** yearly percentage rate divided by 100 and then by 12. - `term` - the number of monthly payments, called the loan's `term`. - `principal` - the amount borrowed, known as the loan's principal (or `balance`). First we have to determine `c`. We have: `c = n /d` with `n = r * balance` and `d = 1 - (1 + r)**(-term)` where `**` is the `power` function (you can look at the reference below). The payment `c` is composed of two parts. The first part pays the interest (let us call it `int`) due for the balance of the given month, the second part repays the balance (let us call this part `princ`) hence for the following month we get a `new balance = old balance - princ` with `c = int + princ`. Loans are structured so that the amount of principal returned to the borrower starts out small and increases with each mortgage payment. While the mortgage payments in the first years consist primarily of interest payments, the payments in the final years consist primarily of principal repayment. A mortgage's amortization schedule provides a detailed look at precisely what portion of each mortgage payment is dedicated to each component. In an example of a $100,000, 30-year mortgage with a rate of 6 percents the amortization schedule consists of 360 monthly payments. The partial amortization schedule below shows with 2 decimal floats the balance between principal and interest payments. --|num_payment|c |princ |int |Balance | --|-----------|-----------|-----------|-----------|-----------| --|1 |599.55 |99.55 |500.00 |99900.45 | --|... |599.55 |... |... |... | --|12 |599.55 |105.16 |494.39 |98,771.99 | --|... |599.55 |... |... |... | --|360 |599.55 |596.57 |2.98 |0.00 | #### Task: Given parameters ``` rate: annual rate as percent (don't forgent to divide by 100*12) bal: original balance (borrowed amount) term: number of monthly payments num_payment: rank of considered month (from 1 to term) ``` the function `amort` will return a formatted string (for example): `"num_payment %d c %.0f princ %.0f int %.0f balance %.0f" (with arguments num_payment, c, princ, int, balance`) ***In Common Lisp:*** return a list with num-payment, c, princ, int, balance each rounded. #### Examples: ``` amort(6, 100000, 360, 1) -> "num_payment 1 c 600 princ 100 int 500 balance 99900" amort(6, 100000, 360, 12) -> "num_payment 12 c 600 princ 105 int 494 balance 98772" ``` #### Ref <https://en.wikipedia.org/wiki/Mortgage_calculator>
reference
def amort(rate, bal, term, num_payments): monthlyRate = rate / (12 * 100) c = bal * (monthlyRate * (1 + monthlyRate) * * term) / (((1 + monthlyRate) * * term) - 1) newBalance = bal for i in range(num_payments): interest = newBalance * monthlyRate princ = c - interest newBalance = newBalance - princ return 'num_payment %s c %.0f princ %.0f int %.0f balance %.0f' % (num_payments, c, princ, interest, newBalance)
Financing a purchase
59c68ea2aeb2843e18000109
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/59c68ea2aeb2843e18000109
6 kyu
Consider the following expansion: ``` solve("3(ab)") = "ababab" -- because "ab" repeats 3 times solve("2(a3(b))") = "abbbabbb" -- because "a3(b)" == "abbb", which repeats twice. ``` Given a string, return the expansion of that string. Input will consist of only lowercase letters and numbers (1 to 9) in valid parenthesis. There will be no letters or numbers after the last closing parenthesis. More examples in test cases. Good luck! Please also try [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2)
algorithms
def solve(s): s1 = s[:: - 1] s2 = '' for i in s1: if i . isalpha(): s2 += i elif i . isdigit(): s2 = s2 * int(i) return s2[:: - 1]
Simple string expansion
5a793fdbfd8c06d07f0000d5
[ "Algorithms" ]
https://www.codewars.com/kata/5a793fdbfd8c06d07f0000d5
5 kyu
# Introduction and Warm-up (Highly recommended) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) ___ # Task **_Given_** an *array/list [] of integers* , **_Find_** **_The maximum difference_** *between the successive elements in its sorted form*. ___ # Notes * **_Array/list_** size is *at least 3* . * **_Array/list's numbers_** Will be **mixture of positives and negatives also zeros_** * **_Repetition_** of numbers in *the array/list could occur*. * **_The Maximum Gap_** is *computed Regardless the sign*. ___ # Input >> Output Examples ``` maxGap ({13,10,5,2,9}) ==> return (4) ``` ## **_Explanation_**: * **_The Maximum Gap_** *after sorting the array is* `4` , *The difference between* ``` 9 - 5 = 4 ``` . ___ ``` maxGap ({-3,-27,-4,-2}) ==> return (23) ``` ## **_Explanation_**: * **_The Maximum Gap_** *after sorting the array is* `23` , *The difference between* ` |-4- (-27) | = 23` . * **_Note_** : *Regardless the sign of negativity* . ___ ``` maxGap ({-7,-42,-809,-14,-12}) ==> return (767) ``` ## **_Explanation_**: * **_The Maximum Gap_** *after sorting the array is* `767` , *The difference between* ` | -809- (-42) | = 767` . * **_Note_** : *Regardless the sign of negativity* . ___ ``` maxGap ({-54,37,0,64,640,0,-15}) //return (576) ``` ## **_Explanation_**: * **_The Maximum Gap_** *after sorting the array is* `576` , *The difference between* ` | 64 - 640 | = 576` . * **_Note_** : *Regardless the sign of negativity* . ___ ___ ___ # [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) # [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored) ___ ## ALL translations are welcomed ## Enjoy Learning !! # Zizou
reference
def max_gap(numbers): lst = sorted(numbers) return max(b - a for a, b in zip(lst, lst[1:]))
Maximum Gap (Array Series #4)
5a7893ef0025e9eb50000013
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5a7893ef0025e9eb50000013
7 kyu
In graph theory, a graph is a collection of nodes with connections between them. Any node can be connected to any other node exactly once, and can be connected to no nodes, to some nodes, or to every other node. Nodes cannot be connected to themselves A path through a graph is a sequence of nodes, with every node connected to the node following and preceding it. A closed path is a path which starts and ends at the same node. An open path: ``` 1 -> 2 -> 3 ``` a closed path: ``` 1 -> 2 -> 3 -> 1 ``` A graph is connected if there is a path from every node to every other node. A graph is a tree if it is connected and there are no closed paths. Your job is to write a function 'isTree', which returns true if a graph is a tree, and false if it is not a tree. Graphs will be given as an array with each item being an array of integers which are the nodes that node is connected to. For example, this graph: ``` 0--1 | | 2--3--4 ``` has array: ``` [[1,2], [0,3], [0,3], [1,2,4], [3]] ``` Note that it is also not a tree, because it contains closed path: ``` 0->1->3->2->0 ``` A node with no connections is an empty array Note that if node 0 is connected to node 1, node 1 is also connected to node 0. This will always be true. The order in which each connection is listed for each node also does not matter. Good luck!
algorithms
def isTree(matrix): visited_nodes = set([0]) crossed_edges = set() agenda = [0] while agenda: node = agenda . pop() for i in matrix[node]: if (node, i) in crossed_edges: continue if i in visited_nodes: return False agenda . append(i) crossed_edges . add((i, node)) visited_nodes . add(i) return len(visited_nodes) == len(matrix)
Mistaking a forest for a tree
5a752a0b0136a1266c0000b5
[ "Algorithms" ]
https://www.codewars.com/kata/5a752a0b0136a1266c0000b5
5 kyu
In this kata the function returns an array/list of numbers without its last element. The function is already written for you and the basic tests pass, but random tests fail. Your task is to figure out why and fix it. Good luck! Hint: watch out for side effects. ~~~if:javascript,coffeescript Some good reading: [MDN Docs about arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) ~~~ ~~~if:python Some good reading: [Python Lists](http://www.compciv.org/guides/python/fundamentals/lists-mutability/) ~~~
refactoring
def without_last(lst): return lst[: - 1]
Working with arrays I (and why your code fails in some katas)
5a4ff3c5fd56cbaf9800003e
[ "Fundamentals", "Arrays", "Refactoring" ]
https://www.codewars.com/kata/5a4ff3c5fd56cbaf9800003e
7 kyu
This is harder version of [Square sums (simple)](/kata/square-sums-simple). # Square sums Write function that, given an integer number `N`, returns array of integers `1..N` arranged in a way, so sum of each 2 consecutive numbers is a square. Solution is valid if and only if following two criterias are met: 1. Each number in range `1..N` is used once and only once. 2. Sum of each 2 consecutive numbers is a perfect square. ### Example For N=15 solution could look like this: `[ 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8 ]` ### Verification 1. All numbers are used once and only once. When sorted in ascending order array looks like this: `[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]` 2. Sum of each 2 consecutive numbers is a perfect square: ``` 16 16 16 16 16 16 16 /+\ /+\ /+\ /+\ /+\ /+\ /+\ [ 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8 ] \+/ \+/ \+/ \+/ \+/ \+/ \+/ 9 25 9 25 9 25 9 9 = 3*3 16 = 4*4 25 = 5*5 ``` If there is no solution, return `False` (empty vector in C++ ; `null` in Java). For example if `N=5`, then numbers `1,2,3,4,5` cannot be put into square sums row: `1+3=4`, `4+5=9`, but `2` has no pairs and cannot link `[1,3]` and `[4,5]` <br> # Tests constraints: ```if:coffeescript * `1 <= N <= 1300` ``` ```if:javascript * `1 <= N <= 1300` ``` ```if:cpp * `1 <= N <= 1300` ``` ```if:java * `1 <= N <= 1600` ``` ```if:python * `1 <= N <= 1000` ``` * All possible values of `N` are tested * Brute force solutions can only go up to `N=50`. * Code size is restricted to 20K max, and external modules are disabled: inlining all results precalculated is not an option. <br> # Have fun! Simple version of this Kata is [here](/kata/square-sums-simple).
bug_fixes
__import__('sys'). setrecursionlimit(10000) def square_sums(n): squares = [sq * sq for sq in range(2, int((n * 2 - 1) * * .5) + 1)] Graph = {i: [j - i for j in squares if 0 < j - i <= n and j - i != i] for i in range(1, n + 1)} def get_result(G, res, ind): if len(res) == n: return res for next_ind in sorted((G . keys() if ind == 0 else G[ind]), key=lambda x: len(G[x])): for i in G[next_ind]: G[i]. remove(next_ind) res . append(next_ind) next_result = get_result(G, res, next_ind) if next_result != False: return next_result for i in G[next_ind]: G[i]. append(next_ind) res . pop() return False return get_result(Graph, [], 0)
Square sums
5a667236145c462103000091
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/5a667236145c462103000091
1 kyu
Given two arrays `a1` and `a2` of positive integers find the set of common elements between them and return the elements (a set) that have a sum or difference equal to *either* array length. - All elements will be positive integers greater than 0 - If there are no results an empty set should be returned - Each operation should only use two elements Examples ``` a1 = [1, 2, 3, 4, 5, 6] a2 = [1, 2, 4, 6, 7, 8, 9, 10] ``` should return `{2, 4, 6}` because all three integers exist in both arrays and `a1` has a length of 6 (2+4) and `a2` has a length of 8 (2+6). ``` a1 = [1, 2, 3, 5, 10, 15] a2 = [1, 2, 3, 4, 5, 6, 10, 12, 15, 16] ``` should return `{1, 5, 15}` because all 3 integers exist in both arrays and `a1` has a length of 6 (1+5) and `a2` has a length of 10 (15-5).
reference
def a1_thick_and_hearty(a1, a2): s = set(a1) & set(a2) return set(n for n in s if any(m != n and m in s for m in [len(a1) + n, abs(len(a1) - n), len(a2) + n, abs(len(a2) - n)]))
A1 Thick and Hearty
5a77e4af373c2edf72000085
[ "Lists", "Permutations", "Fundamentals" ]
https://www.codewars.com/kata/5a77e4af373c2edf72000085
6 kyu
The goal of this Kata is to reduce the passed integer to a single digit (if not already) by converting the number to binary, taking the sum of the binary digits, and if that sum is not a single digit then repeat the process. - If the passed integer is already a single digit there is no need to reduce ```if:haskell,python,ruby,julia - `n` will be an integer such that `0 < n < 10^20` ``` ```if:c - `n` will be an integer such that `0 <= n < 2^64` ``` ```if:javascript - `n` will be an integer such that `0 < n < 10⁹` ``` For example given `5665` the function should return `5`: ``` 5665 --> (binary) 1011000100001 1011000100001 --> (sum of binary digits) 5 ``` Given `123456789` the function should return `1`: ``` 123456789 --> (binary) 111010110111100110100010101 111010110111100110100010101 --> (sum of binary digits) 16 16 --> (binary) 10000 10000 --> (sum of binary digits) 1 ```
reference
def single_digit(n): while n > 9: n = bin(n). count("1") return n
Single digit
5a7778790136a132a00000c1
[ "Binary", "Fundamentals" ]
https://www.codewars.com/kata/5a7778790136a132a00000c1
7 kyu
You are given a function `f` defined on the interval `[0, 1]` such that for some `x_max` in the interval `[0, 1]`, the function `f` is strictly increasing on the interval `[0, x_max]` and strictly decreasing on the interval `[x_max, 1]`. Your job is to determine `x_max` within an distance less than `1e-6` (i.e., `|x_max - x_ans| < 1e-6` must hold for the value `x_ans` to be accepted as a correct answer). Computing `f(x)` for some value `x` will cost you one coin, and you are given 30 coins. In other words, you can evaluate `f` at at most 30 values of `x`. Note that you may not assume anything about the function `f` other than what is mentioned above. In particular, `f` is not necessarily a polynomial, differentiable, or even continuous.
reference
def max_x(f): tau = (5 * * .5 - 1) / 2 a, b, c, d, coins = 0, 1, 1 - tau, tau, 0 fc, fd = f(c), f(d) for _ in range(28): if fc >= fd: a, b, c, d = a, d, a + (d - a) * (1 - tau), c fc, fd = f(c), fc else: a, b, c, d = c, b, d, c + (b - c) * (tau) fc, fd = fd, f(d) return (a + b) / 2
Golden Section Search
5a7671e6373c2e8c3e00008d
[ "Fundamentals" ]
https://www.codewars.com/kata/5a7671e6373c2e8c3e00008d
6 kyu
There are two main ways to write out a quadratic function, standard form: `f(x) = a(x^2)+bx+c` and vertex form:<br /> `f(x) = a((x-h)^2) + k` (where (h,k) are the coordinates of the vertex of the parabola). # Your Task is to write a function `getVertex` that takes three parameters `a`, `b`, and `c` and returns an array of two numbers `[h,k]` such that `a(x^2)+bx+c = a((x-h)^2) + k`.<br><br> Note: Make sure it works for `a` values other than 1.
algorithms
def getVertex(a, b, c): h = b / (- 2 * a) k = c - (a * h * * 2) return [h, k]
Parabolas: Standard to Vertex Form
5a74d00c0025e979c9000145
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5a74d00c0025e979c9000145
7 kyu
When developing a game, it's often useful to be able to control time. We could slow it down when a character dies, or speed it up to make things look flashy, or stop time altogether when the player pauses the game. Let's write an object we can use to simulate time and mess with it as we wish! ## new SimTime() Creates a new SimTime instance. Nothing special here. Once an instance has been created, we can use its methods to play with time, and get the current "simulated" time. ```javascript let sim = new SimTime(); ``` ```python sim = SimTime() ``` ```ruby sim = SimTime.new ``` ## instance.get() Returns the current time withing the simulation. This value will start at 0. ```javascript sim.get() === 0 ``` ```python sim.get() == 0 ``` ```ruby sim.get == 0 ``` ## instance.set\_speed(new\_speed) At the current realtime and simtime, the simulation speed is set to `new_speed`. From the current realtime until the speed is changed again, simulated time should reflect this new speed. Note: speed can go negative and may lead simulated time "into the past". ```javascript sim.set_speed(2); // now each change in real time will be doubled for simulate time sim.set_speed(1); // now changes in simulated time will be the same as in real time ``` ```python sim.set_speed(2) # now each change in real time will be doubled for simulate time sim.set_speed(1) # now changes in simulated time will be the same as in real time ``` ```ruby sim.set_speed(2) # now each change in real time will be doubled for simulate time sim.set_speed(1) # now changes in simulated time will be the same as in real time ``` ## instance.update(current\_realtime) Used to tell the simulation what the current time is outside, in the real world. This will be used to calculate the change in realtime, and therefore the change in simulated time. Real time only moves in one direction. So if `current_realtime` doesn't make sense (moves backwards), throw an error. ```javascript // assuming current speed is 1 sim.update(10); sim.get() === 10; ``` ```python # assuming current speed is 1 sim.update(10) sim.get() == 10 ``` ```ruby # assuming current speed is 1 sim.update(10) sim.get == 10 ``` ___ ## Example: ```javascript // sim time = 0, real time = 0, sim speed = 1 sim.update(12); sim.get() === 12; sim.set_speed(3); // from now onwards, change in sim time // will be multiplied by the speed of 3 sim.update(15); // realtime changed by 3 // simtime should change by 3 * 3 = 9 // 12 + (3 * 3) = 21 sim.get() === 21; sim.update(17); // adding 2 * 3 instead of 2 again sim.get() === 27; sim.set_speed(1); // from now on change in sim time // will be multiplied by the speed of 1 sim.update(18); // adding 1 to sim time sim.get() === 28; ``` ```python # sim time = 0, real time = 0, sim speed = 1 sim.update(12) sim.get() == 12 sim.set_speed(3) # from now onwards, change in realtime # will be multiplied by the speed of 3 sim.update(15) # realtime changed by 3 # simtime should change by 3 * 3 = 9 # 12 + (3 * 3) = 21 sim.get() == 21 sim.update(17) # adding 2 * 3 instead of 2 again sim.get() == 27 sim.set_speed(1) # from now on change in sim time # will be multiplied by the speed of 1 sim.update(18) # adding 1 to sim time sim.get() == 28 ``` ```ruby # sim time = 0, real time = 0, sim speed = 1 sim.update(12) sim.get == 12 sim.set_speed(3) # from now onwards, change in realtime # will be multiplied by the speed of 3 sim.update(15) # realtime changed by 3 # simtime should change by 3 * 3 = 9 # 12 + (3 * 3) = 21 sim.get == 21 sim.update(17) # adding 2 * 3 instead of 2 again sim.get == 27 sim.set_speed(1) # from now on change in sim time # will be multiplied by the speed of 1 sim.update(18) # adding 1 to sim time sim.get == 28 ```
algorithms
class SimTime: def __init__(self): self . sim_time = 0 self . real_time = 0 self . speed = 1 def get(self): return self . sim_time def set_speed(self, new_speed): self . speed = new_speed def update(self, current_realtime): assert current_realtime >= self . real_time self . sim_time += (current_realtime - self . real_time) * self . speed self . real_time = current_realtime
Time Simulation
5858326b994864753d0000d1
[ "Algorithms" ]
https://www.codewars.com/kata/5858326b994864753d0000d1
6 kyu
In recreational mathematics, a [Keith number](https://en.wikipedia.org/wiki/Keith_number) or repfigit number (short for repetitive Fibonacci-like digit) is a number in the following integer sequence: `14, 19, 28, 47, 61, 75, 197, 742, 1104, 1537, 2208, 2580, 3684, 4788, 7385, 7647, 7909, ...` (sequence A007629 in the OEIS) Keith numbers were introduced by Mike Keith in 1987. They are computationally very challenging to find, with only about 100 known. Implement the code to check if the given number is a Keith number. Return the number number of iteration needed to confirm it; otherwise return `false`. **Note:** 1-digit numbers are **not** Keith numbers by definition ## Examples ``` n = 197 # --> [1, 9, 7] # calculation iteration 1 + 9 + 7 = 17 # 1 9 + 7 + 17 = 33 # 2 7 + 17 + 33 = 57 # 3 17 + 33 + 57 = 107 # 4 33 + 57 + 107 = 197 # 5 ``` As `197` is the same as the initial number, so it's a Keith number: return `5` Another example: ``` n = 196 # calculation iteration 1 + 9 + 6 = 16 # 1 ... ``` `196` is not a Keith number, so return `false`
algorithms
def is_keith_number(n): numList = [int(i) for i in str(n)] # int array if len(numList) > 1: # min 2 digits itr = 0 while numList[0] <= n: # replace array entries by its sum: numList[itr % len(numList)] = sum(numList) itr += 1 if n in numList: # keith-condition return itr return False
Keith Numbers
590e4940defcf1751c000009
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/590e4940defcf1751c000009
6 kyu
##Tabs to spaces! Suppose that in a developer team the agreed standard is to always use spaces for alignment. Somebody from another team with whom they cooperate uses another convention and regularly checks in code containing tabs. Now all the times he changes spaces to tabs or others change his tabs to spaces that will appear as a diff in the version control system. Although most diff tools can be configured to ignore whitespace diffs, this still can be very annoying as it can add unnecessary difficulty for the comparison of different versions. So it might be worthwhile to write a script which periodically searches the codebase to convert tabs to spaces, without changing the visible code layout. This is the goal of the kata. In some editors, one can align words under each other with tabs in the following manner: in a common convention a tab can mean up to 4 spaces. It can mean any number of spaces between 1 and 4. - When a tab is the 1st character in a row it means 4 spaces. - When a tab is the 2nd character in a row it means just 3 spaces. - When a tab is the 3rd character in a row it means just 2 spaces. - When a tab is the 4th character in a row it means just 1 space. - When a tab is the 5th character in a row it again means 4 spaces. And so on... The amount of spaces should calculated sequentially, from the leftmost tab in every line. Write a function tabToSpaces that takes one argument, the text, and replaces every tab with spaces. In the test cases tabs are represented by '\t' and newlines are represented by '\n'. Example: ``` a bbb (a tab equals 3 spaces) aa bb (a tab equals 2 spaces) aaa b (a tab equals 1 space) b (a tab equals 4 spaces) ```
reference
def tab_to_spaces(text): return text . expandtabs(4)
Tabs to spaces
5779474882d7d0a10f000005
[ "Fundamentals" ]
https://www.codewars.com/kata/5779474882d7d0a10f000005
7 kyu
A pixmap shall be turned from black to white, turning all pixels to white in the process. But for optical reasons this shall *not* happen linearly, starting at the top and continuing line by line to the bottom: ```haskell for_ [0..height-1] $ \ y -> for_ [0..width-1] $ \ x -> setBit x y ``` ```lambdacalc # pseudocode for [0..height] \ y . for [0..width] \ x . set-bit x y ``` ```python for y in range(height): for x in range(width): set_bit(x, y) ``` ```javascript for ( let y=0; y<height; y++ ) for ( let x=0; x<width; x++ ) setBit(x, y); ``` ```kotlin for (y in 0 until height) for (x in 0 until width) setBit(x, y) ``` ```rust for y in 0..height { for x in 0..width { set_bit(x, y); ``` Instead it shall be done by a systematic dithering routine which selects the coordinates on which pixels are to be set in a precise pattern so that the geometrical distance between two consecutive pixels is large and a specific optical effect results. The following diagrams show the order of the coordinates the algorithm shall produce: 2×2: ``` 1 3 4 2 ``` 4×4: ``` 1 9 3 11 13 5 15 7 4 12 2 10 16 8 14 6 ``` 8×8: ``` 1 33 9 41 3 35 11 43 49 17 57 25 51 19 59 27 13 45 5 37 15 47 7 39 61 29 53 21 63 31 55 23 4 36 12 44 2 34 10 42 52 20 60 28 50 18 58 26 16 48 8 40 14 46 6 38 64 32 56 24 62 30 54 22 ``` The pattern continues like that for each square pixmap with a width and height of a power of two (16, 32, 64, …). But the width and the height of the pixmap can be arbitrary positive numbers. If the pixmap's width and/or height are not a power of two, the coordinates the algorithm would produce outside of the pixmap are skipped: 3×3: ``` 1 6 3 8 5 9 4 7 2 ``` 6×5: ``` 1 16 6 21 3 18 25 10 28 13 26 11 8 23 5 20 9 24 29 14 27 12 30 15 4 19 7 22 2 17 ``` Write an algorithm which produces the coordinates of the dithering for a given `width` and `height`. ~~~if:haskell,lambdacalc, To pass the tests, write a function `dithering` which returns a list of coordinate tuples: ``` dithering 6 5 -> [ (0, 0), (4, 4), (4, 0), (0, 4), (2, 2), (2, 0), (2, 4) .. ] ``` ~~~ ~~~if:python,javascript, To pass the tests, write a _generator function_ `dithering` which yields coordinate tuples: ```python dithering(6, 5) -> (0, 0), (4, 4), (4, 0), (0, 4), (2, 2), (2, 0), (2, 4) .. ``` ```javascript dithering(6, 5) => [0, 0], [4, 4], [4, 0], [0, 4], [2, 2], [2, 0], [2, 4] .. ``` ~~~ ~~~if:kotlin To pass the tests, write a function `dithering` which returns a list of coordinate pairs: ```kotlin dithering(6, 5) -> listOf( Pair(0, 0), Pair(4, 4), Pair(4, 0), Pair(0, 4), Pair(2, 2), Pair(2, 0), Pair(2, 4) .. ) ``` ~~~ ~~~if:rust To pass the tests, write a function `dithering` which returns an iterator of tuples: ```rust dithering(6, 5).take(6) -> (0, 0), (4, 4), (4, 0), (0, 4), (2, 2), (2, 0) ``` ~~~ ~~~if:lambdacalc ### Encodings purity: `LetRec` numEncoding: `BinaryScott` export deconstructors `fst, snd` for your `Pair` encoding and deconstructor `foldr` for your `List` encoding ~~~ ## Animation This is how the dithering looks like for a 16×16 pixel image: ![Dithering 16×16](data:image/gif;base64,R0lGODlhIAAgAIAAAAAAAP///yH+KGNyZWF0ZWQgMjAyNCBieSBNYWRqb3N6IGZvciBjb2Rld2Fycy5jb20AIf8LTkVUU0NBUEUyLjADAQAAACH5BAQyAAAALAAAAAAgACAAAAIehI+py+0Po5y02ouz3rz7D4biSJbmiabqyrbuC5sFACH5BAQBAAAALAAAAAACAAIAAAICjFMAIfkEBAEAAAAsEAAQAAIAAgAAAgKMUwAh+QQEAQAAACwQAAAAAgACAAACAoxTACH5BAQBAAAALAAAEAACAAIAAAICjFMAIfkEBAEAAAAsCAAIAAIAAgAAAgKMUwAh+QQEAQAAACwYABgAAgACAAACAoxTACH5BAQBAAAALBgACAACAAIAAAICjFMAIfkEBAEAAAAsCAAYAAIAAgAAAgKMUwAh+QQEAQAAACwIAAAAAgACAAACAoxTACH5BAQBAAAALBgAEAACAAIAAAICjFMAIfkEBAEAAAAsGAAAAAIAAgAAAgKMUwAh+QQEAQAAACwIABAAAgACAAACAoxTACH5BAQBAAAALAAACAACAAIAAAICjFMAIfkEBAEAAAAsEAAYAAIAAgAAAgKMUwAh+QQEAQAAACwQAAgAAgACAAACAoxTACH5BAQBAAAALAAAGAACAAIAAAICjFMAIfkEBAEAAAAsBAAEAAIAAgAAAgKMUwAh+QQEAQAAACwUABQAAgACAAACAoxTACH5BAQBAAAALBQABAACAAIAAAICjFMAIfkEBAEAAAAsBAAUAAIAAgAAAgKMUwAh+QQEAQAAACwMAAwAAgACAAACAoxTACH5BAQBAAAALBwAHAACAAIAAAICjFMAIfkEBAEAAAAsHAAMAAIAAgAAAgKMUwAh+QQEAQAAACwMABwAAgACAAACAoxTACH5BAQBAAAALAwABAACAAIAAAICjFMAIfkEBAEAAAAsHAAUAAIAAgAAAgKMUwAh+QQEAQAAACwcAAQAAgACAAACAoxTACH5BAQBAAAALAwAFAACAAIAAAICjFMAIfkEBAEAAAAsBAAMAAIAAgAAAgKMUwAh+QQEAQAAACwUABwAAgACAAACAox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gKEUQAh+QQEAQAAACwIAB4AAgACAAACAoRRACH5BAQBAAAALAgABgACAAIAAAIChFEAIfkEBAEAAAAsGAAWAAIAAgAAAgKEUQAh+QQEAQAAACwYAAYAAgACAAACAoRRACH5BAQBAAAALAgAFgACAAIAAAIChFEAIfkEBAEAAAAsAAAOAAIAAgAAAgKEUQAh+QQEAQAAACwQAB4AAgACAAACAoRRACH5BAQBAAAALBAADgACAAIAAAIChFEAIfkEBAEAAAAsAAAeAAIAAgAAAgKEUQA7)
algorithms
def dithering(width, height): size = 1 while width > size or height > size: size *= 2 if size == 1: yield (0, 0) else: for (x, y) in dithering(size / 2, size / 2): for t in ((x, y), (x + size / 2, y + size / 2), (x + size / 2, y), (x, y + size / 2)): if t[0] < width and t[1] < height: yield t
Dithering
5426006a60d777c556001aad
[ "Algorithms" ]
https://www.codewars.com/kata/5426006a60d777c556001aad
4 kyu
Imagine that we have ATM with multiple currencies. The users can withdraw money of in any currency that the ATM has. Our function must analyze the currency and value of what the users wants, and give money to the user starting from bigger values to smaller. The ATM gives the **least amount of notes** possible. This kata has a preloaded dictionary of possible bank note values for different currencies (`RUB, EUR, UAH, USD, CUP, SOS`): ```python VALUES = { "EUR": [5, 10, 20, 50, 100, 200, 500], "USD": ... } ``` ```ruby VALUES = { "EUR" => [5, 10, 20, 50, 100, 200, 500], "USD" => ... } ``` ```javascript const VALUES = { "EUR": [5, 10, 20, 50, 100, 200, 500], "USD": ... } // Note: VALUES and its internal arrays are frozen, don't try to mutate them ``` The function should return a string containing how many bank notes of each value the ATM will give out, for example: ``` "8 * 100 USD, 2 * 20 USD, 1 * 2 USD" ``` If it can't do that because there are no notes for this value, it should return: ``` "Can't do *value* *currency*. Value must be divisible by *amount*!" ``` (replace `*value*`, `*currency*` and `*amount*` with the relevant details) If it doesn't have the requested currency at all, it should return: ``` "Sorry, have no *currency*." ``` ### Notes: * Letter case and word order doesn't matter in the input: e.g. `"EUR 1000"` and `"1000eur"` are **the same**. See test cases for more user input samples. * **Do not** create your own `VALUES` dictionary/hash or you'll get broken tests.
reference
import re def atm(value): match = re . fullmatch('([A-Z]+) ?(\d+)|(\d+) ?([A-Z]+)', value . upper()) currency = match . group(1) or match . group(4) value = int(match . group(2) or match . group(3)) if currency not in VALUES: return "Sorry, have no {}." . format(currency) if value % VALUES[currency][0]: return "Can't do {} {}. Value must be divisible by {}!" . format(value, currency, VALUES[currency][0]) result = [] for v in VALUES[currency][:: - 1]: if value and v <= value: result . append("{} * {} {}" . format(value / / v, v, currency)) value %= v return ", " . join(result)
ATM money counter
5665a6a07b5afe0aba00003a
[ "Regular Expressions", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5665a6a07b5afe0aba00003a
6 kyu
If you deposit $100 each year into a bank account with yearly 1% interest rate, how many years will it take you to accumulate minimum $5000? What if the interest is 3% instead? This is the question you will answer in this kata for the interest rates 1, 2, 3, 4, 5 and 6% given a yearly deposit amount and target amount. It works like this: - The user inputs a fixed amount they wish to deposit each year and a minimum retirement target - The function calculates how many years it will take to reach the retirement target using various yearly fixed interest rates: 1, 2, 3, 4, 5, 6 % - All deposits happen on 1. January and all interests are deposited 31st December You will create a function which takes paramters (```yearly_deposit```) and (```min_target_balance```) that returns a dictionairy of (interest rate, years to save) pairs. For javascript return an object where the key is string and value is int. See example: ```python def calculate_retirement(yearly_deposit, min_target_balance): ''' @param yearly_deposit (int) yearly deposit amount @param min_target_balance (int) minimum target balance @return dictionary of (interest rate (int), years to save (int)) pair ''' pass calculate_retirement(100, 300) => {1: 3, 2: 3, 3: 3, 4: 3, 5: 3, 6: 3} # This tells us that at interest rate 1% it takes 3 years, # at interest rate 2% it takes 3 years...etc # 2 % interest rate explained: # Year 1: 1.jan 100 deposited into account # Year 1: 31.dec interest payment (100 * 1.02) = 102 (new balance) # Year 2: 1.jan 100 deposited into account, 202 (new balance) # Year 2: 31.dec interest payment 202 * 1.02 = 206.04 (new balance) # Year 3: 1.jan 100 deposited into account, 306.04 (new balance) # Year 3: 31.dec interest payment 306.04 * 1.02 = 312.1608 (new balance) # Minimum target was 300 which was reached during 3rd year, # the answer is 3 for interest rate 2% calculate_retirement(100, 700) => {1: 7, 2: 7, 3: 7, 4: 7, 5: 6, 6: 6} calculate_retirement(100, 1000) => {1: 10, 2: 10, 3: 9, 4: 9, 5: 8, 6: 8} calculate_retirement(100, 10000) => {1: 70, 2: 55, 3: 47, 4: 41, 5: 36, 6: 33} ``` Info: - No silly test cases will be used such as: negative/0 deposit amount, negative/0 target balance, astronomical input sizes.
algorithms
import math def calculate_retirement(P, FV): rates = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0} for i in range(1, 7): r = i / 100 rates[i] = math . ceil(math . log( 1 + (FV * r) / (P * r + P)) / math . log(1 + r)) return rates
Save for retirement
58177df1e7f457b89d000327
[ "Mathematics", "Algorithms", "Logic" ]
https://www.codewars.com/kata/58177df1e7f457b89d000327
7 kyu
# Password Check - Binary to String A wealthy client has forgotten the password to his business website, but he has a list of possible passwords. His previous developer has left a file on the server with the name password.txt. You open the file and realize it's in binary format. Write a script that takes an array of possible passwords and a string of binary representing the possible password. Convert the binary to a string and compare to the password array. If the password is found, return the password string, else return false; ```javascript decodePass(['password123', 'admin', 'admin1'], '01110000 01100001 01110011 01110011 01110111 01101111 01110010 01100100 00110001 00110010 00110011'); => 'password123' decodePass(['password321', 'admin', 'admin1'], '01110000 01100001 01110011 01110011 01110111 01101111 01110010 01100100 00110001 00110010 00110011'); => false decodePass(['password456', 'pass1', 'test12'], '01110000 01100001 01110011 01110011 01110111 01101111 01110010 01100100 00110001 00110010 00110011'); => false ``` ```python decode_pass(['password123', 'admin', 'admin1'], '01110000 01100001 01110011 01110011 01110111 01101111 01110010 01100100 00110001 00110010 00110011'); => 'password123' decode_pass(['password321', 'admin', 'admin1'], '01110000 01100001 01110011 01110011 01110111 01101111 01110010 01100100 00110001 00110010 00110011'); => False decode_pass(['password456', 'pass1', 'test12'], '01110000 01100001 01110011 01110011 01110111 01101111 01110010 01100100 00110001 00110010 00110011'); => False ``` ```csharp DecodePass(["password123", "admin", "admin1"], "01110000 01100001 01110011 01110011 01110111 01101111 01110010 01100100 00110001 00110010 00110011"); => "password123" DecodePass(["password321", "admin", "admin1"], "01110000 01100001 01110011 01110011 01110111 01101111 01110010 01100100 00110001 00110010 00110011"); => null DecodePass(["password456", "pass1", "test12"], "01110000 01100001 01110011 01110011 01110111 01101111 01110010 01100100 00110001 00110010 00110011"); => null ```
reference
def decode_pass(pass_list, bits): s = "" . join(chr(int(x, 2)) for x in bits . split()) return s if s in pass_list else False
Password Check - Binary to String
5a731b36e19d14400f000c19
[ "Binary", "Strings", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5a731b36e19d14400f000c19
7 kyu
Convert DD (decimal degrees) position to DMS (degrees, minutes, seconds). ##### Inputs: `dd_lat` and `dd_lon` 2 floats representing the latitude and the longitude in degree -i.e. 2 floats included in [-90, 90] and [-180, 180]. Note that latitude 0 is north, longitude 0 is east. ##### Outputs: A tuple of DMS latitudes formated as follows: `DDD*mm'ss.sss"C` With: - `DDD`: degrees - `mm`: minutes - `ss.sss`: seconds rounded to 3 decimals - `C`: first letter uppercase of the cardinal direction ##### ressources about WGS 84 on [Wikipedia](https://en.wikipedia.org/wiki/World_Geodetic_System#WGS84)
reference
from math import modf def dms(number: float, cardinal_dirs: str) - > str: rem, D = modf(abs(number)) rem, M = modf(rem * 60) S = rem * 60 return f' { D : 03.0 f } * { M : 02.0 f } \' { S : 06.3 f } " { cardinal_dirs [ number < 0 ]} ' def convert_to_dms(latitude: str, longitude: str) - > tuple: return f' { dms ( float ( latitude ), "NS" )} ', f' { dms ( float ( longitude ), "EW" )} '
GPS coordinate conversions - DD to DMS
5a72fd224a6b3463b00000a0
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5a72fd224a6b3463b00000a0
7 kyu
`This kata is the first of the ADFGX Ciphers, the harder version can be found `<a href='https://www.codewars.com/kata/adfgx-un-simplified/python' target='_blank'>here</a>. The <a href='https://en.wikipedia.org/wiki/ADFGVX_cipher' target='_blank'>ADFGX Cipher</a> is a pretty well-known Cryptographic tool, and is essentially a modified <a href="https://en.wikipedia.org/wiki/Polybius_square" target="_blank">Polybius Square</a>. Rather than having numbers as coordinates on the table, it has the letters: `A, D, F, G, X` Also, because this is the first step, and to help simplify things, you won't have to worry about a key, or the corresponding columnar transposition. In this kata ;) All you have to do is encrypt and decrypt a string into `ADFGX` format. `adfgx_encrypt() and adfgx_decrypt()` will be passed a string, `plaintext` and `ciphertext` respectively, and an adfgx`square`, for which will guide the operations. Now for some examples to clear confusion: ```python adfgx_encrypt("helloworld", "bchigklnmoqprstuvwxyzadef") A D F G X A b c h i g D k l n m o F q p r s t -> square (PLEASE NOTE, j SHOULD BE TREATED AS i) G u v w x y X z a d e f "helloworld" -> plaintext EVALUATES TO: F -> "AF" A h -------------- G -> "XG" X e AND SO FORTH... #Results in: adfgx_encrypt("helloworld", "bchigklnmoqprstuvwxyzadef") == "AFXGDDDDDXGFDXFFDDXF" ``` Now decryption: ```python adfgx_decrypt("FGXGADGDXGFXAXXGFGFGAADGXG", "aczlmuqngoipvstkrwfxhdbey) A D F G X A a c z l m D u q n g o F i p v s t -> square (PLEASE NOTE, j SHOULD BE TREATED AS i) G k r w f x X h d b e y "FGXGADGDXGFXAXXGFGFGAADGXG" -> ciphertext "FG" == "s" "XG" == "e" AND SO ON: adfgx_decrypt("FGXGADGDXGFXAXXGFGFGAADGXG", "aczlmuqngoipvstkrwfxhdbey) == "secretmessage" ``` PLEASE NOTE: ALL INPUT WILL BE VALID, NO NEED TO ERROR CHECK :D What are you waiting for?! Go create `adfgx_encrypt() and adfgx_decrypt()`! Good Luck!
reference
from itertools import product import re KEY = [a + b for a, b in product("ADFGX", repeat=2)] def adfgx_encrypt(plaintext, square): d = dict(zip(square, KEY)) oddity = d['i'] if 'i' in d else d['j'] return '' . join(d . get(c, oddity) for c in plaintext) def adfgx_decrypt(ciphertext, square): d = dict(zip(KEY, square)) IJkey = [k for k, v in d . items() if v in 'ij']. pop() return '' . join(d . get(c, d[IJkey]) for c in re . findall(r'.{2}', ciphertext))
ADFGX Simplified
57f171f618e9fa58ef000083
[ "Cryptography", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/57f171f618e9fa58ef000083
6 kyu
In this Kata, we are going to reverse a string while maintaining the spaces (if any) in their original place. For example: ``` solve("our code") = "edo cruo" -- Normal reversal without spaces is "edocruo". -- However, there is a space at index 3, so the string becomes "edo cruo" solve("your code rocks") = "skco redo cruoy". solve("codewars") = "srawedoc" ``` More examples in the test cases. All input will be lower case letters and in some cases spaces. Good luck! Please also try: [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2) [Simple remove duplicates](https://www.codewars.com/kata/5ba38ba180824a86850000f7)
algorithms
def solve(s): it = reversed(s . replace(' ', '')) return '' . join(c if c == ' ' else next(it) for c in s)
Simple string reversal
5a71939d373c2e634200008e
[ "Algorithms" ]
https://www.codewars.com/kata/5a71939d373c2e634200008e
7 kyu
This is a classic needing (almost) no further introduction. Given a N x N chess board, place N queens on it so none can attack another: I.e. no other queens can be found horizontally, vertically or diagonally to the current. On the board below, no further queens can be positioned. <pre style="font-family:courier">+-+-+ |Q| | +-+-+ | | | +-+-+</pre><br/> In this example a queen can be located in position a or position b - but not in both, thereby making (0,0) an invalid first position: <pre style="font-family:courier">+-+-+-+ |Q| | | +-+-+-+ | | |a| +-+-+-+ | |b| | +-+-+-+</pre><br/> Return value must by an array of N x-positions. That is, the y position is given by the index. For following board, expected answer is `[1, 3, 0, 2]`: <pre style="font-family:courier">+-+-+-+-+ | |X| | | x=1, y=0 +-+-+-+-+ | | | |X| x=3, y=1 +-+-+-+-+ |X| | | | x=0, y=2 +-+-+-+-+ | | |X| | x=2, y=3 +-+-+-+-+</pre><br/> Only one solution per N is expected. If no solution can be found, return an empty array. That is, for a 1 x 1 board, the output is [0]. Input is a value positive number (N>0) and can be quite large, so try to make your solution efficient. See sample tests to check how large `N` can be. Have fun :) ---- Next steps: - [N queens puzzle (with one mandatory queen position)](https://www.codewars.com/kata/561bed6a31daa8df7400000e) - [N queens problem (with one mandatory queen position) - challenge version](https://www.codewars.com/kata/5985ea20695be6079e000003)
algorithms
def nQueen(n): if n == 2 or n == 3: return [] r, odds, evens = n % 6, list(range(1, n, 2)), list(range(0, n, 2)) if r == 2: evens[: 2] = evens[: 2][:: - 1] evens . append(evens . pop(2)) if r == 3: odds . append(odds . pop(0)) evens . extend(evens[: 2]) del evens[: 2] return odds + evens
N queens problem (with no mandatory queen position)
52cdc1b015db27c484000031
[ "Performance", "Algorithms" ]
https://www.codewars.com/kata/52cdc1b015db27c484000031
4 kyu
Description: Before smartphones and blackberry's without a qwerty keyboard, and prior to the development of T9 (predictive text entry) systems, the method to type words was called "multi-tap" and involved pressing a button repeatedly to cycle through the possible values. ------- ------- ------- | | | ABC | | DEF | | 1 | | 2 | | 3 | ------- ------- ------- ------- ------- ------- | GHI | | JKL | | MNO | | 4 | | 5 | | 6 | ------- ------- ------- ------- ------- ------- |PQRS | | TUV | | WXYZ| | 7 | | 8 | | 9 | ------- ------- ------- ------- ------- ------- | | |space| | | | * | | 0 | | # | ------- ------- ------- For example, to type a letter "R" you would press the 7 key three times (as the screen display for the current character cycles through P->Q->R->S->7). A character is "locked in" once the user presses a different key or pauses for a short period of time (thus, no extra button presses are required beyond what is needed for each letter individually). The zero key handles spaces, with one press of the key producing a space and two presses producing a zero. For this assignment, write a module that can calculate the button presses sequence required for any phrase. Punctuation can be ignored for this exercise. Likewise, you can assume the phone doesn't distinguish between upper/lowercase characters (but you should allow your module to accept input in either for convenience). For e.g. to type "HELLO WORLD", user would have to press the below sequence: 4433555p555666096667775553 p indicates a pause which is required before a character should get locked before the next character on the same key has to be pressed. In the above example, a pause is required before the keys can be pressed for the second instance of the character "L" Try avoiding the obvious a-z combinations in order to support ease in change of Keypad combinations
reference
from itertools import groupby from operator import itemgetter _LAYOUT = (' 0', '1', 'ABC2', 'DEF3', 'GHI4', 'JKL5', 'MNO6', 'PQRS7', 'TUV8', 'WXYZ9') _KEYMAP = {c: str(i) * j for i, key in enumerate(_LAYOUT) for j, c in enumerate(key, 1)} def sequence(phrase): presses = (_KEYMAP . get(c . upper(), c) for c in phrase) return '' . join('p' . join(group) for __, group in groupby(presses, key=itemgetter(0)))
Dumbphone Keypads
5680e56f4797a55076000044
[ "Fundamentals" ]
https://www.codewars.com/kata/5680e56f4797a55076000044
6 kyu
We define the sequence ```SF``` in the following way in terms of four previous sequences: ```S1```, ```S2```, ```S3``` and ```ST``` <a href="http://imgur.com/kCiwfWT"><img src="http://i.imgur.com/kCiwfWT.jpg?1" title="source: imgur.com" /></a> We are interested in collecting the terms of SF that are multiple of ten. The first term multiple of ten of this sequence is ```60``` Make the function ```find_mult10_SF()``` that you introduce the ordinal number of a term multiple of 10 of SF and gives us the value of this term. Let's see some cases: ```python find_mult10_SF(1) == 60 find_mult10_SF(2) == 70080 find_mult10_SF(3) == 90700800 ``` ``` haskell findMult10SF 1 `shouldBe` 60 findMult10SF 2 `shouldBe` 70080 findMult10SF 3 `shouldBe` 90700800 ``` Memoization is advisable to have a more agile code for tests. ~~~if-not:rust,go Your code will be tested up to the 300-th term, multiple of 10. ~~~ ~~~if:rust,go Your code will be tested up to the 300-th term, multiple of 10, in fixed tests, then 100 random numbers in the interval [301, 2000). ~~~ Happy coding!!
reference
def find_mult10_SF(n): return 16 * * n * (81 * * n + 9) / / 24
Multiples of Ten in a Sequence Which Values Climb Up
561d54055e399e2f62000045
[ "Fundamentals", "Algorithms", "Mathematics", "Data Structures", "Sorting", "Memoization" ]
https://www.codewars.com/kata/561d54055e399e2f62000045
6 kyu
Given a number N, can you fabricate the two numbers NE and NO such that NE is formed by even digits of N and NO is formed by odd digits of N? Examples: | input | NE | NO | |:------:|:----:|:---:| | 126453 | 264 | 153 | | 3012 | 2 | 31 | | 4628 | 4628 | 0 | `0` is considered as an even number. In C and JavaScript you should return an array of two elements such as the first is NE and the second is NO.
reference
def even_and_odd(n): ne = "" no = "" for x in str(n): if int(x) % 2 == 0: ne += x else: no += x if len(ne) == 0: ne = "0" if len(no) == 0: no = "0" return (int(ne), int(no))
Even and Odd !
594adadee075005308000122
[ "Fundamentals" ]
https://www.codewars.com/kata/594adadee075005308000122
7 kyu
# Background <a href="https://en.wikipedia.org/wiki/There_Was_an_Old_Lady_Who_Swallowed_a_Fly">There was an Old Lady who Swallowed a Fly</a> <pre style='color:orange'> There was an old lady who swallowed a <span style="color:red;background:black">fly</span>; I don't know why she swallowed a fly - perhaps she'll die! There was an old lady who swallowed a <span style="color:red;background:black">spider</span>; That wriggled and jiggled and tickled inside her! She swallowed the spider to catch the fly; I don't know why she swallowed a fly - Perhaps she'll die! There was an old lady who swallowed a <span style="color:red;background:black">bird</span>; How absurd to swallow a bird! She swallowed the bird to catch the spider; That wriggled and jiggled and tickled inside her! She swallowed the spider to catch the fly; I don't know why she swallowed a fly - Perhaps she'll die! There was an old lady who swallowed a <span style="color:red;background:black">cat</span>; Fancy that she swallowed a cat! She swallowed the cat to catch the bird, She swallowed the bird to catch the spider; That wriggled and jiggled and tickled inside her! She swallowed the spider to catch the fly; I don't know why she swallowed a fly - Perhaps she'll die! There was an old lady that swallowed a <span style="color:red;background:black">dog</span>; What a hog, to swallow a dog! She swallowed the dog to catch the cat, She swallowed the cat to catch the bird, She swallowed the bird to catch the spider; That wriggled and jiggled and tickled inside her! She swallowed the spider to catch the fly; I don't know why she swallowed a fly - Perhaps she'll die! ` There was an old lady who swallowed a <span style="color:red;background:black">goat</span>; She just opened her throat and swallowed a goat! She swallowed the goat to catch the dog, She swallowed the dog to catch the cat, She swallowed the cat to catch the bird, She swallowed the bird to catch the spider; That wriggled and jiggled and tickled inside her! She swallowed the spider to catch the fly; I don't know why she swallowed a fly - Perhaps she'll die! There was an old lady who swallowed a <span style="color:red;background:black">cow</span>; I don't know how she swallowed a cow! She swallowed the cow to catch the goat, She swallowed the goat to catch the dog, She swallowed the dog to catch the cat, She swallowed the cat to catch the bird, She swallowed the bird to catch the spider; That wriggled and jiggled and tickled inside her! She swallowed the spider to catch the fly; I don't know why she swallowed a fly - Perhaps she'll die! There was an old lady who swallowed a <span style="color:red;background:black">horse</span>; ...She's dead, of course! </pre> # Kata Task You are a forensic investigator attending a suspicious scene where an old lady has been found dead. According to distressed witnesses she had been observed recklessly swallowing a variety of animals, just as in the nursery rhyme. An autopsy is conducted, and some of the swallowed animals are found to be still alive! But which ones? INPUT * List of `animals` in the order the old lady attempted to swallow them OUTPUT * List of animals found to be still alive inside the old lady (same order as swallowed) # Notes * As in the rhyme, swallowing a horse will cause immediate death * The swallowed animals can catch their prey before they too may be caught * Even though the rhyme does not say "*She swallowed the horse to catch the cow*" you should assume this was why she did it! <hr/> <pre style="color:black;background:gray;"> * No animals were harmed in the making of this Kata. * Don't worry about the old lady either. This was not a true story. </pre>
algorithms
def old_lady_swallows(animals: list) - > list: ord_an = [None, 'fly', 'spider', 'bird', 'cat', 'dog', 'goat', 'cow', 'horse', None] res = [] for a in animals: ind_a = ord_an . index(a) res = [x for x in res if x != ord_an[ind_a - 1]] if ord_an[ind_a + 1] not in res: res . append(a) if a == 'horse': break return res
There was an Old Lady who Swallowed a Fly
5a68ffe3e626c5e85700002d
[ "Algorithms" ]
https://www.codewars.com/kata/5a68ffe3e626c5e85700002d
6 kyu
The task is simply stated. Given an integer <code>n</code> (<code>3 < n < 10<sup>9</sup></code>), find the length of the smallest list of [*perfect squares*](https://en.wikipedia.org/wiki/Square_number) which add up to <code>n</code>. Come up with the best algorithm you can; you'll need it! <strong>Examples:</strong> <ul> <li><code>sum_of_squares(17) = 2</code> <br> 17 = 16 + 1 (16 and 1 are perfect squares).</li> <li><code>sum_of_squares(15) = 4</code> <br> 15 = 9 + 4 + 1 + 1. There is no way to represent 15 as the sum of three perfect squares.</li> <li><code>sum_of_squares(16) = 1</code> <br> 16 itself is a perfect square.</li> </ul> <strong>Time constraints:</strong> 5 easy (sample) test cases: <code>n < 20</code> 5 harder test cases: <code>1000 < n < 15000</code> 5 maximally hard test cases: <code>5e8 < n < 1e9</code> ```if:rust,go 1000 random maximally hard test cases: <code>1e8 < n < 1e9</code> ``` ```if:java 300 random maximally hard test cases: <code>1e8 < n < 1e9</code> ``` ```if:c# 350 random maximally hard test cases: <code>1e8 < n < 1e9</code> ``` ```if:python 15 random maximally hard test cases: <code>1e8 < n < 1e9</code> ``` ```if:ruby 25 random maximally hard test cases: <code>1e8 < n < 1e9</code> ``` ```if:javascript 100 random maximally hard test cases: <code>1e8 < n < 1e9</code> ``` ```if:crystal 250 random maximally hard test cases: <code>1e8 < n < 1e9</code> ``` ```if:c 100 random maximally hard test cases: <code>1e8 < n < 1e9</code> ``` ```if:cpp 100 random maximally hard test cases: <code>1e8 < n < 1e9</code> ``` ```if:cobol 15 random maximally hard test cases: `1e8 < n < 1e9` ``` ```if:haskell 100 random maximally hard test cases: `1e8 < n < 1e9` ```
algorithms
def one_square(n): return round(n * * .5) * * 2 == n def two_squares(n): while n % 2 == 0: n / /= 2 p = 3 while p * p <= n: while n % (p * p) == 0: n / /= p * p while n % p == 0: if p % 4 == 3: return False n / /= p p += 2 return n % 4 == 1 def three_squares(n): while n % 4 == 0: n / /= 4 return n % 8 != 7 def sum_of_squares(n): if one_square(n): return 1 if two_squares(n): return 2 if three_squares(n): return 3 return 4
Sums of Perfect Squares
5a3af5b1ee1aaeabfe000084
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/5a3af5b1ee1aaeabfe000084
4 kyu
### Introduction and Warm-up (Highly recommended) ### [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) ___ ## Task **_Given_** an *array/list [] of integers* , **_Find the product of the k maximal_** numbers. ___ ### Notes * **_Array/list_** size is *at least 3* . * **_Array/list's numbers_** *Will be* **_mixture of positives , negatives and zeros_** * **_Repetition_** of numbers in *the array/list could occur*. ___ ### Input >> Output Examples ``` maxProduct ({4, 3, 5}, 2) ==> return (20) ``` #### _Explanation_: * **_Since_** *the size (k) equal 2* , then **_the subsequence of size 2_** *whose gives* **_product of maxima_** is `5 * 4 = 20` . ___ ``` maxProduct ({8, 10 , 9, 7}, 3) ==> return (720) ``` #### _Explanation_: * **_Since_** *the size (k) equal 3* , then **_the subsequence of size 3_** *whose gives* **_product of maxima_** is ` 8 * 9 * 10 = 720` . ___ ``` maxProduct ({10, 8, 3, 2, 1, 4, 10}, 5) ==> return (9600) ``` #### _Explanation_: * **_Since_** *the size (k) equal 5* , then **_the subsequence of size 5_** *whose gives* **_product of maxima_** is ` 10 * 10 * 8 * 4 * 3 = 9600` . ___ ``` maxProduct ({-4, -27, -15, -6, -1}, 2) ==> return (4) ``` #### _Explanation_: * **_Since_** *the size (k) equal 2* , then **_the subsequence of size 2_** *whose gives* **_product of maxima_** is ` -4 * -1 = 4` . ___ ``` maxProduct ({10, 3, -1, -27} , 3) return (-30) ``` #### _Explanation_: * **_Since_** *the size (k) equal 3* , then **_the subsequence of size 3_** *whose gives* **_product of maxima_** is ` 10 * 3 * -1 = -30 ` . ___ ___ ___ ___ #### [Playing with Numbers Series](https://www.codewars.com/collections/playing-with-numbers) #### [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) #### [For More Enjoyable Katas](http://www.codewars.com/users/MrZizoScream/authored) ___ ##### ALL translations are welcomed ##### Enjoy Learning !! ##### Zizou
reference
from functools import reduce from operator import mul from heapq import nlargest def maxProduct(lst, n): return reduce(mul, nlargest(n, lst))
Product Of Maximums Of Array (Array Series #2)
5a63948acadebff56f000018
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5a63948acadebff56f000018
7 kyu
Additive number is a string whose digits can form an additive sequence. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. For example:<br/> ```"112358"``` is an additive number because the digits can form an additive sequence: ```1, 1, 2, 3, 5, 8``` ```1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8``` Write ```javascript function findAdditiveNumbers(num) ``` ```python def find_additive_numbers(num) ``` that will take in a string and return all the numbers that make up the sequence. <br/> <br/> ```javascript findAdditiveNumbers('112358') === ['1','1','2','3','5','8'] findAdditiveNumbers('199100199') === ['1','99','100','199'] findAdditiveNumbers('1023') === [] findAdditiveNumbers('112356') === [] // 6 != 5+3 ``` ```python find_additive_numbers('112358') == ['1','1','2','3','5','8'] find_additive_numbers('199100199') == ['1','99','100','199'] find_additive_numbers('1023') == [] find_additive_numbers('112356') == [] # 6 != 5+3 ``` <b>Note: Numbers in the additive sequence cannot have leading zeros, so sequence ```1, 2, 03``` or ```1, 02, 3``` is invalid</b>
algorithms
def find_additive_numbers(num): for k in range(2, len(num)): for j in range(1, k): if k - j > 1 and num[j] == '0': continue a, b = j, k out = [num[: a], num[a: b]] while b < len(num): x = int(out[- 2]) + int(out[- 1]) a, b = b, b + len(str(x)) y = int(num[a: b]) if x != y: break out . append(str(y)) else: return out return []
Additive Numbers
5693239fb761dc8670000001
[ "Parsing", "Algorithms" ]
https://www.codewars.com/kata/5693239fb761dc8670000001
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: What's a reversible prime? That is: A prime, reverse all the digits, get a new number. If the new number is also a prime, then it is a reversible prime . We can get a sequence of reversible prime: ``` n(start from 0) --> 0 1 2 3 4 5 6 7 8 ..... reversible prime --> 2 3 5 7 11 13 17 31 37 ..... ``` # Task Complete function `reversiblePrime`. Function accept argument `n`(a integer, 0 <= n <= 10000). Returns the n-th reversible prime. # Some examples: ``` reversiblePrime(0) === 2 reversiblePrime(1) === 3 reversiblePrime(5) === 13 reversiblePrime(10) === 73 reversiblePrime(20) === 167 reversiblePrime(100) === 1669 ```
algorithms
from gmpy2 import is_prime, next_prime def gen(): prime = 0 while True: prime = next_prime(prime) if is_prime(int(str(prime)[:: - 1])): yield prime primes, result = gen(), [] def reversible_prime(n): while len(result) <= n: result . append(next(primes)) return result[n]
n-th reversible prime
5826c14622be6ef2a4000033
[ "Puzzles", "Algorithms" ]
https://www.codewars.com/kata/5826c14622be6ef2a4000033
6 kyu
### Please also check out other katas in [Domino Tiling series](https://www.codewars.com/collections/5d19554d13dba80026a74ff5)! --- # Task A domino is a rectangular block with `2` units wide and `1` unit high. A domino can be placed on a grid in two ways: horizontal or vertical. ``` ## or # # ``` You have infinitely many dominoes, and you want to fill a board that is `N` units wide and `2` units high: ``` <--- N ---> ############### ############### ``` The task is to find **the number of ways** you can fill the given grid with dominoes. # The Twist However, you can quickly find that the answer is exactly the Fibonacci series (and yeah, CW has already too many of them), so here is a twist: Now you have infinite supply of dominoes in `K` colors, and you have to fill the given grid **without any two adjacent dominoes having the same color**. Two dominoes are adjacent if they share an edge. A valid filling of a 2 x 10 board with three colors could be as follows (note that two same-colored dominoes can share a point): ``` 1131223312 2231332212 ``` Since the answer will be very large, please give your answer **modulo 12345787**. # Examples ```python # K == 1: only one color two_by_n(1, 1) == 1 two_by_n(3, 1) == 0 # K == 2: two colors two_by_n(1, 2) == 2 two_by_n(4, 2) == 4 two_by_n(7, 2) == 2 # K == 3: three colors two_by_n(1, 3) == 3 two_by_n(2, 3) == 12 two_by_n(5, 3) == 168 # yes, the numbers grow quite quickly # You must handle big values two_by_n(10, 5) == 7802599 two_by_n(20, 10) == 4137177 ``` ```javascript // K == 1: only one color twoByN(1, 1) == 1 twoByN(3, 1) == 0 // K == 2: two colors twoByN(1, 2) == 2 twoByN(4, 2) == 4 twoByN(7, 2) == 2 // K == 3: three colors twoByN(1, 3) == 3 twoByN(2, 3) == 12 twoByN(5, 3) == 168 // yes, the numbers grow quite quickly // You must handle big values twoByN(10, 5) == 7802599 twoByN(20, 10) == 4137177 ``` ```scala // K == 1: only one color twoByN(1, 1) == 1 twoByN(3, 1) == 0 // K == 2: two colors twoByN(1, 2) == 2 twoByN(4, 2) == 4 twoByN(7, 2) == 2 // K == 3: three colors twoByN(1, 3) == 3 twoByN(2, 3) == 12 twoByN(5, 3) == 168 // yes, the numbers grow quite quickly // You must handle big values twoByN(10, 5) == 7802599 twoByN(20, 10) == 4137177 ``` # Constraints `1 <= N <= 10000` `1 <= K <= 100` All inputs are valid integers.
games
def two_by_n(n, k): s = [1, k, 2 * k * (k - 1)] for _ in range(2, n): s . append((k - 2) * s[- 1] + (k - 1) * (k - 1) * s[- 2]) return s[n] % 12345787
Domino Tiling - 2 x N Board
5a59e029145c46eaac000062
[ "Mathematics", "Algorithms", "Dynamic Programming", "Puzzles" ]
https://www.codewars.com/kata/5a59e029145c46eaac000062
4 kyu
# Disclaimer This Kata is an insane step-up from [GiacomoSorbi's Kata](https://www.codewars.com/kata/total-increasing-or-decreasing-numbers-up-to-a-power-of-10/python), so I recommend to solve it first before trying this one. # Problem Description A positive integer `n` is called an *increasing number* if its digits are in increasing order (e.g. 123, 144568, 56799). Similarly, `n` is called a *decreasing number* if its digits are in decreasing order (e.g. 210, 76642, 998500). Note that the numbers whose digits are all the same (e.g. 1111, 22222) are both increasing and decreasing. Given the maximum number of digits (`max_digits`), how many positive integers in the range are either increasing or decreasing (or both)? Since your answer will be very large, please give your answer **modulo 12345787**. Also note that, unlike Giacomo's version, the number zero is excluded from the counts (because it's not positive). # Constraints `1 <= max_digits <= 10 ** 9` **Note the input size!** The input will be always a valid integer. # Examples ```python # Up to two digits, all numbers are either increasing or decreasing insane_inc_or_dec(1) == 9 insane_inc_or_dec(2) == 99 insane_inc_or_dec(3) == 474 insane_inc_or_dec(4) == 1674 insane_inc_or_dec(5) == 4953 insane_inc_or_dec(6) == 12951 ``` # Acknowledgement This problem was inspired by [Project Euler #113: Non-bouncy Numbers](https://projecteuler.net/problem=113). If you enjoyed this Kata, please also have a look at [my other Katas](https://www.codewars.com/users/Bubbler/authored)!
games
from math import comb def insane_inc_or_dec(max_digits): ''' Derivation summerized: Counting the number of increasing (or decreasing) numbers with d digits is equivalent to counting the number of ways to put d "balls" in 9 (or 10) boxes representing each digit, e.g. for decreasing numbers: | |oo| |o| | | | | | | = 886 ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ 9 8 7 6 5 4 3 2 1 0 Number of ways to put d balls in n boxes is comb(n + d - 1, d). Overcounting: Numbers with all identical digits from 1 to 9 are counted as both increasing and decreasing. Zeros, e.g. 0 or 000, are counted but should not be. => Subtract 10 * max_digits Useful identity: sum(comb(n + x, x) for x in range(1, d)) = comb(n + d + 1, d) - 1 = comb(n + d, n + 1) - 1 ''' return (comb(max_digits + 10, 10) + comb(max_digits + 9, 9) - 2 - max_digits * 10) % 12345787
Insane Increasing or Decreasing Numbers
5993e6f701726f0998000030
[ "Algorithms", "Mathematics", "Puzzles", "Performance" ]
https://www.codewars.com/kata/5993e6f701726f0998000030
4 kyu
Get the list of integers for 'totalAuthored' and 'totalCompleted' of the ```n```th ranker at Codewars Leaderboard. ```(1 <= n <= 500)``` See Example Test Cases for the expected data format. (Note 1 : Mind the title of this kata as well as [https://dev.codewars.com/](https://dev.codewars.com/) ) (Note 2 : It is recommended to finish [Codewars Leaderboard](https://www.codewars.com/kata/codewars-leaderboard/) before this kata. )
reference
from bs4 import BeautifulSoup import requests req = requests . get("https://www.codewars.com/users/leaderboard"). content bs = BeautifulSoup(req, "html.parser") tr = [x . attrs["data-username"] for x in bs . find_all(lambda x: "data-username" in x . attrs)] def get_codeChallenges(n): req = requests . get( f"https://www.codewars.com/api/v1/users/ { tr [ n - 1 ]} "). json()["codeChallenges"] return [req["totalAuthored"], req["totalCompleted"]]
Codewars API
5a6b80cb880385a8f7000089
[ "Fundamentals" ]
https://www.codewars.com/kata/5a6b80cb880385a8f7000089
5 kyu
In this Kata you will rotate a binary tree. You need to implement two methods to rotate a binary tree: one to rotate it to the **left** and one to rotate it to the **right**. If rotation is impossible, return the tree unchanged. ```if:javascript, You need not always ( though you may ) return a _new_ tree ( or entirely new subtrees ), but you should _not_ modify your argument. ``` #### Tree structure ```java Node { Node left Node right int value } ``` ```haskell data Tree a = Empty | Node { left, right :: Tree a , value :: a } deriving (Show,Eq,Foldable) ``` ```javascript Object { left: Object || null , right: Object || null , value: Number } || null Non-null Objects will have all their properties ``` #### What is a binary tree? A binary tree is a tree graph, in which each element can't have more than `2` children. Values can not be duplicated, so (sub)trees can be associated with, and denoted by, their value. #### What does rotate mean? What does it mean to rotate a binary tree in this case? The rotation changes the root of the tree to be the left or right child of the current root. For example: ``` 9 / \ 7 11 / \ 5 8 ``` In this case the root is `9`, its left child is `7`, and its right child is `11`. If we rotate it to the right, we'll get this tree: ``` 7 / \ 5 9 / \ 8 11 ``` We move the left child of the old root (`7`) to be the new root, and move its right child (`8`) to be the new left child of the old root. If we rotate it to the left, we'll get another tree: ``` 11 / 9 / 7 / \ 5 8 ``` We move the right child of the old root (`11`) to be the new root, and move its left child (`null` in this case) to be the new right child of the old root. #### Why to rotate it? https://twitter.com/mxcl/status/608682016205344768 Good luck!
algorithms
def rotate_right(tree): if tree . left is not None: new_right = tree tree = tree . left new_right . left = tree . right tree . right = new_right return tree def rotate_left(tree): if tree . right is not None: new_left = tree tree = tree . right new_left . right = tree . left tree . left = new_left return tree
The Binary Tree, or There and Back Again
5a6de0ec0136a1761d000093
[ "Algorithms", "Data Structures", "Trees" ]
https://www.codewars.com/kata/5a6de0ec0136a1761d000093
6 kyu
This is related to <a href="https://www.codewars.com/kata/cat-years-dog-years">my other Kata</a> about cats and dogs. # Kata Task I have a cat and a dog which I got as kitten / puppy. I forget when that was, but I do know their current ages as `catYears` and `dogYears`. Find how long I have owned each of my pets and return as a list [`ownedCat`, `ownedDog`] NOTES: * Results are truncated whole numbers of "human" years ## Cat Years * `15` cat years for first year * `+9` cat years for second year * `+4` cat years for each year after that ## Dog Years * `15` dog years for first year * `+9` dog years for second year * `+5` dog years for each year after that <hr> **References** * http://www.catster.com/cats-101/calculate-cat-age-in-cat-years * http://www.slate.com/articles/news_and_politics/explainer/2009/05/a_dogs_life.html
reference
def owned_cat_and_dog(cy, dy): cat = 0 if cy < 15 else 1 if cy < 24 else 2 + (cy - 24) / / 4 dog = 0 if dy < 15 else 1 if dy < 24 else 2 + (dy - 24) / / 5 return [cat, dog]
Cat Years, Dog Years (2)
5a6d3bd238f80014a2000187
[ "Fundamentals" ]
https://www.codewars.com/kata/5a6d3bd238f80014a2000187
7 kyu
We are introducing a new variant of the popular game [Codenames](https://czechgames.com/en/codenames/) for two players. We are looking at a board of 5x5 words. Players try to guess the words of the other team but without guessing one of their own words. Your job is to create a board for two players. Therefore, you assign the 5x5 words to the two teams: blue ("B") and red ("R"). Because we don't want the players to see each other's words you will have to show them only their words and hide the others. By default each player gets a total of 7 words. Write a function that will return two 5x5 matrixes. One for the red team and one for the blue team. All the cards that are not relevant for the team are hidden and should be marked with an "-". You can put the cards of each team anywhere you like but they should not overlap. You should not reuse your solution as tests will check for randomness. The function should also work for different values. E.g. if red and blue both get 10 words. Even if it wouldn't be fair in a real game, sometimes one player will also get less or more cards than the other. This would be a valid solution: Team Blue: ```python [ ['B', '-', '-', '-', 'B'], ['-', '-', 'B', '-', 'B'], ['-', '-', '-', '-', '-'], ['-', 'B', '-', '-', '-'], ['B', '-', '-', '-', 'B'] ] ``` Team Red: ```python [ ['-', '-', 'R', '-', '-'], ['-', 'R', '-', '-', '-'], ['-', '-', '-', 'R', '-'], ['-', '-', 'R', 'R', '-'], ['-', 'R', 'R', '-', '-'] ] ``` Good luck!
algorithms
from random import sample def player_matrixes(R=7, B=7): res = sample('R' * R + 'B' * B + '-' * (25 - R - B), k=25) red_matrix = [[res[5 * x + y] if res[5 * x + y] != 'B' else '-' for y in range(5)] for x in range(5)] blue_matrix = [[res[5 * x + y] if res[5 * x + y] != 'R' else '-' for y in range(5)] for x in range(5)] return { "R": red_matrix, "B": blue_matrix, }
Codenames - matrix conversions
5a6ccef6b17101c74900004e
[ "Matrix", "Algorithms" ]
https://www.codewars.com/kata/5a6ccef6b17101c74900004e
6 kyu
As you see in Example test cases, the os running this service is ```posix```. Return the output by executing the command given as the string on posix os. See the example test cases for the expected data format.
reference
import os def get_output(s): return os . popen(s). read()
Posix command
5a6986abe626c5d3e9000063
[ "Fundamentals" ]
https://www.codewars.com/kata/5a6986abe626c5d3e9000063
7 kyu
This is simple version of harder [Square Sums](/kata/square-sums). # Square sums Write function `square_sums_row` ( or `squareSumsRow` or `SquareSumsRow` ) that, given integer number `N` (in range `2..43`), returns array of integers `1..N` arranged in a way, so sum of each 2 consecutive numbers is a square. Solution is valid if and only if following two criterias are met: 1. Each number in range `1..N` is used once and only once. 2. Sum of each 2 consecutive numbers is a perfect square. ### Example For N=15 solution could look like this: `[ 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8 ]` ### Verification 1. All numbers are used once and only once. When sorted in ascending order array looks like this: `[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]` 2. Sum of each 2 consecutive numbers is a perfect square: ``` 16 16 16 16 16 16 16 /+\ /+\ /+\ /+\ /+\ /+\ /+\ [ 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8 ] \+/ \+/ \+/ \+/ \+/ \+/ \+/ 9 25 9 25 9 25 9 9 = 3*3 16 = 4*4 25 = 5*5 ``` If there is no solution, return `false` ( `None` in Scala, `Nothing` in Haskell ). For example if `N=5`, then numbers `1,2,3,4,5` cannot be put into square sums row: `1+3=4`, `4+5=9`, but `2` has no pairs and cannot link `[1,3]` and `[4,5]`. # Have fun! Harder version of this Kata is [here](/kata/square-sums).
algorithms
def square_sums_row(n): def dfs(): if not inp: yield res for v in tuple(inp): if not res or not ((res[- 1] + v) * * .5 % 1): res . append(v) inp . discard(v) yield from dfs() inp . add(res . pop()) inp, res = set(range(1, n + 1)), [] return next(dfs(), False)
Square sums (simple)
5a6b24d4e626c59d5b000066
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/5a6b24d4e626c59d5b000066
5 kyu
Your task is to define a function that understands basic mathematical expressions and solves them. For example: ```python calculate("1 + 1") # => 2 calculate("18 + 4*6") # => 42 calculate("245 - 826") # => -581 calculate("09 + 000482") # => 491 calculate("8 / 4 + 6") # => 8 calculate("5 + 1 / 5") # => 5.2 calculate("1+2+3") # => 6 calculate("9 /3 + 12/ 6") # => 5 ``` <h3>Notes:</h3> - Input string will contain numbers (may be integers and floats) and arithmetic operations. - Input string may contain spaces, and all space characters should be ignored. - Operations that will be used: addition (+), subtraction (-), multiplication (*), and division (/) - Operations must be done in the order of operations: First multiplication and division, then addition and subtraction. - In this kata, input expression will not have negative numbers. (ex: "-4 + 5") - If output is an integer, return as integer. Else return as float. - If input string is empty, contains letters, has a wrong syntax, contains division by zero or is not a string, return False.
algorithms
import re def calculate(input): try: return eval(re . sub(r'(\d+)', lambda m: str(int(m . group(1))), input)) except: return False
Calculate the expression
582b3b085ad95285c4000013
[ "Mathematics", "Strings", "Algorithms" ]
https://www.codewars.com/kata/582b3b085ad95285c4000013
5 kyu
This function will take in a list of strings and put them into a hashmap. A hashmap is a quick way to store and lookup items you might need based on the 'hash' of the item (https://en.wikipedia.org/wiki/Hash_table). In this example, we're going to create hashes based on the sum of the characters. Each charater has a decimal value (ascii value) and the sum of those decimal values will be the hash. Your goal is to take the list of strings, hash them, and return a dictionary with hashes as keys and a list of strings, with that hash, as values.
reference
from functools import reduce from collections import defaultdict def my_hash_map(list_of_strings): return reduce(lambda h, s: h[sum(map(ord, s))]. append(s) or h, list_of_strings, defaultdict(list))
Make Your Own Hashmap
5a6a02adcadebf618400002b
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5a6a02adcadebf618400002b
7 kyu
Your job is to write a function that takes a string and a maximum number of characters per line and then inserts line breaks as necessary so that no line in the resulting string is longer than the specified limit. If possible, line breaks should not split words. However, if a single word is longer than the limit, it obviously has to be split. In this case, the line break should be placed after the first part of the word (see examples below). Really long words may need to be split multiple times. ## Input * A word consists of one or more letters. * The input text will be the empty string or a string consisting of one or more words separated by single spaces. It will not contain any punctiation or other special characters. * The limit will always be an integer greater or equal to one. ## Rules * Fit as many words as you can on a single line. * Always try to break on spaces. * If a single word is longer than a line, break it apart by appending as much of it as possible to the previous line, then break it again if it still doesn't fit the current line, etc. * Lines must not contain leading or trailing spaces. ## Examples **Note:** Line breaks in the results have been replaced with two backslashes, `\\`, to improve readability. ("test", 7) -> "test" ("hello world", 7) -> "hello\\world" ("a lot of words for a single line", 10) -> "a lot of\\words for\\a single\\line" ("this is a test", 4) -> "this\\is a\\test" ("a longword", 6) -> "a long\\word" ("areallylongword", 6) -> "areall\\ylongw\\ord" ("greedy whenthewordistoolong", 6) -> "greedy\\whenth\\ewordi\\stoolo\\ng" ("greedy whenthewordistoolong", 7) -> "greedy\\whenthe\\wordist\\oolong" (=> no trailing space) **Note:** Sometimes spaces are hard to see in the test results window.
algorithms
def word_wrap(text, limit): st = iter(text . split()) cur = next(st, None) res = [''] while cur: if len(res[- 1]) + len(cur) + (res[- 1] != '') <= limit: res[- 1] += ' ' * (res[- 1] != '') + cur cur = next(st, None) elif len(cur) > limit and limit - len(res[- 1]) - 1 > 0: ind = limit - len(res[- 1]) - (res[- 1] != '') res[- 1] += ' ' * (res[- 1] != '') + cur[: ind] cur = cur[ind:] res . append('') else: res . append('') return '\n' . join(res)
Word Wrap
55fd8b5e61d47237810000d9
[ "Algorithms" ]
https://www.codewars.com/kata/55fd8b5e61d47237810000d9
5 kyu
Consider a sequence generation that follows the following steps. We will store removed values in variable `res`. Assume `n = 25`: ```Haskell -> [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] Let's remove the first number => res = [1]. We get.. -> [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]. Let's remove 2 (so res = [1,2]) and every 2-indexed number. We get.. -> [3,5,7,9,11,13,15,17,19,21,23,25]. Now remove 3, then every 3-indexed number. res = [1,2,3]. -> [5,7,11,13,17,19,23,25]. Now remove 5, and every 5-indexed number. res = [1,2,3,5]. We get.. -> [7,11,13,17,23,25]. Now remove 7 and every 7-indexed. res = [1,2,3,5,7]. But we know that there are no other 7-indexed elements, so we include all remaining numbers in res. So res = [1,2,3,5,7,11,13,17,23,25] and sum(res) = 107. Note that when we remove every n-indexed number, we must remember that indices start at 0. So for every 3-indexed number above: [3,5,7,9,11,13,15,17,19,21,23], we remove index0=3, index3= 9, index6=15,index9=21, etc. Note also that if the length of sequence is greater than x, where x is the first element of the sequence, you should continue the remove step: remove x, and every x-indexed number until the length of sequence is shorter than x. In our example above, we stopped at 7 because the the length of the remaining sequence [7,11,13,17,23,25] is shorter than 7. ``` You will be given a number `n` and your task will be to return the sum of the elements in res, where the maximum element in res is `<= n`. For example: ```Python Solve(7) = 18, because this is the sum of res = [1,2,3,5,7]. Solve(25) = 107 ``` More examples in the test cases. Good luck!
algorithms
def solve(n): zoznam = [int(i) for i in range(2, n + 1)] res = [1] while zoznam != []: res . append(zoznam[0]) del zoznam[0:: zoznam[0]] return sum(res)
Array reduction
5a6761be145c4691ee000090
[ "Algorithms" ]
https://www.codewars.com/kata/5a6761be145c4691ee000090
6 kyu
In this Kata, you will check if it is possible to convert a string to a palindrome by changing one character. For instance: ```Haskell solve ("abbx") = True, because we can convert 'x' to 'a' and get a palindrome. solve ("abba") = False, because we cannot get a palindrome by changing any character. solve ("abcba") = True. We can change the middle character. solve ("aa") = False solve ("ab") = True ``` Good luck! Please also try [Single Character Palindromes](https://www.codewars.com/kata/5a2c22271f7f709eaa0005d3)
algorithms
def solve(s): v = sum(s[i] != s[- 1 - i] for i in range((len(s)) / / 2)) return v == 1 or not v and len(s) % 2
Single character palindromes II
5a66ea69e6be38219f000110
[ "Algorithms" ]
https://www.codewars.com/kata/5a66ea69e6be38219f000110
7 kyu
Following on from [Points of Reflection](https://www.codewars.com/kata/points-of-reflection), given a number of points and a single midpoint, a 2D shape can be inferred. *Task:* You will be given two inputs. The first will be a two-dimensional sequence in which the inner sequences contain two elements representing partial coordinates of a 2D shape. The second input will be a two-element sequence representing the shape's mid-point. Using the existing coordinates and the mid-point, return the complete shape as a two-dimensional array. The output sorting must be the original points of shape followed by the reflected points in the same order than the points in shape. ```if:python Any point representation must be a tuple ``` Oh and, nice try cheaters! You will now have to refactor. You may no longer modify the test inputs ;) Thanks to [FArekkusu](https://www.codewars.com/users/FArekkusu) and [hobovsky](https://www.codewars.com/users/hobovsky) for their contributions to improving this kata.
algorithms
def symmetric_shape(shape, q): return shape + list(map(lambda x: (2 * q[0] - x[0], 2 * q[1] - x[1]), shape))
Shape Symmetry
57c13e724677bbc5fc000a0b
[ "Mathematics", "Geometry", "Algorithms" ]
https://www.codewars.com/kata/57c13e724677bbc5fc000a0b
7 kyu
Carpe Diem! Yolo! On Fleek? Crushing it. You've got some awesome phrases that you want to hang up on your wall. The problem is that you don't have any frames laying around. So instead, you decide to write a program to create your frame. Write a function called `frame` that will take two parameters as input: a phrase and optionally a character for the border of the frame. ``` frame("Yolo", '@'); ``` Returns: ``` @@@@@@@@ @ @ @ Yolo @ @ @ @@@@@@@@ ``` Notice that the framed phrase has a single space to the left and to the right. Also, there is an empty line both above and below the phrase. If a second parameter is not given, assume the frame should be decorated using the `*` character. You can assume that all phrases are a single line (no new line characters), and that the second parameter to the function (the frame character) is always a single character. If an empty string is passed in, return an emtpy frame. For example: ``` frame(""); ``` returns: ``` **** * * * * **** ```
reference
def frame(phr='', ch='*'): l = len(phr) + 4 line = ch * l middle = ch + ' ' * (l - 2) + ch return line + '\n' + middle + '\n' + ((ch + ' ' + phr + ' ' + ch + '\n') if phr else '') + middle + '\n' + line
Rithm Series: Frame a Phrase Simple
5867d76b36959fa4a400034e
[ "Fundamentals", "ASCII Art" ]
https://www.codewars.com/kata/5867d76b36959fa4a400034e
7 kyu
Get n seconds before the target time. See Example Test Cases about the format.
reference
from datetime import * def seconds_ago(s, n): return str(datetime . strptime(s, '%Y-%m-%d %H:%M:%S') - timedelta(seconds=n))
N seconds ago
5a631508e626c5f127000055
[ "Fundamentals" ]
https://www.codewars.com/kata/5a631508e626c5f127000055
7 kyu
<p>A rectangle can be split up into a grid of 1x1 squares, the amount of which being equal to the product of the two dimensions of the rectangle. Depending on the size of the rectangle, that grid of 1x1 squares can also be split up into larger squares, for example a 3x2 rectangle has a total of 8 squares, as there are 6 distinct 1x1 squares, and two possible 2x2 squares. A 4x3 rectangle contains 20 squares.</p><p> Your task is to write a function `findSquares` that returns the total number of squares for any given rectangle, the dimensions of which being given as two integers with the first always being equal to or greater than the second.</p>
algorithms
def findSquares(x, y): return sum((x - i) * (y - i) for i in range(y))
Squares in a Rectangle
5a62da60d39ec5d947000093
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5a62da60d39ec5d947000093
6 kyu
## Task: * Complete the pattern using the following set of characters: `■`,` `, `◥`, `◤`, `◣`, `◢` * In this kata, we need draw a Heart. ## Rules: - parameter `n` The width of heart, an even number, n>=6, the heart's height increases with n, look at example. - return a string, `■ ◥◤◣◢` represents the heart, and ```Full width space character``` pad at heart's left and right side. ## Examples: (Please do not mind the black stripes, this is codewars description display effect, not perfect) <div style="width:320px"> draw(6) <div style=" font-family:courrier; display:grid; grid-template-rows: repeat(5, 0.9em); grid-template-columns: repeat(6, 0.9em); justify-items: center; align-content: center; "><div>◢</div><div>■</div><div>◣</div><div>◢</div><div>■</div><div>◣</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◥</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◤</div><div> </div><div>◥</div><div>■</div><div>■</div><div>◤</div><div> </div><div> </div><div> </div><div>◥</div><div>◤</div><div> </div><div> </div></div> draw(8) <div style=" font-family:courrier; display:grid; grid-template-rows: repeat(6, 0.9em); grid-template-columns: repeat(8, 0.9em); justify-items: center; align-content: center; "><div>◢</div><div>■</div><div>■</div><div>◣</div><div>◢</div><div>■</div><div>■</div><div>◣</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◥</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◤</div><div> </div><div>◥</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◤</div><div> </div><div> </div><div> </div><div>◥</div><div>■</div><div>■</div><div>◤</div><div> </div><div> </div><div> </div><div> </div><div> </div><div>◥</div><div>◤</div><div> </div><div> </div><div> </div></div> draw(10) <div style=" font-family:courrier; display:grid; grid-template-rows: repeat(7, 0.9em); grid-template-columns: repeat(10, 0.9em); justify-items: center; align-content: center; "><div>◢</div><div>■</div><div>■</div><div>■</div><div>◣</div><div>◢</div><div>■</div><div>■</div><div>■</div><div>◣</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◥</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◤</div><div> </div><div>◥</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◤</div><div> </div><div> </div><div> </div><div>◥</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◤</div><div> </div><div> </div><div> </div><div> </div><div> </div><div>◥</div><div>■</div><div>■</div><div>◤</div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div>◥</div><div>◤</div><div> </div><div> </div><div> </div><div> </div></div> draw(12) <div style=" font-family:courrier; display:grid; grid-template-rows: repeat(9, 0.9em); grid-template-columns: repeat(12, 0.9em); justify-items: center; align-content: center; "><div>◢</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◣</div><div>◢</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◣</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◥</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◤</div><div> </div><div>◥</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◤</div><div> </div><div> </div><div> </div><div>◥</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◤</div><div> </div><div> </div><div> </div><div> </div><div> </div><div>◥</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◤</div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div>◥</div><div>■</div><div>■</div><div>◤</div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div>◥</div><div>◤</div><div> </div><div> </div><div> </div><div> </div><div> </div></div> draw(18) <div style=" font-family:courrier; display:grid; grid-template-rows: repeat(13, 0.9em); grid-template-columns: repeat(18, 0.9em); justify-items: center; align-content: center; "><div>◢</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◣</div><div>◢</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◣</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◥</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◤</div><div> </div><div>◥</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◤</div><div> </div><div> </div><div> </div><div>◥</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◤</div><div> </div><div> </div><div> </div><div> </div><div> </div><div>◥</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◤</div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div>◥</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◤</div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div>◥</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◤</div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div>◥</div><div>■</div><div>■</div><div>■</div><div>■</div><div>◤</div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div>◥</div><div>■</div><div>■</div><div>◤</div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div>◥</div><div>◤</div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div><div> </div></div>
games
def draw(n): shape = ['◢' + (n / / 2 - 2) * '■' + '◣◢' + (n / / 2 - 2) * '■' + '◣'] shape . extend(n / / 6 * ['■' * n]) shape . extend(['◥' + i * 2 * '■' + '◤' for i in range(n / / 2 - 1, - 1, - 1)]) return '\n' . join(row . center(n, ' ') for row in shape)
■□ Pattern □■ : Heart
56e8d06029035a0c7c001d85
[ "ASCII Art" ]
https://www.codewars.com/kata/56e8d06029035a0c7c001d85
6 kyu
Given three arrays of integers, return the sum of elements that are common in all three arrays. For example: ``` common([1,2,3],[5,3,2],[7,3,2]) = 5 because 2 & 3 are common in all 3 arrays common([1,2,2,3],[5,3,2,2],[7,3,2,2]) = 7 because 2,2 & 3 are common in the 3 arrays ``` More examples in the test cases. Good luck!
algorithms
from collections import Counter def common(a, b, c): return sum((Counter(a) & Counter(b) & Counter(c)). elements())
Common array elements
5a6225e5d8e145b540000127
[ "Arrays", "Performance", "Algorithms" ]
https://www.codewars.com/kata/5a6225e5d8e145b540000127
6 kyu
### Task You will be given a string of English digits "stuck" together, like this: `"zeronineoneoneeighttwoseventhreesixfourtwofive"` Your task is to split the string into separate digits: `"zero nine one one eight two seven three six four two five"` ### Examples ``` "three" --> "three" "eightsix" --> "eight six" "fivefourseven" --> "five four seven" "ninethreesixthree" --> "nine three six three" "fivethreefivesixthreenineonesevenoneeight" --> "five three five six three nine one seven one eight" ```
reference
import re def uncollapse(digits): return ' ' . join(re . findall('zero|one|two|three|four|five|six|seven|eight|nine', digits))
Uncollapse Digits
5a626fc7fd56cb63c300008c
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/5a626fc7fd56cb63c300008c
6 kyu
In this kata we are focusing on the Numpy python package. You must write a function called `looper` which takes three integers `start, stop and number` as input and returns a list from `start` to `stop` with `number` total values in the list. Five examples are shown below: ``` looper(1, 5, 1) = [1.0] looper(1, 5, 2) = [1.0, 5.0] looper(1, 5, 3) = [1.0, 3.0, 5.0] looper(1, 5, 4) = [1.0, 2.333333333333333, 3.6666666666666665, 5.0] looper(1, 5, 5) = [1.0, 2.0, 3.0, 4.0, 5.0] ```
games
from numpy import linspace def looper(start, stop, number): return list(linspace(start, stop, number))
Looper
5a35f08b9e5f4923790010dc
[ "NumPy", "Puzzles" ]
https://www.codewars.com/kata/5a35f08b9e5f4923790010dc
7 kyu
FizzBuzz is often one of the first programming puzzles people learn. Now undo it with reverse FizzBuzz! Write a function that accepts a string, which will always be a valid section of FizzBuzz. Your function must return an array that contains the numbers in order to generate the given section of FizzBuzz. Notes: - If the sequence can appear multiple times within FizzBuzz, return the numbers that generate the first instance of that sequence. - All numbers in the sequence will be greater than zero. - You will never receive an empty sequence. ## Examples ``` reverse_fizzbuzz("1 2 Fizz 4 Buzz") --> [1, 2, 3, 4, 5] reverse_fizzbuzz("Fizz 688 689 FizzBuzz") --> [687, 688, 689, 690] reverse_fizzbuzz("Fizz Buzz") --> [9, 10] ```
games
def reverse_fizzbuzz(s): if s == 'Fizz': return [3] if s == 'Buzz': return [5] if s == 'Fizz Buzz': return [9, 10] if s == 'Buzz Fizz': return [5, 6] if s == 'FizzBuzz': return [15] s = s . split() for i in range(len(s)): if s[i]. isdigit(): start = int(s[i]) - i return list(range(start, start + len(s)))
Reverse FizzBuzz
5a622f5f85bef7a9e90009e2
[ "Puzzles" ]
https://www.codewars.com/kata/5a622f5f85bef7a9e90009e2
6 kyu
Given an array of ints, return the index such that the sum of the elements to the right of that index equals the sum of the elements to the left of that index. If there is no such index, return `-1`. If there is more than one such index, return the left-most index. For example: ``` peak([1,2,3,5,3,2,1]) = 3, because the sum of the elements at indexes 0,1,2 == sum of elements at indexes 4,5,6. We don't sum index 3. peak([1,12,3,3,6,3,1]) = 2 peak([10,20,30,40]) = -1 ``` ```haskell --For Haskell peak [1,12,3,3,6,3,1] == Just 2 peak [10,20,30,40] == Nothing ``` ```cobol * For COBOL (1-based index) peak [1,12,3,3,6,3,1] => 3 peak [10,20,30,40] => -1 ``` The special case of an array of zeros (for instance `[0,0,0,0]`) will not be tested. More examples in the test cases. Good luck! Please also try [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2)
algorithms
def peak(arr): for i, val in enumerate(arr): if sum(arr[: i]) == sum(arr[i + 1:]): return i return - 1
Peak array index
5a61a846cadebf9738000076
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5a61a846cadebf9738000076
7 kyu
You are trying to cross a river by jumping along stones. Every time you land on a stone, you hop forwards by the value of that stone. If you skip *over* a stone then its value doesn't affect you in any way. Eg: ``` x--x-----x--> [1][2][5][1] ``` Of course, crossing from the other side might give you a different answer: ``` <--------x--x [1][2][5][1] ``` Given an array of positive integers, return the total number of steps it would take to go all the way across the river (and past the end of the array) and then all the way back. All arrays will contain at least one element, and may contain up to 100 elements. ### Examples ``` x--x-----x--> [1][2][1][2] <----x-----x therefore hop_across([1,2,1,2]) = 3 + 2 = 5 x-----x--------x------> [2][2][3][1][1][2][1] <--------x--x-----x--x therefore hop_across([2,2,3,1,1,2,1]) = 3 + 4 = 7 ```
reference
def hop_across(lst): def one_side(lst): i = 0 steps = 0 while i < len(lst): i += lst[i] steps += 1 return steps return one_side(lst) + one_side(lst[:: - 1])
Hop Across
5a60d519400f93fc450032e5
[ "Fundamentals" ]
https://www.codewars.com/kata/5a60d519400f93fc450032e5
7 kyu
Consider an array containing cats and dogs. Each dog can catch only one cat, but cannot catch a cat that is more than `n` elements away. Your task will be to return the maximum number of cats that can be caught. For example: ```Haskell solve(['D','C','C','D','C'], 2) = 2, because the dog at index 0 (D0) catches C1 and D3 catches C4. solve(['C','C','D','D','C','D'], 2) = 3, because D2 catches C0, D3 catches C1 and D5 catches C4. solve(['C','C','D','D','C','D'], 1) = 2, because D2 catches C1, D3 catches C4. C0 cannot be caught because n == 1. solve(['D','C','D','D','C'], 1) = 2, too many dogs, so all cats get caught! ``` Do not modify the input array. More examples in the test cases. Good luck!
algorithms
def solve(arr, reach): dogs, nCats = {i for i, x in enumerate(arr) if x == 'D'}, 0 for i, c in enumerate(arr): if c == 'C': catchingDog = next( (i + id for id in range(- reach, reach + 1) if i + id in dogs), None) if catchingDog is not None: nCats += 1 dogs . remove(catchingDog) return nCats
Arrays of cats and dogs
5a5f48f2880385daac00006c
[ "Algorithms" ]
https://www.codewars.com/kata/5a5f48f2880385daac00006c
6 kyu
Write a function that returns an array with each element representing one bit of a 32 bit integer in such a way that if printed it would appear as the binary representation of the integer (Least Significant Bit on the right). e.g. 1 = 00000000000000000000000000000001 Assign either a 1 or a 0 to the array element depending on whether the bit at the corresponding position is a 1 or 0. For example (input -> output): ``` 1 -> [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1] -1 -> [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] ``` The function takes one argument (n) which is the integer to be converted to binary.
algorithms
def showBits(n): return list(map(int, '{:032b}' . format(n if n >= 0 else 2 * * 32 + n)))
Binary Representation of an Integer
5a5f3034cadebf76db000023
[ "Binary", "Algorithms" ]
https://www.codewars.com/kata/5a5f3034cadebf76db000023
7 kyu
Simple transposition is a basic and simple cryptography technique. We make 2 rows and put first a letter in the Row 1, the second in the Row 2, third in Row 1 and so on until the end. Then we put the text from Row 2 next to the Row 1 text and thats it. Complete the function that receives a string and encrypt it with this simple transposition. ## Example For example if the text to encrypt is: `"Simple text"`, the 2 rows will be: <table border="1"> <tr> <th>Row 1</th> <td>S</td> <td>m</td> <td>l</td> <td> </td> <td>e</td> <td>t</td> </tr> <tr> <th>Row 2</th> <td>i</td> <td>p</td> <td>e</td> <td>t</td> <td>x</td> <td> </td> </tr> </table> <br> So the result string will be: `"Sml etipetx"`
reference
def simple_transposition(text): return text[:: 2] + text[1:: 2]
Simple transposition
57a153e872292d7c030009d4
[ "Algorithms", "Cryptography", "Fundamentals" ]
https://www.codewars.com/kata/57a153e872292d7c030009d4
6 kyu
I often send "bit letter" to my colleagues to talk about our boss or what do we have for dinner. A bit letter takes 1 char, just like ASCII, but there are some "parameters" in upper 3 bits to describe it. ``` 0 0 0 0 0 0 0 0 [punctuation] [capital] [letter index] ``` ###### [punctuation] 0 = null; 1 = space (before letter); 2 = comma (after letter); 3 = dot (after letter) ###### [capital] 0 = lowercase; 1 = uppercase; ###### [letter index] The letter's index in alphabet, start with 0. ========================== For example: ``` 'a' = 0B00000000 = 0 (a) 'A' = 0B00100000 = ‭32‬ (A) " a" = 0B01000000 = 64 (space + a) "A," = 0B10100000 = ‭160‬ (A + comma) "a." = 0B11000000 = ‭192‬ (a + dot) ``` ========================== ```if:cpp Complete function `std::string bitLetter(std::vector<unsigned char> n)`, for example, if n=`{ 39,4,11,11,142,86,14,17,11,195 }`, function will return `"Hello, world."`. ``` ```if:python Complete function `bit_letter(n)`, for example, if n=`[39,4,11,11,142,86,14,17,11,195]`, function will return `'Hello, world.'`. ```
reference
def bit_letter(n): def code(n): x, i = divmod(n, 32) p, c = divmod(x, 2) return ' ' * (p == 1) + chr(97 + i - c * 32) + ',.' [p - 2] * (p > 1) return '' . join(code(i) for i in n)
Bit Letters
580f5818a88b4a5b2500061d
[ "Fundamentals" ]
https://www.codewars.com/kata/580f5818a88b4a5b2500061d
6 kyu
Every positive integer can be written as a sum of [Fibonacci numbers](https://en.wikipedia.org/wiki/Fibonacci_number). For example `10 = 8 + 2` _or_ `5 + 3 + 2` _or_ `3 + 3 + 2 + 2`. Apparently, this representation is not unique. It becomes unique, if we rule out *consecutive* Fibonacci numbers: this is [Zeckendorf's theorem](https://en.wikipedia.org/wiki/Zeckendorf%27s_theorem), first proven by Lekkerkerker in 1952. In the example above, this excludes the last two representations (containing the consecutive Fibonacci numbers `2` and `3`), and we are left with the *Zeckendorf representation* `10 = 8 + 2`. Complete the function that returns the Zeckendorf representation of a given integer `n` as a list of Fibonacci numbers in decreasing order. Return an empty list for `n = 0` and `None/nil` for negative `n`. _Hint: Be greedy!_ --- Footnote: The Zeckendorf representation is closely connected to the Fibonacci coding.
reference
def Zeckendorf_rep(n): if n >= 0: fibs, res = [1, 2], [] while fibs[- 1] < n: fibs . append(sum(fibs[- 2:])) while n > 0: x = fibs . pop() if x <= n: res . append(x) n -= x return res
Zeckendorf representation
555b605a76962690ea0000c8
[ "Fundamentals" ]
https://www.codewars.com/kata/555b605a76962690ea0000c8
6 kyu
# Let's watch a parade! ## Brief You're going to watch a parade, but you only care about one of the groups marching. The parade passes through the street where your house is. Your house is at number `location` of the street. Write a function `parade_time` that will tell you the times when you need to appear to see all appearences of that group. ## Specifications You'll be given: * A `list` of `string`s containing `groups` in the parade, in order of appearance. A group may appear multiple times. You want to see all the parts of your favorite group. * An positive `integer` with the `location` on the parade route where you'll be watching. * An positive `integer` with the `speed` of the parade * A `string` with the `pref`ferred group you'd like to see You need to return the time(s) you need to be at the parade to see your favorite group as a `list` of `integer`s. It's possible the group won't be at your `location` at an exact `time`. In that case, just be sure to get there right before it passes (i.e. the largest integer `time` before the float passes the `position`). ## Example ```python groups = ['A','B','C','D','E','F'] location = 3 speed = 2 pref = 'C' v Locations: |0|1|2|3|4|5|6|7|8|9|... F E D C B A | | time = 0 > > F E D C B A | | time = 1 > > F E D C B|A| time = 2 > > F E D|C|B A time = 3 ^ parade_time(['A','B','C','D','E','F'], 3, 2,'C']) == [3] ```
algorithms
def parade_time(groups, location, speed, pref): return [c / / speed for c, p in enumerate(groups, 1 + location) if p == pref]
Time to Watch a Parade!
560d41fd7e0b946ac700011c
[ "Algorithms" ]
https://www.codewars.com/kata/560d41fd7e0b946ac700011c
7 kyu