description
stringlengths
38
154k
category
stringclasses
5 values
solutions
stringlengths
13
289k
name
stringlengths
3
179
id
stringlengths
24
24
tags
listlengths
0
13
url
stringlengths
54
54
rank_name
stringclasses
8 values
This kata is about singly-[linked lists](http://en.wikipedia.org/wiki/Linked_list). A linked list is an ordered set of data elements, each containing a link to its successor (and sometimes its predecessor, known as a double linked list). You are you to implement an algorithm to find the kth to last element. `k` will be an integer greater than or equal to `1`. ## Example For example given the following linked list: `a -> b -> c -> d` * if k = 1 then d should be returned * if k = 2 then c should be returned * if k = 3 then b should be returned * if k = 4 then a should be returned * if k exceeds the length of the list then `None`(Python) or `null`(Java, JavaScript) or `false` (C) should be returned Each item in the linked list is a `Node` containing two fields: * data - the value of the node * next - pointing to the next node in the list, or to a null reference (null/NULL/None, depending on your language) for the last Node. An empty list is represented as a null reference.
algorithms
# pass in the linked list # to access the head of the linked list # linked_list.head def search_k_from_end(linked_list, k): head = linked_list . head vals = [] while head: vals . append(head . data) head = head . next return vals[- k] if k <= len(vals) else None
Node Mania
5567e7d0adb11174c50000a7
[ "Linked Lists", "Algorithms", "Data Structures" ]
https://www.codewars.com/kata/5567e7d0adb11174c50000a7
6 kyu
Calculate the number of items in a vector that appear at the same index in each vector, with the same value. ```clojure (vector-affinity [1 2 3 4 5] [1 2 2 4 3]) ; => 0.6 (vector-affinity [1 2 3] [1 2 3]) ; => 1.0 ``` ```python vector_affinity([1, 2, 3, 4, 5], [1, 2, 2, 4, 3]) # => 0.6 vector_affinity([1, 2, 3], [1, 2, 3]) # => 1.0 ``` Affinity value should be realized on a scale of 0.0 to 1.0, with 1.0 being absolutely identical. Two identical sets should always be evaulated as having an affinity or 1.0. Hint: The last example test case holds a significant clue to calculating the affinity correctly.
algorithms
def vector_affinity(a, b): longer = len(a) if len(a) > len(b) else len(b) return len([i for i, j in zip(a, b) if i == j]) / float(longer) if longer > 0 else 1.0
Vector Affinity
5498505a43e0fd83620010a9
[ "Data Structures", "Algorithms" ]
https://www.codewars.com/kata/5498505a43e0fd83620010a9
6 kyu
We define the score of permutations of combinations, of an integer number (the function to obtain this value:```sc_perm_comb```) as the total sum of all the numbers obtained from the permutations of all the possible combinations of its digits. For example we have the number 348. ```python sc_perm_comb(348) = 3 + 4 + 8 + 34 + 38 + 48 + 43 + 83 + 84 + 348 + 384 + 834 + 843 + 438 + 483 = 3675 ``` If the number has a digit 0, the numbers formed by a leading 0 should be discarded: ```python sc_perm_comb(340) = 3 + 4 + 34 + 30 + 40 + 43 + 340 + 304 + 430 + 403 = 1631 ``` Duplicate permutations can occur if the number has more than once the same digit, but they should be added only once in the result: ```python sc_perm_comb(333) = 3 + 33 + 333 = 369 ``` If the number has only one digit its score is the same number: ```python sc_perm_comb(6) = 6 sc_perm_comb(0) = 0 ``` Enjoy it!!
reference
from itertools import permutations def sc_perm_comb(num): sNum = str(num) return sum({int('' . join(p)) for d in range(1, len(sNum) + 1) for p in permutations(sNum, d)})
Score From Permutations Of Combinations of an Integer
5676ffaa8da527f234000025
[ "Fundamentals", "Mathematics", "Permutations" ]
https://www.codewars.com/kata/5676ffaa8da527f234000025
6 kyu
A vector operation takes two or more vectors, applies an operation to each set of elements, and returns a vector of the results. For example, if `x = [1, 2]` and `y = [6, 4]`, then `x + y = [1 + 6, 2 + 4]`, or `[7, 6]`. Your task has two parts. In Part 1, you'll define a higher order funciton, `vector_op`, that can execute vector operations. In Part 2 you'll define a series of functions to pass as `f` to `vector_op`. **Part 1:** Define a higher order function, `vector_op(f, *vs)` `vector_op` takes the following arguments: 1. `f`, a function, that performs an operation on successive elements of an iterable, e.g., `sum` 2. `*vs` An arbitrary number of vectors of equal length. We will use the `list` data structure for a vectors. Write `vector_op` so that it can take an arbitrary number of lists as arguments after `f` or an iterator of lists. `vector_op` returns a vector (a `list`) of the same length as those passed as arguments, and is the result of element-wise application of the operation to the vector arguments. **Special Cases:** 1. With only one vector, it returns that vector unchanged, regardless of which valid f argument you pass. 2. If any number of empty vectors are passed, it returns an empty vector. EXAMPLES: ```python vector_op(sum, [1, 2], [6, 4]) => [7, 6] vector_op(sum, [1, 2], [6, 4], [2, 1]) => [9, 7] vector_op(sum, [1, 2]) => [1, 2] # Special Case 1 vector_op(sum, [], [], [], [], [], [], []) => [] # Special Case 2 ``` **Part 2:** Define a series of functions to pass to `vector_op` In python, we already have a builtin function `sum` that performs a scalar arithmetic operation on an iterable. When we pass `sum`to `vector_op`we have the vector version of addition. We're going to define two more functions that we perform scalar operations on iterables, and will perform vector operations when passed to `vector_op`. **Multiplication:** Define a function `iter_mult` that performs scalar multiplication on an iterable, and performs vector multiplication on an arbitrary number of arguments when passed as `f` to your higher order function `vector_op`. ```python iter_mult([5, 4, 3]) => 60 iter_mult(1) => TypeError # as with the built-in sum(), iter_mult() needs an iterable argument ``` **Equals:** Define a function `iter_eq` that compares the first and second element of an iterable of two elements and returns `True` or `False` based on that comparison. When you pass it as `f` to `vector_op` it will allow you to return a vector with the results of element-wise comparison of two vectors. ```python iter_eq([2, 2]) => True # [2, 1] would be False ``` Now you can perform vector multiplication and vector comparisons. ```python vector_op(iter_mult, [1, 2], [6, 4]) => [6, 8] vector_op(iter_mult, [1, 2]) => [1, 2] vector_op(iter_eq, [1, 2], [3, 2]) => [False, True] vector_op(iter_eq, [1, 2]) => [1, 2] ``` **More Notes:** 1. Once you complete this, it's trivial to define a vector version of any basic arithmetic or comparative operation. 2. `iter_mult`and `iter_eq` are not tested for corner cases that aren't applicable to their use in `vector_op`. 3. `vector_op` is not tested on vectors of unequal length.
reference
from functools import partial, reduce from operator import eq, mul def vector_op(f, * vs): return list(map(f, zip(* vs))) iter_mult = partial(reduce, mul) iter_eq = partial(reduce, eq)
Vector Operations and Functionals
59a8dc83ba7b60426b000059
[ "Mathematics", "Linear Algebra", "Fundamentals" ]
https://www.codewars.com/kata/59a8dc83ba7b60426b000059
6 kyu
Hi! Welcome to my first kata. In this kata the task is to take a list of integers (positive and negative) and split them according to a simple rule; those ints greater than or equal to the key, and those ints less than the key (the itself key will always be positive). However, in this kata the goal is to sort the numbers IN PLACE, so DON'T go messing around with the order in with the numbers appear. You are to return a nested list. If the list is empty, simply return an empty list. Confused? Okay, let me walk you through an example... The input is: [1, 1, 1, 0, 0, 6, 10, 5, 10], the key is: 6 Okay so the first five numbers are less than the key, 6, so we group them together. [1, 1, 1, 0, 0] The next two numbers, 6 & 10, are both >= 6 to they belong in a seperate group, which we will add to the first group. Like so: [[1, 1, 1, 0, 0], [6, 10]] The next two numbers are 5 & 10. Since the key is 6 these two numbers form seperate groups, which we will add to the previous result. like so: [[1, 1, 1, 0, 0], [6, 10], [5], [10]] And voila! We're done. Here are a few more basic examples: group_ints([1, 0], key= 0) --> [[1,0]] group_ints([1, 0, -1, 5], key= 0) --> [[1, 0], [-1], [5]] group_ints([1, 0, -1, 5], key= 5) --> [[1, 0, -1], [5]] Good luck guys/gals!
reference
from itertools import groupby def group_ints(lst, key=0): return [list(g) for _, g in groupby(lst, lambda a: a < key)] # PEP8: function name should use snake_case groupInts = group_ints
Sorting Integers into a nested list
583fe48ca20cfc3a230009a1
[ "Fundamentals", "Algorithms", "Sorting" ]
https://www.codewars.com/kata/583fe48ca20cfc3a230009a1
6 kyu
The purpose of this kata is to write a program that can do some algebra. Write a function `expand` that takes in an expression with a single, one character variable, and expands it. The expression is in the form `(ax+b)^n` where `a` and `b` are integers which may be positive or negative, `x` is any single character variable, and `n` is a natural number. If a = 1, no coefficient will be placed in front of the variable. If a = -1, a "-" will be placed in front of the variable. The expanded form should be returned as a string in the form `ax^b+cx^d+ex^f...` where `a`, `c`, and `e` are the coefficients of the term, `x` is the original one character variable that was passed in the original expression and `b`, `d`, and `f`, are the powers that `x` is being raised to in each term and are in decreasing order. If the coefficient of a term is zero, the term should not be included. If the coefficient of a term is one, the coefficient should not be included. If the coefficient of a term is -1, only the "-" should be included. If the power of the term is 0, only the coefficient should be included. If the power of the term is 1, the caret and power should be excluded. ___ ## Examples: ```javascript expand("(x+1)^2"); // returns "x^2+2x+1" expand("(p-1)^3"); // returns "p^3-3p^2+3p-1" expand("(2f+4)^6"); // returns "64f^6+768f^5+3840f^4+10240f^3+15360f^2+12288f+4096" expand("(-2a-4)^0"); // returns "1" expand("(-12t+43)^2"); // returns "144t^2-1032t+1849" expand("(r+0)^203"); // returns "r^203" expand("(-x-1)^2"); // returns "x^2+2x+1" ``` ```python expand("(x+1)^2") # returns "x^2+2x+1" expand("(p-1)^3") # returns "p^3-3p^2+3p-1" expand("(2f+4)^6") # returns "64f^6+768f^5+3840f^4+10240f^3+15360f^2+12288f+4096" expand("(-2a-4)^0") # returns "1" expand("(-12t+43)^2") # returns "144t^2-1032t+1849" expand("(r+0)^203") # returns "r^203" expand("(-x-1)^2") # returns "x^2+2x+1" ``` ```java KataSolution.expand("(x+1)^2"); // returns "x^2+2x+1" KataSolution.expand("(p-1)^3"); // returns "p^3-3p^2+3p-1" KataSolution.expand("(2f+4)^6"); // returns "64f^6+768f^5+3840f^4+10240f^3+15360f^2+12288f+4096" KataSolution.expand("(-2a-4)^0"); // returns "1" KataSolution.expand("(-12t+43)^2"); // returns "144t^2-1032t+1849" KataSolution.expand("(r+0)^203"); // returns "r^203" KataSolution.expand("(-x-1)^2"); // returns "x^2+2x+1" ``` ```csharp KataSolution.Expand("(x+1)^2"); // returns "x^2+2x+1" KataSolution.Expand("(p-1)^3"); // returns "p^3-3p^2+3p-1" KataSolution.Expand("(2f+4)^6"); // returns "64f^6+768f^5+3840f^4+10240f^3+15360f^2+12288f+4096" KataSolution.Expand("(-2a-4)^0"); // returns "1" KataSolution.Expand("(-12t+43)^2"); // returns "144t^2-1032t+1849" KataSolution.Expand("(r+0)^203"); // returns "r^203" KataSolution.Expand("(-x-1)^2"); // returns "x^2+2x+1" ``` ```ruby expand("(x+1)^2") # returns "x^2+2x+1" expand("(p-1)^3") # returns "p^3-3p^2+3p-1" expand("(2f+4)^6") # returns "64f^6+768f^5+3840f^4+10240f^3+15360f^2+12288f+4096" expand("(-2a-4)^0") # returns "1" expand("(-12t+43)^2") # returns "144t^2-1032t+1849" expand("(r+0)^203") # returns "r^203" expand("(-x-1)^2") # returns "x^2+2x+1" ``` ```scala BinomialExpansion.expand("(x+1)^2") // returns "x^2+2x+1" BinomialExpansion.expand("(p-1)^3") // returns "p^3-3p^2+3p-1" BinomialExpansion.expand("(2f+4)^6") // returns "64f^6+768f^5+3840f^4+10240f^3+15360f^2+12288f+4096" BinomialExpansion.expand("(-2a-4)^0") // returns "1" BinomialExpansion.expand("(-12t+43)^2") // returns "144t^2-1032t+1849" BinomialExpansion.expand("(r+0)^203") // returns "r^203" BinomialExpansion.expand("(-x-1)^2") // returns "x^2+2x+1" ``` ```rust expand("(x+1)^2"); // returns "x^2+2x+1" expand("(p-1)^3"); // returns "p^3-3p^2+3p-1" expand("(2f+4)^6"); // returns "64f^6+768f^5+3840f^4+10240f^3+15360f^2+12288f+4096" expand("(-2a-4)^0"); // returns "1" expand("(-12t+43)^2"); // returns "144t^2-1032t+1849" expand("(r+0)^203"); // returns "r^203" expand("(-x-1)^2"); // returns "x^2+2x+1" ``` ```if:scala ___Note for Scala Users___ For the generalized equation `(ax+b)^n`, - a ranges from -100 to 100 - b ranges from -100 to 100 - n ranges from 0 to 10 ```
algorithms
import re P = re . compile(r'\((-?\d*)(\w)\+?(-?\d+)\)\^(\d+)') def expand(expr): a, v, b, e = P . findall(expr)[0] if e == '0': return '1' o = [int(a != '-' and a or a and '-1' or '1'), int(b)] e, p = int(e), o[:] for _ in range(e - 1): p . append(0) p = [o[0] * coef + p[i - 1] * o[1] for i, coef in enumerate(p)] res = '+' . join(f' { coef }{ v } ^ { e - i } ' if i != e else str(coef) for i, coef in enumerate(p) if coef) return re . sub(r'\b1(?=[a-z])|\^1\b', '', res). replace('+-', '-')
Binomial Expansion
540d0fdd3b6532e5c3000b5b
[ "Mathematics", "Algebra", "Algorithms" ]
https://www.codewars.com/kata/540d0fdd3b6532e5c3000b5b
3 kyu
Normally, we decompose a number into binary digits by assigning it with powers of 2, with a coefficient of `0` or `1` for each term: `25 = 1*16 + 1*8 + 0*4 + 0*2 + 1*1` The choice of `0` and `1` is... not very binary. We shall perform the *true* binary expansion by expanding with powers of 2, but with a coefficient of `1` or `-1` instead: `25 = 1*16 + 1*8 + 1*4 - 1*2 - 1*1` Now *this* looks binary. --- Given any positive number `n`, expand it using the true binary expansion, and return the result as an array, from the most significant digit to the least significant digit. `true_binary(25) == [1,1,1,-1,-1]` It should be trivial (the proofs are left as an exercise to the reader) to see that: - Every odd number has infinitely many true binary expansions - Every even number has no true binary expansions Hence, `n` will always be an odd number, and you should return the *least* true binary expansion for any `n`. Also, note that `n` can be very, very large, so your code should be very efficient.
algorithms
def true_binary(n): return [- 1 if x == '0' else 1 for x in bin(n)[1: - 1]]
The Binary Binary Expansion
59a818191c55c44f3900053f
[ "Algorithms" ]
https://www.codewars.com/kata/59a818191c55c44f3900053f
5 kyu
<img src="https://static1.squarespace.com/static/56a1a14b05caa7ee9f26f47d/t/5719c5d91d07c0bcdda31d01/1464935309584/ant_bridge_TS.jpg"/> # Background My pet bridge-maker ants are marching across a terrain from left to right. If they encounter a gap, the first one stops and then next one climbs over him, then the next, and the next, until a bridge is formed across the gap. What clever little things they are! Now all the other ants can walk over the ant-bridge. When the last ant is across, the ant-bridge dismantles itself similar to how it was constructed. This process repeats as many times as necessary (there may be more than one gap to cross) until all the ants reach the right hand side. # Kata Task My little ants are marching across the terrain from left-to-right in the order ```A``` then ```B``` then ```C```... What order do they exit on the right hand side? # Notes * ```-``` = solid ground * ```.``` = a gap * The number of ants may differ but there are always enough ants to bridge the gaps * The terrain never starts or ends with a gap * Ants cannot pass other ants except by going over ant-bridges * If there is ever ambiguity which ant should move, then the ant at the **back** moves first # Example ## Input * ants = ````GFEDCBA```` * terrain = ```------------...-----------``` ## Output * result = ```EDCBAGF``` ## Details <table> <tr><td>Ants moving left to right.<td><pre> GFEDCBA ------------...----------- </pre> <tr><td>The first one arrives at a gap.<td><pre> GFEDCB A ------------...----------- </pre> <tr><td>They start to bridge over the gap...<td><pre> GFED ABC ------------...----------- </pre> <tr><td>...until the ant-bridge is completed!<td><pre> GF ABCDE ------------...----------- </pre> <tr><td>And then the remaining ants can walk across the bridge.<td><pre> F G ABCDE ------------...----------- </pre> <tr><td>And when no more ants need to cross...<td><pre> ABCDE GF ------------...----------- </pre> <tr><td>... the bridge dismantles itself one ant at a time....<td><pre> CDE BAGF ------------...----------- </pre> <tr><td>...until all ants get to the other side<td><pre> EDCBAGF ------------...----------- </pre> <tr><td><td> </table>
algorithms
def ant_bridge(ants, terrain): n_ants = len(ants) terrain = terrain . replace('-.', '..') terrain = terrain . replace('.-', '..') count = terrain . count('.') % n_ants return ants[- count:] + ants[: - count]
Ant Bridge
599385ae6ca73b71b8000038
[ "Algorithms" ]
https://www.codewars.com/kata/599385ae6ca73b71b8000038
5 kyu
# The President's phone is broken He is not very happy. The only letters still working are uppercase ```E```, ```F```, ```I```, ```R```, ```U```, ```Y```. An angry tweet is sent to the department responsible for presidential phone maintenance. # Kata Task Decipher the tweet by looking for words with known meanings. * ```FIRE``` = *<span style='color:yellow'>"You are fired!"</span>* * ```FURY``` = *<span style='color:yellow'>"I am furious."</span>* If no known words are found, or unexpected letters are encountered, then it must be a *<span style='color:yellow'>"Fake tweet."</span>* # Notes * The tweet reads left-to-right. * Any letters not spelling words ```FIRE``` or ```FURY``` are just ignored * If multiple of the same words are found in a row then plural rules apply - * ```FIRE``` x 1 = *"You are fired!"* * ```FIRE``` x 2 = *"You and you are fired!"* * ```FIRE``` x 3 = *"You and you and you are fired!"* * etc... * ```FURY``` x 1 = *"I am furious."* * ```FURY``` x 2 = *"I am really furious."* * ```FURY``` x 3 = *"I am really really furious."* * etc... # Examples * ex1. <span style='background:black'><span style='color:red'>FURY</span>YY<span style='color:red'>FIRE</span>YY<span style='color:red'>FIRE</span></span> = *"I am furious. You and you are fired!"* * ex2. <span style='background:black'><span style='color:red'>FIRE</span>YY<span style='color:red'>FURY</span>Y<span style='color:red'>FURY</span>YFURRY<span style='color:red'>FIRE</span></span> = *"You are fired! I am really furious. You are fired!"* * ex3. <span style='background:black'>FYRYFIRUFIRUFURE</span> = *"Fake tweet."* ---- DM :-)
algorithms
def fire_and_fury(tweet): if not all(c in 'EFIRUY' for c in tweet): return 'Fake tweet.' s = [0] for i in range(0, len(tweet) - 3): if tweet[i: i + 4] == 'FIRE': if s[- 1] > 0: s[- 1] += 1 else: s . append(1) elif tweet[i: i + 4] == 'FURY': if s[- 1] < 0: s[- 1] -= 1 else: s . append(- 1) return 'Fake tweet.' if len(s) == 1 else ' ' . join(['You' + ' and you' * (s[i] - 1) + ' are fired!' if s[i] > 0 else 'I am' + ' really' * (- s[i] - 1) + ' furious.' for i in range(1, len(s))])
FIRE and FURY
59922ce23bfe2c10d7000057
[ "Regular Expressions", "Strings", "Algorithms" ]
https://www.codewars.com/kata/59922ce23bfe2c10d7000057
6 kyu
Calculate how many times a number can be divided by a given number. ### Example For example the number `6` can be divided by `2` two times: ```py 1. 6 / 2 = 3 2. 3 / 2 = 1 remainder = 1 ``` `100` can be divided by `2` six times: ```py 1. 100 / 2 = 50 2. 50 / 2 = 25 3. 25 / 2 = 12 remainder 1 4. 12 / 2 = 6 5. 6 / 2 = 3 6. 3 / 2 = 1 remainder 1 ```
algorithms
from math import log def divisions(n, divisor): return int(log(n, divisor))
Number of Divisions
5913152be0b295cf99000001
[ "Algorithms" ]
https://www.codewars.com/kata/5913152be0b295cf99000001
7 kyu
A simple kata, my first. simply tranform an array into a string, like so: ```javascript transform([4, -56, true, "box"]) => "4-56truebox" ``` ```haskell transform [ 5, 7, 8, 9, 0, 5 ] -> "578905" ``` have fun coding!
reference
def transform(s): return '' . join(map(str, s))
transform an array into a string
59a602dc57019008d900004e
[ "Fundamentals" ]
https://www.codewars.com/kata/59a602dc57019008d900004e
null
Write a program that will take a string of digits and give you all the possible consecutive slices of length `n` in that string. Raise an error if `n` is larger than the length of the string. ## Examples For example, the string `"01234"` has the following 2-digit slices: ``` [0, 1], [1, 2], [2, 3], [3, 4] ``` The same string has the following 4-digit slices: ``` [0, 1, 2, 3], [1, 2, 3, 4] ```
algorithms
def series_slices(digits, n): if n > len(digits): raise ValueError else: return [[int(digit) for digit in digits[i: i + n]] for i in range(0, len(digits) - n + 1)]
Slices of a Series of Digits
53f9a36864b19d8be7000609
[ "Algorithms", "Data Structures" ]
https://www.codewars.com/kata/53f9a36864b19d8be7000609
6 kyu
In most languages, division immediately produces decimal values, and therefore, adding two fractions gives a decimal result: ```ruby (1/2) + (1/4) #=> 0.75 ``` But what if we want to be able to add fractions and get a fractional result? ```ruby (1/2) + (1/4) #=> 3/4 ``` #### Task: Your job here is to implement a function, `add_fracs` that takes any number of fractions (positive OR negative) as strings, and yields the exact fractional value of their sum _in simplest form_. If the sum is greater than one (or less than negative one), it should return an improper fraction. If there are no arguments passed, (`add_fracs()`), return an empty string. Inputs will always be valid fractions, and the output should also be a string. If the result is an integer, like '2/1', just return '2'. Input numerators (but NOT denominators) can be zero. #### How the function will be called: ```ruby add_fracs(any_number_of_fractions1, any_number_of_fractions2, any_number_of_fractions3, ...) #=> a fraction as a string ``` #### Some examples (see example test cases for more): ```ruby add_fracs() #=> "" add_fracs("1/2") #=> "1/2" add_fracs("1/2", "1/4") #=> "3/4" add_fracs("1/2", "3/4") #=> "5/4" add_fracs("2/4", "6/4", "4/4") #=> "3" add_fracs("2/3", "1/3", "4/6") #=> "5/3" add_fracs("-2/3", "5/3", "-4/6") #=> "1/3" ``` If there are any issues with the description, test cases or anything else, please do let me know by commenting or marking an issue. Otherwise, make sure to rank and mark as ready. Enjoy! Also check out my other creations — [Split Without Loss](https://www.codewars.com/kata/split-without-loss), [Random Integers](https://www.codewars.com/kata/random-integers), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2)
reference
from fractions import Fraction def add_fracs(* args): return str(sum(Fraction(a) for a in args)) if args else ''
Adding Fractions
5816f2580e80c5e075000a4f
[ "Fundamentals" ]
https://www.codewars.com/kata/5816f2580e80c5e075000a4f
6 kyu
Your task is to build a model<sup>1</sup> which can predict y-coordinate.<br> You can pass tests if predicted y-coordinates are inside error margin.<br><br> You will receive train set which should be used to build a model. <br> After you build a model tests will call function ```predict``` and pass x to it. <br><br> Error is going to be calculated with <a href='http://www.statisticshowto.com/rmse/'>RMSE</a>. <br><br> Side note: Points in test cases are from different polynomials (up to 5th degree). <br><br> Easier version: <a href='https://www.codewars.com/kata/data-mining-number-1'>Data mining #1</a> <br><br> Blocked libraries: <i>sklearn, pandas, tensorflow, numpy, scipy</i> <br><br> Explanation<br> [1] <i>A mining model is created by applying an algorithm to data, but it is more than an algorithm or a metadata container: it is a set of data, statistics, and patterns that can be applied to new data to generate predictions and make inferences about relationships.</i>
algorithms
from functools import reduce class Datamining: def __init__(self, train_set): self . p = train_set[: 5] def lagrange_interp(self, x): return sum(reduce(lambda p, n: p * n, [(x - xi) / (xj - xi) for (i, (xi, yi)) in enumerate(self . p) if j != i], yj) for (j, (xj, yj)) in enumerate(self . p)) def predict(self, x): return self . lagrange_interp(x)
Data mining #2
591748b3f014a2593d0000d9
[ "Mathematics", "Machine Learning", "Algorithms", "Data Science" ]
https://www.codewars.com/kata/591748b3f014a2593d0000d9
4 kyu
Math hasn't always been your best subject, and these programming symbols always trip you up! I mean, does `**` mean _"Times, Times"_ or _"To the power of"_? Luckily, you can create the function to write out the expressions for you! The operators you'll need to use are: ``` "+" --> "Plus" "-" --> "Minus" "*" --> "Times" "/" --> "Divided By" "**" --> "To The Power Of" "=" --> "Equals" "!=" --> "Does Not Equal" ``` **Notes:** * the input will always be given as a string, in the following format: `number space operator space number`; for example: `"1 + 3"` or `"2 - 10"` * the numbers used will be `1` to `10` * the valid operators and the relevant texts are stored in the preloaded dictionary/hash `OPERATORS` * **invalid operators will also be tested**, to which you should return `"That's not an operator!"` ### Examples ``` "4 ** 9" --> "Four To The Power Of Nine" "10 - 5" --> "Ten Minus Five" "2 = 2" --> "Two Equals Two" "2 x 3" --> "That's not an operator!" ``` Good luck!
reference
NUMBERS = 'Zero One Two Three Four Five Six Seven Eight Nine Ten' . split() def expression_out(exp): x, op, y = exp . split() x, y = NUMBERS[int(x)], NUMBERS[int(y)] op = OPERATORS . get(op, "That's not an operator!") return '%s %s%s' % (x, op, y) if op[- 1] != '!' else op
Write out expression!
57e2afb6e108c01da000026e
[ "Fundamentals" ]
https://www.codewars.com/kata/57e2afb6e108c01da000026e
7 kyu
Your task is to build a model<sup>1</sup> which can predict y-coordinate.<br> You can pass tests if predicted y-coordinates are inside error margin.<br><br> You will receive train set which should be used to build a model. <br> After you build a model tests will call function ```predict``` and pass x to it. <br><br> Error is going to be calculated with <a href='http://www.statisticshowto.com/rmse/'>RMSE</a>. <br><br> Blocked libraries: <i>sklearn, pandas, tensorflow, numpy, scipy</i> <br><br> Explanation<br> [1] <i>A mining model is created by applying an algorithm to data, but it is more than an algorithm or a metadata container: it is a set of data, statistics, and patterns that can be applied to new data to generate predictions and make inferences about relationships.</i>
algorithms
from statistics import variance, mean class Datamining: def __init__(self, train_set): # This is a simple linear regression model. # Notice we're computing the covariance but from Python 3.10 # the statistics module includes a function for that. avg_x = mean(x for x, _ in train_set) avg_y = mean(y for _, y in train_set) cov = sum((x - avg_x) * (y - avg_y) for x, y in train_set) / (len(train_set) - 1) self . b1 = cov / variance(x for x, _ in train_set) self . b0 = avg_y - self . b1 * avg_x def predict(self, x): return self . b0 + self . b1 * x
Data mining #1
58f89357d13bab79dc000208
[ "Mathematics", "Machine Learning", "Algorithms", "Data Science" ]
https://www.codewars.com/kata/58f89357d13bab79dc000208
5 kyu
## Background A simple statistical analysis of a series of samples can be done with a [Five Figure Summary](http://en.wikipedia.org/wiki/Five-number_summary). The five figure summary gives the lower extreme, upper extreme, lower quartile, median, and upper quartile, all derived from the supplied sample data. Confusingly, the five figure summary often includes a sixth value, which is the number of samples in the series. ## Kata In this Kata you will be given a class outline to complete. The class will be instantiated with a sequence of values, and you must implement the method to return the six-figure version of a five figure summary. You are expected to do the calculations yourself, using pandas or numpy will get you a squinty frown from your sensei! :) ## Inputs 1. At class instantiation you will be given a sequence of values. This sequence may contain non-numerical values: these should be ignored. 1. At summary creation you will be given a maximum number of decimal digits `precision` for all the numerical results. If `None` is supplied, assume full precision has to be returned. ## Calculations * N: Number of valid numeric values in the sequence. * Lower Extreme: The smallest value contained within the sequence. * Upper Extreme: The largest value contained within the sequence. * Median: The centre value of the sorted sequence of valid values. * Lower Quartile: The boundary value between the first and second quarters of the sorted sequence of valid values. * Upper Quartile: The boundary value between the third and fourth quarters of the sorted sequence of valid values. The median and both quartiles may need to be a linear interpolation between two values. ### Linear Interpolation Examples Given a sequence of values `[2, 3, 4, 5, 6, 7, 8, 9]` 1. Position `3.5` would return the mid-point between the values at index `3` and index `4` returning `5.5`. 1. Position `1.25` would return the quarter-point between the values at index `1` and index `2` returning `3.25`. 1. Position `6.75` would return the three-quarter-point between the values at index `6` and index `7` returning `7.75`. ### Outputs You will return a tuple with the calculated values in the following order: (N, lower_extreme, upper_extreme, lower_quartile, median, upper_quartile) Where no precision is defined, and given the rounding/quantization errors with floating point processing, your answers must be within `10 ** -10` of the correct answer. Where precision is defined, your answer is expected to be exact. ### Worked Example data = range(0, 7) StatisticalSummary(data).five_figure_summary(2) => (7, 0, 6, 1.5, 3, 4.5) <br> # Series This kata is part of a series of kata about basis statistics, you are advised to tackle them in sequence. The kata are: * [Intro to Statistics - Part 1: A Five figure summary](http://www.codewars.com/kata/intro-to-statistics-part-1-a-five-figure-summary) * [Intro to Statistics - Part 2: Boxplots](https://www.codewars.com/kata/intro-to-statistics-part-2-boxplots)
algorithms
class StatisticalSummary (object): def __init__(self, seq): self . seq = list(seq) for i in reversed(range(len(self . seq))): if not isinstance(self . seq[i], (int, float, complex)) or isinstance(self . seq[i], bool): self . seq . pop(i) # Discard every value that is not a number self . seq . sort() # Sort by value def __len__(self): # Follow dunder standard return len(self . seq) def median(self): if len(self . seq) % 2 == 0: return (self . seq[int(len(self . seq) / 2)] + self . seq[int(len(self . seq) / 2 - 1)]) / 2 else: return self . seq[len(self . seq) / / 2] def lower_quartile(self): # -1 to adjust for lists staring with index 0 low = self . seq[(len(self) + 3) / / 4 - 1] high = self . seq[(len(self) + 3) / / 4] rest_fraction = (len(self) + 3) % 4 / 4 return (1 - rest_fraction) * low + rest_fraction * high def upper_quartile(self): # -1 to adjust for lists staring with index 0 low = self . seq[(len(self) * 3 + 1) / / 4 - 1] high = self . seq[(len(self) * 3 + 1) / / 4] rest_fraction = (len(self) * 3 + 1) % 4 / 4 return (1 - rest_fraction) * low + rest_fraction * high def five_figure_summary(self, precision=None): if precision == None: precision = 16 self . precision = precision return (len(self), round(self . seq[0], self . precision), round(self . seq[- 1], self . precision), round(self . lower_quartile(), self . precision), round(self . median(), self . precision), round(self . upper_quartile(), self . precision))
Intro to Statistics - Part 1: A Five figure summary
555c7fa8d8cb57834a000028
[ "Statistics", "Algorithms", "Data Science" ]
https://www.codewars.com/kata/555c7fa8d8cb57834a000028
5 kyu
The objective of this Kata is to write a function that creates a dictionary of factors for a range of numbers. The key for each list in the dictionary should be the number. The list associated with each key should possess the factors for the number. If a number possesses no factors (only 1 and the number itself), the list for the key should be `['None']` The function possesses two arguments (`n` and `m`). Where `n` is the starting number and `m` is the ending number. For example: All factors for 2 (`n`) through to 6 (`m`) with the number being the key in the dictionary: ```python {2: ['None'], 3: ['None'], 4: [2], 5: ['None'], 6: [2, 3]} ```
reference
def factorsRange(n, m): res = {} for num in range(n, m + 1): factors = [] for div in range(2, num / / 2 + 1): if num % div == 0: factors . append(div) if len(factors) == 0: factors = ['None'] res[num] = factors return res
Dictionary of Factors
58bf3cd9c4492d942a0000de
[ "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/58bf3cd9c4492d942a0000de
6 kyu
Mr. Khalkhoul, an amazing teacher, likes to answer questions sent by his students via e-mail, but he often doesn't have the time to answer all of them. In this kata you will help him by making a program that finds some of the answers. You are given a `question` which is a string containing the question and some `information` which is a list of strings representing potential answers. Your task is to find among `information` the UNIQUE string that has the highest number of words in common with `question`. We shall consider words to be separated by a single space. You can assume that: * all strings given contain at least one word and have no leading or trailing spaces, * words are composed with alphanumeric characters only You must also consider the case in which you get no matching words (again, ignoring the case): in such a case return `None/nil/null`. Mr. Khalkhoul is countin' on you :)
algorithms
def answer(question, information): score, info = max((sum(word in info . lower(). split( ) for word in question . lower(). split()), info) for info in information) return None if not score else info
Answer the students' questions!
59476f9d7325addc860000b9
[ "Algorithms" ]
https://www.codewars.com/kata/59476f9d7325addc860000b9
6 kyu
In this kata your mission is to rotate matrix counter - clockwise N-times. So, you will have 2 inputs: 1)matrix 2)a number, how many times to turn it And an output is turned matrix. Example: matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] times_to_turn = 1 It should return this: [[4, 8, 12, 16], [3, 7, 11, 15], [2, 6, 10, 14], [1, 5, 9, 13]]) Note: all matrices will be square. Also random tests will have big numbers in input (times to turn) Happy coding!
algorithms
import numpy as np def rotate_against_clockwise(matrix, times): return np . rot90(matrix, times). tolist()
Rotate matrix counter - clockwise N - times!
5919f3bf6589022915000023
[ "Algorithms", "Matrix" ]
https://www.codewars.com/kata/5919f3bf6589022915000023
6 kyu
You're given a string of dominos. For each slot, there are 3 options: * "|" represents a standing domino * "/" represents a knocked over domino * " " represents a space where there is no domino For example: ``` "||| ||||//| |/" ``` Tipping a domino will cause the next domino to its right to fall over as well, but if a domino is already tipped over, or there is a domino missing, the reaction will stop. What you must do is find the resulting string if the first domino is pushed over. So in out example above, the result would be: ``` "/// ||||//| |/" ``` since the reaction would stop as soon as it gets to a space.
reference
def domino_reaction(s): return s . replace("|", "/", min(len(s . split(" ")[0]), len(s . split("/")[0])))
Domino Reaction
584cfac5bd160694640000ae
[ "Fundamentals" ]
https://www.codewars.com/kata/584cfac5bd160694640000ae
6 kyu
Write a function which receives 4 digits and returns the latest time of day that can be built with those digits. The time should be in `HH:MM` format. Examples: ``` digits: 1, 9, 8, 3 => result: "19:38" digits: 9, 1, 2, 5 => result: "21:59" (19:25 is also a valid time, but 21:59 is later) ``` ### Notes - Result should be a valid 24-hour time, between `00:00` and `23:59`. - Only inputs which have valid answers are tested.
games
def late_clock(* a): for h in range(23, - 1, - 1): for m in range(59, - 1, - 1): x = f' { h :0 2 } ' y = f' { m :0 2 } ' s = list(map(int, list(x + y))) if sorted(s) == sorted(a): return f' { x } : { y } '
The latest clock
58925dcb71f43f30cd00005f
[ "Date Time", "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/58925dcb71f43f30cd00005f
6 kyu
Write a function that solves an algebraic expression given as a string. * The expression can include only sums and products. * The numbers in the expression are in standard notation (NOT scientific). * In contrast, the function should return a string with the calculated value given in scientific notation with 5 decimal digits. # Example: ```python strexpression = "5 * 4 + 6" sum_prod(strexpression) = "2.60000e+01" ```
reference
def sum_prod(strexpression): return "%.5e" % (eval(strexpression))
Algebraic string
5759513c94aba6a30900094d
[ "Fundamentals", "Strings", "Parsing" ]
https://www.codewars.com/kata/5759513c94aba6a30900094d
6 kyu
# Task For a given non-empty list of sets `l` return a dictionary where 1. keys are the unique elements across all sets 2. the value is a number of sets in which the key appears. The sets are empty or contains only integers. Don't modify the input list and sets ## Example: ```python # Input: [{1,2,3}, {2,3,4}] # Output: {4: 1, 2: 2, 3: 2, 1: 1} # Explanation: # There are 4 unique elements: 1, 2, 3, 4 # Number 1 appears only in 1 set # Number 2 appears in 2 sets. ... ``` # Restrictions Your code **mustn't**: 1. be longer than 1 line and 140 characters. 2. contain `return` (search is case insensitive) 3. contain `;` (i.e. make it a proper one-liner :)) 4. contain `#` (ergo no explanations :) Let people to enjoy deciphering your puzzling code) 5. contain more than one `=` (Yes, one `=` is enough ;)) # Note This kata is about creativity not proper coding style. Your colleagues/boss won't like you if you make production code like this. :) #### Don't forget to rate the kata after you finish it. :) Happy coding! suic
games
def short(l): return __import__( "collections"). Counter(e for m in l for e in m)
Keep it short (with restrictions)
5851aae410200111f70006c0
[ "Puzzles", "Restricted" ]
https://www.codewars.com/kata/5851aae410200111f70006c0
5 kyu
We have an array with string digits that occurrs more than once, for example, ```arr = ['1', '2', '2', '2', '3', '3']```. How many different string numbers can be generated taking the 6 elements at a time? We present the list of them below in an unsorted way: ``` ['223213', '312322', '223312', '222133', '312223', '223321', '223231', '132223', '132322', '223132', '322321', '322312', '231322', '222313', '221233', '213322', '122323', '321322', '221332', '133222', '123232', '323221', '222331', '132232', '321232', '212323', '232213', '232132', '331222', '232312', '332212', '213223', '123322', '322231', '321223', '231232', '233221', '231223', '213232', '312232', '233122', '322132', '223123', '322123', '232231', '323122', '323212', '122233', '212233', '123223', '332221', '122332', '221323', '332122', '232123', '212332', '232321', '322213', '233212', '313222'] ``` There are ```60``` different numbers and ```122233``` is the lowest one and ```332221``` the highest of all of them. Given an array, ```arr```, with string digits (from '0' to '9'), you should give the exact amount of different numbers that may be generated with the lowest and highest value but both converted into integer values, using all the digits given in the array for each generated string number. The function will be called as ```proc_arr()```. ```python proc_arr(['1', '2', '2', '3', '2', '3']) == [60, 122233, 332221] ``` If the digit '0' is present in the given array will produce string numbers with leading zeroes, that will not be not taken in account when they are converted to integers. ```python proc_arr(['1','2','3','0','5','1','1','3']) == [3360, 1112335, 53321110] ``` You will never receive an array with only one digit repeated n times. Features of the random tests: ``` Low performance tests: Number of tests: 100 Arrays of length between 6 and 10 Higher performance tests: Number of tests: 100 Arrays of length between 30 and 100 ```
reference
from operator import mul from math import factorial from functools import reduce from collections import Counter def proc_arr(arr): s = '' . join(sorted(arr)) return [factorial(len(arr)) / / reduce(mul, map(factorial, Counter(arr). values())), int(s), int(s[:: - 1])]
Generating Numbers From Digits #1
584d05422609c8890f0000be
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic", "Strings" ]
https://www.codewars.com/kata/584d05422609c8890f0000be
6 kyu
In this kata, you've to count lowercase letters in a given string and return the letter count in a hash with 'letter' as key and count as 'value'. The key must be 'symbol' instead of string in Ruby and 'char' instead of string in Crystal. Example: ```javascript letter_count('arithmetics') //=> {"a": 1, "c": 1, "e": 1, "h": 1, "i": 2, "m": 1, "r": 1, "s": 1, "t": 2} ``` ```ruby letterCount('arithmetics') #=> {:a=>1, :c=>1, :e=>1, :h=>1, :i=>2, :m=>1, :r=>1, :s=>1, :t=>2} ``` ```python letter_count('arithmetics') #=> {"a": 1, "c": 1, "e": 1, "h": 1, "i": 2, "m": 1, "r": 1, "s": 1, "t": 2} ``` ```crystal letter_count('arithmetics') #=> {'a'=>1, :'c'=>1, 'e'=>1, 'h'=>1, 'i'=>2, 'm'=>1, 'r'=>1, 's'=>1, 't'=>2} ```
reference
from collections import Counter def letter_count(s): return Counter(s)
Count letters in string
5808ff71c7cfa1c6aa00006d
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5808ff71c7cfa1c6aa00006d
6 kyu
Let's just place tokens on a connect four board. <img src="http://tinyurl.com/js6vz2v" alt="Connect Four Example" style="width: 250px;"/> ** INPUT ** Provided as input the list of columns where a token is placed, from 0 to 6 included. The first player starting is the yellow one (marked with `Y`), then the red (marked with `R`); the other cells might be empty and marked with `-`. ** OUTPUT ** The output is the state of the board after all the tokens in input have been placed. ** ASSUMPTIONS ** - The board is the standard 7x6; - Of course you'll need to deal with gravity; - You don't need to hassle with wrong input, wrong column numbers, checking for full column or going off the board; - the columns list will always include proper column numbers; - Notice: when you read the results in tests, the highest row appears first and the lowest row appears last; debugging using `\n` after each row might help (check example); ** EXAMPLES ** 1. ``` Moves = [0,1,2,5,6] Result: ['-', '-', '-', '-', '-', '-', '-'] ['-', '-', '-', '-', '-', '-', '-'] ['-', '-', '-', '-', '-', '-', '-'] ['-', '-', '-', '-', '-', '-', '-'] ['-', '-', '-', '-', '-', '-', '-'] ['Y', 'R', 'Y', '-', '-', 'R', 'Y'] ``` 2. ``` Moves = [0,1,2,5,6,2,0,0] Result: ['-', '-', '-', '-', '-', '-', '-'] ['-', '-', '-', '-', '-', '-', '-'] ['-', '-', '-', '-', '-', '-', '-'] ['R', '-', '-', '-', '-', '-', '-'] ['Y', '-', 'R', '-', '-', '-', '-'] ['Y', 'R', 'Y', '-', '-', 'R', 'Y'] ``` See test cases for better details.
reference
def connect_four_place(columns): player, board, placed = 1, [['-'] * 7 for _ in range(6)], [- 1] * 7 for c in columns: player ^= 1 board[placed[c]][c] = "YR" [player] placed[c] -= 1 return board
Connect Four - placing tokens
5864f90473bd9c4b47000057
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5864f90473bd9c4b47000057
6 kyu
For all x in the range of integers [0, 2 ** n), let y[x] be the binary exclusive-or of x and x // 2. Find the sum of all numbers in y. Write a function sum_them that, given n, will return the value of the above sum. This can be implemented a simple loop as shown in the initial code. But once n starts getting to higher numbers, such as 2000 (which will be tested), the loop is too slow. There is a simple solution that can quickly find the sum. Find it! Assume that n is a nonnegative integer. Hint: The complete solution can be written in two lines.
games
def sum_them(n): return 2 * * (n - 1) * (2 * * n - 1)
Summing Large Amounts of Numbers
549c7ae26d86c7c3ed000b87
[ "Binary", "Puzzles" ]
https://www.codewars.com/kata/549c7ae26d86c7c3ed000b87
6 kyu
This kata aims to show the vulnerabilities of hashing functions for short messages. When provided with a SHA-256 hash, return the value that was hashed. You are also given the characters that make the expected value, but in alphabetical order. The returned value is less than 10 characters long. Return `nil` for Ruby and Crystal, `None` for Python, `null` for for Java and Javascript when the hash cannot be cracked with the given characters. --- Example: -------- ``` Example arguments: '5694d08a2e53ffcae0c3103e5ad6f6076abd960eb1f8a56577040bc1028f702b', 'cdeo' Correct output: 'code' ```
games
from hashlib import sha256 from itertools import permutations def sha256_cracker(hash, chars): for p in permutations(chars, len(chars)): current = '' . join(p) if sha256(current . encode('utf-8')). hexdigest() == hash: return current
SHA-256 Cracker
587f0abdd8730aafd4000035
[ "Security", "Algorithms", "Puzzles" ]
https://www.codewars.com/kata/587f0abdd8730aafd4000035
6 kyu
Your task is to ___find the next higher number (int) with same '1'- Bits___. I.e. as much `1` bits as before and output next higher than input. Input is always an int in between 1 and 1<<30 (inclusive). No bad cases or special tricks... ### Some easy examples: ``` Input: 129 => Output: 130 (10000001 => 10000010) Input: 127 => Output: 191 (01111111 => 10111111) Input: 1 => Output: 2 (01 => 10) Input: 323423 => Output: 323439 (1001110111101011111 => 1001110111101101111) ``` First some static tests, later on many random tests too;-)!<br> ### Hope you have fun! :-)
algorithms
def next_higher(value): s = f'0 { value : b } ' i = s . rfind('01') s = s[: i] + '10' + '' . join(sorted(s[i + 2:])) return int(s, 2)
Basics 08: Find next higher number with same Bits (1's)
56bdd0aec5dc03d7780010a5
[ "Fundamentals", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/56bdd0aec5dc03d7780010a5
6 kyu
# Story Old MacDingle had a farm... ...and on that farm he had * horses * chickens * rabbits * some apple trees * a vegetable patch Everything is idylic in the MacDingle farmyard **unless somebody leaves the gates open** Depending which gate was left open then... * horses might run away * horses might eat the apples * horses might eat the vegetables * chickens might run away * rabbits might run away * rabbits might eat the vegetables # Kata Task Given the state of the farm gates in the evening, your code must return what the farm looks like the next morning when daylight reveals what the animals got up to. # Legend * ```H``` horse * ```C``` chicken * ```R``` rabbit * ```A``` apple tree * ```V``` vegetables * ```|``` gate (closed), * ```\``` or ```/``` gate (open) * ```.``` everything else # Example <table> <th>Before<td> ```|..HH....\AAAA\CC..|AAA/VVV/RRRR|CCC``` </tr> <th>After<td> ```|..HH....\....\CC..|AAA/.../RRRR|...``` Because: <ul> <li>The horses ate whatever apples they could get to <li>The rabbits ate the vegetables <li>The chickens ran away </ul> </tr> </table> # Notes * If the animals can eat things *and* also run away then they do **BOTH** - it is best not to run away when you are hungry! * An animal cannot "go around" a closed gate... * ...but it is possible to run away from the farm and then **RUN BACK** and re-enter though more open gates on the other side!
algorithms
from itertools import groupby def shut_the_gate(farm): who_eats_whom = {'H': ['A', 'V'], 'R': ['V'], 'C': []} runaway_back, runaway_front, farm = [], [], [ "" . join(j) for k, j in groupby(farm)] def doSomeFarm(i=0): def do(j, s=False): while (j >= 0 if s else j < len(farm)) and farm[j] != '|': if farm[j][0] in who_eats_whom[current[0]]: farm[j] = '.' * len(farm[j]) j += [1, - 1][s] return j while i < len(farm): current = farm[i] if current[0] in who_eats_whom: r, r1 = do(i, 1), do(i) if r == - 1 or r1 == len(farm): farm[i] = '.' * len(farm[i]) [runaway_front, runaway_back][r != - 1]. append(current[0]) i += 1 doSomeFarm() l = len(runaway_back) if l: if farm[0] != '|': farm = ['/'] + " / " . join(runaway_back[:: - 1]). split() + farm doSomeFarm() farm = farm[l * 2:] l = len(runaway_front) if l: if farm[- 1] != '|': farm = farm + ['/'] + ' / ' . join(runaway_front). split() doSomeFarm() farm = farm[: - l * 2] return "" . join(farm)
The Hunger Games - Shut the gate
59218bf66034acb9b7000040
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/59218bf66034acb9b7000040
5 kyu
Tolkein's publisher wishes to implement an online store for the "Lord of the Rings" and "The Hobbit" books. Each book costs $10. However, if 2 titles are purchased, a 5% discount will be received, i.e. purchasing "Fellowship of the Ring" and "Two Towers" will cost $19. If 3 different titles are purchased, a 10% discount will be received. The purchase of all 4 different titles will receive a 20% discount. An additional single title will be full-price. The encoding of an order will be in the form of strings in an array. For example: `[“F”, “T”, “R”, “H”, “H”]` is the encoding of 2 copies of "The Hobbit" and a single copy of each of the titles in the "Lord of the Rings" trilogy. The expected output is a number. E.g. `42` is the expected output for the example above. The output should be the cheapest total cost. For example - if the book order is `["F", "T", "H", "F", "T", "R"]`, valid total costs include `(3*10 discounted by 10%) + (3*10 discounted by 10%)` and `(4*10 discounted by 20%) + (2*10 discounted by 5%)`. The cheapest total cost is `51`. This is a slightly simplified version of http://codingdojo.org/kata/Potter/
algorithms
from collections import Counter def calculate_cart_total(contents): return sum(p * n for p, (_, n) in zip((10, 9, 8, 5), Counter(contents). most_common()))
Tolkien's Book Cart
59a2666349ae65ea69000051
[ "Algorithms" ]
https://www.codewars.com/kata/59a2666349ae65ea69000051
6 kyu
You wrote a program that can calculate the sum of all the digits of a non-negative integer. However, it's not fast enough. Can you make it faster? --- ### Input size ~~~if:haskell Haskell: - 50 random tests of `n <= 2^64` - 50 random tests of `n <= 2^200000` ~~~ ~~~if:python Python: - 50 random tests of `n <= 2^64` - 50 random tests of `n <= 2^120000` ~~~ ~~~if:ruby Ruby: - 50 random tests of `n <= 2^64` - 50 random tests of `n <= 2^100000` ~~~
reference
def digit_sum(n): return sum(map(int, str(n)))
Micro Optimization: Digit Sum
59a2af923203e8220b00008f
[ "Fundamentals" ]
https://www.codewars.com/kata/59a2af923203e8220b00008f
6 kyu
You are given two arrays `arr1` and `arr2`, where `arr2` always contains integers. Write a function such that: For `arr1 = ['a', 'a', 'a', 'a', 'a']`, `arr2 = [2, 4]` the function returns `['a', 'a']` For `arr1 = [0, 1, 5, 2, 1, 8, 9, 1, 5]`, `arr2 = [1, 4, 7]` the function returns `[1, 1, 1]` For `arr1 = [0, 3, 4]`, `arr2 = [2, 6]` the function returns `[4]` For `arr1=["a","b","c","d"]` , `arr2=[2,2,2]`, the function returns `["c","c","c"]` For `arr1=["a","b","c","d"]`, `arr2=[3,0,2]` the function returns `["d","a","c"]` Note that when an element inside `arr2` is greater than the index of the last element of `arr1` no element of `arr1` should be added to the resulting array. If either `arr1` or `arr2` is empty, you should return an empty arr (empty list in python, empty vector in c++). Note for c++ use std::vector<T> arr1, arr2.
games
def find_array(arr1, arr2): return [arr1[i] for i in arr2 if i < len(arr1)]
Find array
59a2a3ba5eb5d4e609000055
[ "Puzzles" ]
https://www.codewars.com/kata/59a2a3ba5eb5d4e609000055
7 kyu
Write a function that returns a list of all the integers from `lower` ( inclusive ) to `upper` ( exclusive ) in a such way that no two adjacent numbers in the list are numerically adjacent ( e.g. `5` cannot be next to `4` or `6` ). The maximum sequence length tested is 10<sup>7</sup>. The minimum sequence length tested is _long enough._ #### Examples For `solution(0,6)`: `5,0,4,1,3,2` would not be acceptable, because `3` and `2` are adjacent. `0,2,5,3,1,4` would be acceptable.
algorithms
def generate_sequence(lower, upper): return list(range(lower + 1, upper, 2)) + list(range(lower, upper, 2))
No adjacent integers sequence generator
59a20f283203e8bd8c000006
[ "Algorithms" ]
https://www.codewars.com/kata/59a20f283203e8bd8c000006
6 kyu
You will be given the number of angles of a shape with equal sides and angles, and you need to return the number of its sides, and the measure of the interior angles. Should the number be equal or less than `2`, return: ``` "this will be a line segment or a dot" ``` Otherwise return the result in the following format: ``` "This shape has s sides and each angle measures d" ``` (replace `s` with number of sides and `d` with the measure of the interior angles). Angle measure should be **floored to the nearest integer**. Number of sides will be tested from `0` to `180`. Have Fun!
games
def describe_the_shape(n): return "this will be a line segment or a dot" if n < 3 else \ "This shape has %s sides and each angle measures %s" % (n, (n - 2) * 180 / / n)
Describe the shape
59a1ea8b70e25ef8e3002992
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/59a1ea8b70e25ef8e3002992
7 kyu
The `Stanton` measure of an array is computed as follows: count the number of occurences for value `1` in the array. Let this count be `n`. The `Stanton` measure is the number of times that `n` appears in the array. Write a function which takes an integer array and returns its `Stanton` measure. #### Examples The Stanton measure of `[1, 4, 3, 2, 1, 2, 3, 2]` is `3`, because `1` occurs `2` times in the array and `2` occurs `3` times. The Stanton measure of `[1, 4, 1, 2, 11, 2, 3, 1]` is `1`, because `1` occurs `3` times in the array and `3` occurs `1` time.
reference
def stanton_measure(arr): return arr . count(arr . count(1))
Stanton measure
59a1cdde9f922b83ee00003b
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/59a1cdde9f922b83ee00003b
7 kyu
The number `198` has the property that `198 = 11 + 99 + 88, i.e., if each of its digits is concatenated twice and then summed, the result will be the original number`. It turns out that `198` is the only number with this property. However, the property can be generalized so that each digit is concatenated `n` times and then summed. ## Examples ``` original number =2997 , n=3 2997 = 222+999+999+777 and here each digit is concatenated three times. original number=-2997 , n=3 -2997 = -222-999-999-777 and here each digit is concatenated three times. ``` ## Task ```if:python Write a function named `check_concatenated_sum` that tests if a number has this generalized property. ``` ```if-not:python Write a function named `checkConcatenatedSum` that tests if a number has this generalized property. ```
reference
def check_concatenated_sum(n, r): return abs(n) == sum(int(e * r) for e in str(abs(n)) if r)
Concatenated Sum
59a1ec603203e862bb00004f
[ "Fundamentals" ]
https://www.codewars.com/kata/59a1ec603203e862bb00004f
7 kyu
A happy number is a number defined by the following process: starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are **happy numbers**, while those that do not end in 1 are unhappy numbers (or sad numbers) (Wikipedia). Write a function that takes `n` as parameter and return `true` if and only if `n` is an happy number, `false` otherwise. ## Examples For example number `7` is happy because after a number of steps the computed sequence ends up with a 1: `7, 49, 97, 130, 10, 1 ` While `3` is not, and would give us an infinite sequence: `3, 9, 81, 65, 61, 37, 58, 89, 145, 42, 20, 4, 16, 37, 58, 89, 145, 42, 20, 4, 16, 37, ...` Happy coding!
algorithms
def is_happy(n): seen = set() while n != 1: n = sum(int(d) * * 2 for d in str(n)) if n not in seen: seen . add(n) else: return False return True
Happy numbers
5464cbfb1e0c08e9b3000b3e
[ "Algorithms" ]
https://www.codewars.com/kata/5464cbfb1e0c08e9b3000b3e
6 kyu
An array is defined to be `inertial`if the following conditions hold: ``` a. it contains at least one odd value b. the maximum value in the array is even c. every odd value is greater than every even value that is not the maximum value. ``` eg:- ``` So [11, 4, 20, 9, 2, 8] is inertial because a. it contains at least one odd value [11,9] b. the maximum value in the array is 20 which is even c. the two odd values (11 and 9) are greater than all the even values that are not equal to 20 (the maximum), i.e., [4, 2, 8] ``` Write a function called `is_inertial` that accepts an integer array and returns `true` if the array is inertial; otherwise it returns `false`.
reference
def is_inertial(arr): mx = max(arr, default=1) miO = min((x for x in arr if x % 2 == 1), default=float("-inf")) miE2 = max((x for x in arr if x % 2 == 0 and x != mx), default=float("-inf")) return mx % 2 == 0 and miE2 < miO
Inertial Array
59a151c53f64cdd94c00008f
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/59a151c53f64cdd94c00008f
7 kyu
You'll be given a string of random characters (numbers, letters, and symbols). To decode this string into the key we're searching for: (1) count the number occurences of each ascii lowercase letter, and (2) return an ordered string, 26 places long, corresponding to the number of occurences for each corresponding letter in the alphabet. For example: ```python '$aaaa#bbb*cc^fff!z' gives '43200300000000000000000001' ^ ^ ^ ^ ^ ^^^ ^ ^ [4] [3] [2][3][1] abc f z 'z$aaa#ccc%eee1234567890' gives '30303000000000000000000001' ^ ^ ^ ^ ^ ^ ^ ^ [1][3] [3] [3] a c e z ``` Remember, the string returned should always be 26 characters long, and only count lowercase letters. Note: You can assume that each lowercase letter will appears a maximum of 9 times in the input string.
reference
from collections import Counter from string import ascii_lowercase def decrypt(test_key): cnt = Counter(test_key) return '' . join(str(cnt[a]) for a in ascii_lowercase)
Simple decrypt algo
58693136b98de0e4910001ab
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/58693136b98de0e4910001ab
6 kyu
This kata builds on [Number Climber](http://www.codewars.com/kata/number-climber). For every positive number N there exists a unique sequence starting at 1 and ending at N, where each number in the sequence is either the double of the previous number or the double plus one. For example, if N = 13, then the sequence is [1, 3, 6, 13]. Given a number F, we can map the sequence by multiplying each number by F. So, for the example above and F = 7, we get the sequence ```[1 * 7, 3 * 7, 6 * 7, 13 * 7] = [7, 21, 42, 91]```. Notice: 1. The last number in the sequence is ```N * F``` 2. Each number in the sequence is either the double of the previous number or the double plus F. Write a function ```multiply``` that takes two positive integers as arguments and returns the product of the two numbers. You are *only* allowed to use - left and right shifts `<<, >>`, - addition and subtraction `+, -` - logical operators `^, &, |, ~` - comparisons `<, <=, >=, >`. You may *not* use the `*` operator or a builtin or imported multiplication function. Also, you may not use any integer literal. Use the preprovided `zero` and `one` to denote the numbers 0 and 1 respectively.
reference
def multiply(x, y): s = zero while y: s += y & one and x y >>= one x <<= one return s
Write your own multiplication function
55988922d24a02ccd0000063
[ "Fundamentals" ]
https://www.codewars.com/kata/55988922d24a02ccd0000063
6 kyu
In genetic algorithms, a crossover allows 2 chromosomes to exchange part of their genes. For more details, you can visit these wikipedia links : <a href="https://en.wikipedia.org/wiki/Genetic_algorithm">Genetic algorithm</a> and <a href="https://en.wikipedia.org/wiki/Crossover_(genetic_algorithm)">Crossover</a>. A chromosome is represented by a list of genes.<br> Consider for instance 2 chromosomes : ``` xs (with genes [x,x,x,x,x,x]) and ys (with genes [y,y,y,y,y,y]) ``` A single-point crossover at index 2 would give : ```haskell new chromosome1 = [x,x,y,y,y,y] and new chromosome2 = [y,y,x,x,x,x] ``` ```ocaml new chromosome1 = [x;x;y;y;y;y] and new chromosome2 = [y;y;x;x;x;x] ``` ```python new chromosome1 = [x,x,y,y,y,y] and new chromosome2 = [y,y,x,x,x,x] ``` ```go new chromosome1 = []int { x,x,y,y,y,y } and new chromosome2 = []int { y,y,x,x,x,x } ``` ```scala new chromosome1 = List(x,x,y,y,y,y) and new chromosome2 = List(y,y,x,x,x,x) ``` ```rust new chromosome1 = [x,x,y,y,y,y] and new chromosome2 = [y,y,x,x,x,x] ``` A two-point crossover at indices 1 and 3 would give : ```haskell new chromosome1 = [x,y,y,x,x,x] and new chromosome2 = [y,x,x,y,y,y] ``` ```ocaml new chromosome1 = [x;y;y;x;x;x] and new chromosome2 = [y;x;x;y;y;y] ``` ```python new chromosome1 = [x,y,y,x,x,x] and new chromosome2 = [y,x,x,y,y,y] ``` ```go new chromosome1 = []int { x,y,y,x,x,x } and new chromosome2 = []int { y,x,x,y,y,y } ``` ```scala new chromosome1 = List(x,y,y,x,x,x) and new chromosome2 = List(y,x,x,y,y,y) ``` ```rust new chromosome1 = [x,y,y,x,x,x] and new chromosome2 = [y,x,x,y,y,y] ``` We want to generalize this to the notion of n-point crossover, and create a generic function with the following signature : ```haskell crossover :: [Int] -> [a] -> [a] -> ([a],[a]) crossover ns xs ys = undefined ``` ```ocaml crossover : Int -> 'a list -> 'a list -> 'a list * 'a list crossover ns xs ys = ``` ```python # crossover() takes a list of indices ns (integers) and 2 lists xs and ys # It returns a tuple of lists: ([],[]) def crossover(ns, xs, ys) ``` ```go func Crossover(ns []int, xs []int,ys []int) ([]int, []int) ``` ```scala def crossover[T](ns: List[Int], xs: List[T], ys: List[T]): (List[T],List[T]) ``` ```rust fn crossover(ns: &[usize], xs: &[u8], ys: &[u8]) -> (Vec<u8>,Vec<u8>) ``` where `ns` would be a list of cross-point indices. We could compute a triple-point crossover of 2 chromosomes xs and ys the following way : ```haskell crossover [2,5,21] xs ys ``` ```ocaml crossover [2;5;21] xs ys ``` ```python crossover([2,5,21], xs, ys) ``` ```go Crossover(int[] { 2, 5, 21 }, xs, ys) ``` ```scala crossover(List(2,5,21), xs, ys) ``` ```rust crossover(&[2,5,21], &xs, &ys); ``` The transformed first chromosome must appear at the first position of the tuple. the second one at the second position. Therefore : ```haskell (crossover [1] ['a','b','c'] ['x','y','z']) `shouldBe` (['a','y','z'],['x','b','c']) ``` ```ocaml (crossover [1] ['a';'b';'c'] ['x';'y';'z']) should be (['a';'y';'z'],['x';'b';'c']) ``` ```python crossover([1],['a','b','c'],['x','y','z']) should be (['a','y','z'],['x','b','c']) ``` ```go Crossover([]int { 1 }, []int {1,2,3}, []int {11,12,13}) should be ([]int { 1,12,13 }, int[] { 11,2,3 }) ``` ```scala crossover(List(1),List('a','b','c'),List('x','y','z')) should be (List('a','y','z'), List('x','b','c')) ``` ```rust crossover(&[1], &[1,2,3], &[11,12,13]) should be (vec![1,12,13],vec![11,2,3]) ``` If a cross-point index is repeated, it should be considered only once. Indices can also be provided unordered, so your function could be called with the following indices : ```haskell crossover [7,5,3,5] xs ys ``` ```ocaml crossover [7;5;3;5] xs ys ``` ```python crossover([7,5,3,5], xs, ys) ``` ```go Crossover(int[] { 7,5,3,5 }, xs, ys) ``` ```scala crossover(List(7,5,3,5), xs, ys) ``` ```rust crossover(&[7,5,3,5], &xs, &ys) ``` In this case, you would have to consider only indices [7,5,3] and deal with the fact they are unordered. Chromosome indices are 0-based and you can also assume that : <ol> <li> (length xs) == (length ys) </li> <li> crossover indices will never exceed the length of xs or ys. </li> </ol>
reference
def crossover(ns, xs, ys): for i in sorted(set(ns)): xs, ys = xs[: i] + ys[i:], ys[: i] + xs[i:] return xs, ys
N-Point Crossover
57339a5226196a7f90001bcf
[ "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/57339a5226196a7f90001bcf
6 kyu
Create an SQLite3 database `/tmp/movies.db` Your database should have a table named `MOVIES` that contains the following data: <table> <thead> <tr> <th>Name</th> <th>Year</th> <th>Rating</th> </tr> </thead> <tbody> <tr> <td>Rise of the Planet of the Apes </td> <td>2011</td> <td>77</td> </tr> <tr> <td>Dawn of the Planet of the Apes</td> <td>2014</td> <td>91</td> </tr> <tr> <td>Alien</td> <td>1979</td> <td>97</td> </tr> <tr> <td>Aliens</td> <td>1986</td> <td>98</td> </tr> <tr> <td>Mad Max</td> <td>1979</td> <td>95</td> </tr> <tr> <td>Mad Max 2: The Road Warrior</td> <td>1981</td> <td>100</td> </tr> </tbody> </table> --------------- In Haskell, both of the [persistent][1] and [esqueleto][2] modules are available... You will be expected to create a monadic action `mkMoviesDB :: IO ()` [1]: https://hackage.haskell.org/package/persistent [2]: https://hackage.haskell.org/package/esqueleto
reference
import sqlite3 from contextlib import closing with sqlite3 . connect('/tmp/movies.db') as db: with closing(db . cursor()) as cursor: cursor . execute(''' CREATE TABLE MOVIES(id INTEGER PRIMARY KEY, Name TEXT unique, Year INTEGER, Rating INTEGER) ''') movies = [("Rise of the Planet of the Apes", 2011, 77), ("Dawn of the Planet of the Apes", 2014, 91), ("Alien", 1979, 97), ("Aliens", 1986, 98), ("Mad Max", 1979, 95), ("Mad Max 2: The Road Warrior", 1981, 100)] cursor . executemany( "INSERT INTO MOVIES(Name, Year, Rating) VALUES(?,?,?)", movies) db . commit()
I Liked the SQL Better...
53d2c97d7152a59b64001033
[ "SQL", "Databases", "Fundamentals" ]
https://www.codewars.com/kata/53d2c97d7152a59b64001033
6 kyu
Write a ```timer()``` decorator that validates if a function it decorates is executed within *(less than)* a given ```seconds``` interval and returns a boolean ```True``` or ```False``` accordingly. Example: ``` from time import sleep @timer(1) def foo(): sleep(0.1) @timer(1) def bar(): sleep(1.1) >>> foo() True >>> bar() False ```
reference
from time import time from functools import wraps def timer(limit): def dec(func): @ wraps(func) def time_func(* args, * * kwargs): time_start = time() func(* args, * * kwargs) return time() - time_start < limit return time_func return dec
Timer Decorator
56f84d093b164c2e490013cb
[ "Fundamentals", "Design Patterns", "Object-oriented Programming", "Date Time" ]
https://www.codewars.com/kata/56f84d093b164c2e490013cb
6 kyu
Let's look at the following generator: ``` def gen(): for i in range(2): for j in range(3): yield (i, j) ``` If we print all yielded values, we'll get ``` (0, 0) (0, 1) (0, 2) (1, 0) (1, 1) (1, 2) ``` For a given parameter list N you must return an iterator, which goes through all possible tuples A, where Ai changes from 0 to Ni.
reference
from itertools import product def multiiter(* args): return product(* map(range, args))
Multirange iterator
56bc72f866a2ab1890000be0
[ "Iterators", "Fundamentals" ]
https://www.codewars.com/kata/56bc72f866a2ab1890000be0
6 kyu
How many days are we represented in a foreign country? My colleagues make business trips to a foreign country. We must find the number of days our company is represented in a country. Every day that one or more colleagues are present in the country is a day that the company is represented. A single day cannot count for more than one day. Write a function that recieves a list of pairs and returns the number of days that the company is represented in the foreign country. The first number of the pair is the number of the day of arrival and the second number of the pair is the day of departure of someone who travels, i.e. 1 january is number 1 and 31 of december is 365. Example: ```c days_represented(2, {{10, 17}, {200, 207}}); ``` ```haskell daysRepresented [(10,17),(200,207)] ``` ```java daysRepresented (new int[][] {{10,17},{200,207}}) ``` ```javascript daysRepresented ([[10,17],[200,207]]) ``` ```python days_represented([[10,17],[200,207]]) ``` Returns 16 because there are two trips of 8 days, which add up to 16. Happy coding and rank this kata if you wish ;-)
reference
def days_represented(a): return len({i for x, y in a for i in range(x, y + 1)})
How many days are we represented in a foreign country?
58e93b4706db4d24ee000096
[ "Lists", "Fundamentals" ]
https://www.codewars.com/kata/58e93b4706db4d24ee000096
7 kyu
Part 2/3 of my kata series. [Part 1](http://www.codewars.com/kata/riemann-sums-i-left-side-rule) The description changes little in this second part. Here we simply want to improve our approximation of the integral by using trapezoids instead of rectangles. The left/right side rules have a serious bias and the trapezoidal rules averages those approximations! The same assumptions exist but are pasted here for convenience. - f will always take a single float argument - f will always be a "nice" function, don't worry about NaN - n will always be a natural number (0, N] - b > a - and n will be chosen appropriately given the length of [a, b] (as in I will not have step sizes smaller than machine epsilon) - *!!! round answers to the nearest hundredth!!!*
reference
def riemann_trapezoidal(f, n, a, b): dx = (b - a) / n return round(sum(f(a + i * dx) + f(a + (i + 1) * dx) for i in range(n)) * dx / 2, 2)
riemann sums II (trapezoidal rule)
5562b6de2f508f1adc000089
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5562b6de2f508f1adc000089
6 kyu
The aim of this kata is to determine the number of sub-function calls made by an unknown function. You have to write a function named `count_calls` which: * takes as parameter a function and its arguments (args, kwargs) * calls the function * returns a tuple containing: * the number of function calls made inside it and inside all the sub-called functions recursively * the function return value. NB: The call to the function itself is not counted. HINT: The sys module may come in handy.
reference
import sys def count_calls(func, * args, * * kwargs): """Count calls in function func""" calls = [- 1] def tracer(frame, event, arg): if event == 'call': calls[0] += 1 return tracer sys . settrace(tracer) rv = func(* args, * * kwargs) return calls[0], rv
Counting inner calls in an unknown function.
53efc28911c36ff01e00012c
[ "Recursion", "Language Features" ]
https://www.codewars.com/kata/53efc28911c36ff01e00012c
4 kyu
In your class, you have started lessons about geometric progression. Since you are also a programmer, you have decided to write a function that will print first `n` elements of the sequence with the given constant `r` and first element `a`. Result should be separated by comma and space. ### Example ```python geometric_sequence_elements(2, 3, 5) == '2, 6, 18, 54, 162' ``` ```ruby geometric_sequence_elements(2, 3, 5) == '2, 6, 18, 54, 162' ``` ```javascript geometricSequenceElements(2, 3, 5) == '2, 6, 18, 54, 162' ``` ```php geometric_sequence_elements(2, 3, 5); // => '2, 6, 18, 54, 162' ``` ```csharp Kata.GeometricSequenceElements(2, 3, 5); // => "2, 6, 18, 54, 162" ``` ```elixir Kata.geometric_sequence_elements(2, 3, 5) == "2, 6, 18, 54, 162" ``` ```kotlin geometricSequenceElements(2, 3, 5) == "2, 6, 18, 54, 162" ``` More info: https://en.wikipedia.org/wiki/Geometric_progression
reference
def geometric_sequence_elements(a, r, n): return ", " . join(str(a * r * * i) for i in range(n))
Geometric Progression Sequence
55caef80d691f65cb6000040
[ "Fundamentals" ]
https://www.codewars.com/kata/55caef80d691f65cb6000040
7 kyu
Implement a function `reverse_list` which takes a singly-linked list of nodes and returns a matching list in the reverse order. Assume the presense of a class `Node`, which exposes the property `value`/`Value` and `next`/`Next`. `next` must either be set to the next `Node` in the list, or to `None` (or `null`) to indicate the end of the list. To assist in writing tests, a function `make_linked_list` (`Node.asLinkedList()` in Java) has also been defined, which converts a python list to a linked list of `Node`. The final tests will use a very long list. Be aware that a recursive solution will run out of stack.
algorithms
def reverse_list(node): res = None while node: res = Node(node . value, res) node = node . next return res
Reverse a singly-linked list
57262ca48565846f33001365
[ "Algorithms" ]
https://www.codewars.com/kata/57262ca48565846f33001365
6 kyu
The [Linear Congruential Generator (LCG)](https://en.wikipedia.org/wiki/Linear_congruential_generator) is one of the oldest pseudo random number generator functions. The algorithm is as follows: ## X<sub>n+1</sub>=(aX<sub>n</sub> + c) mod m where: * `a`/`A` is the multiplier (we'll be using `2`) * `c`/`C` is the increment (we'll be using `3`) * `m`/`M` is the modulus (we'll be using `10`) X<sub>0</sub> is the seed. # Your task Define a method `random`/`Random` in the class `LCG` that provides the next random number based on a seed. You never return the initial seed value. Similar to [random](https://docs.python.org/3/library/random.html#random.random) return the result as a floating point number in the range `[0.0, 1.0)` # Example ```python # initialize the generator with seed = 5 LCG(5) # first random number (seed = 5) LCG.random() = 0.3 # (2 * 5 + 3) mod 10 = 3 --> return 0.3 # next random number (seed = 3) LCG.random() = 0.9 # (2 * 3 + 3) mod 10 = 9 --> return 0.9 # next random number (seed = 9) LCG.random() = 0.1 # next random number (seed = 1) LCG.random() = 0.5 ``` ```ruby # initialize the generator with seed = 5 LCG(5) # first random number (seed = 5) LCG.random() = 0.3 # (2 * 5 + 3) mod 10 = 3 --> return 0.3 # next random number (seed = 3) LCG.random() = 0.9 # (2 * 3 + 3) mod 10 = 9 --> return 0.9 # next random number (seed = 9) LCG.random() = 0.1 # next random number (seed = 1) LCG.random() = 0.5 ``` ```crystal # initialize the generator with seed = 5 LCG(5) # first random number (seed = 5) LCG.random() = 0.3 # (2 * 5 + 3) mod 10 = 3 --> return 0.3 # next random number (seed = 3) LCG.random() = 0.9 # (2 * 3 + 3) mod 10 = 9 --> return 0.9 # next random number (seed = 9) LCG.random() = 0.1 # next random number (seed = 1) LCG.random() = 0.5 ``` ```javascript // initialize the generator with seed = 5 LCG(5) // first random number (seed = 5) LCG.random() = 0.3 # (2 * 5 + 3) mod 10 = 3 --> return 0.3 // next random number (seed = 3) LCG.random() = 0.9 # (2 * 3 + 3) mod 10 = 9 --> return 0.9 // next random number (seed = 9) LCG.random() = 0.1 // next random number (seed = 1) LCG.random() = 0.5 ``` ```csharp LCG myLCG = new LCG(5); // Initialize the generator with a seed of 5 myLCG.Random(); // => 0.3 ((2 * 5 + 3) mod 10 = 3) myLCG.Random(); // => 0.9 ((2 * 3 + 3) mod 10 = 9) myLCG.Random(); // => 0.1 ((2 * 9 + 3) mod 10 = 1) myLCG.Random(); // => 0.5 ((2 * 1 + 3) mod 10 = 5) ```
algorithms
class LCG (object): def __init__(self, x): self . _seed = x def random(self): self . _seed = (2 * self . _seed + 3) % 10 return self . _seed / 10
PRNG: Linear Congruential Generator
594979a364becbc1ab00003a
[ "Algorithms" ]
https://www.codewars.com/kata/594979a364becbc1ab00003a
7 kyu
Write a function name `nextPerfectSquare` / ```next_perfect_square``` that returns the first perfect square that is greater than its integer argument. A `perfect square` is a integer that is equal to some integer squared. For example 16 is a perfect square because `16=4*4`. ``` example n next perfect square 6 9 36 49 0 1 -5 0 ``` ```if-not:csharp caution! the largest number tested is closer to `Number.MAX_SAFE_INTEGER` ``` ```if:csharp Caution! The largest number test is close to `Int64.MaxValue` ```
reference
def next_perfect_square(n): return n >= 0 and (int(n * * 0.5) + 1) * * 2
nextPerfectSquare
599f403119afacf9f1000051
[ "Fundamentals" ]
https://www.codewars.com/kata/599f403119afacf9f1000051
7 kyu
This is the Performance version of [simple version](http://www.codewars.com/kata/574be65a974b95eaf40008da). If your code runs more than 7000ms, please optimize your code or try the [simple version](http://www.codewars.com/kata/574be65a974b95eaf40008da) ## Task A game I played when I was young: Draw 4 cards from playing cards, use ```+ - * / and ()``` to make the final results equal to 24. You will coding in function ```equalTo24```. Function accept 4 parameters ```a b c d```(4 numbers), value range is 1-100. The result is a string such as ```"2*2*2*3"``` ,```(4+2)*(5-1)```; If it is not possible to calculate the 24, please return `"It's not possible!"` All four cards are to be used, only use three or two cards are incorrect; Use a card twice or more is incorrect too. You just need to return one correct solution, don't need to find out all the possibilities. The different between "challenge version" and "simple version": ``` 1) a,b,c,d range: In "challenge version" it is 1-100, In "simple version" it is 1-13. 2) "challenge version" has 1000 random testcases, "simple version" only has 20 random testcases. ``` ### Some examples: ```javascript equalTo24(1,2,3,4) //can return "(1+3)*(2+4)" or "1*2*3*4" equalTo24(2,3,4,5) //can return "(5+3-2)*4" or "(3+4+5)*2" equalTo24(3,4,5,6) //can return "(3-4+5)*6" equalTo24(1,1,1,1) //should return "It's not possible!" equalTo24(13,13,13,13) //should return "It's not possible!" ``` ```coffeescript equalTo24(1,2,3,4) # can return "(1+3)*(2+4)" or "1*2*3*4" equalTo24(2,3,4,5) # can return "(5+3-2)*4" or "(3+4+5)*2" equalTo24(3,4,5,6) # can return "(3-4+5)*6" equalTo24(1,1,1,1) # should return "It's not possible!" equalTo24(13,13,13,13) # should return "It's not possible!" ``` ### Series: - [Count animals](http://www.codewars.com/kata/57121e6fcdbf63eb94000e51) - [A*B=C](http://www.codewars.com/kata/5714594d2817ff681c000783) - [Half it III](http://www.codewars.com/kata/5717293a672b20c4b30008d0) - [Half it IV](http://www.codewars.com/kata/5719b28964a584476500057d) - [Excel Puzzle #1](http://www.codewars.com/kata/571b93687beb0a8ade000a80) - [Excel Puzzle #2](http://www.codewars.com/kata/571d946faa2dcbe939000df4) - [Equal to 24](http://www.codewars.com/kata/574e890e296e412a0400149c)
games
from itertools import permutations import math def equal_to_24(* aceg): ops = '+-*/' OPS = { '+': lambda a, b: a + b, '-': lambda a, b: a - b, '*': lambda a, b: a * b, '/': lambda a, b: a / b if b else math . inf } for b in ops: for d in ops: for f in ops: for (a, c, e, g) in permutations(aceg): B, D, F = OPS[b], OPS[d], OPS[f] for (i, exp) in enumerate(make_exp(a, B, c, D, e, F, g)): if exp == 24: return make_string(a, b, c, d, e, f, g)[i] return "It's not possible!" def make_exp(a, b, c, d, e, f, g): return [ f(d(b(a, c), e), g), d(b(a, c), f(e, g)), b(a, d(c, f(e, g))), b(a, f(d(c, e), g)), f(b(a, d(c, e)), g)] def make_string(a, b, c, d, e, f, g): return [f"(( { a }{ b }{ c } ) { d }{ e } ) { f }{ g } ", f"( { a }{ b }{ c } ) { d } ( { e }{ f }{ g } )", f" { a }{ b } ( { c }{ d } ( { e }{ f }{ g } ))", f" { a }{ b } (( { c }{ d }{ e } ) { f }{ g } )", f"( { a }{ b } ( { c }{ d }{ e } )) { f }{ g } "]
Fastest Code : Equal to 24
574e890e296e412a0400149c
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/574e890e296e412a0400149c
2 kyu
This kata explores writing an AI for a two player, turn based game called *NIM*. The Board -------------- The board starts out with several piles of straw. Each pile has a random number of straws. ``` Pile 0: |||| Pile 1: || Pile 2: ||||| Pile 3: | Pile 4: |||||| ...or more concisely: [4,2,5,1,6] ``` The Rules -------------- - The players take turns picking a pile, and removing any number of straws from the pile they pick - A player must pick at least one straw - If a player picks the last straw, she wins! The Task ------------ In this kata, you have to write an AI to play the straw picking game. You have to encode an AI in a function `choose_move` (or `chooseMove`, or `choose-move`) that takes a board, represented as a list of positive integers, and returns ```python (pile_index, number_of_straws) ``` ```haskell (pileIndex, numberOfStraws) ``` ```javascript [pile_index, number_of_straws] ``` ```clojure [pile-index, number-of-straws] ``` Which refers to an index of a pile on the board, and some none-zero number of straws to draw from that pile. The test suite is written so that your AI is expected to play 50 games and win every game it plays.
games
from operator import xor def choose_move(game_state): """Chooses a move to play given a game state""" x = reduce(xor, game_state) for i, amt in enumerate(game_state): if amt ^ x < amt: return (i, amt - (amt ^ x))
NIM the game
54120de842dff35232000195
[ "Mathematics", "Games", "Puzzles" ]
https://www.codewars.com/kata/54120de842dff35232000195
4 kyu
Imagine that you are given two sticks. You want to end up with three sticks of equal length. You are allowed to cut either or both of the sticks to accomplish this, and can throw away leftover pieces. Write a function, maxlen, that takes the lengths of the two sticks (L1 and L2, both positive values), that will return the maximum length you can make the three sticks.
reference
def maxlen(s1, s2): sm, lg = sorted((s1, s2)) return min(max(lg / 3, sm), lg / 2)
Three sticks
57c1f22d8fbb9fd88700009b
[ "Fundamentals" ]
https://www.codewars.com/kata/57c1f22d8fbb9fd88700009b
7 kyu
It's important day today: the class has just had a math test. You will be given a list of marks. Complete the function that will: * Calculate the average mark of the whole class and round it to 3 decimal places. * Make a dictionary/hash with keys `"h", "a", "l"` to make clear how many `h`igh, `a`verage and `l`ow marks they got. High marks are 9 & 10, average marks are 7 & 8, and low marks are 1 to 6. * Return list `[class_average, dictionary]` if there are different type of marks, or `[class_average, dictionary, "They did well"]` if there are only high marks. ## Examples ```python [10, 9, 9, 10, 9, 10, 9] ==> [9.429, {'h': 7, 'a': 0, 'l': 0}, 'They did well'] [5, 6, 4, 8, 9, 8, 9, 10, 10, 10] ==> [7.9, {'h': 5, 'a': 2, 'l': 3}] ``` ```ruby [10, 9, 9, 10, 9, 10, 9] ==> [9.429, {'h': 7, 'a': 0, 'l': 0}, 'They did well'] [5, 6, 4, 8, 9, 8, 9, 10, 10, 10] ==> [7.9, {'h': 5, 'a': 2, 'l': 3}] ```
reference
from statistics import mean def test(r): dct = {'l': 0, 'a': 0, 'h': 0} for n in r: dct['lah' [(n > 6) + (n > 8)]] += 1 return [round(mean(r), 3), dct] + ['They did well'] * (sum(dct . values()) == dct['h'])
Test's results
599db0a227ca9f294b0000c8
[ "Fundamentals", "Lists" ]
https://www.codewars.com/kata/599db0a227ca9f294b0000c8
7 kyu
From [Wikipedia](https://en.wikipedia.org/wiki/N-back): "The n-back task is a continuous performance task that is commonly used as an assessment in cognitive neuroscience to measure a part of working memory and working memory capacity. \[...\] The subject is presented with a sequence of stimuli, and the task consists of indicating when the current stimulus matches the one from `n` steps earlier in the sequence. The load factor `n` can be adjusted to make the task more or less difficult." In this kata, your task is to "teach" your computer to do the n-back task. Specifically, you will be implementing a function that counts the number of "targets" (stimuli that match the one from `n` steps earlier) in a sequence of digits. Your function will take two parameters: * `n`, a positive integer: the number of steps to look back to find a match * `sequence`, a sequence of digits containing `0` or more targets A few hints: * The first digit in a sequence can never be a target * Targets can be "chained" together (e.g., for `n = 1` and `sequence = [1, 1, 1]`, there are `2` targets) ~~~if:lambdacalc Encodings: * purity: `LetRec` * numEncoding: `Scott` * export constructors `nil, cons` for your `List` encoding ~~~
reference
def count_targets(n, sequence): return sum(a == b for a, b in zip(sequence, sequence[n:]))
n-back
599c7f81ca4fa35314000140
[ "Fundamentals" ]
https://www.codewars.com/kata/599c7f81ca4fa35314000140
6 kyu
<img src="https://i.imgur.com/ta6gv1i.png?1" title="source: imgur.com" /> The code provided is supposed return a person's **Full Name** given their ```first``` and ```last``` names. But it's not working properly. # Notes The first and/or last names are never null, but may be empty. # Task Fix the bug so we can all go home early.
bug_fixes
class Dinglemouse (object): def __init__(self, first_name, last_name): self . first_name = first_name self . last_name = last_name def get_full_name(self): return (self . first_name + ' ' + self . last_name). strip()
FIXME: Get Full Name
597c684822bc9388f600010f
[ "Debugging" ]
https://www.codewars.com/kata/597c684822bc9388f600010f
7 kyu
Create a function to determine whether or not two circles are colliding. You will be given the position of both circles in addition to their radii: ```javascript function collision(x1, y1, radius1, x2, y2, radius2) { // collision? } ``` ```c bool IsCollision(float x1, float y1, float r1, float x2, float y2, float r2) // collision? } ``` ```python def collision(x1, y1, radius1, x2, y2, radius2): # collision? ``` If a collision is detected, return true. If not, return false. Here's a geometric diagram of what the circles passed in represent: ![alt text](https://cdn.tutsplus.com/gamedev/uploads/legacy/031_whenWorldsCollide/img4.png "Logo Title Text 1")
reference
from math import dist def collision(x1, y1, radius1, x2, y2, radius2): return radius1 + radius2 >= dist((x1, y1), (x2, y2))
Collision Detection
599da159a30addffd00000af
[ "Fundamentals" ]
https://www.codewars.com/kata/599da159a30addffd00000af
7 kyu
# Background I drink too much coffee. Eventually it will probably kill me. *Or will it..?* Anyway, there's no way to know. *Or is there...?* # The Discovery of the Formula I proudly announce my discovery of a formula for measuring the life-span of coffee drinkers! For * ```h``` is a health number assigned to each person (8 digit date of birth YYYYMMDD) * ```CAFE``` is a cup of *regular* coffee * ```DECAF``` is a cup of *decaffeinated* coffee To determine the life-time coffee limits: * Drink cups of coffee (i.e. add to ```h```) until any part of the health number includes `DEAD` * If the test subject can survive drinking <u>five thousand</u> cups wihout being ```DEAD``` then coffee has no ill effect on them # Kata Task Given the test subject's date of birth, return an array describing their life-time coffee limits ```[ regular limit , decaffeinated limit ]``` ## Notes * The limits are ```0``` if the subject is unaffected as described above * At least 1 cup must be consumed (Just thinking about coffee cannot kill you!) # Examples * <b>John</b> was born 19/Jan/1950 so ```h=19500119```. His coffee limits are ```[2645, 1162]``` which is only about 1 cup per week. You better cut back John...How are you feeling? You don't look so well. * <b>Susan</b> (11/Dec/1965) is unaffected by decaffeinated coffee, but regular coffee is very bad for her ```[111, 0]```. Just stick to the decaf Susan. * <b>Elizabeth</b> (28/Nov/1964) is allergic to decaffeinated coffee. Dead after only 11 cups ```[0, 11]```. Read the label carefully Lizzy! Is it worth the risk? * <b>Peter</b> (4/Sep/1965) can drink as much coffee as he likes ```[0, 0]```. You're a legend Peter!! <hr> Hint: https://en.wikipedia.org/wiki/Hexadecimal <hr> <div style='color:red'> *Note: A life-span prediction formula this accurate has got to be worth a lot of money to somebody! I am willing to sell my copyright to the highest bidder. Contact me via the discourse section of this Kata.* </div>
games
def coffee_limits(year, month, day): h = int(f' { year :0 4 }{ month :0 2 }{ day :0 2 } ') return [limit(h, 0xcafe), limit(h, 0xdecaf)] def limit(h, c): for i in range(1, 5000): h += c if 'DEAD' in f' { h : X } ': return i return 0
Death by Coffee
57db78d3b43dfab59c001abe
[ "Puzzles" ]
https://www.codewars.com/kata/57db78d3b43dfab59c001abe
6 kyu
# Task You are a spy. You lurk in the enemy's control zone. Your task is to get the length data of a railway, accurate to meters. Although you have taken all kinds of technical measures, you still haven't finished your task. Now, You can only use the last method: Take the train, record the sounds you hear, and then calculate the length of the railroad. You will hear these voices: ``` 1. "呜呜呜". This is the whistle of the train when it comes in or out of the station. That is, When you hear the sound for the first time, the train leaves the station and goes into high speed; When you hear the sound for the second time, The train pulled into the station and goes into low speed. and so on. 2. "哐当". This is the sound of the train hitting the railroad track. That is, Every time you hear it, the train advances 20 meters(high speed) or 10 meters(low speed). 3. Any other sound. These are all noise, please ignore them ;-) ``` # Examples ``` For sounds="呜呜呜哐当哐当哐当哐当哐当呜呜呜哐当哐当哐当哐当哐当" The output should be 150. For sounds="呜呜呜哐当哐当哐当哐当哐当呜呜呜哐当哐当哐当哐当哐当呜呜呜哐当哐当哐当哐当哐当呜呜呜哐当哐当哐当哐当哐当" The output should be 300. For sounds="呜呜呜哐当哐当面包饮料矿泉水了啊,哐当桶面火腿肠茶叶蛋了啊哐当哐当呜呜呜哐当哐当哐当北京站到了,下车的旅客请带好您的行李,准备下车哐当哐当" The output should be 150. ``` Happy Coding `^_^`
reference
def length_of_railway(sounds): sounds = sounds . replace('呜呜呜', 'a'). replace('哐当', 'b') result = 0 speed = 10 for sound in sounds: if sound == 'a': speed = 20 if speed != 20 else 10 elif sound == 'b': result += speed return result
Happy Coding : a Spy On the Train
599cf86d01a4108584000064
[ "Fundamentals" ]
https://www.codewars.com/kata/599cf86d01a4108584000064
6 kyu
How much bigger is a 16-inch pizza compared to an 8-inch pizza? A more pragmatic question is: How many 8-inch pizzas "fit" in a 16-incher? The answer, as it turns out, is exactly four 8-inch pizzas. For sizes that don't correspond to a round number of 8-inchers, you must <strong>round</strong> the number of <em>slices</em> (one 8-inch pizza = 8 slices), e.g.: ```python how_many_pizzas(16) -> "pizzas: 4, slices: 0" how_many_pizzas(12) -> "pizzas: 2, slices: 2" how_many_pizzas(8) -> "pizzas: 1, slices: 0" how_many_pizzas(6) -> "pizzas: 0, slices: 4" how_many_pizzas(0) -> "pizzas: 0, slices: 0" ``` ```crystal how_many_pizzas(16) -> "pizzas: 4, slices: 0" how_many_pizzas(12) -> "pizzas: 2, slices: 2" how_many_pizzas(8) -> "pizzas: 1, slices: 0" how_many_pizzas(6) -> "pizzas: 0, slices: 5" how_many_pizzas(0) -> "pizzas: 0, slices: 0" ``` ```javascript how_many_pizzas(16) -> "pizzas: 4, slices: 0" how_many_pizzas(12) -> "pizzas: 2, slices: 2" how_many_pizzas(8) -> "pizzas: 1, slices: 0" how_many_pizzas(6) -> "pizzas: 0, slices: 5" how_many_pizzas(0) -> "pizzas: 0, slices: 0" ``` ```ruby how_many_pizzas(16) -> "pizzas: 4, slices: 0" how_many_pizzas(12) -> "pizzas: 2, slices: 2" how_many_pizzas(8) -> "pizzas: 1, slices: 0" how_many_pizzas(6) -> "pizzas: 0, slices: 5" how_many_pizzas(0) -> "pizzas: 0, slices: 0" ``` ```swift how_many_pizzas(16) -> "pizzas: 4, slices: 0" how_many_pizzas(12) -> "pizzas: 2, slices: 2" how_many_pizzas(8) -> "pizzas: 1, slices: 0" how_many_pizzas(6) -> "pizzas: 0, slices: 5" how_many_pizzas(0) -> "pizzas: 0, slices: 0" ``` Get coding quick, so you can choose the ideal size for your next meal! <link href="https://afeld.github.io/emoji-css/emoji.css" rel="stylesheet"><i class="em em-pizza"></i>
reference
def how_many_pizzas(n): return 'pizzas: {}, slices: {}' . format(* divmod(n * n / / 8, 8))
8 inch pizza equivalence
599bb194b7a047b04d000077
[ "Geometry", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/599bb194b7a047b04d000077
6 kyu
Write a function that takes a string which has integers inside it separated by spaces, and your task is to convert each integer in the string into an integer and return their sum. ### Example ```python summy("1 2 3") ==> 6 ``` ```rust summy("1 2 3") -> 6 ``` ```julia summy("1 2 3") --> 6 ``` Good luck!
algorithms
def summy(string_of_ints): return sum(map(int, string_of_ints . split()))
Summy
599c20626bd8795ce900001d
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/599c20626bd8795ce900001d
7 kyu
Your friend asks you to explain the difference between the python string methods, `isdecimal()`, `isdigit()`, and `isnumeric()`. Create two lists to show the difference. The first list: `digits_not_decimals` should be a list with all the Unicode characters that are digits, but not decimals. The second list: `numeric_not_digits`should be a list with all the Unicode characters that are numeric but not digits.
reference
from sys import maxunicode as mu digits_not_decimals = [chr(c) for c in range( mu + 1) if chr(c). isdigit() and not chr(c). isdecimal()] numeric_not_digits = [chr(c) for c in range( mu + 1) if chr(c). isnumeric() and not chr(c). isdigit()]
So many kinds of numbers!
599b4e682b862b8498000021
[ "Fundamentals" ]
https://www.codewars.com/kata/599b4e682b862b8498000021
7 kyu
Write a function that, given a string of text (possibly with punctuation and line-breaks), returns an array of the top-3 most occurring words, in descending order of the number of occurrences. Assumptions: ------------ - A word is a string of letters (A to Z) optionally containing one or more apostrophes (`'`) in ASCII. - Apostrophes can appear at the start, middle or end of a word (`'abc`, `abc'`, `'abc'`, `ab'c` are all valid) - Any other characters (e.g. `#`, `\`, `/` , `.` ...) are not part of a word and should be treated as whitespace. - Matches should be case-insensitive, and the words in the result should be lowercased. - Ties may be broken arbitrarily. - If a text contains fewer than three unique words, then either the top-2 or top-1 words should be returned, or an empty array if a text contains no words. Examples: ------------ ``` "In a village of La Mancha, the name of which I have no desire to call to mind, there lived not long since one of those gentlemen that keep a lance in the lance-rack, an old buckler, a lean hack, and a greyhound for coursing. An olla of rather more beef than mutton, a salad on most nights, scraps on Saturdays, lentils on Fridays, and a pigeon or so extra on Sundays, made away with three-quarters of his income." --> ["a", "of", "on"] "e e e e DDD ddd DdD: ddd ddd aa aA Aa, bb cc cC e e e" --> ["e", "ddd", "aa"] " //wont won't won't" --> ["won't", "wont"] ``` Bonus points (not really, but just for fun): ------------ 1. Avoid creating an array whose memory footprint is roughly as big as the input text. 2. Avoid sorting the entire array of unique words.
algorithms
from collections import Counter import re def top_3_words(text): c = Counter(re . findall( r"[a-z']+", re . sub(r" '+ ", " ", text . lower()))) return [w for w, _ in c . most_common(3)]
Most frequently used words in a text
51e056fe544cf36c410000fb
[ "Strings", "Filtering", "Algorithms", "Regular Expressions" ]
https://www.codewars.com/kata/51e056fe544cf36c410000fb
4 kyu
An integer partition of `n` is a weakly decreasing list of positive integers which sum to `n`. For example, there are 7 integer partitions of 5: ```python [5], [4,1], [3,2], [3,1,1], [2,2,1], [2,1,1,1], [1,1,1,1,1]. ``` Write a function which returns the number of integer partitions of `n`. The function should be able to find the number of integer partitions of `n` for `n` at least as large as 100.
algorithms
def partitions(n, k=1, cache={}): if k > n: return 0 if n == k: return 1 if (n, k) in cache: return cache[n, k] return cache . setdefault((n, k), partitions(n, k + 1) + partitions(n - k, k))
Number of integer partitions
546d5028ddbcbd4b8d001254
[ "Mathematics", "Algorithms", "Discrete Mathematics" ]
https://www.codewars.com/kata/546d5028ddbcbd4b8d001254
4 kyu
The palindromic number `595` is interesting because it can be written as the sum of consecutive squares: `6^2 + 7^2 + 8^2 + 9^2 + 10^2 + 11^2 + 12^2 = 595`. There are exactly eleven palindromes below one-thousand that can be written as consecutive square sums. Note that `1 = 0^2 + 1^2` has not been included as this problem is concerned with the squares of positive integers. Given an input `n`, find the count of all the numbers less than `n` that are both palindromic and can be written as the sum of consecutive squares. For instance: `values(1000) = 11`. See test examples for more cases. Good luck! This Kata is borrowed from [Project Euler #125](https://projecteuler.net/problem=125) If you like this Kata, please try: [Fixed length palindromes](https://www.codewars.com/kata/59f0ee47a5e12962cb0000bf) [Divisor harmony](https://www.codewars.com/kata/59bf97cd4f98a8b1cd00007e)
algorithms
def values(n): pal = set() for i in range(1, int(n * * 0.5)): sos = i * i while sos < n: i += 1 sos += i * i if str(sos) == str(sos)[:: - 1] and sos < n: pal . add(sos) return len(pal)
Palindrome integer composition
599b1a4a3c5292b4cc0000d5
[ "Performance", "Algorithms" ]
https://www.codewars.com/kata/599b1a4a3c5292b4cc0000d5
5 kyu
## Task You're given an integer `n` (`0 <= n <= 10000`). You need to create a function which returns: 1. `Fizz` when `n` is divisible by `3` 2. `Buzz` when `n` is divisible by `5` 3. `Fizz Buzz` when `n` is divisible by both `3` and `5` 4. Otherwise it should return the string representation of `n` ## Restrictions Your code __mustn't__ contain: 1. `if` 2. `==` or `!=` 3. `+` or `-` 4. `str` (including `strip`, `lstrip`, `rstrip`) 5. `def` 6. `eval` or `exec` 7. `return` 8. `import` **The check for restricted words is case-insensitive.** ## Note: **Feel free to rate the kata when you finish it :)**
games
dic = { (0, 0): 'Fizz Buzz', (0, 1): 'Fizz', (1, 0): 'Buzz', (1, 1): 0 } def fizz_buzz(x): return ( dic[(min(x % 3, 1), min(x % 5, 1))] or '{}' . format(x))
Fizz Buzz (with restrictions)
584911a20d8b8f5b70000149
[ "Restricted", "Puzzles" ]
https://www.codewars.com/kata/584911a20d8b8f5b70000149
5 kyu
It's March and you just can't seem to get your mind off brackets. However, it is not due to basketball. You need to extract statements within strings that are contained within brackets. You have to write a function that returns a list of statements that are contained within brackets given a string. If the value entered in the function is not a string, well, you know where that variable should be sitting. Good luck!
reference
import re REGEX = re . compile(r'\[(.*?)\]') def bracket_buster(strng): try: return REGEX . findall(strng) except TypeError: return 'Take a seat on the bench.'
Bracket Buster
56ff322e79989cff16000e39
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/56ff322e79989cff16000e39
6 kyu
## Description We have a big list of jobs to do, and all of the jobs have been assigned a difficulty rating. Difficulties will be an integer, and they may be positive, negative or zero. Jim and Bob have the job of doing all the jobs, but we need to find the position in the container where we can make a cut so that Jim and Bob have the most even workload to perform. ## Kata Your task is to write a function that identifies the place to split the workload for Jim and Bob, it will be supplied with a container of difficulty ratings, and you must return a tuple/array with (the optimum location of the split, the difference between the two total workloads). If no workload is provided, then return `(None, None)`/`[null, null]`. ### Worked Example The workload we are give to split is as follows: ```python split_workload([1, 6, 2, 3, 5, 4, 1]) ``` ```javascript splitWorkload([1, 6, 2, 3, 5, 4, 1]) ``` If we try cutting at each position then: ``` Split Jim's work Bob's work Ratio Difference 0 [], [1, 6, 2, 3, 5, 4, 1] 0:22 22 1 [1] [6, 2, 3, 5, 4, 1] 1:21 20 2 [1, 6] [2, 3, 5, 4, 1] 7:15 8 3 [1, 6, 2] [3, 5, 4, 1] 9:13 4 4 [1, 6, 2, 3] [5, 4, 1] 12:10 2 5 [1, 6, 2, 3, 5] [4, 1] 17:5 12 6 [1, 6, 2, 3, 5, 4] [1] 21:1 20 7 [1, 6, 2, 3, 5, 4, 1] [] 22:0 22 ``` As you can see when we split at position 4, we get the most even split with a difference of only 2. In the event of a tie where the minimum difference occurs more than once, we take the first position that gives the most even split. Thus for our example, the result would be: ```python split_workload([1, 6, 2, 3, 5, 4, 1]) -> (4, 2) ``` ```javascript splitWorkload([1, 6, 2, 3, 5, 4, 1]) -> [4, 2] ``` You get self-awarded bonus points if your answer runs in `O(n)` time and memory constraints.
algorithms
def split_workload(workload): if not workload: return None, None diff = sum(workload) best_i, best_diff = None, float('inf') for i, work in enumerate(workload): if abs(diff) < best_diff: best_i, best_diff = i, abs(diff) # For each shift in the workload # the difference between workload changes by twice the work shifted diff -= 2 * work return best_i, best_diff
Evening up a workload
56431c04ed1454a35d00003b
[ "Lists", "Algorithms" ]
https://www.codewars.com/kata/56431c04ed1454a35d00003b
6 kyu
You're going on a trip with some students and it's up to you to keep track of how much money each Student has. A student is defined like this: ```ruby class Student attr_reader :name attr_reader :fives attr_reader :tens attr_reader :twenties def initialize(name, fives, tens, twenties) @name = name @fives = fives @tens = tens @twenties = twenties end end ``` ```python class Student: def __init__(self, name, fives, tens, twenties): self.name = name self.fives = fives self.tens = tens self.twenties = twenties ``` ```c #define NAMELIM 0x8 struct student { char name[NAMELIM + 1]; unsigned fives; unsigned tens; unsigned twenties; }; ``` ```nasm struc student .name: resb 9 alignb 4 .fives: resd 1 .tens: resd 1 .twenties: resd 1 endstruc student_sz equ 0h18 ``` ```javascript class Student { constructor(name, fives, tens, twenties) { this.name = name; this.fives = fives; this.tens = tens; this.twenties = twenties; } } ``` ```scala case class Student(name: String, fives: Int, tens: Int, twenties: Int) ``` As you can tell, each Student has some fives, tens, and twenties. Your job is to return the name of the student with the most money. If every student has the same amount, then return `"all"`. Notes: * Each student will have a unique name * There will always be a clear winner: either one person has the most, or everyone has the same amount * If there is only one student, then that student has the most money
algorithms
def most_money(students): total = [] for student in students: total . append((student . fives * 5) + (student . tens * 10) + (student . twenties * 20)) if min(total) == max(total) and len(students) > 1: return "all" else: return students[total . index(max(total))]. name
Who has the most money?
528d36d7cc451cd7e4000339
[ "Object-oriented Programming", "Algorithms" ]
https://www.codewars.com/kata/528d36d7cc451cd7e4000339
6 kyu
In this kata, we simply want to expand a matrix with some padding. For simplicity, we will take a square nxn matrix and expand it to a 2nx2n matrix. By expand I mean: ``` .------ n .------------------2n | | | fill | | | ===> | | | | | .--------n | n------ n | | | | | | | | | | | | | n--------n | | | 2n-----------------2n ``` in python the function signature is `def expand(matrix, fill)` matrix is the nxn matrix that you need to expand and fill is the value you should use for padding Oh and by the way, *n is divisible by 2* and *n >= 2* Finally, I give you `print_mat(m)` which will print matrix m for you in the console.
reference
def expand(maze, fill): unit = len(maze) / 2 brick = [fill] * unit block = [4 * brick] * unit return block + [brick + row + brick for row in maze] + block
matrix expanding
5568c4ed1597b393b6000066
[ "Arrays", "Fundamentals", "Matrix" ]
https://www.codewars.com/kata/5568c4ed1597b393b6000066
6 kyu
The built-in print function for Python class instances is not very entertaining. In this kata, we will implement a function ```show_me(instance)``` that takes an instance as parameter and returns the string ```"Hi, I'm one of those (classname)s! Have a look at my (attrs)."``` , where (classname) is the class name and (attrs) are the class's attributes. If (attrs) contains only one element, just write it. For more than one element (e.g. a, b, c), it should list all elements sorted by name in ascending order (e.g. "... look at my a, b and c."). Example: For an instance ```porsche = Vehicle(2, 4, 'gas')``` of the class ```python class Vehicle: def __init__(self, seats, wheels, engine): self.seats = seats self.wheels = wheels self.engine = engine ``` the function call ```show_me(porsche)``` should return the string ```"Hi, I'm one of those Vehicles! Have a look at my engine, seats and wheels."```.
reference
def show_me(instname): classname = instname . __class__ . __name__ attrs = " and" . join(", " . join(attr for attr in sorted( instname . __dict__ . keys())). rsplit(",", 1)) return f"Hi, I'm one of those { classname } s! Have a look at my { attrs } ."
You look like a classy instance! Show me what you've got! - Part 1
561f9d37e4786544e0000035
[ "Data Structures", "Strings", "Lists", "Fundamentals", "Object-oriented Programming" ]
https://www.codewars.com/kata/561f9d37e4786544e0000035
6 kyu
<font size=1px>Description overhauled by V</font> --- I've invited some kids for my son's birthday, during which I will give to each kid some amount of candies. Every kid hates receiving less amount of candies than any other kids, and I don't want to have any candies left - giving it to my kid would be bad for his teeth. However, not every kid invited will come to my birthday party. What is the minimum amount of candies I have to buy, so that no matter how many kids come to the party in the end, I can still ensure that each kid can receive the same amount of candies, while leaving no candies left? It's ensured that at least one kid will participate in the party.
algorithms
from math import lcm def candies_to_buy(amount_of_kids_invited): return lcm(* range(1, amount_of_kids_invited + 1))
Kids and candies
56cca888a9d0f25985000036
[ "Algorithms" ]
https://www.codewars.com/kata/56cca888a9d0f25985000036
6 kyu
In recreational mathematics, a magic square is an arrangement of distinct numbers (i.e., each number is used once), usually integers, in a square grid, where the numbers in each row, and in each column, and the numbers in the main and secondary diagonals, all add up to the same number, called the "magic constant." For example, the following "square": 4 9 2 -> 15 3 5 7 -> 15 8 1 6 -> 15 /v v v \ 15 15 15 15 15 A 3x3 magic square will have its sums always resulting to 15, this number is called the "magic constant" and changes according to the square size. In this problem you will have to create a function that receives a 3x3 'square' and returns True if it is magic and False otherwise. The sum of rows, columns or diagonals should **always** equal **15**. For example, the above square will be passed like: `[4, 9, 2, 3, 5, 7, 8, 1, 6]` and the output should be True `[9, 4, 7, 3, 5, 2, 8, 6, 1]` should return False ### Note: This kata is very easy. If you want to try some more "difficult" ones you may try these : * [Magic Square - Verify 3x3](https://www.codewars.com/kata/magic-square-verify-3x3) * [Double Even Magic Square](https://www.codewars.com/kata/double-even-magic-square) * [Odd Magic Square](https://www.codewars.com/kata/odd-magic-square)
reference
def is_magical(sq): return sum(sq[2: 7: 2]) == sum(sq[:: 4]) == sum(sq[:: 3]) == sum(sq[1:: 3]) == sum(sq[2:: 3]) == sum(sq[: 3]) == sum(sq[3: 6]) == sum(sq[6:])
Magic Square Validator
57be6a612eaf7cc3af000178
[ "Fundamentals" ]
https://www.codewars.com/kata/57be6a612eaf7cc3af000178
7 kyu
*Recreation of [Project Euler problem #6](https://projecteuler.net/problem=6)* Find the difference between the sum of the squares of the first `n` natural numbers `(1 <= n <= 100)` and the square of their sum. ## Example For example, when `n = 10`: * The square of the sum of the numbers is: (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10)<sup>2</sup> = 55<sup>2</sup> = 3025 * The sum of the squares of the numbers is: 1<sup>2</sup> + 2<sup>2</sup> + 3<sup>2</sup> + 4<sup>2</sup> + 5<sup>2</sup> + 6<sup>2</sup> + 7<sup>2</sup> + 8<sup>2</sup> + 9<sup>2</sup> + 10<sup>2</sup> = 385 Hence the difference between square of the sum of the first ten natural numbers and the sum of the squares of those numbes is: 3025 - 385 = 2640
reference
def difference_of_squares(x): r = range(1, x + 1, 1) return (sum(r) * * 2) - (sum(z * * 2 for z in r))
Difference Of Squares
558f9f51e85b46e9fa000025
[ "Fundamentals" ]
https://www.codewars.com/kata/558f9f51e85b46e9fa000025
7 kyu
[Currying and partial application](http://www.2ality.com/2011/09/currying-vs-part-eval.html) are two ways of transforming a function into another function with a generally smaller arity. While they are often confused with each other, they work differently. The goal is to learn to differentiate them. ## Currying > Is the technique of transforming a function that takes multiple arguments in such a way that it can be called as a chain of functions each with a single argument. Currying takes a function: ``` f: X × Y → R ``` and turns it into a function: ``` f': X → (Y → R) ``` Instead of calling `f` with two arguments, we invoke `f'` with the first argument. The result is a function that we then call with the second argument to produce the result. Thus, if the uncurried `f` is invoked as: ``` f(3, 5) ``` then the curried `f'` is invoked as: `f'(3)(5)` ### Example Given this function: ```javascript function add(x, y, z) { return x + y + z; } ``` ```python def add(x, y, z): return x + y + z ``` ```php function add($x, $y, $z) { return $x + $y + $z; } ``` We can call in a normal way: ```javascript add(1, 2, 3); //6 ``` ```python add(1, 2, 3) # => 6 ``` ```php add(1, 2, 3); //6 ``` But we can create a curried version of `add(a, b, c)`function: ```javascript function curriedAdd(a) { return function(b) { return function (c) { return add(a, b, c); }; }; } curriedAdd(1)(2)(3); //6 ``` ```python curriedAdd = lambda a: (lambda b: (lambda c: add(a,b,c))) curriedAdd(1)(2)(3) # => 6 ``` ```php function curriedAdd($a) { return function($b) use ($a) { return function($c) use ($a, $b) { return add($a, $b, $c); }; }; } curriedAdd(1)(2)(3); //6 ``` ## Partial application > Is the process of fixing a number of arguments to a function, producing another function of smaller arity. Partial application takes a function: ``` f: X × Y → R ``` and a fixed value `x` for the first argument to produce a new function ``` f': Y → R ``` `f'` does the same as `f`, but only has to fill in the second parameter which is why its arity is one less than the arity of `f`. One says that the first argument is bound to `x`. ### Example ```javascript function partialAdd(a) { return function(b, c) { return add(a, b, c); }; } partialAdd(1)(2, 3); //6 ``` ```python partialAdd = lambda a: (lambda *args: add(a,*args)) partialAdd(1)(2, 3) # => 6 ``` ```php function partialAdd($a) { return function($b, $c) use ($a) { return add($a, $b, $c); }; } partialAdd(1)(2, 3); //6 ``` ------------- Your work is to implement a generic `curryPartial()` function allows either currying or partial application. For example: ```javascript var curriedAdd = curryPartial(add); curriedAdd(1)(2)(3); //6 var partialAdd = curryPartial(add, 1); partialAdd(2, 3); //6 ``` ```python curriedAdd = curryPartial(add) curriedAdd(1)(2)(3) # => 6 partialAdd = curryPartial(add, 1) partialAdd(2, 3) # => 6 ``` ```php $add = function ($a, $b, $c) { return $a + $b + $c; }; $curriedAdd = curryPartial($add); $curriedAdd(1)(2)(3); //6 function add($a, $b, $c) { return $a + $b + $c; } $partialAdd = curryPartial('add', 1); $partialAdd(2, 3); //6 ``` We want the function be very flexible. All these examples should produce the same result: ```javascript curryPartial(add)(1)(2)(3); //6 curryPartial(add, 1)(2)(3); //6 curryPartial(add, 1)(2, 3); //6 curryPartial(add, 1, 2)(3); //6 curryPartial(add, 1, 2, 3); //6 curryPartial(add)(1, 2, 3); //6 curryPartial(add)(1, 2)(3); //6 curryPartial(add)()(1, 2, 3); //6 curryPartial(add)()(1)()()(2)(3); //6 curryPartial(add)()(1)()()(2)(3, 4, 5, 6); //6 curryPartial(add, 1)(2, 3, 4, 5); //6 ``` ```python curryPartial(add)(1)(2)(3) # =>6 curryPartial(add, 1)(2)(3) # =>6 curryPartial(add, 1)(2, 3) # =>6 curryPartial(add, 1, 2)(3) # =>6 curryPartial(add, 1, 2, 3) # =>6 curryPartial(add)(1, 2, 3) # =>6 curryPartial(add)(1, 2)(3) # =>6 curryPartial(add)()(1, 2, 3) # =>6 curryPartial(add)()(1)()()(2)(3) # =>6 curryPartial(add)()(1)()()(2)(3, 4, 5, 6) # =>6 curryPartial(add, 1)(2, 3, 4, 5) # =>6 ``` ```php curryPartial($add)(1)(2)(3); # =>6 curryPartial($add, 1)(2)(3); # =>6 curryPartial($add, 1)(2, 3); # =>6 curryPartial($add, 1, 2)(3); # =>6 curryPartial($add, 1, 2, 3); # =>6 curryPartial($add)(1, 2, 3); # =>6 curryPartial($add)(1, 2)(3); # =>6 curryPartial($add)()(1, 2, 3); # =>6 curryPartial($add)()(1)()()(2)(3); # =>6 curryPartial($add)()(1)()()(2)(3, 4, 5, 6); # =>6 curryPartial($add, 1)(2, 3, 4, 5); # =>6 ``` And also all of these: ```javascript curryPartial(curryPartial(curryPartial(add, 1), 2), 3); //6 curryPartial(curryPartial(add, 1, 2), 3); //6 curryPartial(curryPartial(add, 1), 2, 3); //6 curryPartial(curryPartial(add, 1), 2)(3); //6 curryPartial(curryPartial(add, 1)(2), 3); //6 curryPartial(curryPartial(curryPartial(add, 1)), 2, 3); //6 ``` ```python curryPartial(curryPartial(curryPartial(add, 1), 2), 3) # =>6 curryPartial(curryPartial(add, 1, 2), 3) # =>6 curryPartial(curryPartial(add, 1), 2, 3) # =>6 curryPartial(curryPartial(add, 1), 2)(3) # =>6 curryPartial(curryPartial(add, 1)(2), 3) # =>6 curryPartial(curryPartial(curryPartial(add, 1)), 2, 3) # =>6 ``` ```php curryPartial(curryPartial(curryPartial($add, 1), 2), 3); # =>6 curryPartial(curryPartial($add, 1, 2), 3); # =>6 curryPartial(curryPartial($add, 1), 2, 3); # =>6 curryPartial(curryPartial($add, 1), 2)(3); # =>6 curryPartial(curryPartial($add, 1)(2), 3); # =>6 curryPartial(curryPartial(curryPartial($add, 1)), 2, 3); # =>6 ```
reference
class CurryPartial: def __init__(self, func, * args): self . func = func self . args = args def __call__(self, * args): return CurryPartial(self . func, * (self . args + args)) def __eq__(self, other): try: return self . func(* self . args) == other except TypeError: return CurryPartial(self . func, * self . args[: - 1]) == other def curry_partial(f, * initial_args): "Curries and partially applies the initial arguments to the function" return CurryPartial(f, * initial_args)
Currying vs. Partial Application
53cf7e37e9876c35a60002c9
[ "Functional Programming" ]
https://www.codewars.com/kata/53cf7e37e9876c35a60002c9
4 kyu
The Ulam sequence `U` is defined by `u0 = u`, `u1 = v`, with the general term `uN` for `N > 2` given by the least integer expressible uniquely as the sum of two distinct earlier terms. In other words, the next number is always the smallest, unique sum of any two previous terms. Complete the function that creates an Ulam Sequence starting with the given `u0` and `u1`, and contains `n` terms. ## Example The first 10 terms of the sequence `U(u0=1, u1=2)` are: 1, 2, 3, 4, 6, 8, 11, 13, 16, 18. Let's see it in details: * The first term after the initial 1, 2 is obviously 3, because 1 + 2 = 3 * The next term is 1 + 3 = 4 (we don't have to worry about 4 = 2 + 2 since it is a sum of a *single term* instead of *distinct terms*) * 5 is not a member of the sequence since it is representable in two ways: 1 + 4 and 2 + 3 * 6 is a memeber, as 2 + 4 = 6 * etc. Description Reference: http://mathworld.wolfram.com/UlamSequence.html --- Performance version: https://www.codewars.com/kata/ulam-sequences-performance-edition
algorithms
from itertools import combinations from collections import defaultdict def ulam_sequence(u0, u1, n): seq = [u0, u1, u0 + u1] while len(seq) < n: candidates = defaultdict(int) for a, b in combinations(seq, 2): candidates[a + b] += 1 for num, pairs in sorted(candidates . items()): if num > seq[- 1] and pairs == 1: seq . append(num) break return seq
Ulam Sequences
5995ff073acba5fa3a00011d
[ "Number Theory", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5995ff073acba5fa3a00011d
6 kyu
The Stern-Brocot sequence is much like the Fibonacci sequence and has some cool implications. Let's learn about it: It starts with `[1, 1]` and adds **two** new terms every iteration: `nextTerm` which is the sum of a previous pair; and `termAfterThat` which is the second term of this previous pair. Here is how to find those terms: ``` [1, 1] + [nextTerm: 1 + 1 = 2; termAfterThat: 1] ==> [1, 1, 2, 1] ^ ^ ``` Then you shift the pairs with one index in the sequence: ``` [1, 1, 2, 1] + [1 + 2, 2] ==> [1, 1, 2, 1, 3, 2] ^ ^ ``` And so on... doing this for 2 more iterations will yield: ``` [1, 1, 2, 1, 3, 2, 3, 1, 4, 3] ``` Complete the code that takes a positive integer `n`, and returns the index of the first occurrence of `n` in the sequence. Note: indexing start at zero. ## Examples ``` [1, 1, 2, 1, 3, 2, 3, 1, 4, 3, ...] ^ ^ ^ n = 2 ==> 2 n = 3 ==> 4 n = 4 ==> 8 ```
algorithms
seq = [1, 1] for i in range(10 * * 4): a, b = seq[i: i + 2] seq . extend([a + b, b]) stern_brocot = seq . index
Stern-Brocot Sequence Part I
59986011d85bdd7fd7000621
[ "Number Theory", "Algorithms" ]
https://www.codewars.com/kata/59986011d85bdd7fd7000621
6 kyu
Consider the following series: `0,1,2,3,4,5,6,7,8,9,10,22,11,20,13,24...`There is nothing special between numbers `0` and `10`. Let's start with the number `10` and derive the sequence. `10` has digits `1` and `0`. The next possible number that does not have a `1` or a `0` is `22`. All other numbers between `10` and `22` have a `1` or a `0`. From `22`, the next number that does not have a `2` is `11`. Note that `30` is also a possibility because it is the next *higher* number that does not have a `2`, but we must select the *lowest* number that fits and **is not already in the sequence**. From `11`, the next lowest number that does not have a `1` is `20`. From `20`, the next lowest number that does not have a `2` or a `0` is `13`, then `24` , then `15` and so on. Once a number appers in the series, it cannot appear again. You will be given an index number and your task will be return the element at that position. See test cases for more examples. Note that the test range is `n <= 500`. Good luck! If you like this Kata, please try: [Sequence convergence](https://www.codewars.com/kata/59971e64bfccc70748000068) [https://www.codewars.com/kata/unique-digit-sequence-ii-optimization-problem](https://www.codewars.com/kata/unique-digit-sequence-ii-optimization-problem)
algorithms
masks = [0] * 10 for i in range(10 * * 4): for c in str(i): masks[int(c)] |= 1 << i def find_num(n): seq, x = 1, 0 for j in range(n): M = seq for m in masks: if x & m: M |= m x = ~ M & (M + 1) seq |= x return x . bit_length() - 1
Unique digits sequence
599688d0e2800dda4e0001b0
[ "Algorithms" ]
https://www.codewars.com/kata/599688d0e2800dda4e0001b0
5 kyu
The Abundancy (A) of a number `n` is defined as: ## (sum of divisors of n) / n For example: ```python A(8) = (1 + 2 + 4 + 8) / 8 = 15/8 A(25) = (1 + 5 + 25) / 25 = 31/25 ``` Friendly Pairs are pairs of numbers (m, n), such that their abundancies are equal: A(n) = A(m). Write a function that returns `"Friendly!"` if the two given numbers are a Friendly Pair. Otherwise return their respective abundacies as strings separated by a space, e.g. `"1 15/8"` Notes: - All fractions must be written in their most reduced form (e.g. `2/3` instead of `8/12`) - Every number that is being checked is under 2400 - Floats should be left on without rounding when you compare the abundancies of the two numbers ## Examples ```python n = 6, m = 28 ==> "Friendly!" n = 3, m = 9 ==> "4/3 13/9" ```
algorithms
from fractions import Fraction def getDivisors(x): for n in range(1, int(x * * .5) + 1): if not x % n: yield n if n != x / / n: yield x / / n def friendlyNumbers(m, n): a, b = sum(getDivisors(m)), sum(getDivisors(n)) return "Friendly!" if a / m == b / n else "{} {}" . format(Fraction(a, m), Fraction(b, n))
Friendly Pairs I
59974515b4c40be3cc000263
[ "Number Theory", "Algorithms" ]
https://www.codewars.com/kata/59974515b4c40be3cc000263
6 kyu
Consider the following series: `1, 2, 4, 8, 16, 22, 26, 38, 62, 74, 102, 104, 108, 116, 122` It is generated as follows: * For single digit integers, add the number to itself to get the next element. * For other integers, multiply all the non-zero digits and add the result to the original number to get the next element. For example: `16 + (6 * 1) = 22` and `104 + (4 * 1) = 108`. Let's begin the same series with a seed value of `3` instead of `1`: `3, 6, 12, 14, 18, 26, 38, 62, 74, 102, 104, 108, 116, 122` Notice that the two sequences converge at `26` and are identical therefter. We will call the series seeded by a value of `1` the "base series" and the other series the "test series". Let's look another test series that starts with `15` `15, 20, 22, 26, 38, 62, 74, 102, 104, 108, 116, 122` The sequences converge at `22` if the test series starts with `15` You will be given a seed value for the test series and your task will be to return the number of integers that have to be generated in the test series before it converges to the base series. In the case above: ``` convergence(3) = 5, the length of [3, 6, 12, 14, 18]. convergence(15) = 2, the length of [15, 20]. ``` Good luck! If you like this Kata, please try: [Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3) [Unique digit sequence](https://www.codewars.com/kata/599688d0e2800dda4e0001b0) [Divisor harmony](https://www.codewars.com/kata/59bf97cd4f98a8b1cd00007e)
algorithms
from operator import mul from functools import reduce def genSequence(n): yield n while True: n += reduce(mul, [int(d) for d in str(n) if d != '0']) if n > 9 else n yield n def extract(seq, v): return sorted(seq). index(v) def convergence(n): gen1, genN = genSequence(1), genSequence(n) seq1, seqN = {next(gen1)}, {next(genN)} while True: a, b = next(gen1), next(genN) seq1 . add(a) seqN . add(b) if a in seqN: return extract(seqN, a) if b in seq1: return extract(seqN, b)
Sequence convergence
59971e64bfccc70748000068
[ "Algorithms" ]
https://www.codewars.com/kata/59971e64bfccc70748000068
6 kyu
A [rock-paper-scissors](https://en.wikipedia.org/wiki/Rock%E2%80%93paper%E2%80%93scissors) robo player paticipates regularly in the same knockout tournament but almost always without succes. Can you improve this robo player and make it a tournament winner? <img style="height:200px" src="https://web.archive.org/web/20190219224406if_/http://blogs.discovermagazine.com/notrocketscience/files/2011/07/Rockpaperscissors.jpg" /> ### Task - A match is between 2 players. The first that wins 20 games of [Rock-Paper-Scissors](https://en.wikipedia.org/wiki/Rock%E2%80%93paper%E2%80%93scissors) is the winner of the match and continues to the next round. The other player is eliminated from the tournament. - If your bot wins 5 rounds, the final included, it has won the tournament. - The number of opponents is limited. Each opponent has its own strategy that does not change. - The tournament is played on the preloaded `RockPaperScissorsPlayground`: ```java RockPaperScissorsPlayground playground = new RockPaperScissorsPlayground(); boolean result = playground.playTournament(myPlayer); ``` ```csharp RockPaperScissorsPlayground playground = new RockPaperScissorsPlayground(); bool result = playground.PlayTournament(myPayer); ``` ```python playground = RockPaperScissorsPlayground() result = playground.play_tournament(myPlayer) ``` This kata starts with a working bot, altough it plays with a poor random strategy. It can compete on the `RockPaperScissorsPlayground` because it implements: ```java interface RockPaperScissorsPlayer { // Your name as displayed in match results. String getName(); // Used by playground to notify you that a new match will start. void setNewMatch(String opponentName); // Used by playground to get your game shape (values: "R", "P" or "S"). String getShape(); // Used by playground to inform you about the shape your opponent played in the game. void setOpponentShape(String shape); } ``` ```csharp public interface IRockPaperScissorsPlayer { // Your name as displayed in match results. string Name { get; } // Used by playground to notify you that a new match will start. void SetNewMatch(string opponentName); // Used by playground to get your game shape (values: "R", "P" or "S"). string GetShape(); // Used by playground to inform you about the shape your opponent played in the game. void SetOpponentShape(string shape); } ``` ```python class RockPaperScissorsPlayer: # Your name as displayed in match results. def get_name(self): pass # Used by playground to get your game shape (values: "R", "P" or "S"). def get_shape(self): pass # Used by playground to notify you that a new match will start. def set_new_match(self, opponentName): pass # Used by playground to inform you about the shape your opponent played in the game. def set_opponent_shape(self, shape): pass ``` #### Note The best way to solve this kata is: - Extend methods `get shape` and `set opponent shape` to make the patterns of your opponents visible to you and analyse their strategies and weaknesses. - If the strategy of an opponent is clear to you, adapt your bot to the opponent. - Continue until your bot can beat all opponents by skill instead of sheer luck.
algorithms
from itertools import cycle class Player (RockPaperScissorsPlayer): STRATEGIES = { 'Vitraj Bachchan': 'R', 'Sven Johanson': 'RRSPPR', 'Max Janssen': 'P', 'Bin Jinhao': 'RPRSPS', 'Jonathan Hughes': 'SRP', } def __init__(self): self . cycle = None def get_name(self): return "MyPlayer" def get_shape(self): return next(self . cycle) def set_new_match(self, opponentName): self . cycle = cycle(self . STRATEGIES . get(opponentName, 'S')) def set_opponent_shape(self, shape): pass
RPS Knockout Tournament Winner
58691792a44cfcf14700027c
[ "Games", "Algorithms", "Game Solvers", "Design Patterns", "Object-oriented Programming" ]
https://www.codewars.com/kata/58691792a44cfcf14700027c
6 kyu
Write a function that accepts two parameters (sum and multiply) and find two numbers [x, y], where x + y = sum and x * y = multiply. Example: sum = 12 and multiply = 32 In this case, x equals 4 and y equals 8. x = 4 y = 8 Because x + y = 4 + 8 = 12 = sum x \* y = 4 \* 8 = 32 = multiply The result should be [4, 8]. Note: 0 <= x <= 1000 0 <= y <= 1000 If there is no solution, your function should return null (or None in python). You should return an array (list in python) containing the two values [x, y] and it should be sorted in ascending order. One last thing: x and y are integers (no decimals).
algorithms
def sum_and_multiply(sum, multiply): for x in range(sum + 1): if x * (sum - x) == multiply: return [x, sum - x]
Sum and Multiply
59971206e06bbf4407002382
[ "Algorithms" ]
https://www.codewars.com/kata/59971206e06bbf4407002382
7 kyu
Since there are lots of katas requiring you to round numbers to 2 decimal places, you decided to extract the method to ease out the process. And you can't even get this right! Quick, fix the bug before everyone in CodeWars notices that you can't even round a number correctly!
bug_fixes
from decimal import Decimal, ROUND_HALF_UP def round_by_2_decimal_places(n): return n . quantize(Decimal('.01'), rounding=ROUND_HALF_UP)
Round and Round
5996eb39cdc8eb39f80000a0
[ "Fundamentals", "Debugging" ]
https://www.codewars.com/kata/5996eb39cdc8eb39f80000a0
6 kyu
## Task Generate a sorted list of all possible IP addresses in a network. For a subnet that is not a valid IPv4 network return `None`. ## Examples ``` ipsubnet2list("192.168.1.0/31") == ["192.168.1.0", "192.168.1.1"] ipsubnet2list("213.256.46.160/28") == None ```
reference
import ipaddress as ip def ipsubnet2list(subnet): try: return list(map(str, ip . ip_network(subnet). hosts())) except: pass
IPv4 subnet to list
5980d4e258a9f5891e000062
[ "Networks", "Fundamentals" ]
https://www.codewars.com/kata/5980d4e258a9f5891e000062
6 kyu
In this Kata, you will create a function that converts a string with letters and numbers to the inverse of that string (with regards to Alpha and Numeric characters). So, e.g. the letter `a` will become `1` and number `1` will become `a`; `z` will become `26` and `26` will become `z`. Example: `"a25bz"` would become `"1y226"` Numbers representing letters (`n <= 26`) will always be separated by letters, for all test cases: * `"a26b"` may be tested, but not `"a262b"` * `"cjw9k"` may be tested, but not `"cjw99k"` A list named `alphabet` is preloaded for you: `['a', 'b', 'c', ...]` A dictionary of letters and their number equivalent is also preloaded for you called `alphabetnums = {'a': '1', 'b': '2', 'c': '3', ...}`
games
import re def AlphaNum_NumAlpha(s): return re . sub(r'[0-9]+|[a-z]', lambda x: alphabet[(int(x . group()) - 1) % 26] if x . group(). isdigit() else str(alphabet . index(x . group()) + 1), s)
Alpha to Numeric and Numeric to Alpha
5995ceb5d4280d07f6000822
[ "Algorithms", "Strings" ]
https://www.codewars.com/kata/5995ceb5d4280d07f6000822
6 kyu
Write a code that receives an array of numbers or strings, goes one by one through it while taking one value out, leaving one value in, taking, leaving, and back again to the beginning until all values are out. It's like a circle of people who decide that every second person will leave it, until the last person is there. So if the last element of the array is taken, the first element that's still there, will stay. The code returns a new re-arranged array with the taken values by their order. The first value of the initial array is always taken. Examples: ```python arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] -> [1, 3, 5, 7, 9, 2, 6, 10, 8, 4] arr = ['this', 'code', 'is', 'right', 'the'] -> ['this', 'is', 'the', 'right', 'code'] ```
algorithms
from collections import deque def yes_no(arr): d, result = deque(arr), [] while d: result . append(d . popleft()) d . rotate(- 1) return result
Yes No Yes No
573c84bf0addf9568d001299
[ "Algorithms" ]
https://www.codewars.com/kata/573c84bf0addf9568d001299
6 kyu
When provided with a String, capitalize all vowels For example: Input : "Hello World!" Output : "HEllO WOrld!" Note: Y is not a vowel in this kata.
reference
def swap(st): tr = str . maketrans('aeiou', 'AEIOU') return st . translate(tr)
Changing letters
5831c204a31721e2ae000294
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/5831c204a31721e2ae000294
7 kyu
# Regular Expression for Binary Numbers Divisible by n Create a function that will return a regular expression string that is capable of evaluating binary strings (which consist of only `1`s and `0`s) and determining whether the given string represents a number divisible by `n`. ## Tests Inputs `1 <= n <= 18` will be tested Each `n` will be tested against random invalid tests and random valid tests (which may or may not pass the regex test itself, accordingly). ## Notes * Strings that are not binary numbers should be rejected. * Keep your solution under 5000 characters. This means you can't hard-code the answers. * Only these characters may be included in your returned string: ~~~if-not:c `01?:*+^$()[]|` ~~~ ~~~if:c `01?*+^$()|` (POSIX Extended Regular Expressions subset) ~~~ ~~~if:javascript ## Javascript Notes * Do **not** include the regex caps `/.../`. Your string will be used as such: `RegExp(regexDivisibleBy(3))` in the tests. * No funny business! There should be no need for prototyping, so don't even think about it. ~~~ ~~~if:python ## Python Notes * Whenever you use parentheses `(...)`, instead use non-capturing ones `(?:...)`. This is due to `module re`'s restriction in the number of capturing (or named) groups, which is capped at 99. * Each regex will be tested with `re.search`, so be sure to include both starting and ending marks in your regex. * The second anti-cheat test checks if you used any of `re`, `sys`, or `print` in your code. You won't need to print anything since each test will show what numbers your code is being tested on. ~~~ ~~~if:java ## Java Notes * The second anti-cheat test checks if you used any of `System`, `io`, `regex`, `zip` in your code. You won't need to print anything since each test will show what numbers your code is being tested on. ~~~ ~~~if:cpp ## C++ Notes * The second anti-cheat test checks if you used the STL's regex library in your code. * The macro constant `_GLIBCXX_REGEX_STATE_LIMIT` which limits the maximum size of a regex has been set to `400000`, as the default limit would be too constraining for the larger inputs. ~~~ ~~~if:kotlin ## Kotlin Notes * The second anti-cheat test checks if you used any of `System`, `io`, `regex`, `zip` in your code. You won't need to print anything since each test will show what numbers your code is being tested on. ~~~ ~~~if:ruby ## Ruby Notes * Each regex will be tested with `Regexp.new(string).match?(n.to_s(2))`, so be sure to include both starting and ending marks in your regex. * The second anti-cheat test checks if you used any of `Regexp`, `print`, `puts`... or even `p` in your code (so please avoid `p` as a variable name too!). You won't need to print anything since each test will show what numbers your code is being tested on. ~~~ ~~~if:rust ## Rust Notes * Each regex will be tested with `regex::Regex.is_match()`, so be sure to include both starting and ending marks in your regex. * The second anti-cheat test checks if you used the `regex` or `std::io` modules in your code; the tests will take care of compiling the regex string for you. ~~~
algorithms
def regex_divisible_by(n): if n == 1: return '^[01]*$' G = {(i, (2 * i + j) % n): str(j) for i in range(n) for j in (0, 1)} for k in range(n - 1, 0, - 1): loop = '' if (k, k) not in G else G[(k, k)] + '*' I = {i for i, j in G if i != k and j == k} J = {j for i, j in G if i == k and j != k} for i in I: for j in J: if (i, j) in G: G[(i, j)] = '(?:%s|%s)' % (G[(i, j)], G[(i, k)] + loop + G[(k, j)]) else: G[(i, j)] = '(?:%s)' % (G[(i, k)] + loop + G[(k, j)]) G = {c: G[c] for c in G if k not in c} return '^%s*$' % G[(0, 0)]
Regular Expression for Binary Numbers Divisible by n
5993c1d917bc97d05d000068
[ "Algorithms", "Puzzles", "Regular Expressions", "Strings" ]
https://www.codewars.com/kata/5993c1d917bc97d05d000068
1 kyu
Create a function that converts a given ASCII string to its hexadecimal SHA-256 hash. ``` sha256("Hello World!") => "7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069" ```
algorithms
from hashlib import sha256 def to_sha256(s): return sha256(s . encode('utf-8')). hexdigest()
SHA-256
587fb57e12fc6eadf200009b
[ "Strings", "Cryptography", "Algorithms" ]
https://www.codewars.com/kata/587fb57e12fc6eadf200009b
6 kyu
Write a function that verifies provided argument is either an integer or a floating-point number, returning true if it is or false otherwise. *__Pointers__* * Numeric quantities are _signed_ (optionally when positive, e.g. "+5" is valid notation) * Floats less than 1 (___not considering possible exponent!___) can be written without a leading "0" (e.g. ".00001") * Order-of-magnitude (i.e. 10, 100, 1000, etc.) can be written in [E notation](http://en.wikipedia.org/wiki/Scientific_notation) (the exponent is also signed, optionally so if positive, e.g. all the following are valid 1***e***2, 1***E***2, 1e***-***2, 1E-2, 1e***+***2) * Probably obvious, but no spaces are allowed anywhere (we aim to represent a real-life number) * __You can mix-n'-match any or all above pointers in any single numeric quantity__
games
def i_or_f(arr): # Your code here (and maybe somewhere else? Hint, hint) try: float(arr) return True except: return False
Float or Integer verifier
541a9774204d12252f00045d
[ "Regular Expressions", "Puzzles" ]
https://www.codewars.com/kata/541a9774204d12252f00045d
6 kyu
Implement a function `k_permutations_of_n` that accepts a list of elements `lst` and an integer `k`, and returns all permutations of elements from the list `lst`. Permutations should be a list containing all unique lists of `k` elements from `lst`, in any order. For example, if `lst == [1,2,3]` and `k == 2` the result should be: ```python [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]] ``` * if `k > len(lst)` the function should return an empty list, i.e.`[]` * if `k == 0`, the function should return `[[]]`, because there is exactly `1` way to arrange `0` elements (remember that `0! == 1`). You can assume that the input list `lst` contains unique elements.
algorithms
from itertools import permutations def k_permutations_of_n(lst: list, k: int) - > list: return [list(p) for p in permutations(lst, k)]
k-permutations of n
5592890bb4af624e930000b5
[ "Algorithms", "Recursion", "Permutations" ]
https://www.codewars.com/kata/5592890bb4af624e930000b5
6 kyu
Return the secret integer in a range based on the response from the `guess_bot`. You are given a low and high range (inclusive) and an instance of `GuessBot` (`guess_bot`). You are only to interact with `guess_bot` by its method: `guess_number(num)` which returns a string. `guess_bot` is a bit of an asshole and only returns the following strings when you call `guess_number(number)`: - ```'Smaller'```: Your guess is too big - ```'Larger'```: Your guess is too small - ```'Correct'```: Your guess is correct - ```'You failed, you bring great shame to your family name'```: You ran out of tries - ```'What are you, deaf?'```: Returned if you continously call guess_number after you already guessed the correct number __You only have log2(N) calls to guess_number before the bot starts calling you a failure. N is the number of possible integers in the [low, high] range.__ 1 <= N <= 10^14 low <= high Hint: use binary search
algorithms
def find_secret_number(low, high, f): while low <= high: mid = (low + high) / / 2 r = f . guess_number(mid) if r == 'Larger': low = mid + 1 elif r == 'Smaller': high = mid - 1 else: return mid
Guess the secret integer (binary search)
5749b2fc8bf8b6fbd3001ff3
[ "Algorithms" ]
https://www.codewars.com/kata/5749b2fc8bf8b6fbd3001ff3
6 kyu
Passer ratings are the generally accepted standard for evaluating NFL quarterbacks. I knew a rating of 100 is pretty good, but never knew what makes up the rating. So out of curiosity I took a look at the wikipedia page and had an idea or my first kata: https://en.wikipedia.org/wiki/Passer_rating ## Formula There are four parts to the NFL formula: ```python A = ((Completions / Attempts) - .3) * 5 B = ((Yards / Attempts) - 3) * .25 C = (Touchdowns / Attempts) * 20 D = 2.375 - ((Interceptions / Attempts) * 25) ``` However, if the result of any calculation is greater than `2.375`, it is set to `2.375`. If the result is a negative number, it is set to zero. Finally the passer rating is: `((A + B + C + D) / 6) * 100` Return the rating rounded to the nearest tenth. ## Example Last year Tom Brady had 432 attempts, 3554 yards, 291 completions, 28 touchdowns, and 2 interceptions. His passer rating was 112.2 Happy coding!
algorithms
def passer_rating(att, yds, comp, td, ints): def limit(x): return min(max(x, 0), 2.375) att = float(att) # for python 2 compatibility A = ((comp / att) - .3) * 5 B = ((yds / att) - 3) * .25 C = (td / att) * 20 D = 2.375 - ((ints / att) * 25) A, B, C, D = map(limit, (A, B, C, D)) return round((A + B + C + D) / 6 * 100, 1)
NFL Passer Ratings
59952e17f902df0e5f000078
[ "Algorithms" ]
https://www.codewars.com/kata/59952e17f902df0e5f000078
7 kyu
The `mystery` function is defined over the non-negative integers. The more common name of this function is concealed in order to not tempt you to search the Web for help in solving this kata, which most definitely would be a very dishonorable thing to do. Assume `n` has `m` bits. Then `mystery(n)` is the number whose binary representation is the entry in the table `T(m)` at index position `n`, where `T(m)` is defined recursively as follows: ``` T(1) = [0, 1] ``` `T(m + 1)` is obtained by taking two copies of `T(m)`, reversing the second copy, prepending each entry of the first copy with `0` and each entry of the reversed copy with `1`, and then concatenating the two. For example: ``` T(2) = [ 00, 01, 11, 10 ] ``` and ``` T(3) = [ 000, 001, 011, 010, 110, 111, 101, 100 ] ``` `mystery(6)` is the entry in `T(3)` at index position 6 (with indexing starting at `0`), i.e., `101` interpreted as a binary number. So, `mystery(6)` returns `5`. Your mission is to implement the function `mystery`, where the argument may have up to 63 bits. Note that `T(63)` is far too large to compute and store, so you'll have to find an alternative way of implementing `mystery`. ```if-not:commonlisp You are also asked to implement `mystery_inv` ( or `mysteryInv` ), the inverse of `mystery`. Finally, you are asked to implement a function `name_of_mystery` ( or `nameOfMystery` ), which shall return the name that `mystery` is more commonly known as. After passing all tests you are free to learn more about this function on Wikipedia or another place. ``` ```if:commonlisp You are also asked to implement `mystery-inv`, the inverse of `mystery`. Finally, you are asked to implement a function `mystery-name`, which shall return the name that `mystery` is more commonly known as. After passing all tests you are free to learn more about this function on Wikipedia or another place. ``` Hint: If you don't know the name of `mystery`, remember there is information in passing as well as failing a test.
reference
def mystery(n): return n ^ (n >> 1) def mystery_inv(n): mask = n >> 1 while mask != 0: n = n ^ mask mask = mask >> 1 return n def name_of_mystery(): return "Gray code"
Mystery Function
56b2abae51646a143400001d
[ "Fundamentals" ]
https://www.codewars.com/kata/56b2abae51646a143400001d
4 kyu
Please write a function that sums a list, but ignores any duplicate items in the list. For instance, for the list [3, 4, 3, 6] , the function should return 10.
reference
def sum_no_duplicates(l): return sum(n for n in set(l) if l . count(n) == 1)
Sum a list but ignore any duplicates
5993fb6c4f5d9f770c0000f2
[ "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/5993fb6c4f5d9f770c0000f2
7 kyu
You are provided with a skeleton of the class 'Fraction', which accepts two arguments (numerator, denominator). EXAMPLE: ```python fraction1 = Fraction(4, 5) ``` ```csharp Fraction fraction1 = new Fraction(4, 5); ``` ```haskell fraction1 = fraction 4 5 ``` ```java Fraction fraction1 = new Fraction(4, 5); ``` Your task is to make this class string representable, and addable while keeping the result in the minimum representation possible. EXAMPLE: ```python print (fraction1 + Fraction(1, 8)) outputs: 37/40 ``` ```csharp Console.Write(fraction1 + new Fraction(1, 8)); // Outputs: 37/40 ``` ```haskell show (fraction 1 + fraction 1 8) -- outputs: 37/40 ``` ```java System.out.println(fraction1.add(new Fraction(1, 8))); // Outputs: 37/40 ``` NB: DON'T use the built_in class 'fractions.Fraction' Enjoy!
reference
# Something goes Here ... class Fraction: def __init__(self, numerator, denominator): g = gcd(numerator, denominator) self . top = numerator / g self . bottom = denominator / g # Equality test def __eq__(self, other): first_num = self . top * other . bottom second_num = other . top * self . bottom return first_num == second_num # The rest goes here def __add__(self, other): numerator = self . top * other . bottom + self . bottom * other . top denominator = self . bottom * other . bottom return Fraction(numerator, denominator) def __str__(self): return str(self . top) + "/" + str(self . bottom) def gcd(x, y): if (y == 0): return x return gcd(y, x % y)
Fractions class
572bbd7c72a38bd878000a73
[ "Fundamentals", "Object-oriented Programming" ]
https://www.codewars.com/kata/572bbd7c72a38bd878000a73
6 kyu
Convert a hash into an array. Nothing more, Nothing less. ``` {name: 'Jeremy', age: 24, role: 'Software Engineer'} ``` should be converted into ``` [["age", 24], ["name", "Jeremy"], ["role", "Software Engineer"]] ``` ```if:python,javascript,crystal **Note**: The output array should be sorted alphabetically by key name. ``` Good Luck!
reference
def convert_hash_to_array(hash): return sorted(map(list, hash . items()))
Convert Hash To An Array
59557b2a6e595316ab000046
[ "Arrays", "Lists", "Fundamentals" ]
https://www.codewars.com/kata/59557b2a6e595316ab000046
7 kyu