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
Another Fibonacci... yes but with other kinds of result. The function is named `aroundFib` or `around_fib`, depending of the language. Its parameter is `n` (positive integer). First you have to calculate `f` the value of `fibonacci(n)` with `fibonacci(0) --> 0` and `fibonacci(1) --> 1` (see: <https://en.wikipedia.org/wiki/Fibonacci_number>) - 1) Find the count of each digit `ch` in `f` (`ch`: digit from 0 to 9), call this value `cnt` and find the maximum value of cnt; call this maximum value `maxcnt`. If there are ties, the digit `ch` to consider is the first one - in natural digit order - giving `maxcnt`. - 2) Cut the value `f` into chunks of length at most `25`. The last chunk may be 25 long or less. ``` Example: for `n=100` you have only one chunk `354224848179261915075` Example: for `n=180` f is `18547707689471986212190138521399707760` and you have two chunks `1854770768947198621219013` and `8521399707760`. First length here is 25 and second one is 13. ``` - At last return a string in the following format: "Last chunk ...; Max is ... for digit ..." where Max is `maxcnt` and digit the first `ch` (in 0..9) leading to `maxcnt`. ``` Example: for `n=100` -> "Last chunk 354224848179261915075; Max is 3 for digit 1" Example: for `n=180` -> "Last chunk 8521399707760; Max is 7 for digit 7" Example: for `n=18000` -> "Last chunk 140258776000; Max is 409 for digit 1" ``` #### Beware: `fib(18000)` has `3762` digits. Values of `n` are between `500` and `25000`. #### Note Please maybe ask before translating.
reference
def around_fib(n): a, b = 0, 1 for i in range(n - 1): a, b = b, a + b fib = str(b) lst = len(fib) % 25 if lst == 0: lst = 25 maxcnt = 0 digit = - 1 for i in '0123456789': c = fib . count(i) if c > maxcnt: maxcnt = c digit = i return "Last chunk {}; Max is {} for digit {}" . format(fib[- lst:], maxcnt, digit)
Around Fibonacci: chunks and counts
59bf943cafcda28e31000130
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/59bf943cafcda28e31000130
5 kyu
Given a certain number, how many multiples of three could you obtain with its digits? Suposse that you have the number 362. The numbers that can be generated from it are: ``` 362 ----> 3, 6, 2, 36, 63, 62, 26, 32, 23, 236, 263, 326, 362, 623, 632 ``` But only: ```3, 6, 36, 63``` are multiple of three. We need a function that can receive a number ann may output in the following order: - the amount of multiples - the maximum multiple Let's see a case the number has a the digit 0 and repeated digits: ``` 6063 ----> 0, 3, 6, 30, 36, 60, 63, 66, 306, 360, 366, 603, 606, 630, 636, 660, 663, 3066, 3606, 3660, 6036, 6063, 6306, 6360, 6603, 6630 ``` In this case the multiples of three will be all except 0 ``` 6063 ----> 3, 6, 30, 36, 60, 63, 66, 306, 360, 366, 603, 606, 630, 636, 660, 663, 3066, 3606, 3660, 6036, 6063, 6306, 6360, 6603, 6630 ``` The cases above for the function: ```python find_mult_3(362) == [4, 63] find_mult_3(6063) == [25, 6630] ``` In Javascript ```findMult_3()```. The function will receive only positive integers (num > 0), and you don't have to worry for validating the entries. Features of the random tests: ``` Number of test = 100 1000 ≤ num ≤ 100000000 ``` Enjoy it!!
reference
from itertools import permutations def find_mult_3(num): num_list = tuple(map(int, str(num))) poss = set() for i in range(1, len(num_list) + 1): poss |= set(permutations(num_list, i)) res = set() for p in poss: if p[0] != 0 and sum(p) % 3 == 0: res . add(p) res = [sum(x * 10 * * n for n, x in enumerate(p[:: - 1])) for p in res] return [len(res), max(res)]
Find All the Possible Numbers Multiple of 3 with the Digits of a Positive Integer.
5828b9455421a4a4e8000007
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic", "Strings", "Permutations" ]
https://www.codewars.com/kata/5828b9455421a4a4e8000007
5 kyu
Given a string, remove any characters that are unique from the string. Example: input: "abccdefee" output: "cceee"
algorithms
def only_duplicates(string): return "" . join([x for x in string if string . count(x) > 1])
Only Duplicates
5a1dc4baffe75f270200006b
[ "Fundamentals", "Strings", "Algorithms" ]
https://www.codewars.com/kata/5a1dc4baffe75f270200006b
6 kyu
# Task Given a person, trace their ancestory and create a <a href=https://en.wikipedia.org/wiki/Pedigree_chart>Pedigree Chart</a> Return the chart as a string. # Example Pedigree Chart for: XXXXX ``` |16 _______ |08 _______ | |17 _______ |04 _______ | | |18 _______ | |09 _______ | |19 _______ |02 _______ | | |20 _______ | | |10 _______ | | | |21 _______ | |05 _______ | | |22 _______ | |11 _______ | |23 _______ 01 XXXXX | |24 _______ | |12 _______ | | |25 _______ | |06 _______ | | | |26 _______ | | |13 _______ | | |27 _______ |03 _______ | |28 _______ | |14 _______ | | |29 _______ |07 _______ | |30 _______ |15 _______ |31 _______ ``` # Data There is a pre-loaded population of related and/or unrelated people. Useful attributes of each ```Person``` are exposed by methods: *Pseudo-code* ```java class Person { String sex() // "M" or "F" String name() List<Person> parents() } ``` ```python class Person: sex: str # "M" or "F" name: str parents() -> List[Person] ``` ```csharp class Person { string Sex() // "M" or "F" string Name() ImmutableList<Person> Parents() } ``` # Notes * Always create a chart of 31 people. If you are unable to fill in a name then write underscores ```_______``` instead, as shown in the example * Only go 4 generations deep. This Kata is only making a single chart. * With the exception of Person 01 all chart *even numbers are male* and all chart *odd numbers are female*. e.g. 06/07 are father/mother of 03. * The chart returned must be a ```\n``` separated string, with no trailing spaces on each line. The last line also ends with ```\n```. Please refer to test example for guidance.
algorithms
from itertools import islice from collections import deque result = ( " |16 {15}\n" + " |08 {7}\n" + " | |17 {16}\n" + " |04 {3}\n" + " | | |18 {17}\n" + " | |09 {8}\n" + " | |19 {18}\n" + " |02 {1}\n" + " | | |20 {19}\n" + " | | |10 {9}\n" + " | | | |21 {20}\n" + " | |05 {4}\n" + " | | |22 {21}\n" + " | |11 {10}\n" + " | |23 {22}\n" + "01 {0}\n" + " | |24 {23}\n" + " | |12 {11}\n" + " | | |25 {24}\n" + " | |06 {5}\n" + " | | | |26 {25}\n" + " | | |13 {12}\n" + " | | |27 {26}\n" + " |03 {2}\n" + " | |28 {27}\n" + " | |14 {13}\n" + " | | |29 {28}\n" + " |07 {6}\n" + " | |30 {29}\n" + " |15 {14}\n" + " |31 {30}\n"). format def gen(person): queue = deque([person]) while True: p = queue . popleft() if p is None: yield "_______" queue . append(None) queue . append(None) else: yield p . name p1, p2 = (p . parents() + (None, None))[: 2] if p1 and p1 . sex == "F": p1, p2 = p2, p1 queue . append(p1) queue . append(p2) def chart(person): return result(* islice(gen(person), 31))
Family Tree - Ancestors
5871690ba44cfc0834000303
[ "Algorithms" ]
https://www.codewars.com/kata/5871690ba44cfc0834000303
5 kyu
For this kata, we're given an image in which some object of interest (e.g. a face, or a license plate, or an aircraft) appears as a large block of contiguous pixels all of the same colour. (Probably some image-processing has already occurred to achieve this, but we needn't worry about that.) We want to find the **centre** of the object in the image. We'll do this by finding which pixels of the given colour have maximum depth. The depth of a pixel P is the minimum number of steps (up, down, left, or right) you have to take from P to reach either a pixel of a different colour or the edge of the image. ![pixel depths pic](http://www.stat.auckland.ac.nz/~geoff/codewars/pixeldepthspic.png) In the picture, the red pixel marked "3" has a depth of 3: it takes at least 3 steps from there to reach something other than another red pixel. Note that the steps need not be all in the same direction. Only one red pixel has depth 3: the one right in the middle of the red region. Similarly, the blue pixel marked "2" has a depth of 2 (but it is not the only one with this depth). The green and purple pixels all have depth 1. The pixels of a given colour with the largest depth will be found at the centre of the biggest solid region(s) of that colour. Those are the ones we want. The function you'll write (```central_pixels```) belongs to the following data structure: ```cpp struct Image { unsigned *pixels; unsigned width, height; vector<unsigned> central_pixels(unsigned colour) const; // other functions ... }; ``` ```c typedef struct { unsigned *pixels; unsigned width, height; } Image; ``` ```java public class Image { int[] pixels; int width, height; // functions ... } ``` ```javascript class Image { constructor(data, w, h) { this.pixels = data.slice(); this.width = w; this.height = h; } } ``` ```python class Image: def __init__(self, data, w, h): self.pixels = data self.width = w self.height = h ``` The image data consists of a one-dimensional array ```pixels``` of unsigned integers (or just integers, in languages that don't have unsigned integers as such), which correspond to pixels in row-by-row order. (That is, the top row of pixels comes first, from left to right, then the second row, and so on, with the pixel in the bottom right corner last of all.) The values of the ```pixels``` array elements represent colours via some one-to-one mapping whose details need not concern us. The ```central_pixels``` function should find and return all the positions (```pixels``` array indices) of the pixels having the greatest depth among all pixels of colour ```colour```). **Note 1.** The final test in the suite (```Big_Test```) is a 16-megapixel image (1 megapixel in the Python version), so you will need to consider the time and space requirements of your solution for images up to that size. **Note 2.** The order of pixel positions in the returned array is not important; sort them however you like. **Hint.** It is possible to get this done in **two** passes through the pixel data.
reference
class Central_Pixels_Finder (Image): def central_pixels(self, colour): size = self . width * self . height depths = [0] * size internal = [] for position, pcolour in enumerate(self . pixels): if pcolour == colour: depths[position] = 1 if (position > self . width and position < size - self . width and position % self . width and (position + 1) % self . width): internal . append(position) depths[position] += min(depths[position - 1], depths[position - self . width]) max_depth = 1 for position in internal[:: - 1]: depths[position] = min(depths[position], depths[position + 1] + 1, depths[position + self . width] + 1) max_depth = max(depths[position], max_depth) return [position for position, depth in enumerate(depths) if depth == max_depth]
Centre of attention
58c8c723df10450b21000024
[ "Algorithms", "Arrays" ]
https://www.codewars.com/kata/58c8c723df10450b21000024
3 kyu
<blockquote style="max-width:360px;min-width:200px;border-color:#777;background-color:#111;font-family:Georgia,Verdana,serif"><strong>&ldquo;Do you bite your thumb at us, sir?&rdquo;</strong><br/><p style="text-align:right;font-family:serif"><i>Romeo and Juliet</i> Act I: Sc. 1</p></blockquote> <p>Prince Escalus and the citizens of Verona have become weary of the ongoing blood-feud between the Montagues and the Capulets. Escalus has decided to settle the feud once and for all with a game of <a href='https://en.wikipedia.org/wiki/Tug_of_war' style="color:#9f9;text-decoration:none">tug of war</a> between the two houses, resulting in the losing family leaving the city.</p> <h2 style='color:#f88'>Objective</h2> <p>This version of tug of war will begin with one member from each house on opposite sides of the center line. Gradually over time, additional members from each house will join their respective side until a winner has been declared or there are no more additional participants.<br/> A house wins if the opposing house touches the center point.</p> <p>Your goal is to write a function that returns the winner between the two houses and the elapsed time when victory is declared.</p> <h2 style='color:#f88'>Input</h2> The function will accept two arguments: <ul> <li>An integer distance <code>n</code> between the two closest members of opposite families (see test example below)</li> <li>An array/list of subarrays. Each subarray will contain three integer values: <ul> <li>The pulling force of the participant from House Capulet</li> <li>The pulling force of the participant from House Montague</li> <li>The number of seconds since the last participants had joined the tug of war</li> </ul> </li> </ul> <p>Inputs will always be valid.</p> <h2 style='color:#f88'>Output</h2> An array with two elements: <ul> <li>The winning house: either <code>Montague</code> or <code>Capulet</code> (string)</li> <li>The elapsed time in seconds (integer)</li> </ul> <p>If the tug of war results in a deadlock, return <code>null</code> or <code>None</code>.</p> <p><span style="color:#f88"><b>Rope Movement</b></span><br/> When the aggregate pulling force on one side is equal to that of the other, there is no rope movement. If this is the state after all house members have joined the tug of war, the result is a deadlock.</p> <p>If one side has a greater aggregate pulling force, the rope moves at a rate of <code>n * decimeters/second</code> where <code>n</code> is the difference in total pulling force between the Capulets and Montagues currently engaaged in the tug of war.</p> <h2 style='color:#f88'>Test Example</h2> <div style='background:#000;display:flex;flex-direction:column;justify-content:center;width:370px;height:360px;padding:5px'><img src="https://i.imgur.com/sjRqcqJ.png" alt="status at 0 seconds"><br/><img src="https://i.imgur.com/Ol6B3ze.png" alt="status at 8 seconds"></div> <p style='font-size:0.9em'>The first image above represents the status at <code>0</code> seconds (<code>members[0]</code>).<br/> The image below it represents the status at <code>8</code> seconds (<code>members[1]</code>).</p> <ul> <li>In the above images, the solid green triangle marks the <span style='color:#00dc00'><b>center point</b></span>.</li> <li>At <code>0</code> seconds, a member from each side joins.<br/> <code>8</code> seconds later, the line will have moved <code>2.4</code> meters to the left. Another member from each house joins behind their respective preceding member.</li> </ul> ```javascript let members = [[35,32,0],[38,46,8],[27,24,12],[30,28,22],[39,36,31],[32,40,12],[28,18,6],[47,50,16]]; tugOfWar(20,members); //['Capulet', 154] ``` ```python members = [[35,32,0],[38,46,8],[27,24,12],[30,28,22],[39,36,31],[32,40,12],[28,18,6],[47,50,16]] tug_of_war(20,members) #['Capulet', 154] ``` If you enjoyed this kata, be sure to check out [my other katas](https://www.codewars.com/users/docgunthrop/authored).
algorithms
from decimal import Decimal from math import ceil DECI = Decimal(10) def tug_of_war(n, arr): n /= Decimal(2) pos = fm = fc = elapsed = 0 f = 0 for c_m, t in ((c / DECI - m / DECI, t) for c, m, t in arr): delta = f * t if abs(pos + delta) >= n: break pos += delta elapsed += t f += c_m if f: return ['Capulet' if f > 0 else 'Montague', elapsed + ceil((n + pos * (1 if f < 0 else - 1)) / abs(f))]
Shakespearean Tug of War
5a1a46ef80171fc2b0000064
[ "Algorithms" ]
https://www.codewars.com/kata/5a1a46ef80171fc2b0000064
6 kyu
Write a method that takes a number and returns a string of that number in English. Your method should be able to handle any number between 0 and 99999. If the given number is outside of that range or not an integer, the method should return an empty string. ## Examples ``` 0 --> "zero" 27 --> "twenty seven" 100 --> "one hundred" 7012 --> "seven thousand twelve" 99205 --> "ninety nine thousand two hundred five" ```
algorithms
def number_to_english(n): z = '''zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen''' D = {i: w for i, w in enumerate(z . split())} for i, w in enumerate('twenty thirty forty fifty sixty seventy eighty ninety' . split(), 2): D[i * 10] = w if not isinstance(n, int) or not (0 <= n <= 99999): return '' d, r = divmod(n, 1000) s = [number_to_english(d), 'thousand'] if d else [] d, r = divmod(r, 100) if d: s += [number_to_english(d), 'hundred'] if r and r in D: s, r = s + [D[r]], 0 d, r = divmod(r, 10) s += ([number_to_english(d * 10)] if d else []) + \ ([number_to_english(r)] if r else []) return ' ' . join(s) if s else D[0]
Ninety Nine Thousand Nine Hundred Ninety Nine
5463c8db865001c1710003b2
[ "Strings", "Parsing", "Algorithms" ]
https://www.codewars.com/kata/5463c8db865001c1710003b2
5 kyu
# Count distinct elements in every window of size k Given an array of size `n`, and an integer `k`, return the count of distinct contiguous numbers for all windows of size `k`. `k` will always be lower than or equal to `n`. ## Example ``` Input: array = {1, 2, 1, 3, 4, 2, 3} k = 4 Since we have n = 7 and k = 4, we have 4 windows with 4 contiguous elements. Answer: [3,4,4,3] ``` ## Explanation ``` 1st window is `{1, 2, 1, 3}`, which has `3` distinct numbers 2nd window is `{2, 1, 3, 4}`, which has `4` distinct numbers 3rd window is `{1, 3, 4, 2}`, which has `4` distinct numbers 4th window is `{3, 4, 2, 3}`, which has `3` distinct numbers ``` ## WARNING Be careful about performance: your function will have to manage `150` random tests with arrays of length between `10 000` and `20 000` and size of the window between `1 000` and `10 000` !
algorithms
from collections import Counter def count_contiguous_distinct(k, arr): counts = Counter(arr[: k]) distinct = len(counts) windows = [distinct] for i in range(k, len(arr)): counts[arr[i - k]] -= 1 if not counts[arr[i - k]]: distinct -= 1 if not counts[arr[i]]: distinct += 1 counts[arr[i]] += 1 windows . append(distinct) return windows
Distinct contiguous elements in every window of size k
5945f0c207693bc53100006b
[ "Arrays", "Performance", "Algorithms" ]
https://www.codewars.com/kata/5945f0c207693bc53100006b
5 kyu
When you were little, your mother used to make the most delicious cookies, which you could not resist. So, every now and then, when your mother didn't see you, you sneaked into the kitchen, climbed onto a stool to reach the cookie jar, and stole a cookie or two. However, sometimes while doing this, you would hear foot steps approaching, so you quickly jumped down from the stool and, when your mother entered the kitchen, you pretended as if nothing had happened (whistle, whistle innocently). However, your mother knew. How did she know? You forgot to put the lid back on the cookie jar! Oh, no! Growing older (and still not able to resist your mother's cookies), you deviced a contraption that would automatically put the lid back on the cookie jar, _no matter what would happen_. The class `CookieJar` is provided: ```Python class CookieJar(object): def __init__(self): self._is_open = False def take(self): if not self._is_open: raise ValueError("Cookie jar is closed") return "Cookie" def open_jar(self): self._is_open = True def close_jar(self): self._is_open = False def is_open(self): return self._is_open ``` Your task is to implement the 'contraption' `SelfClosing` (class, method, whatever; it's your choice) such that, given an instance`cookie_jar` of `CookieJar`, you may call: ```Python with SelfClosing(cookie_jar) as jar: cookie = jar.take() ``` after which, `cookie_jar.is_open() == False`, _no matter what_. Do not alter the provided code. (Tests will be performed with a code that differs slightly from the one provided, so modifying it is to no avail.) Enjoy!
reference
from contextlib import contextmanager @ contextmanager def SelfClosing(jar): try: jar . open_jar() yield jar finally: jar . close_jar()
Self-closing Cookie Jar
583b33786e3994f54e000142
[ "Object-oriented Programming", "Fundamentals" ]
https://www.codewars.com/kata/583b33786e3994f54e000142
5 kyu
Evaluate the given string with the given conditons. The conditions will be passed in an array and will be formatted like this: ``` {symbol or digit}{comparison operator}{symbol or digit} ``` Return the results in an array. The characters in the conditions will always be in the string. Characters in the string are chosen from ascii letters + `@#$%^&*()_{}[]` ## Example ```Python input string: "aab#HcCcc##l#" conditions: ["a<b", "#==4", "c>=C", "H!=a"] ``` The conditions in this example array can be interpreted as: * `"a<b"`: The number of times `"a"` occurs in the string should be less than the number of times `"b"` occurs in the string * `"#==4"`: `"#"` should occur exactly 4 times in the string * `"c>=C"`: `"c"` should occur greater than or equal to the number of times `"C"` occurs * `"H!=a"`: The number of times `"H"` occurs should not equal the number of times `"a"` occurs In this example condition 1 is `false` and 2, 3, 4 are `true`. So the return value will be an array as such: ```Python [False, True, True, True] ```
algorithms
from collections import Counter from operator import le, lt, ge, gt, eq, ne def string_evaluation(s, conditions): cnt = Counter(s) ops = {'<=': le, '<': lt, '>=': ge, '>': gt, '==': eq, '!=': ne} result = [] for condition in conditions: left = condition[0] right = condition[- 1] result . append(ops[condition[1: - 1]]( cnt[left] if not left . isdigit() else int(left), cnt[right] if not right . isdigit() else int(right) )) return result
String Evaluation
57f548337763f20e02000114
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/57f548337763f20e02000114
6 kyu
Your task is to validate rhythm with a meter. _________________________________________________ Rules: 1. Rhythmic division requires that in one whole note (1) there are two half notes (2) or four quarter notes (4) or eight eighth notes (8). <pre>Examples: 1 = 2 + 2, 1 = 4 + 4 + 4 + 4 ... Note that: 2 = 4 + 4, 4 = 8 + 8, 2 = 8 + 8 + 4 ... 2. Meter gives an information how many rhythmic types of notes should be in one bar. Bar is the the primary section of a musical score. <pre>Examples: 4/4 -> 4 quarter notes in a bar 5/2 -> 5 half notes in a bar 3/8 -> 3 eighth notes in a bar Note that: for 4/4 valid bars are: '4444', '88888888', '2488' ... for 5/2 valid bars are: '22222', '2244244', '8888244888844' ... for 3/8 valid bars are: '888', '48' ... 3. Anacrusis occurs when all bars but the first and last are valid, and the notes in the first and last bars when combined would also make a valid bar. <pre> Examples: for 4/4 valid anacrusis is -> 44|...|44 or 88|...|888888 or 2|...|488 for 5/2 valid anacrusis is -> 22|...|222 or 222|...|22 or 2244|...|244 for 3/8 valid anacrusis is -> 8|...|88 or 4|...|8 or 8|...|4 Note: When anacrusis is valid but other bars in score are not -> return 'Invalid rhythm' ________________________________________________ Input: <pre>meter - array: eg. [4, 4], score - string, bars separated with '|': eg. '4444|8484842|888' Output: string message: 'Valid rhythm', 'Valid rhythm with anacrusis' or 'Invalid rhythm'
reference
from fractions import Fraction VALID_CHARS = {"1", "2", "4", "8"} def note_sum(s): return sum(Fraction(1, x) for x in map(int, s)) def validate_rhythm(meter, score): if meter[1] not in [1, 2, 4, 8]: return "Invalid rhythm" ss = score . split("|") if not all(s and all(x in VALID_CHARS for x in s) for s in ss): return "Invalid rhythm" note = Fraction(* meter) if all(note_sum(s) == note for s in ss): return "Valid rhythm" ss[0] += ss . pop() if all(note_sum(s) == note for s in ss): return "Valid rhythm with anacrusis" return "Invalid rhythm"
#02 - Music Theory - Validate rhythm
57091b473f1008c03f001a2a
[ "Logic", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/57091b473f1008c03f001a2a
6 kyu
The task is very simple. You must to return pyramids. Given a number ```n``` you print a pyramid with ```n``` floors For example , given a ```n=4``` you must to print this pyramid: ``` /\ / \ / \ /______\ ``` Other example, given a ```n=6``` you must to print this pyramid: ``` /\ / \ / \ / \ / \ /__________\ ``` Another example, given a ```n=10```, you must to print this pyramid: ``` /\ / \ / \ / \ / \ / \ / \ / \ / \ /__________________\ ``` Note: a line feed character is needed at the end of the string. Case `n=0` should so return `"\n"`.
games
def pyramid(n): return '\n' . join("/{}\\" . format(" _" [r == n - 1] * r * 2). center(2 * n). rstrip() for r in range(n)) + '\n'
Return pyramids
5a1c28f9c9fc0ef2e900013b
[ "Strings", "Algorithms", "ASCII Art", "Puzzles" ]
https://www.codewars.com/kata/5a1c28f9c9fc0ef2e900013b
7 kyu
In a game of chess, a queen is the most powerful piece on the board. She can move an unlimited number of squares in a straight line in any of 8 directions (forwards, backwards, left, right, and each of the four diagonals in between). The diagram below shows the queen's influence from her current position - she would be able to take any piece on a square marked with an 'X'. <br> <figure> <img style="display:block; margin:auto;" src="https://s-media-cache-ak0.pinimg.com/originals/57/7f/04/577f04f3bd21238fd74626155968aeca.jpg"> </figure> <figcaption style="text-align:center; font-size:12px;"> Image from: https://www.pinterest.com/pin/567453621770398092/ </figcaption> <br> An opponent's king who can be taken by the queen is said to be in 'check', and would then need to find some way to escape this situation. In any normal game of chess, the queen would work with her army on an 8x8 board to threaten the king in this way, and ultimately try to win the game. However, for this kata, the queen will work by herself on a 5x5 board. The 5x5 chessboard will be represented as a 2 dimensional array, (ie: an array containing 5 other arrays, each containing 5 single character elements). Empty spaces within each sub-array will be represented by an asterix: ```"*"```, while one of these 25 elements will be represented by a ```"q"``` (queen) and a ```"k"``` (king). Both will be represented in lower case. The 2 dimensional chessboard array would look something like this: ```javascript var board = [ [ '*', '*', '*', '*', '*' ], [ '*', '*', '*', '*', 'k' ], [ '*', '*', '*', '*', '*' ], [ '*', 'q', '*', '*', '*' ], [ '*', '*', '*', '*', '*' ] ]; ``` Your task is to write a function which will return ```true``` if the king is in check, and ```false``` if he isn't. Click <a href="https://en.wikipedia.org/wiki/Chess">here</a> for a more in-depth instruction on chess.
reference
def check(board): for x, line in enumerate(board): for y, c in enumerate(line): if c == 'q': xq, yq = x, y elif c == 'k': xk, yk = x, y return yk == yq or xk == xq or abs(xq - xk) == abs(yq - yk)
Check by Queen
5a1cae0832b8b99e2900000c
[ "Fundamentals" ]
https://www.codewars.com/kata/5a1cae0832b8b99e2900000c
6 kyu
You are given an array of integers. Your task is to sort odd numbers within the array in ascending order, and even numbers in descending order. Note that zero is an even number. If you have an empty array, you need to return it. For example: ``` [5, 3, 2, 8, 1, 4] --> [1, 3, 8, 4, 5, 2] odd numbers ascending: [1, 3, 5 ] even numbers descending: [ 8, 4, 2] ```
reference
def sort_array(xs): es = sorted(x for x in xs if x % 2 == 0) os = sorted((x for x in xs if x % 2 != 0), reverse=True) return [(es if x % 2 == 0 else os). pop() for x in xs]
Sort odd and even numbers in different order
5a1cb5406975987dd9000028
[ "Arrays", "Fundamentals", "Sorting" ]
https://www.codewars.com/kata/5a1cb5406975987dd9000028
6 kyu
<h1>Happy traveller [Part 2]</h1> <p>In the <a href="https://www.codewars.com/kata/happy-traveller-number-1">previous part</a> we calculated possible ways to reach point <b>X</b>.</p> <p>For this time you become a treasure hunter! On each step you can get the reward. But in some points you can meet robbers or thieves. In order to continue your journey safe, you have to pay them.</p> <p>Accidentally you have found a map, indicating all that points, like this:</p> <pre> 0 1 2 3 0 [-1, 2, 3, 5] 1 [ 2, -2, 5, -1] 2 [ 0, 0, -5, 0] 3 [ 4, -1, 7, 2] </pre><br> <p>So, your new <b>TASK is to find the maximum possible accumulated cash</b> in order to decide wich way to go =) <blockquote> As before, a play grid is NxN and Always square! <p> You start from a random point. I mean, you are given the coordinates of your start position in format (row, col). </p> From any point you can go only <b>UP</b> or <b>RIGHT</b>. </p> <p>Assume input params are always valid. </p> </blockquote> <p> Implement a function <b>count_cash(MAP, (row, col))</b> which returns int; MAP is random 2d array of signed integers</p> Example: <ul> <li></li> <li>count_cash(1, (0, 0))<br> <pre> you map [@] [5] </pre> You are already in the target point, so dig out your treasure and return 5 </li> <li></li> <li> count_cash(MAP, (1, 0))<br> <pre> you map [o, X] [1, 0] [@, o] [0, 2] </pre> You are at point @; you can move UP-RIGHT(and gain 0+1+0 coins) or RIGHT-UP (0+2+0), 2>1, so return 2. </li> <li></li> <li>count_cash(MAP, (1, 1))<br> <pre> you map [o, X] [ 1, -6] [o, @] [-2, 3] </pre> You are at point @; you can move only UP(3-6), you have not enough money, so you probably die ^^. Anyway return the result: -3 </li> <li></li> <li>count_cash(MAP, (1, 0))<br> <pre> you map [o, o, X] [ 2, 3, -1] [@, o, o] [-1, 5, -2] [o, o, o] [ 4, -2, 6] </pre> You are at point @; you can move UP-RIGHT-RIGHT (-1+2+3-1=3) or RIGHT-UP-RIGHT(-1+5+3-1=6), or RIGHT-RIGHT-UP(-1+5-2-1=1), so just return 6 </li> </ul><br> I think it's pretty clear =) <br><br> btw. you can use preloaded Grid class, which constructs 2d array for you. It's very very basic and simple. You can use numpy instead or any other way to produce the correct answer =) <code> grid = Grid(2, 2, 0)<br> samegrid = Grid.square(2)</code> will give you a grid[2][2], which you can print easily to console. <code> print(grid) </code> <pre> [0, 0] [0, 0] </pre> Enjoy! to be continued...
algorithms
def count_cash(MAP, coords): lenY, (r, c) = len(MAP), coords s = [float("-inf")] * (len(MAP[0]) - c + 1) s[1] = 0 for x in range(r, - 1, - 1): for i in range(1, len(s)): s[i] = max(s[i - 1], s[i]) + MAP[x][c + i - 1] return s[- 1]
Happy traveller [#2]
586e2bc03f3675a4e70000e1
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/586e2bc03f3675a4e70000e1
5 kyu
Write a function generator that will generate the first `n` primes grouped in tuples of size `m`. If there are not enough primes for the last tuple it will have the remaining values as `None`. ## Examples ```python For n = 11 and m = 2: (2, 3), (5, 7), (11, 13), (17, 19), (23, 29), (31, None) For n = 11 and m = 3: (2, 3, 5), (7, 11, 13), (17, 19, 23), (29, 31, None) For n = 11 and m = 5: (2, 3, 5, 7, 11), (13, 17, 19, 23, 29), (31, None, None, None, None)] For n = 3 and m = 1: (2,), (3,), (5,) ``` Note: large numbers of `n` will be tested, up to 50000
reference
from gmpy2 import next_prime as np def get_primes(h, g): a = 2 while h > 0: m, f = g, [] while m > 0: a, f, m, h = np(a), f + [a] if h > 0 else f + [None], m - 1, h - 1 yield tuple(f)
Group prime numbers
593e8d839335005b42000097
[ "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/593e8d839335005b42000097
6 kyu
### Story You are a h4ck3r n00b: you "acquired" a bunch of password hashes, and you want to decypher them. Based on the length, you already guessed that they must be SHA-1 hashes. You also know that these are weak passwords: maximum 5 characters long and use only lowercase letters (`a-z`), no other characters. Happy hacking! **Notes:** * pre-generating the full hash table is not advised, due to the time-limit on the CW platform * there will be only a few tests for 5-letter words *(hint: start from the beginning of the alphabet)* * if your solution times out, try running it again - the CW runner is sometimes a bit slow(er) --- ### My other katas If you enjoyed this kata then please try [my other katas](https://www.codewars.com/users/anter69/authored)! :-) #### *Translations are welcome!*
algorithms
import hashlib import itertools def password_cracker(hash): for length in range(6): for candidate in map("" . join, itertools . product("abcdefghijklmnopqrstuvwxyz", repeat=length)): if hashlib . sha1(candidate . encode()). hexdigest() == hash: return candidate
Real Password Cracker
59146f7b4670ba520900000a
[ "Security", "Cryptography", "Algorithms" ]
https://www.codewars.com/kata/59146f7b4670ba520900000a
6 kyu
# Minesweeper Write a program that adds the numbers to a minesweeper board Minesweeper is a popular game where the user has to find the mines using numeric hints that indicate how many mines are directly adjacent (horizontally, vertically, diagonally) to a square. In this exercise you have to create some code that counts the number of mines adjacent to a square and transforms boards like this (where `*` indicates a mine): +-----+ | * * | | * | | * | | | +-----+ into this: +-----+ |1*3*1| |13*31| | 2*2 | | 111 | +-----+ ``` python inp = ["+------+", "| * * |", "| * |", "| * |", "| * *|", "| * * |", "| |", "+------+"] board(inp) ["+------+", "|1*22*1|", "|12*322|", "| 123*2|", "|112*4*|", "|1*22*2|", "|111111|", "+------+"] ``` Implementation note: The board function must validate its input and raise a ValueError/Error with a meaningfull error message if the input turns out to be malformed.
games
def board(inp): return ["" . join([ret(i, k, z) for k, z in enumerate(j)]) for i, j in enumerate(inp)] def ret(i, j, s): if s in {"+", "-", "|", "*"}: return s t = sum(1 for m in range(j - 1, j + 2) for l in range(i - 1, i + 2) if inp[l][m] == "*") return str(t) if t else " "
Minesweeper
587b2ddb87264729e6000128
[ "Algorithms", "Puzzles" ]
https://www.codewars.com/kata/587b2ddb87264729e6000128
6 kyu
Section numbers are strings of dot-separated integers. The highest level sections (chapters) are numbered 1, 2, 3, etc. Second level sections are numbered 1.1, 1.2, 1.3, 2.1, 2.2, 2.3, etc. Next level sections are numbered 1.1.1, 1.1.2, 1.1.2, 1.2.1, 1.2.2, erc. There is no bound on the number of sections a document may have, nor is there any bound on the number of levels. A section of a certain level may appear directly inside a section several levels higher without the levels between. For example, section 1.0.1 may appear directly under section 1, without there being any level 2 section. Section 1.1 comes after section 1.0.1. Sections with trailing ".0" are considered to be the same as the section with the trailing ".0" truncated. Thus, section 1.0 is the same as section 1, and section 1.2.0.0 is the same as section 1.2. ```if:python Write a function `compare(section1, section2)` that returns `-1`, `0`, or `1` depending on whether `section1` is before, same as, or after `section2` respectively. ``` ```if:javascript Write a function `cmp(section1, section2)` that returns `-1`, `0`, or `1` depending on whether `section1` is before, same as, or after `section2` respectively. ``` ```if:haskell Write a function `cmp section1 section2` that returns `LT`, `EQ` or `GT` depending on whether `section1` is before, same as, or after `section2` respectively. ```
reference
def compare(s1, s2): v1, v2 = version(s1), version(s2) return - 1 if v1 < v2 else 1 if v1 > v2 else 0 def version(s): v = [int(n) for n in s . split(".")] while (v[- 1] == 0): v = v[0: - 1] return v
Compare section numbers
5829c6fe7da141bbf000021b
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/5829c6fe7da141bbf000021b
6 kyu
Everyday we go to different places to get our things done. Those places can be represented by specific location points `[ [<lat>, <long>], ... ]` on a map. I will be giving you an array of arrays that contain coordinates of the different places I had been on a particular day. Your task will be to find `peripheries (outermost edges)` of the bounding box that contains all the points. The response should only contain `Northwest and Southeast` points as follows: `{ "nw": [<lat>, <long>], "se": [ <lat>, <long>] }`. You are adviced to draw the points on a 2D plan to visualize: ``` N ^ p(nw) ______________|________________ | | | | | all other | | | points | | | | ----------------------------------------> E | | | | all other | | | points | | |______________|________________| | p(se) ```
reference
def box(coords): lat, long = zip(* coords) return {"nw": [max(lat), min(long)], "se": [min(lat), max(long)]}
Northwest and Southeast corners
58ed139326f519019a000053
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/58ed139326f519019a000053
6 kyu
The local transport authority is organizing an online picture contest. Participants must take pictures of transport means in an original way, and then post the picture on Instagram using a specific ```hashtag```. The local transport authority needs your help. They want you to take out the ```hashtag``` from the posted message. Your task is to implement the function ```void omit_hashtag(char* message, const char* hashtag)``` ## Examples ``` * ("Sunny day! #lta #vvv", "#lta") -> "Sunny day! #vvv" (notice the double space) * ("#lta #picture_contest", "#lta") -> " #picture_contest" ``` ## Notes * When multiple occurences of the hashtag are found, delete only the first one. * You should modify the ```message```, as the function returns a void type. * There can be erroneous messages where the hashtag isn't present. The message should in this case stay untouched. * The hashtag only consists of alphanumeric characters.
reference
def omit_hashtag(message, hashtag): return message . replace(hashtag, "", 1)
Picture Contest - Extract the message
5a06238a80171f824300003c
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5a06238a80171f824300003c
7 kyu
Same as [the original](https://www.codewars.com/kata/simple-fun-number-258-is-divisible-by-6) (same rules, really, go there for example and I strongly recommend completing it first), but with more than one asterisk (but always at least one). For example, `"*2"` should return `["12", "42", "72"]`. Similarly, `"*2*"` should return `["024", "120", "126", "222", "228", "324", "420", "426", "522", "528", "624", "720", "726", "822", "828", "924"]`. Order matters and returning the right one is part of the challenge itself, yep! More examples in the test codes and, of course, if you cannot generate any number divisible by 6, just return `[]` (or `[] of String` in Crystal).
reference
from itertools import product def is_divisible_by_6(s): if s[- 1] in '13579': return [] ss = s . replace('*', '{}') return [v for v in (ss . format(* p) for p in product(* (['0123456789'] * s . count('*')))) if not int(v) % 6]
Is Divisible By 6 Mk II
5a1a8b7ec374cbea92000086
[ "Permutations", "Strings", "Combinatorics", "Number Theory", "Fundamentals" ]
https://www.codewars.com/kata/5a1a8b7ec374cbea92000086
6 kyu
Two students are giving each other test answers during a test. They don't want to be caught so they are sending each other coded messages. For example one student is sending the following message: `"Answer to Number 5 Part b"`. He starts with a square grid (in this example a 5x5 grid) and he writes the message down, including with spaces: ``` Answe r to Numbe r 5 P art b ``` He then starts writing the message down one column at a time, from the top to the bottom. The encoded message is now: `"ArNran u rstm5twob e ePb"` You are the teacher of this class. Your job is to decipher the messages and bust the students. ## Task Complete the function that takes one parameter (the encoded message) and return the original message. **Note:** The length of the string is always going to be a perfect square. Have fun !!!
games
def decipherMessage(s): ll = int(len(s) * * 0.5) return '' . join(s[i:: ll] for i in range(ll))
Decipher Student Messages
5a1a144f8ba914bbe800003f
[ "Strings", "Ciphers" ]
https://www.codewars.com/kata/5a1a144f8ba914bbe800003f
6 kyu
Your task is to write a function ```angle_planes(lstPts)``` that calculates the [angle between two planes](http://www.vitutor.com/geometry/distance/angle_planes.html), each of them being defined by a [tuple of three points](http://www.had2know.com/academics/equation-plane-through-3-points.html). Input: > lstPts – list of 6 tuples that contain 3 coordinates: x, y and z for each point. The first three points are defining the first plane, the second three are for the second one. All coordinates are integers. Output: > A float: the angle between the two planes in [radians](https://en.wikipedia.org/wiki/Radian) and rounded off to 2 decimal places. Example: ```python angle_planes([(2,1,2),(1,2,2),(2,2,0), (2,0,0),(2,0,2),(0,2,2)]) ``` Should return ``` 0.34 ```
algorithms
import numpy as np def angle_planes(lstPts): vectPlans = [np . cross(np . subtract(p1, p2), np . subtract(p1, p3)) for p1, p2, p3 in [lstPts[: 3], lstPts[3:]]] n1, n2, vp = map(np . linalg . norm, vectPlans + [np . cross(* vectPlans)]) return round(np . arcsin(vp / (n1 * n2)), 2)
Angle between two planes
57de888c758d9ebfd7000061
[ "Geometry", "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/57de888c758d9ebfd7000061
6 kyu
Given an array containing only zeros and ones, find the index of the zero that, if converted to one, will make the longest sequence of ones. For instance, given the array: ``` [1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1] ``` replacing the zero at index 10 (counting from 0) forms a sequence of 9 ones: ``` [1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1] '------------^------------' ``` Your task is to complete the function that determines where to replace a zero with a one to make the maximum length subsequence. **Notes:** - If there are multiple results, return the last one: `[1, 1, 0, 1, 1, 0, 1, 1] ==> 5` - The array will always contain only zeros and ones. Can you do this in one pass?
algorithms
def replace_zero(arr): m, im, i, lst = 0, - 1, - 1, '' . join(map(str, arr)). split('0') for a, b in zip(lst, lst[1:]): i += len(a) + 1 candidate = len(a) + len(b) + 1 if m <= candidate: im, m = i, candidate return im
Zeros and Ones
5a00a8b5ffe75f8888000080
[ "Puzzles", "Logic", "Algorithms" ]
https://www.codewars.com/kata/5a00a8b5ffe75f8888000080
6 kyu
A person's _Life Path Number_ is calculated by adding each individual number in that person's date of birth, until it is reduced to a single digit number. Complete the function that accepts a date of birth (as a string) in the following format: `"yyyy-mm-dd"`. The function shall return a one digit integer between 1 and 9 which represents the Life Path Number of the given date of birth. You do not need to check that the input is correct format, you can assume that it will always be a valid date (as a string) with given format. ### Example For example, Albert Einstein's birthday is March 14, 1879 (`"1879-03-14"`). The calculation of his Life Path Number would look like this: ``` year : 1 + 8 + 7 + 9 = 25 --> 2 + 5 = 7 month : 0 + 3 = 3 day : 1 + 4 = 5 result: 7 + 3 + 5 = 15 --> 1 + 5 = 6 ``` Einstein's Life Path Number is therefore: 6
reference
def life_path_number(s): return int(s . replace("-", "")) % 9 or 9
Life Path Number
5a1a76c8a7ad6aa26a0007a0
[ "Recursion", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/5a1a76c8a7ad6aa26a0007a0
7 kyu
Given a sequence of integers, return the sum of all the integers that have an even index (odd index in COBOL), multiplied by the integer at the last index. Indices in sequence start from 0. If the sequence is empty, you should return 0.
reference
def even_last(numbers): return sum(numbers[:: 2]) * numbers[- 1] if numbers else 0
Evens times last
5a1a9e5032b8b98477000004
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5a1a9e5032b8b98477000004
7 kyu
# Context According to <a href="https://en.wikipedia.org/wiki/Seventh_son_of_a_seventh_son">Wikipedia</a> : "The seventh son of a seventh son is a concept from folklore regarding special powers given to, or held by, such a son. **The seventh son must come from an unbroken line with no female siblings born between, and be, in turn, born to such a seventh son.**" # Your task You will be given a string of JSON, consisting of a family tree containing people's names, genders and children. Your task will be to find the seventh sons of seventh sons in the family tree, and return a __set__ of their names. If there are none, return an __empty set__. ## Tips * Have a good look at the sample test cases. * For a seventh son to be a seventh son, there must not be any daughters in the line leading to him. There may be daughters after him, though. * **You may want to use the json module for this one.**
reference
import json def f(data, level): if level == 0: yield data['name'] return children = data['children'] if len(children) >= 7 and all(child['gender'] == 'male' for child in children[: 7]): yield from f(children[6], level - 1) for child in children: yield from f(child, 2) def find_seventh_sons_of_seventh_sons(jstring): data = json . loads(jstring) return set(f(data, 2))
Seventh JSON of a seventh JSON
5a15b54bffe75f31990000e0
[ "JSON", "Recursion", "Fundamentals" ]
https://www.codewars.com/kata/5a15b54bffe75f31990000e0
6 kyu
Complete the function that counts the number of unique consonants in a string (made up of printable ascii characters). Consonants are letters used in English other than `"a", "e", "i", "o", "u"`. Remember, your function needs to return the number of unique consonants - disregarding duplicates. For example, if the string passed into the function reads `"add"`, the function should return `1` rather than `2`, since `"d"` is a duplicate. Similarly, the function should also disregard duplicate consonants of differing cases. For example, `"Dad"` passed into the function should return `1` as `"d"` and `"D"` are duplicates. ## Examples ``` "add" ==> 1 "Dad" ==> 1 "aeiou" ==> 0 "sillystring" ==> 7 "abcdefghijklmnopqrstuvwxyz" ==> 21 "Count my unique consonants!!" ==> 7 ```
algorithms
CONSONANTS = set('bcdfghjklmnpqrstvwxyz') def count_consonants(text): return len(CONSONANTS . intersection(text . lower()))
How Many Unique Consonants?
5a19226646d843de9000007d
[ "Strings", "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/5a19226646d843de9000007d
7 kyu
In this Kata, you will be given an array and your task will be to determine if an array is in ascending or descending order and if it is rotated or not. Consider the array `[1,2,3,4,5,7,12]`. This array is sorted in `Ascending` order. If we rotate this array once to the left, we get `[12,1,2,3,4,5,7]` and twice-rotated we get `[7,12,1,2,3,4,5]`. These two rotated arrays are in `Rotated Ascending` order. Similarly, the array `[9,6,5,3,1]` is in `Descending` order, but we can rotate it to get an array in `Rotated Descending` order: `[1,9,6,5,3]` or `[3,1,9,6,5]` etc. Arrays will never be unsorted, except for those that are rotated as shown above. Arrays will always have an answer, as shown in the examples below. More examples: ```Haskell solve([1,2,3,4,5,7]) = "A" -- Ascending solve([7,1,2,3,4,5]) = "RA" -- Rotated ascending solve([4,5,6,1,2,3]) = "RA" -- Rotated ascending solve([9,8,7,6]) = "D" -- Descending solve([5,9,8,7,6]) = "RD" -- Rotated Descending ``` More examples in the test cases. Good luck!
algorithms
def solve(arr): if sorted(arr) == arr: return "A" if sorted(arr)[:: - 1] == arr: return "D" return "RA" if arr[0] > arr[- 1] else "RD"
Simple array rotation
5a16cab2c9fc0e09ce000097
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5a16cab2c9fc0e09ce000097
6 kyu
Calculate the trace of a square matrix. A square matrix has `n` rows and `n` columns, where `n` is any integer > 0. The entries of the matrix can contain any number of integers. The function should return the calculated trace of the matrix, or `nil/None` if the array is empty or not square; you can otherwise assume the input will be valid (of the form described below). The trace of an n-by-n square matrix **A** is defined to be the sum of the elements on the main diagonal (the diagonal from the upper left to the lower right) of **A**. A matrix will be defined as an array of arrays, where the 1st entry represents the 1st row, the 2nd entry the 2nd row, and so on. For example, the following code... ```ruby,python [[1, 2, 3], [4, 5, 6], [7, 8, 9]] ``` represents the matrix ``` |1 2 3| |4 5 6| |7 8 9| ``` which has a trace of `1 + 5 + 9 = 15`. You can read more about the trace of a matrix at these sources: * http://en.wikipedia.org/wiki/Trace_(linear_algebra) * http://mathworld.wolfram.com/MatrixTrace.html ~~~if:ruby Note: The `Matrix` class is disabled. ~~~ ~~~if:python Note: `Numpy` is disabled. ~~~
algorithms
def trace(matrix): if not matrix or len(matrix) != len(matrix[0]): return None return sum(matrix[i][i] for i in range(len(matrix)))
Matrix Trace
55208f16ecb433c5c90001d2
[ "Linear Algebra", "Mathematics", "Matrix", "Algorithms" ]
https://www.codewars.com/kata/55208f16ecb433c5c90001d2
6 kyu
In this Kata, you will be given an array of integers whose elements have both a negative and a positive value, except for one integer that is either only negative or only positive. Your task will be to find that integer. Examples: `[1, -1, 2, -2, 3] => 3` `3` has no matching negative appearance `[-3, 1, 2, 3, -1, -4, -2] => -4` `-4` has no matching positive appearance `[1, -1, 2, -2, 3, 3] => 3` (the only-positive or only-negative integer may appear more than once) Good luck!
algorithms
def solve(arr): return sum(set(arr))
Array element parity
5a092d9e46d843b9db000064
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5a092d9e46d843b9db000064
7 kyu
<h1>Coffee Vending Machine Problems [Part 1]</h1> You have a vending machine, but it can not give the change back. You decide to implement this functionality. First of all, you need to know the minimum number of coins for this operation (i'm sure you don't want to return 100 pennys instead of 1$ coin). So, find an optimal number of coins required, if you have unlimited set of coins with given denominations. Assume all inputs are valid positive integers, and every set of coin denominations has len 4 for simplicity; Examples: <pre> optimal_number_of_coins(1, [1, 2, 5, 10]) (1 penny) so returns 1 optimal_number_of_coins(5, [1, 2, 5, 10]) (5) so returns 1 optimal_number_of_coins(6, [1, 3, 5, 10]) (3+3 or 5+1) = 6 so returns 2 optimal_number_of_coins(10, [1, 2, 5, 10]) (10) so returns 1 optimal_number_of_coins(12, [1, 3, 5, 10]) (10+1+1) = 12 so returns 3 optimal_number_of_coins(53, [1, 2, 5, 25]) (25+25+2+1) = 53 so returns 4 optimal_number_of_coins(7, [1, 1, 1, 25]) (1+1+1+1+1+1+1) = 7 so returns 7 </pre>etc.. Have fun =)
algorithms
def optimal_number_of_coins(n, coins): dp = [0 if not i else float("inf") for i in range(n + 1)] for i in range(1, n + 1): for j in range(len(coins)): if coins[j] <= i: temp = dp[i - coins[j]] if temp != float("inf") and temp + 1 < dp[i]: dp[i] = temp + 1 return dp[n]
Vending Machine Problems [#1]
586b1b91c66d181c2c00016f
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/586b1b91c66d181c2c00016f
6 kyu
A special type of prime is generated by the formula `p = 2^m * 3^n + 1` where `m` and `n` can be any non-negative integer. The first `5` of these primes are `2, 3, 5, 7, 13`, and are generated as follows: ``` 2 = 2^0 * 3^0 + 1 3 = 2^1 * 3^0 + 1 5 = 2^2 * 3^0 + 1 7 = 2^1 * 3^1 + 1 13 = 2^2 * 3^1 + 1 ..and so on ``` You will be given a range and your task is to return the number of primes that have this property. For example, `solve(0,15) = 5`, because there are only `5` such primes `>= 0 and < 15`; they are `2,3,5,7,13`. The upper limit of the tests will not exceed `1,500,000`. More examples in the test cases. Good luck! If you like Prime Katas, you will enjoy this Kata: [Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3)
algorithms
sb_primes = [2, 3, 5, 7, 13, 17, 19, 37, 73, 97, 109, 163, 193, 257, 433, 487, 577, 769, 1153, 1297, 1459, 2593, 2917, 3457, 3889, 10369, 12289, 17497, 18433, 39367, 52489, 65537, 139969, 147457, 209953, 331777, 472393, 629857, 746497, 786433, 839809, 995329, 1179649, 1492993] def solve(x, y): return sum(x <= p < y for p in sb_primes)
Stone bridge primes
5a1502db46d84395ab00008a
[ "Algorithms" ]
https://www.codewars.com/kata/5a1502db46d84395ab00008a
6 kyu
This kata is definitely harder than the first one. See the last one here: http://www.codewars.com/kata/the-unknown-but-known-variables-addition This one is a programming problem as well as a puzzle. And this is one of those annoying puzzles that is going to seem impossible, as the answer is not like a riddle, but something random some jerk over the internet came up with. But I have confidence you will solve it. There will be a string input in this format: ```'a*b'``` 2 lower-case letters (a-z) seperated by a '*' Return the product of the two variables. The product will always be a positive integer or 0. There is one correct answer for a pair of variables. I know the answers, it is your task to find out. Once you crack the code for a couple of the pairs, you should have the answer for the rest. It is like when you were in school doing math and you saw ```"12 = c*b"``` and you needed to find out what c and b were. However you don't have a 12. You have an UnKNOWN there as well. Example: X = a*b. You don't know what X is, and you don't know what b is or a, but it is a puzzle and you will find out. As part of this puzzle, there is two hints or clues on solving this. I won't tell you what the other one is. But the first is: ```The key is in the title.``` Given the input as a string - Return the product of the two variables as int.
games
def score(c): return abs(ord(c) - ord('n')) def the_var(s): a, b = s . split("*") return score(a) * score(b)
The U-n-KNOWN but known variables: Multiplication
571a8920b29485b065000582
[ "Puzzles" ]
https://www.codewars.com/kata/571a8920b29485b065000582
6 kyu
# Linked List Implement a doubly linked list Like an array, a linked list is a simple linear data structure. Several common data types can be implemented using linked lists, like queues, stacks, and associative arrays. A linked list is a collection of data elements called *nodes*. In a *singly linked list* each node holds a value and a link to the next node. In a *doubly linked list* each node also holds a link to the previous node. You will write an implementation of a doubly linked list. Implement a Node to hold a value and pointers to the next and previous nodes. Then implement a List which holds references to the first and last node and offers an array-like interface for adding and removing items: * `push` (*insert value at back*); * `pop` (*remove value at back*); * `shift` (*remove value at front*). * `unshift` (*insert value at front*); To keep your implementation simple, the tests will not cover error conditions. Specifically: `pop` or `shift` will never be called on an empty list. If you want to know more about linked lists, check [Wikipedia](https://en.wikipedia.org/wiki/Linked_list). ## Source Classic computer science topic
algorithms
from collections import deque class DoublyLinkedList (deque): push, shift, unshift = deque . append, deque . popleft, deque . appendleft
Doubly Linked List
58901ac726bd581274000096
[ "Data Structures", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/58901ac726bd581274000096
6 kyu
When multiple master devices are connected to a single bus (https://en.wikipedia.org/wiki/System_bus), there needs to be an arbitration in order to choose which of them can have access to the bus (and 'talk' with a slave). We implement here a very simple model of bus mastering. Given `n`, a number representing the number of **masters** connected to the bus, and a fixed priority order (the first master has more access priority than the second and so on...), the task is to choose the selected master. In practice, you are given a string `inp` of length `n` representing the `n` masters' requests to get access to the bus, and you should return a string representing the masters, showing which (only one) of them was granted access: ``` The string 1101 means that master 0, master 1 and master 3 have requested access to the bus. Knowing that master 0 has the greatest priority, the output of the function should be: 1000 ``` ## Examples ```c * arbitrate("001000101", 9) -> "001000000" * arbitrate("000000101", 9) -> "000000100" ``` ```javascript * arbitrate("001000101", 9) -> "001000000" * arbitrate("000000101", 9) -> "000000100" * `n` is not mandatory for solving the kata ``` ## Notes * The resulting string (`char* `) should be allocated in the `arbitrate` function, and will be free'ed in the tests. * `n` is always greater or equal to 1.
reference
def arbitrate(s, n): i = s . find('1') + 1 return s[: i] + '0' * (n - i)
Bus mastering - Who is the most prioritary?
5a0366f12b651dbfa300000c
[ "Strings", "Fundamentals", "Bits" ]
https://www.codewars.com/kata/5a0366f12b651dbfa300000c
7 kyu
Implement a function to calculate the sum of the numerical values in a nested list. For example : ```python sum_nested([1, [2, [3, [4]]]]) -> 10 ``` ```javascript sumNested([1, [2, [3, [4]]]]) => 10 ```
reference
def sum_nested(lst): return sum(sum_nested(x) if isinstance(x, list) else x for x in lst)
Sum of a nested list
5a15a4db06d5b6d33c000018
[ "Recursion", "Lists", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/5a15a4db06d5b6d33c000018
7 kyu
In this Kata, you will write a function `doubles` that will remove double string characters that are adjacent to each other. For example: `doubles('abbcccdddda') = 'aca'`, because, from left to right: ```Haskell a) There is only one 'a' on the left hand side, so it stays. b) The 2 b's disappear because we are removing double characters that are adjacent. c) Of the 3 c's, we remove two. We are only removing doubles. d) The 4 d's all disappear, because we first remove the first double, and again we remove the second double. e) There is only one 'a' at the end, so it stays. ``` Two more examples: `doubles('abbbzz') = 'ab'` and `doubles('abba') = ""`. In the second example, when we remove the b's in `'abba'`, the double `a` that results is then removed. The strings will contain lowercase letters only. More examples in the test cases. Good luck!
algorithms
def doubles(s): cs = [] for c in s: if cs and cs[- 1] == c: cs . pop() else: cs . append(c) return '' . join(cs)
String doubles
5a145ab08ba9148dd6000094
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/5a145ab08ba9148dd6000094
7 kyu
Chocolate factory produces unusual chocolate. Chocolate bars come in the form of **_long tiles 1 × N_**, which consists of N squares. Each square shows the portrait of one of the famous N confectioners of this company. Different chocolates have the same N confectioners' portraits, but in a different order. # Task Write a method, that for a given order of portraits of two chocolate bars determines a minimum number of breaks, that you need to perform on a first bar to form a second bar by repositioning the broken parts. # Restriction - you can break a bar only on the boundaries of its' squares. - you can’t flip initial bar or it's parts. # Input data - N - integer number (2 ≤ N ≤ 1000000), specifies the size of a chocolate bar, i.e. the number of squares in it. All bakers are numbered from 1 to N. - firstBar, secondBar - integer arrays of N different numbers each (all the numbers don't exceed N) - portraits' order in the first and second bars respectively. It is known that these orders are different. Your task is to calculate a single number - the minimum number of breaks that you need to perform on a first bar, to form a second bar by repositioning the broken parts. Example: ```java int N = 5; int firstBar[] = {4, 3, 2, 5, 1}; int secondBar[] = {1, 2, 5, 3, 4}; chocolate(N, firstBar, secondBar); // => returns 3 ``` ```python n = 5 first_bar = [4, 3, 2, 5, 1] second_bar = [1, 2, 5, 3, 4] chocolate(n, first_bar, second_bar) # => returns 3 ```
algorithms
def chocolate(n, first_bar, second_bar): return len(set(zip(first_bar, first_bar[1:])) - set(zip(second_bar, second_bar[1:])))
Chocolate problem
559a9a9ed391015e0700010f
[ "Algorithms", "Logic", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/559a9a9ed391015e0700010f
6 kyu
Sam wants to know how many times the variable `i` gets incremented after `n` seconds, but he has no idea how to stop the loop. Help him so that the function can return `i` after `n` seconds. ``` 0 <= n <= 3 (Artifacts for the delay is allowed up to 0.5 seconds) ``` NB: The value `i` is not so important in this kata because it is dependent on the state of server in practice. But if `n==0`, the expected value for `i` is `0`.
bug_fixes
import time def increment_loop(n): start = time . time() i = 0 while time . time() - start < n: i += 1 return i
Stop the loop after n seconds
5a147735ffe75f1c75000199
[ "Date Time", "Debugging" ]
https://www.codewars.com/kata/5a147735ffe75f1c75000199
7 kyu
The business has been suffering for years under the watch of Homie the Clown. Every time there is a push to production it requires 500 hands-on deck, a massive manual process, and the fire department is on stand-by along with Fire Marshall Bill the king of manual configuration management. He is called a Fire Marshall because production pushes often burst into flames and rollbacks are a hazard. The business demands change and as such has hired a new leader who wants to convert it all to DevOps…..there is a new Sheriff in town. The Sheriff's first order of business is to build a DevOps team. He likes Microservices, Cloud, Open-Source, and wants to push to production 9500 times per day without even pressing a button, beautiful seamless immutable infrastructure properly baked in the Continuous Delivery oven is the goal. The only problem is Homie the Clown along with Legacy Pete are grandfathered in and union, they started out in the era of green screens and punch cards and are set in their ways. They are not paid by an outcome but instead are measured by the amount of infrastructure under management and total staff headcount. The Sheriff has hired a new team of DevOps Engineers. They advocate Open Source, Cloud, and never doing a manual task more than one time. They believe Operations to be a first class citizen with Development and are preparing to shake things up within the company. Since Legacy is not going away, yet, the Sheriff's job is to get everyone to cooperate so DevOps and the Cloud will be standard. The New Kids on the Block have just started work and are looking to build common services with Legacy Pete and Homie the Clown. ``` Every Time the NKOTB propose a DevOps pattern…… Homie stands up and says "Homie don't Play that!" IE: NKOTB Say -> "We need Cloud now!" Homie Say -> "Cloud! Homie dont play that!" NKOTB Say -> "We need Automation now!" Homie Say -> "Automation! Homie dont play that!" NKOTB Say -> "We need Microservices now!" Homie Say -> "Microservices! Homie dont play that!" ``` Task You will receive a two-dimensional array with strings made of the NKOTB’s requirements. Each Array contains a domain of DevOps patterns that each of the 5 NKOTB are asking for. The requirements array will ALWAYS have five sub-arrays structured like this: ``` requirements[0] = monitoring requirements[1] = automation requirements[2] = deployment requirements[3] = cloud requirements[4] = microservices Each sub-array will always contain strings in the same format The strings will always be in the following format(case insensitive): "We need Microservices now!" Your job is to create the response from Homie the Clown following the pattern above. Then return the responses in an array. "Microservices! Homie dont play that!" ``` The first word of the response is always Capitalized and all other letters are lowercase regardless of how you recieve them, the rest of the sentence is always in the format ``` Homie dont play that!```. Strings should be returned in the same order. ``` In addition to the responses create a count of each domain and return it as the last element of the return array in the following format. '6 monitoring objections, 4 automation, 6 deployment pipeline, 6 cloud, and 3 microservices.' ``` For more information on Homie the Clown. https://www.youtube.com/watch?v=_QhuBIkPXn0 Fire Marshall Bill on Vacation! https://www.youtube.com/watch?v=IIIsCB4Y8sw#t=202.002651
reference
def nkotb_vs_homie(requirements): return ["{}! Homie dont play that!" . format(a[8: - 5]. title()) for b in requirements for a in b] + \ ["{} monitoring objections, {} automation, {} deployment pipeline, {} cloud, and {} microservices." . format(* (len(x) for x in requirements))]
DevOps New Kids On The Block VS Homie The Clown
58b497914c5d0af407000049
[ "Fundamentals" ]
https://www.codewars.com/kata/58b497914c5d0af407000049
7 kyu
My 6th kata, implement a lexicographic sort order to make longer items go **before** any of their prefixes. In Python, write a function (`custom_sort`) that takes an input list (`lst`) of strings. The function should return a new list of strings sorted lexiographically but with longer items before their prefixes. The test cases give some examples. You can assume that all strings will consist of ASCII printable characters and that the largest character will be `'~'`, which is `chr(126)`. For an extra challenge code a solution that makes no such assumptions. Do vote and provide any feedback on the kata. If you like this kata, do checkout my other katas.
algorithms
import functools def cmp(a, b): for x, y in zip(a, b): if x < y: return - 1 if y < x: return 1 if len(a) > len(b): return - 1 if len(b) > len(a): return 1 return 0 def custom_sort(lst): return sorted(lst, key=functools . cmp_to_key(cmp))
Lexographic sort with a twist
5901b2f47591f339b5000059
[ "Algorithms", "Arrays", "Sorting", "Data Structures" ]
https://www.codewars.com/kata/5901b2f47591f339b5000059
6 kyu
You have `n` dices each one having `s` sides numbered from 1 to `s`. How many outcomes add up to a specified number `k`? For example if we roll four normal six-sided dices we have four outcomes that add up to 5. (1, 1, 1, 2) (1, 1, 2, 1) (1, 2, 1, 1) (2, 1, 1, 1) There are 100 random tests with: - `0 <= n <= 10` - `1 <= s <= 20` - `0 <= k <= n * s` Notes: - there is always exactly 1 case to reach `k = 0` regardless of the number of dice you have - without any dice, it's not possible to reach any positive `k`
reference
from numpy . polynomial import polynomial def outcome(n, s, k): try: return polynomial . polypow([0] + [1] * s, n)[k] except IndexError: return 0
Sum of dices
58ff61d2d6b38ee5270000bc
[ "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/58ff61d2d6b38ee5270000bc
6 kyu
Hi guys, welcome to introduction to DocTesting. The kata is composed of two parts; in part (1) we write three small functions, and in part (2) we write a few doc tests for those functions. Lets talk about the functions first... The reverse_list function takes a list and returns the reverse of it. If given an empty list, simply return an empty list. The second function... The sum_list function takes a list as input and adds up all the values, returning an integer. If the list is empty, return 0. The third function... The head_of_list function simply returns the first item in the list. If the list is empty return None. Each of these functions can be easily written with a single line of code; there are some tests for correctness but no tests for effciency. Once you have implemented all three of these functions you can move onto phase two, which is writing doc tests. If you haven't written doc tests before then I suggest you check out the following documentation: https://docs.python.org/3/library/doctest.html To complete this kata all you have to do is write **EXACTLY TWO** doc tests for each of the three functions (any more/less than that and you will fail the tests). Here is an example: def double(y): """Function returns y * 2 >>> double(2) 4 """ return y * 2 In the example above we have a function called 'double' and a single doctest. When we run the doctest module Python will check if double(2) equals 4. If it does not, then the doctest module will flag up an error. Please note that this is intended as a beginners introduction to docstrings, if you try to do something clever (such as writing doc tests to catch exceptions, or tinkering with the 'option flags'), you will probably fail a test or two. This is due to how the tests are written. Oh and one last thing, don't try and get too 'cheeky' and try something like: """ >>> True True """ such a solution is (a) not in the spirit of things and (b) I got tests for that! :p Good Luck! ~~~~~~~~~~~~~~~ Issues & Helpful hints ~~~~~~~~~~~~~~~~~~~~~~~ 1) In addition to the 'don't get too clever rule', please try to be precise when making your doctests; [1,2] may fail where [1, 2] may succeed. Likewise, ">>>function(x)" may fail where ">>> function(x)" is likely to suceed *(note the difference is single " " character)*. In short, if you fail a test the first thing to check is that you dont have any unecessary characters/spaces and/or odd formating. 2) As you shall see from the kata discussion testing for None is tricky and lots of people are struggling to get None tests working. So I'm going to quickly show you a way to test for not that will (should) pass the kata: def is_string(string): """ returns the string if the string is Not empty, otherwise returns None >>> is_string("") is None True """ return string if string else None 3) If you happen to be struggling to actually complete the three functions in the first place then I would recomend you google *"Python Indexing", "Pythons sum function" and "if/else statements in Python"*.
reference
def reverse_list(x): """Takes an list and returns the reverse of it. If x is empty, return []. >>> reverse_list([1, 2, 3, 4]) [4, 3, 2, 1] >>> reverse_list([]) [] """ return x[:: - 1] def sum_list(x): """Takes a list, and returns the sum of that list. If x is empty list, return 0. >>> sum_list([1, 2, 3, 4]) 10 >>> sum_list([]) 0 """ return sum(x) def head_of_list(x): """Takes a list, returns the first item in that list. If x is empty, return None >>> head_of_list([1, 2, 3, 4]) 1 >>> head_of_list([]) is None True """ return x[0] if x else None
An Introduction to DocTesting...
58e4033b5600a17be1000103
[ "Fundamentals" ]
https://www.codewars.com/kata/58e4033b5600a17be1000103
7 kyu
Let's say that in a hypothetical platform that resembles Codewars there is a clan with 2 warriors. The 2nd one in ranking (lets call him **D**) wants to at least reach the honor score of his ally (lets call her **M**). *(Let's say that there is no antagonism here, he just wants to prove his ally that she should be proud to have him in the clan and sees this as the only way to achieve it! :P )* Your task is to help **D** by providing him with the **quickest path** to reach **M**'s honor score. In this hypothetical platform there are 2 kinds of kata to be solved: ``` '2kyu' worth of 1 point '1kyu' worth of 2 points ``` So if for example: ``` M has honor 11 D has honor 2 ``` **D** could reach **M`s** honor by solving kata worth of `9`. He has many options to do this: ``` Solve 9 '2kyus' (9*1 -> 9) => Solve 9 kata Solve 4 '1kyus' and 1 '2kyus' (4*2 + 1*1-> 9) => Solve 5 kata Solve 2 '1kyus' and 5 '2kyus' (2*2 + 5*1 -> 9) => Solve 7 kata etc etc... ``` The **quickest path** to reach the honor score is: ``` 4 '1kyus' and 1 '2kyus' => Solve only 5 kata ``` Create a function `getHonorPath` that accepts 2 arguments `honorScore` & `targetHonorScore` with score integers of 2 warriors and returns an object with the **quickest path** for the first one to reach the 2nd's honor. For example: ``` getHonorPath(2, 11) should return { '1kyus': 4, '2kyus': 1 } getHonorPath(20, 11) should return {} ``` **For the purpose of this kata you do not have to worry about any non-integer arguments for honor scores**
reference
def get_honor_path(score, target): return {'1kyus': (target - score) / / 2, '2kyus': (target - score) % 2} if target > score else {}
Help your fellow warrior!
5660aa6fa60f03856c000045
[ "Fundamentals", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5660aa6fa60f03856c000045
7 kyu
A company is opening a bank, but the coder who is designing the user class made some errors. They need <strong> you </strong> to help them. You <strong>must</strong> include the following:<br/> <strong>Note: These are NOT steps to code the class</strong> - A withdraw method - Subtracts money from balance - One parameter, money to withdraw - Raise a ValueError if there isn't enough money to withdraw - Return a string with name and balance(see examples) * A check method - Adds money to balance - Two parameters, other user and money - Other user will always be valid - Raise a ValueError if other user doesn't have enough money - Raise a ValueError if checking_account isn't true for other user - Return a string with name and balance plus other name and other balance(see examples) - An add_cash method - Adds money to balance - One parameter, money to add - Return a string with name and balance(see examples) Additional Notes: * Checking_account should be stored as a boolean - No input numbers will be negative * Output must end with a period - Float numbers will not be used so, balance should be integer * No currency will be used Examples: ``` Python Jeff = User('Jeff', 70, True) Joe = User('Joe', 70, False) Jeff.withdraw(2) # Returns 'Jeff has 68.' Joe.check(Jeff, 50) # Returns 'Joe has 120 and Jeff has 18.' Jeff.check(Joe, 80) # Raises a ValueError Joe.checking_account = True # Enables checking for Joe Jeff.check(Joe, 80) # Returns 'Jeff has 98 and Joe has 40' Joe.check(Jeff, 100) # Raises a ValueError Jeff.add_cash(20.00) # Returns 'Jeff has 118.' ``` <h1 align = 'Center'><font size = '7'><strong> Good Luck </strong></font></h1>
reference
class User (object): def __init__(self, name, balance, checking_account): self . name = name self . balance = balance self . checking_account = checking_account def withdraw(self, v): if v > self . balance: raise ValueError() self . balance -= v return "{} has {}." . format(self . name, int(self . balance)) def add_cash(self, v): self . balance += v return "{} has {}." . format(self . name, int(self . balance)) def check(self, other, v): if not other . checking_account: raise ValueError() s1, s2 = other . withdraw(v), self . add_cash(v)[: - 1] return "{} and {}" . format(s2, s1) def __str__(self): return "User({}, {}, {})" . format( self . name, self . balance, self . checking_account)
User class for Banking System
5a03af9606d5b65ff7000009
[ "Fundamentals", "Object-oriented Programming" ]
https://www.codewars.com/kata/5a03af9606d5b65ff7000009
7 kyu
You get an input list of 10 random integers between 0 and 100 (`0 <= x <= 100`). Your task is to return the **integer** used to initialize the random number generator (the "seed") (`0 <= n < 10000`) ## Examples ```python input: [17, 72, 97, 8, 32, 15, 63, 97, 57, 60] expected: 1 input: [99, 56, 14, 0, 11, 74, 4, 85, 88, 10] expected: 1234 ```
reference
from random import seed, randint def find_random_seed(A): for s in range(10000): seed(s) if [randint(0, 100) for _ in range(10)] == A: return s
Find the random seed
5a106ce7ffe75f4c200000f7
[ "Fundamentals" ]
https://www.codewars.com/kata/5a106ce7ffe75f4c200000f7
7 kyu
An array is a data structure in which a collection of different data stored continuously in memory. This collection is usually accessed by a numerical index and allows near instant access to all of the data held by the array as opposed to other structures such as binary search trees or linked lists, where the computer has to traverse these structures to find the item being accessed. To demonstrate, we'll calculate the position of an array element using some simple arithmetic. # Task Overview Given: * `begin`, a number which represents the location of the beginning of the array in memory, * `end`, a number which represents the location of the end of the array in memory, * `index`, a zero-based numerical key for the element being accessed, * `size`, a number representing the size in bytes of each item of the array, Return the memory address of the element being accessed. ```if:c In C, `begin` and `end` will be pointers, and you must return a pointer to `array[index].` ``` If the index is negative or the address of the memory being accessed is at or greater than the end of the array, throw an `Error` (JS) / `IndexError` (Python). In C return `NULL` instead. Otherwise, who knows *what* data we could be accessing! # Usage Example ```javascript elementLocation(0x1000, 0x1040, 0x3, 0x8) => 0x1018 elementLocation(0x1000, 0x1040, 0x8, 0x8) // throws Error elementLocation(0x2000, 0x2100, 0x3, 0x4) => 0x200C elementLocation(0x2000, 0x2100, 0x0, 0x4) => 0x2000 ``` ```python element_location(0x1000, 0x1040, 0x3, 0x8) => 0x1018 element_location(0x1000, 0x1040, 0x8, 0x8) # throws IndexError element_location(0x2000, 0x2100, 0x3, 0x4) => 0x200C element_location(0x2000, 0x2100, 0x0, 0x4) => 0x2000 ``` ```c element_location(0x1000, 0x1040, 0x3, 0x8) => 0x1018 element_location(0x1000, 0x1040, 0x8, 0x8) => NULL element_location(0x2000, 0x2100, 0x3, 0x4) => 0x200C element_location(0x2000, 0x2100, 0x0, 0x4) => 0x2000 ``` # Constraints * All types given will be valid. * All numbers given are integers. * `end` will be greater than or equal to `begin` * `begin`, `end`, and `size` will be positive numbers. * `size` will be a power of 2. * `begin` is evenly divisible by 4. * The difference of `begin` and `end` is evenly divisible by `size`.
reference
def element_location(begin: int, end: int, index: int, size: int) - > int: out = begin + index * size if out < begin or out >= end: raise IndexError return out
Where's my Elements at?
5a0ec343c374cb6da0000006
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5a0ec343c374cb6da0000006
7 kyu
<h1>Statistics puzzle</h1> Your function will receive an array of 10000 integer values randomly selected from a uniform distribution (a range of values with equal selection probability). Your function will also receive the minimum and maximum possible values in the range (inclusive). A constant has been added to every value in the array, after it was randomly selected. __You must find the constant.__ <h5>There are no example tests in this kata, so as not to spoil the trick.</h5> <h6>Do not worry *too* much about precision. The tests are lenient.</h6>
games
def find_constant(arr, lb, ub): return min(arr) - lb
Crouching Distribution, Hidden Constant
5a0da79b32b8b98b8d000097
[ "Statistics", "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/5a0da79b32b8b98b8d000097
7 kyu
When it's spring Japanese cherries blossom, it's called "sakura" and it's admired a lot. The petals start to fall in late April. Suppose that the falling speed of a petal is 5 centimeters per second (5 cm/s), and it takes 80 seconds for the petal to reach the ground from a certain branch. Write a function that receives the speed (in cm/s) of a petal as input, and returns the time it takes for that petal to reach the ground **from the same branch**. Notes: * The movement of the petal is quite complicated, so in this case we can see the velocity as a constant during its falling. * Pay attention to the data types. * If the initial velocity is non-positive, the return value should be `0`
algorithms
def sakura_fall(v): return 400 / v if v > 0 else 0
The falling speed of petals
5a0be7ea8ba914fc9c00006b
[ "Algorithms" ]
https://www.codewars.com/kata/5a0be7ea8ba914fc9c00006b
8 kyu
Krazy King BlackJack is just like blackjack, with one difference: the kings! Instead of the kings being simply worth 10 points, kings are worth either 10 points or some other number of points announced by the dealer at the start of the game. Whichever value yields the best hand is the one that plays (much like how aces are worth either 1 or 11 points). Write a function that inputs a list of strings (representing a blackjack hand) and an integer that represents the alternative king value. The function should output an integer representing the value of the hand if it is less than or equal to 21, and False if it exceeds 21. Other than the alternative king value, normal blackjack rules apply. The cards, in order ace-through king, are represented as strings as follows: ```python ['A', '2', '3','4', '5', '6','7', '8', '9','10', 'J', 'Q','K'] ``` A hand has between 2 and 20 cards, inclusive. The alternative king value is between 2 and 9, inclusive. Blackjack rules: the value of a hand is determined by maximizing the value of the sum of its cards while not exceeding 21 if possible. Number cards are worth their value, Jacks ('J') and Queens ('Q') are worth 10, Aces are worth either 1 or 11, and kings, again, are worth either 10 or their alternative value.
algorithms
from itertools import product def krazy_king_blackjack(hand, king_value): VALUE = {str(n): (n,) for n in range(1, 11)} VALUE . update( {'J': (10,), 'Q': (10,), 'K': (10, king_value), 'A': (1, 11)}) possible = [sum(comb) for comb in product(* (VALUE[card] for card in hand)) if sum(comb) <= 21] return max(possible) if possible else False
Krazy King Blackjack
57bb798756449dea77000020
[ "Algorithms", "Logic", "Games" ]
https://www.codewars.com/kata/57bb798756449dea77000020
5 kyu
Let us define a function `f`such as: - (1) for k positive odd integer > 2 : <img src="https://latex.codecogs.com/gif.latex?\bg_green&space;f(k)&space;=&space;\sum_{n=1}^{nb}1/n^{k}" title="\bg_green f(k) = \sum_{n=1}^{nb}1/n^{k}" /> - (2) for k positive even integer >= 2 : <img src="https://latex.codecogs.com/gif.latex?\bg_green&space;f(k)&space;=&space;1/2&space;|B_k|&space;(2\pi)^{k}&space;/&space;k!" title="\bg_green f(k) = 1/2 |B_k| (2\pi)^{k} / k!" /> - (3) for k positive integer > 1 : <img src="https://latex.codecogs.com/gif.latex?\bg_green&space;f(-k)&space;=&space;(-1)^k*B_{k&plus;1}/(k&space;&plus;&space;1))" title="f(-k) = (-1)^k*B_{k+1}/(k + 1))" /> where `|x|` is `abs(x)` and B<font size="1">k</font> the k<sup>th</sup> Bernoulli number. `f` is not defined for `0, 1, -1`. These values will not be tested. #### Guidelines for Bernoulli numbers: https://en.wikipedia.org/wiki/Bernoulli_number http://mathworld.wolfram.com/BernoulliNumber.html https://www.codewars.com/kata/bernoulli-numbers-1 There is more than one way to calculate them. You can make Pascal triangle and then with the basic formula below generate all Bernoulli numbers. 1 + 2B<style size="1">1</style> = 0 ... gives ... B<style size="1">1</style> = - 1/2 1 + 3B<style size="1">1</style> + 3B<style size="1">2</style> = 0 ... gives ... B<style size="1">2</style> = 1/6 1 + 4B<style size="1">1</style> + 6B<style size="1">2</style> + 4B<style size="1">3</style> = 0 ... gives ... B<style size="1">3</style> = 0 1 + 5B<style size="1">1</style> + 10B<style size="1">2</style> + 10B<style size="1">3</style> + 5B<style size="1">4</style> = 0 ... gives ... B<style size="1">4</style> = - 1/30 ... and so on #### Task Function `series(k, nb)` returns (1), (2) or (3) where `k` is the `k` parameter of `f` and `nb` the upper bound in the summation of (1). `nb` is of no use for (2) and (3) but for the sake of simplicity it will always appear in the tests even for cases (2) and (3) with a value of `0`. ``` Examples S(2, 0) = 1.644934066848224.... S(3, 100000) = 1.20205690310973.... S(4, 0) = 1.08232323371113..... S(-5, 0) = -0.003968253968.... S(-11, 0) = 0.02109279609279.... ``` #### Notes - For Java, C#, C++: `k` should be such as `-27 <= k <= 20`; otherwise `-30 <= k <= 30` and be careful of 32-bit integer overflow. - Translators are welcome.
reference
from fractions import Fraction as F from math import factorial, tau B = [1, F(1, 2), F(1, 6), 0, - F(1, 30), 0, F(1, 42), 0, - F(1, 30), 0, F(5, 66), 0, - F(691, 2730), 0, F(7, 6), 0, - F(3617, 510), 0, F(43867, 798), 0, - F(174611, 330), 0, F(854513, 138), 0, - F(236364091, 2730), 0, F(8553103, 6), 0, - F(23749461029, 870), 0, F(8615841276005, 14322), 0] def series(k: int, nb: int) - > float: if k < - 1: return float((- 1) * * k * B[1 - k] / (1 - k)) if k > 2 and k % 2: return sum(1 / n * * k for n in range(1, nb + 1)) if k >= 2 and not k % 2: return abs(B[k]) / 2 * tau * * k / factorial(k) raise ValueError(f'function undefined for { k } ')
Getting along with Bernoulli's numbers
5a02cf76c9fc0ee71d0000d5
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/5a02cf76c9fc0ee71d0000d5
5 kyu
Christmas is coming, and Santa has a long list to go through, to find who deserves presents for the big day. Go through a list of children, and return a list containing every child who appeared on Santa's list. Do not add any child more than once. Output should be sorted. ~~~if:java For java, use Lists. ~~~ Comparison should be case sensitive and the returned list should contain only one copy of each name: `"Sam"` and `"sam"` are different, but `"sAm"` and `"sAm"` are not.
reference
def find_children(santas_list, children): return sorted(set(santas_list) & set(children))
Santa's Naughty List
5a0b4dc2ffe75f72f70000ef
[ "Lists", "Sorting", "Fundamentals" ]
https://www.codewars.com/kata/5a0b4dc2ffe75f72f70000ef
7 kyu
Program the function distance(p1, p2) which returns the distance between the points p1 and p2 in n-dimensional space. p1 and p2 will be given as arrays. Your program should work for all lengths of arrays, and should return -1 if the arrays aren't of the same length or if both arrays are empty sets. If you don't know how to measure the distance between two points, go here: http://mathworld.wolfram.com/Distance.html
reference
def distance(p1, p2): return sum((a - b) * * 2 for a, b in zip(p1, p2)) * * 0.5 if len(p1) == len(p2) > 0 else - 1
Distance between two points
5a0b72484bebaefe60001867
[ "Fundamentals" ]
https://www.codewars.com/kata/5a0b72484bebaefe60001867
7 kyu
You have been speeding on a motorway and a police car had to stop you. The policeman is a funny guy that likes to play games. Before issuing penalty charge notice he gives you a choice to change your penalty. Your penalty charge is a combination of numbers like: speed of your car, speed limit in the area, speed of the police car chasing you, the number of police cars involved, etc. So, your task is to combine the given numbers and make the penalty charge to be as small as possible. For example, if you are given numbers ```[45, 30, 50, 1]``` your best choice is ```1304550``` Examples: ```Python ['45', '30', '50', '1'] => '1304550' ['100', '10', '1'] => '100101' ['32', '3'] => '323' ```
algorithms
# return str of the smallest value of the combined numbers in a_list def penalty(a_list): return '' . join(sorted(a_list, key=lambda n: n + n[: 1]))
Penalty for speeding
5a05a4d206d5b61ba70000f9
[ "Algorithms" ]
https://www.codewars.com/kata/5a05a4d206d5b61ba70000f9
5 kyu
Timothy (age: 16) really likes to smoke. Unfortunately, he is too young to buy his own cigarettes and that's why he has to be extremely efficient in smoking. It's now your task to create a function that calculates how many cigarettes Timothy can smoke out of the given amounts of `bars` and `boxes`: - a bar has 10 boxes of cigarettes, - a box has 18 cigarettes, - out of 5 stubs (cigarettes ends) Timothy is able to roll a new one, - of course the self made cigarettes also have an end which can be used to create a new one... Please note that Timothy never starts smoking cigarettes that aren't "full size" so the amount of smoked cigarettes is always an integer.
algorithms
def start_smoking(bars, boxes): return int(22.5 * (10 * bars + boxes) - 0.5)
Smoking Timmy
5a0aae48ba2a14cfa600016d
[ "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/5a0aae48ba2a14cfa600016d
7 kyu
Were you ever interested in the phenomena of <i>astrology, star signs, tarot, voodoo </i>? (ok not voodoo that's too spooky)...<br> <font size="4" color="#25B6CC">Task:</font><br> Your job for today is to finish the <code>star_sign</code> function by finding the astrological sign, given the birth details as a <code>Date</code> object.<br> Start and end dates for zodiac signs vary on different resources so we will use this table to get consistent results: <ul> <li>Aquarius ------ 21 January - 19 February </li> <li>Pisces --------- 20 February - 20 March</li> <li>Aries ---------- 21 March - 20 April</li> <li>Taurus -------- 21 April - 21 May</li> <li>Gemini -------- 22 May - 21 June</li> <li>Cancer -------- 22 June - 22 July</li> <li>Leo ------------- 23 July - 23 August</li> <li>Virgo ----------- 24 August - 23 September</li> <li>Libra ----------- 24 September - 23 October</li> <li>Scorpio -------- 24 October - 22 November</li> <li>Sagittarius ---- 23 November - 21 December</li> <li>Capricorn ----- 22 December - 20 January</li> </ul> <br> <font color="#25B6CC">Test info:</font> 100 random tests (dates range from January 1st 1940 until now)
games
def star_sign(date): limits = ['', 20, 19, 20, 20, 21, 21, 22, 23, 23, 23, 22, 21] signs = ['Aquarius', 'Pisces', 'Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius', 'Capricorn'] if date . day > limits[date . month]: return signs[date . month - 1] else: return signs[date . month - 2]
It is written in the stars
5888a57cbf87c25c840000c6
[ "Date Time", "Puzzles" ]
https://www.codewars.com/kata/5888a57cbf87c25c840000c6
7 kyu
An element in an array is dominant if it is greater than all elements to its right. You will be given an array and your task will be to return a list of all dominant elements. For example: ``` solve([1,21,4,7,5]) = [21,7,5] because 21, 7 and 5 are greater than elments to their right. solve([5,4,3,2,1]) = [5,4,3,2,1] Notice that the last element is always included. All numbers will be greater than 0. ``` More examples in the test cases. Good luck!
reference
def solve(arr): r = [] for v in arr[:: - 1]: if not r or r[- 1] < v: r . append(v) return r[:: - 1]
Dominant array elements
5a04133e32b8b998dc000089
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5a04133e32b8b998dc000089
7 kyu
In this Kata, you will be given an array of unique elements, and your task is to rearrange the values so that the first max value is followed by the first minimum, followed by second max value then second min value, etc. For example: ```javascript solve([15,11,10,7,12]) = [15,7,12,10,11] ``` ```csharp Kata.Solve(new List<int> {15,11,10,7,12}) => new List<int> {15,7,12,10,11} ``` The first max is `15` and the first min is `7`. The second max is `12` and the second min is `10` and so on. More examples in the test cases. Good luck!
reference
def solve(arr): arr = sorted(arr, reverse=True) res = [] while len(arr): res . append(arr . pop(0)) if len(arr): res . append(arr . pop()) return res
Max-min arrays
5a090c4e697598d0b9000004
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5a090c4e697598d0b9000004
7 kyu
This kata requires you to convert minutes (`int`) to hours and minutes in the format `hh:mm` (`string`). If the input is `0` or negative value, then you should return `"00:00"` **Hint:** use the modulo operation to solve this challenge. The modulo operation simply returns the remainder after a division. For example the remainder of 5 / 2 is 1, so 5 modulo 2 is 1. ## Example If the input is `78`, then you should return `"01:18"`, because 78 minutes converts to 1 hour and 18 minutes. Good luck! :D
reference
def timeConvert(m): return '{:02d}:{:02d}' . format(* divmod(max(int(m), 0), 60))
Easy Time Convert
5a084a098ba9146690000969
[ "Fundamentals" ]
https://www.codewars.com/kata/5a084a098ba9146690000969
7 kyu
In music, if you double (or halve) the pitch of any note you will get to the same note again. "Concert A" is fixed at 440 Hz, and every other note is defined based on that. 880 Hz is also an A, as is 1760 Hz, as is 220 Hz. There are 12 notes in Western music: A, A#, B, C, C#, D, D#, E, F, F#, G, G#. You are given a preloaded dictionary with these 12 notes and one of the pitches that creates that note (starting at Concert A). Now, given a pitch (in Hz), return the corresponding note. (All inputs will be valid notes). ```javascript getNote(440) = A getNote(220) = A getNote(880) = A ``` ```csharp Kata.GetNote(440) => A Kata.GetNote(220) => A Kata.GetNote(880) => A ``` For reference, the notes dictionary looks like this: ```javascript const notesDictionary = { 440: "A", 466.16: "A#", 493.88: "B", 523.25: "C", 554.37: "C#", 587.33: "D", 622.25: "D#", 659.25: "E", 698.46: "F", 739.99: "F#", 783.99: "G", 830.61: "G#" } ``` ```python notes_dictionary = { 440: "A", 466.16: "A#", 493.88: "B", 523.25: "C", 554.37: "C#", 587.33: "D", 622.25: "D#", 659.25: "E", 698.46: "F", 739.99: "F#", 783.99: "G", 830.61: "G#" } ``` ```ruby notes = { 440.00 => "A", 466.16 => "A#", 493.88 => "B", 523.25 => "C", 554.37 => "C#", 587.33 => "D", 622.25 => "D#", 659.25 => "E", 698.46 => "F", 739.99 => "F#", 783.99 => "G", 830.61 => "G#" } ``` ```csharp // This dictionary is part of the Kata class public static Dictionary<double, string> NotesDictionary = new Dictionary<double, string>() { {440, "A"}, {466.16, "A#"}, {493.88, "B"}, {523.25, "C"}, {554.37, "C#"}, {587.33, "D"}, {622.25, "D#"}, {659.25, "E"}, {698.46, "F"}, {739.99, "F#"}, {783.99, "G"}, {830.61, "G#"} }; ``` Musicians: all pitches based on equal tempermanent, taken from [here](http://pages.mtu.edu/~suits/notefreqs.html).
reference
notes = { 440: "A", 466.16: "A#", 493.88: "B", 523.25: "C", 554.37: "C#", 587.33: "D", 622.25: "D#", 659.25: "E", 698.46: "F", 739.99: "F#", 783.99: "G", 830.61: "G#" } def get_note(pitch): for note in notes: if note >= pitch and note % pitch == 0: return notes[note] elif note < pitch and pitch % note == 0: return notes[note]
Pitches and Notes
5a0599908ba914a6cf000138
[ "Fundamentals" ]
https://www.codewars.com/kata/5a0599908ba914a6cf000138
7 kyu
Get the number n to return the sequence from n to 1. The number n can be negative and also large number. (See the range as the following) ``` Example : n=5 >> [5,4,3,2,1] n=-1 >> [-1,0,1] Range : Python -9999 < n < 9999 Javascript -9999 < n < 9999 c++ -9999 < n < 9999 Crystal -9999 < n < 9999 Ruby -9999 < n < 9999 ```
reference
def seq_to_one(n): step = (- 1) * * (n >= 1) return list(range(n, 1 + step, step))
Sequence to 1
5a05fe8a06d5b6208e00010b
[ "Fundamentals" ]
https://www.codewars.com/kata/5a05fe8a06d5b6208e00010b
7 kyu
Let `n` be an integer coprime with `10`, e.g. `7`. `1/7 = 0.142857 142857 142857 ...`. We see that the decimal part has a cycle: `142857`. The length of this cycle is `6`. In the same way: `1/11 = 0.09 09 09 ...`. Cycle length is `2`. #### Task Given an integer `n (n > 1)` the function `cycle(n)` returns the length of the cycle if there is one otherwise (n and 10 not coprimes) return `-1`. #### Examples: ``` cycle(5) = -1 cycle(13) = 6 -> 0.076923 076923 0769 cycle(21) = 6 -> 0.047619 047619 0476 cycle(27) = 3 -> 0.037 037 037 037 0370 cycle(33) = 2 -> 0.03 03 03 03 03 03 03 03 cycle(37) = 3 -> 0.027 027 027 027 027 0 cycle(94) = -1 ``` #### Notes - ``` cycle(22) = -1 since 1/22 ~ 0.0 45 45 45 45 ... ``` - Please ask before translating..
reference
import math def cycle(n): if n % 2 == 0 or n % 5 == 0: return - 1 k = 1 while pow(10, k, n) != 1: k += 1 return k
1/n- Cycle
5a057ec846d843c81a0000ad
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/5a057ec846d843c81a0000ad
6 kyu
I need some help with my math homework. I have a number of problems I need to return the derivative for. They will all be of the form: `ax^b`, where `a` and `b` are both integers, but can be positive or negative. **Notes:** - if `b` is 1, then the equation will be `ax` - if `b` is 0, then the equation will be `0` ## Examples ``` 3x^3 --> 9x^2 3x^2 --> 6x 3x --> 3 3 --> 0 3x^-1 --> -3x^-2 -3x^-2 --> 6x^-3 ``` If you don't remember how derivatives work, here's a link with some basic rules: https://www.mathsisfun.com/calculus/derivatives-rules.html
reference
def get_derivative(s): if '^' in s: f, t = map(int, s . split('x^')) return '{}x' . format(f * t) if t == 2 else '{}x^{}' . format(f * t, t - 1) elif 'x' in s: return s[: - 1] else: return '0'
Calculate Derivative #1 - Single Integer Equation
5a0350c380171ffd7b00012a
[ "Fundamentals", "Mathematics", "Algorithms", "Logic", "Numbers" ]
https://www.codewars.com/kata/5a0350c380171ffd7b00012a
7 kyu
The aim of the kata is to decompose `n!` (factorial n) into its prime factors. Examples: ``` n = 12; decomp(12) -> "2^10 * 3^5 * 5^2 * 7 * 11" since 12! is divisible by 2 ten times, by 3 five times, by 5 two times and by 7 and 11 only once. n = 22; decomp(22) -> "2^19 * 3^9 * 5^4 * 7^3 * 11^2 * 13 * 17 * 19" n = 25; decomp(25) -> 2^22 * 3^10 * 5^6 * 7^3 * 11^2 * 13 * 17 * 19 * 23 ``` Prime numbers should be in increasing order. When the exponent of a prime is 1 don't put the exponent. Notes - the function is `decomp(n)` and should return the decomposition of `n!` into its prime factors in increasing order of the primes, as a string. - factorial can be a very big number (`4000! has 12674 digits`, n can go from 300 to 4000). - In Fortran - as in any other language - the returned string is not permitted to contain any redundant trailing whitespace: you can use `dynamically allocated character strings`.
reference
from collections import defaultdict def dec(n): decomp = defaultdict(lambda: 0) i = 2 while n > 1: while n % i == 0: n /= i decomp[i] += 1 i += 1 return decomp def decomp(n): ans = defaultdict(lambda: 0) for i in range(2, n + 1): for key, value in dec(i). items(): ans[key] += value return ' * ' . join('{}^{}' . format(x, y) if y > 1 else str(x) for x, y in sorted(ans . items()))
Factorial decomposition
5a045fee46d843effa000070
[ "Fundamentals" ]
https://www.codewars.com/kata/5a045fee46d843effa000070
5 kyu
Implement the validate_args decorator, which raises an error **(InvalidArgument)** when the decorated function is called with arguments of the wrong type. Validate_args takes in a sequence of argument types as a variable number of arguments. You do not have to check that the number of arguments matches, only their type (number of arguments will not be tested). Your decorator must be well-behaved, i.e. the returned function must have the same name and docstring as the original, and must be able to handle the same arguments. Example : ```python @validate_args(str) def say_hello(name): return "Hello, " + name say_hello(1) # Raises InvalidArgument say_hello("Python") # Returns "Hello, Python" ``` InvalidArgument is preloaded for you. You may use it as if you had defined it in your own code.
reference
from functools import wraps def validate_args(* types): def decorator(func): @ wraps(func) def wrapper(* args): if all(map(isinstance, args, types)): return func(* args) else: raise InvalidArgument return wrapper return decorator
@validate_args
5a0001a606d5b68a5a000013
[ "Fundamentals" ]
https://www.codewars.com/kata/5a0001a606d5b68a5a000013
5 kyu
Implement the "memoize" decorator, which adds memoization capabilities to a function in order to make it more efficient. In short, memoization means storing computed values instead of recomputing every time. In the example below, this means that you only calculate fib(n) once for every n. The decorated function must return the same values as before for the same inputs. Your decorator must be well-behaved, i.e. the returned function must have the same name and docstring as the original. __Your decorator will only be tested on functions that have a single argument.__ Example : ```python @count_calls def fib(n): """Computes the nth number in the Fibonacci sequence""" return fib(n - 2) + fib(n - 1) if n > 1 else [0, 1][n] fib(10) fib.call_count == 177 # True fib(10) fib.call_count == 344 # True fib = count_calls(memoize(fib)) fib(10) fib.call_count == 19 # True fib(10) fib.call_count == 20 # True ``` The *count_calls* decorator is preloaded for you if you wish to use it. Do not rebind count_calls, as this could cause the tests to fail. __Note: you are not allowed to use the cache and lru_cache decorators from the functools module for this task.__
reference
from functools import wraps def memoize(func): cache = {} @ wraps(func) def wrapper(* args): if args in cache: return cache[args] else: return cache . setdefault(args, func(* args)) return wrapper
@memoize
59ffef8246d8434b0700001d
[ "Fundamentals" ]
https://www.codewars.com/kata/59ffef8246d8434b0700001d
6 kyu
Implement the functools.wraps decorator, which is used to preserve the name and docstring of a decorated function. Your decorator must not modify the behavior of the decorated function. Here's an example : ```python def identity(func): @wraps(func) def wrapper(*args, **kwargs): """Wraps func""" return func(*args, **kwargs) return wrapper @identity def return_one(): """Return one""" return 1 return_one.__name__ == 'return_one' # If wraps hadn't been used, __name__ would be equal to 'wrapper' return_one.__doc__ == 'Return one' # If wraps hadn't been used, __doc__ would be equal to 'Wraps func' ``` __Note: of course, you may not use the functools module for this kata.__
reference
def wraps(wrapped): def wrapper(func): for attr in ('__module__', '__name__', '__qualname__', '__doc__', '__annotations__'): try: value = getattr(wrapped, attr) except AttributeError: pass else: setattr(func, attr, value) func . __dict__ . update(getattr(wrapped, attr, {})) func . __wrapped__ = wrapped return func return wrapper
@wraps
5a010ee3ba2a14f4940001df
[ "Fundamentals" ]
https://www.codewars.com/kata/5a010ee3ba2a14f4940001df
6 kyu
Implement the htmlize decorator, which takes in a string argument and uses it to wrap a function's return value in html tags. Your decorator must be composable (i.e., it must be possible to do several decorations in a row) and well-behaved (i.e., your decorator must not change the name or docstring of the decorated function). Example : ```python @htmlize('section') @htmlize('blockquote') def generate_lorem(n_sentences): ... # Contents hidden for brevity print(generate_lorem(1)) # Prints the following : <section><blockquote>Has nominavi soleat eu homero has te ancillae.</blockquote></section> ```
reference
from functools import wraps def htmlize(tag): def wrapper(f): @ wraps(f) def fexec(* args, * * kwds): return '<{0}>{1}</{0}>' . format(tag, f(* args, * * kwds)) return fexec return wrapper
@htmlize
5a0117798ba9143a64000073
[ "Fundamentals" ]
https://www.codewars.com/kata/5a0117798ba9143a64000073
6 kyu
Implement the "count" decorator, which adds an attribute "call_count" to a function passed in to it, and increments it every time the function is called. The behavior of the decorated function must be the same as before. Your decorator must be well-behaved, i.e. the returned function must have the same name and docstring as the original, and must be able to handle the same arguments. Here's an example : ```python @count_calls def multiply(a, b=1): """Calculates the product of a and b.""" return a * b multiply.call_count == 0 # True for _ in range(3): multiply(1) multiply.call_count == 3 # True ```
reference
from functools import wraps def count_calls(func): @ wraps(func) def wrapper(* args, * * kwds): wrapper . call_count += 1 return func(* args, * * kwds) wrapper . call_count = 0 return wrapper
@count_calls
59ffe8bbffe75f6d94000016
[ "Fundamentals" ]
https://www.codewars.com/kata/59ffe8bbffe75f6d94000016
6 kyu
Observe the process with the array given below and the tracking of the sums of each corresponding array. ``` [5, 3, 6, 10, 5, 2, 2, 1] (34) ----> [5, 3, 6, 10, 2, 1] ----> (27) ------> [10, 6, 5, 3, 2, 1] ----> [4, 1, 2, 1, 1] (9) -----> [4, 1, 2] (7) ``` The tracked sums are : `[34, 27, 9, 7]`. We do not register one of the sums. It is not difficult to see why. We need the function `track_sum` ( or `trackSum` ) that receives an array ( or list ) and outputs a tuple ( or array ) with the following results in the order given below: - array with the tracked sums obtained in the process - final array So for our example given above, the result will be: ```python track_sum([5, 3, 6, 10, 5, 2, 2, 1]) == [[34, 27, 9, 7], [4, 1, 2]] ``` ```javascript trackSum([5, 3, 6, 10, 5, 2, 2, 1]) == [[34, 27, 9, 7], [4, 1, 2]] ``` ```haskell trackSum [ 5, 3, 6, 10, 5, 2, 2, 1 ] == ( [ 34, 27, 9, 7 ], [ 4, 1, 2 ] ) ``` You will find more cases in the Example Tests. Have a good time!
games
def track_sum(arr): a = arr b = sorted(set(a), reverse=True) c = [(x - y) for (x, y) in zip(b, b[1:])] d = sorted(set(c), key=c . index) return [list(map(sum, [a, b, c, d])), d]
Tracking Sums in a Process
56dbb6603e5dd6543c00098d
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic", "Sorting", "Puzzles" ]
https://www.codewars.com/kata/56dbb6603e5dd6543c00098d
6 kyu
Create a function that accepts 3 inputs, a string, a starting location, and a length. The function needs to simulate the string endlessly repeating in both directions and return a substring beginning at the starting location and continues for length. Example: ```python endless_string('xyz', -23, 6) == 'yzxyzx' ``` To visualize: Negative Positive 3 2 1 * 1 2 3 0987654321098765432109876543210123456789012345678901234567890 xyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzxyzx ****** -23 for a length of 6 == 'yzxyzx' Some more examples: ```python endless_string('xyz', 0, 4) == 'xyzx' endless_string('xyz', 19, 2) == 'yz' endless_string('xyz', -4, -4) == 'zxyz' ``` A negative length needs to include the starting position and return the characters to the left of the starting position.
reference
from itertools import cycle, islice def endless_string(stg, i, l): i = min(i, i + l) % len(stg) + (l < 0) j = i + abs(l) return "" . join(islice(cycle(stg), i, j))
Endless String
57048c1275263af10b00063e
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/57048c1275263af10b00063e
6 kyu
There are several (or no) spiders, butterflies, and dragonflies. In this kata, a spider has eight legs. A dragonfly or a butterfly has six legs. A __dragonfly__ has __two__ pairs of wings, while a __butterfly__ has __one__ pair of wings. _I am not sure whether they are biologically correct, but the values apply here._ Given the number of total heads, legs, and __pairs of__ wings, please calculate numbers of each kind of bugs. Of course they are integers. _However, I do not guarantee that they are positive in the test cases. Please regard the negative numbers as cases that do not make sense._ If answers make sense, return `[n_spider, n_butterfly, n_dragonfly]` else, please return `[-1, -1, -1]`. ## Example: `cal_n_bug(3, 20, 3) = [1, 1, 1]` **One** spider, **one** butterfly, **one** dragonfly in total have **three** heads, **twenty** legs (8 for the spider, 6 for the butterfly, and 6 for the dragonfly), and **three** _pairs_ of wings (1 for the butterfly and 2 for the dragonfly).
algorithms
# system of equations: # h = s + b + d # l = 8*s + 6*b + 6*d # w = 0*s + 1*b + 2*d # # get third equation in terms of b # b = w - 2d # # replace b in other equations: # h = s + (w - 2d) + d # l = 8*s + 6*(w - 2d) + 6*d # # get first equation in terms of s # s = h - w + d # # replace in remaining equation: # l = 8*(h - w + d) + 6*(w - 2d) + 6*d # simplify: # l = 8h - 8w + 8d + 6w - 12d + 6d # l = 8h - 2w + 2d # get in terms of d: # d = l/2 - 4h + w def cal_n_bug(h, l, w): d = l / 2 - 4 * h + w s = h - w + d b = w - 2 * d if d < 0 or s < 0 or b < 0: return [- 1, - 1, - 1] return [s, b, d]
Jungerstein's Math Training Room: 2. How many bugs?
58cf479f87c2e967250000e4
[ "Algorithms" ]
https://www.codewars.com/kata/58cf479f87c2e967250000e4
7 kyu
You are given a binary tree. Implement the method findMax which returns the maximal node value in the tree. For example, maximum in the following Tree is 11. ``` 7 / \ / \ 5 2 \ \ 6 11 /\ / 1 9 4 ``` Note: - Tree node values any integer value. - Tree can unbalanced and unsorted. - The root argument is never an empty tree. You are given a tree node class as follows: ```javascript class TreeNode { TreeNode left; TreeNode right; int value; } ``` ```python class TreeNode: def __init__(self, value, left = None, right = None): self.left = left self.right = right self.value = value ```
algorithms
def find_max(root): v = root . value if root . left: v = max(v, find_max(root . left)) if root . right: v = max(v, find_max(root . right)) return v
Find Max Tree Node
5a04450c8ba914083700000a
[ "Algorithms", "Recursion", "Binary Search Trees", "Binary" ]
https://www.codewars.com/kata/5a04450c8ba914083700000a
7 kyu
Write a function that replaces 'two', 'too' and 'to' with the number '2'. Even if the sound is found mid word (like in octopus) or not in lowercase grandma still thinks that should be replaced with a 2. Bless her. ```text 'I love to text' becomes 'I love 2 text' 'see you tomorrow' becomes 'see you 2morrow' 'look at that octopus' becomes 'look at that oc2pus' ``` Note that 'too' should become '2', not '2o'
reference
import re def textin(txt): return re . sub(r'(two|too|to)', '2', txt, flags=re . I)
Grandma learning to text
5a043fbef3251a5a2b0002b0
[ "Fundamentals" ]
https://www.codewars.com/kata/5a043fbef3251a5a2b0002b0
7 kyu
Write a function that takes a list of at least four elements as an argument and returns a list of the middle two or three elements in reverse order.
reference
def reverse_middle(lst): l = len(lst) / / 2 - 1 return lst[l: - l][:: - 1]
Slice the middle of a list backwards
5a043724ffe75fbab000009f
[ "Lists", "Fundamentals" ]
https://www.codewars.com/kata/5a043724ffe75fbab000009f
7 kyu
# Story The citizens of Bytetown, could not stand that the candidates in the mayoral election campaign have been placing their electoral posters at all places at their whim. The city council has finally decided to build an electoral wall for placing the posters and introduce the following rules: ``` Every candidate can place exactly one poster on the wall. All posters are of the same height equal to the height of the wall; the width of a poster can be any integer number of bytes (byte is the unit of length in Bytetown). The wall is divided into segments and the width of each segment is one byte. Each poster must completely cover a contiguous number of wall segments. ``` They have built a wall 1000 bytes long (such that there is enough place for all candidates). When the electoral campaign was restarted, the candidates were placing their posters on the wall and their posters differed widely in width. Moreover, the candidates started placing their posters on wall segments already occupied by other posters. Everyone in Bytetown was curious whose posters will be visible (entirely or in part) on the last day before elections. # Task You are given a 2D integer array `posters`. Each subarray is a 2-elements array. i.e. `[1,10]`. It represents a poster, 1 and 10 represent the starting position and ending position of a poster. Your task is to count the number of visible posters when all the posters are placed given the information about posters' size, their place and order of placement on the electoral wall. You can assume that the poster's pasting order is in accordance with the index order of the array. Still not understand the task? Look at the following example ;-) # Example For `posters =` ``` [ [1,4], [2,6], [8,10], [3,4], [7,10] ]``` the output should be `4` ``` In the following text, the position of byte and the index of poster are 1-based a 1000 bytes wall 0000000000................. (poster-1 paste from byte1 to byte4) 1111000000................. (poster-2 paste from byte2 to byte6) 1222220000................. (poster-3 paste from byte8 to byte10) 1222220333................. (poster-4 paste from byte3 to byte4) 1244220333................. (poster-5 paste from byte7 to byte10) 1244225555................. Now, we can see, poster 1,2,4,5 are visible, but poster 3 was covered by poster 5. ``` For `posters =` ``` [ [1,2], [3,4], [5,6], [7,8], [9,10], [1,10] ] ``` the output should be `1`, because poster 1,2,3,4,5 covered by poster6. ``` # Note - All positions of poster are valid(`1 <= position <= 1000`) - `1 <= posters.length <= 100` - Happy Coding `^_^`
reference
def count_visible(posters): wall = [0] * 1000 for i, (x, y) in enumerate(posters, 1): wall[x - 1: y] = [i] * (y - x + 1) wall = set(wall) wall . discard(0) return len(wall)
Simple Fun #376: The Visible Posters
5a028001ba2a14346b0000d4
[ "Fundamentals" ]
https://www.codewars.com/kata/5a028001ba2a14346b0000d4
7 kyu
Find the total sum of internal angles (in degrees) in an n-sided simple polygon. N will be greater than 2.
reference
def angle(n): return 180 * (n - 2)
Sum of angles
5a03b3f6a1c9040084001765
[ "Geometry", "Fundamentals" ]
https://www.codewars.com/kata/5a03b3f6a1c9040084001765
7 kyu
Your task is to return an array of the first `n` abundant numbers, sorted by their abundance. If the abundance is the same for multiple numbers, sort them numbers from smallest to largest. "An abundant number or excessive number is a number for which the sum of its proper divisors is greater than the number itself. The integer 12 is the first abundant number. Its proper divisors are 1, 2, 3, 4 and 6 for a total of 16. The amount by which the sum exceeds the number is the abundance. The number 12 has an abundance of 4, for example." For example: - `10` is not an abundant because the sum of its proper divisors is 8; `1+2+5=8`. - `12` is an abundant number with an abundance of 4; `1+2+3+4+6=16, 16-12=4`. - `18` is an abundant number with an abundance of 3; `1+2+3+6+9=21, 21-18=3`. The first 5 abundant numbers sorted by their abundance are `[20, 18, 12, 24, 30]` | Number | Sum of Divisors | Abundance | |---|---|---| | 20 | 22 | 2 | | 18 | 21 | 3 | | 12 | 16 | 4 | | 24 | 36 | 12 | | 30 | 42 | 12 | You will be given `n`, a number between 0 and 300 and must return an array of that length, and must do so within the test's time limit.
algorithms
def abundance(n): l, i = [], 2 while len(l) < n: i += 1 a = sum(k for k in range(2, i / / 2 + 1) if i % k == 0) - i if a > 0: l . append((a, i)) return [a for _, a in sorted(l)]
Abundant Array
5811cb19d8a4dadcb8000037
[ "Fundamentals", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5811cb19d8a4dadcb8000037
6 kyu
<h1>Happy traveller [Part 1]</h1> There is a play grid NxN; Always square! <pre> 0 1 2 3 0 [o, o, o, X] 1 [o, o, o, o] 2 [o, o, o, o] 3 [o, o, o, o] </pre><br> <p> You start from a random point. I mean, you are given the coordinates of your start position in format (row, col). </p> <p>And your <b>TASK is to define the number of unique paths to reach position X</b> (always in the top right corner). </p> <p> From any point you can go only <b>UP</b> or <b>RIGHT</b>. </p> <p> Implement a function <b>count_paths(N, (row, col))</b> which returns int; </p> <p>Assume input params are always valid. </p> Example: <ul> <li>count_paths(1, (0, 0))<br> grid 1x1: <pre> [X] </pre> You are already in the target point, so return 0 </li> <li> count_paths(2, (1, 0))<br> grid 2x2: <pre> [o, X] [@, o] </pre> You are at point @; you can move UP-RIGHT or RIGHT-UP, and there are 2 possible unique paths here </li> <li>count_paths(2, (1, 1))<br> grid 2x2: <pre> [o, X] [o, @] </pre> You are at point @; you can move only UP, so there is 1 possible unique path here </li> <li>count_paths(3, (1, 0))<br> grid 3x3: <pre> [o, o, X] [@, o, o] [o, o, o] </pre> You are at point @; you can move UP-RIGHT-RIGHT or RIGHT-UP-RIGHT, or RIGHT-RIGHT-UP, and there are 3 possible unique paths here </li> </ul> I think it's pretty clear =) <br><br> btw. you can use preloaded Grid class, which constructs 2d array for you. It's very very basic and simple. You can use numpy instead or any other way to produce the correct answer =) <code> grid = Grid(2, 2, 0)<br> samegrid = Grid.square(2)</code> will give you a grid[2][2], which you can print easily to console. <code> print(grid) </code> <pre> [0, 0] [0, 0] </pre> Enjoy! You can continue adventures: <a href="https://www.codewars.com/kata/happy-traveller-number-2">Happy traveller [Part 2]</a>
algorithms
from math import comb def count_paths(N, coords): n, m = coords[0], N - coords[1] - 1 return comb(n + m, n) if n + m > 0 else 0
Happy traveller [#1]
586d9a71aa0428466d00001c
[ "Algorithms" ]
https://www.codewars.com/kata/586d9a71aa0428466d00001c
6 kyu
The aim of this kata is to write function ```drawACross``` / ```draw_a_cross``` which returns a cross shape with 'x' characters on a square grid of size and height of our sole input n. All non-'x' characters in the grid should be filled with a space character (" "). For example for ```drawACross(7)``` / ```draw_a_cross(7)```, the function should draw the following grid: ```javascript x x x x x x x x x x x x x ``` The arms of the cross must only intersect through one central 'x' character, and start in the corner of the grid, so for even values of n, return ```"Centered cross not possible!"``` If n<3, function should return ```"Not possible to draw cross for grids less than 3x3!"```
games
def draw_a_cross(n: int) - > str: if n < 3: return "Not possible to draw cross for grids less than 3x3!" if n % 2 == 0: return "Centered cross not possible!" lines = [('x' + ' ' * i + 'x'). center(n) for i in range(n - 2, 0, - 2)] return '\n' . join(lines + ['x' . center(n)] + lines[:: - 1])
Drawing a Cross!
5a036ecb2b651d696f00007c
[ "Fundamentals", "Algorithms", "Games", "ASCII Art" ]
https://www.codewars.com/kata/5a036ecb2b651d696f00007c
7 kyu
Create a function that takes any sentence and redistributes the spaces (and adds additional spaces if needed) so that each word starts with a vowel. The letters should all be in the same order but every vowel in the sentence should be the start of a new word. The first word in the new sentence may start without a vowel. It should return a string in all lowercase with no punctuation (only alphanumeric characters). ## EXAMPLES ```javascript 'It is beautiful weather today!' => 'it isb e a ut if ulw e ath ert od ay' 'Coding is great' => 'c od ing isgr e at' 'my number is 0208-533-2325' => 'myn umb er is02085332325' ```
algorithms
from re import sub def vowel_start(st): return sub(r'(?<=.)([aeiou])', r' \1', sub(r'[^a-z0-9]', '', st . lower()))
Start with a Vowel
5a02e9c19f8e2dbd50000167
[ "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/5a02e9c19f8e2dbd50000167
7 kyu
Farmer Bob have a big farm, where he growths chickens, rabbits and cows. It is very difficult to count the number of animals for each type manually, so he diceded to buy a system to do it. But he bought a cheap system that can count only total number of heads, total number of legs and total number of horns of animals on the farm. Help Bob to figure out how many chickens, rabbits and cows does he have? All chickens have 2 legs, 1 head and no horns; all rabbits have 4 legs, 1 head and no horns; all cows have 4 legs, 1 head and 2 horns. Your task is to write a function ```Python get_animals_count(legs_number, heads_number, horns_number) ``` ```Csharp Dictionary<string, int> get_animals_count(int legs_number, int heads_number, int horns_number) ``` , which returns a dictionary ```python {"rabbits" : rabbits_count, "chickens" : chickens_count, "cows" : cows_count} ``` ```Csharp new Dictionary<string, int>(){{"rabbits", rabbits_count},{"chickens", chickens_count},{"cows", cows_count}} ``` Parameters `legs_number, heads_number, horns_number` are integer, all tests have valid input. Example: ```python get_animals_count(34, 11, 6); # Should return {"rabbits" : 3, "chickens" : 5, "cows" : 3} get_animals_count(154, 42, 10); # Should return {"rabbits" : 30, "chickens" : 7, "cows" : 5} ``` ```Csharp get_animals_count(34, 11, 6); //Should return Dictionary<string, int>(){{"rabbits", 3},{"chickens", 5},{"cows", 3}} get_animals_count(154, 42, 10); //Should return Dictionary<string, int>(){{"rabbits", 30},{"chickens", 7},{"cows", 5}} ```
algorithms
def get_animals_count(legs, heads, horns): cows = horns / / 2 rabbits = legs / / 2 - cows - heads chickens = heads - cows - rabbits return dict(cows=cows, rabbits=rabbits, chickens=chickens)
Help the farmer to count rabbits, chickens and cows
5a02037ac374cbab41000089
[ "Fundamentals", "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/5a02037ac374cbab41000089
7 kyu
Given the number n, return a string which shows the minimum number of moves to complete the tower of Hanoi consisting of n layers. Tower of Hanoi : https://en.wikipedia.org/wiki/Tower_of_Hanoi Example - 2 layered Tower of Hanoi Input: n=2 Start [[2, 1], [], []] Goal [[], [], [2, 1]] Expected Output : '[[2, 1], [], []]\n[[2], [1], []]\n[[], [1], [2]]\n[[], [], [2, 1]]'
algorithms
def hanoiArray(n): A, B, C = list(range(n, 0, - 1)), [], [] res = [str([A, C, B])] def rec(n, X, Y, Z): if not n: return rec(n - 1, X, Z, Y) Y . append(X . pop()) res . append(str([A, C, B])) rec(n - 1, Z, Y, X) rec(n, A, B, C) return '\n' . join(res)
Hanoi Tower Array
5a02a758ffe75f8da5000030
[ "Algorithms" ]
https://www.codewars.com/kata/5a02a758ffe75f8da5000030
6 kyu
Hello, your test today is to create an algorithm. You do not have a description of what it should do, all you have are the inputs and outputs. All inputs are strings and all outputs are required to be. #### Example 1: Input: `abcdefghijklmnopqrstuvwxyz` Output: ```text xxxxxxxxxxxxxxxxxxxxxxxxw y w y tttttttttttttttttttts w y u s w y u ppppppppppppppppo s w y u q o s w y u q llllllllllllk o s w y u q m k o s w y u q m hhhhhhhhg k o s w y u q m i g k o s w y u q m i ddddc g k o s w y u q m i e c g k o s w y u q m i e c g k o s w y u q m i e abb g k o s w y u q m i e g k o s w y u q m i effffff k o s w y u q m i k o s w y u q m ijjjjjjjjjj o s w y u q m o s w y u q mnnnnnnnnnnnnnn s w y u q s w y u qrrrrrrrrrrrrrrrrrr w y u w y uvvvvvvvvvvvvvvvvvvvvvv y yzzzzzzzzzzzzzzzzzzzzzzzzzz ``` ------ #### Example 2: Input: `adbbeb` Output: ```text bbb e b adedd e e ebb ``` ------ #### Example 3: Input: `wordspiral` Output: ```text w w w w w ddddr w s r w s r w s r w s r w s r w s r w s r w s r w s r w rrrrrrrrrrrrrrrrrri w allllllllllll i w s r i w s r i w s r i w s r i w s r i w s r i woooooooooosoooo i spppppppppppppppp ```
algorithms
from itertools import cycle def spiralize(word): x, y, dirs, spiral = 0, 0, cycle([(1, 0), (0, 1), (- 1, 0), (0, - 1)]), {} for c in word: dx, dy = next(dirs) for _ in range(ord(c) - 96): x, y = x + dx, y + dy spiral[(x, y)] = c miX, maX = min(spiral . keys(), key=lambda t: t[0])[ 0], max(spiral . keys(), key=lambda t: t[0])[0] miY, maY = min(spiral . keys(), key=lambda t: t[1])[ 1], max(spiral . keys(), key=lambda t: t[1])[1] return '\n' . join('' . join(spiral . get((x, y), ' ') for y in range(miY, maY + 1)) for x in range(miX, maX + 1))
Word Spiral
583726b8aa6717a718000002
[ "Algorithms" ]
https://www.codewars.com/kata/583726b8aa6717a718000002
5 kyu
This the second part part of the kata: https://www.codewars.com/kata/the-sum-and-the-rest-of-certain-pairs-of-numbers-have-to-be-perfect-squares In this part we will have to create a faster algorithm because the tests will be more challenging. The function ```n_closestPairs_tonum()```, (Javascript: ```nClosestPairsToNum()```), will accept two arguments, ```upper_limit``` and ```k```. The function should return the ```k``` largest pair of numbers [m, n] and the closest to ```upper_limit```. Expressing it in code: ```python n_closestPairs_tonum(upper_limit, k) #-> [[m1, n1], [m2, n2], ...., [mk, nk]] ``` ```javascript nClosestPairsToNum(upperLimit, k) //-> [[m1, n1], [m2, n2], ...., [mk, nk]] ``` Such that: ``` upper_limit >= m1 >= m2 >= ....>= mk > 0 ``` Examples: ```python upper_limit = 1000; k = 4 n_closestPairs_tonum(upper_limit, k) == [[997, 372], [986, 950], [986, 310], [985, 864]] upper_limit = 10000; k = 8 n_closestPairs_tonum(upper_limit, k) == [[9997, 8772], [9997, 2772], [9992, 6392], [9986, 5890], [9985, 7176], [9985, 4656], [9981, 9900], [9973, 9348]] ``` Features of the tests: ``` 1000 ≤ upper_limit ≤ 200000 2 ≤ k ≤ 20 ``` Enjoy it!
algorithms
def n_closestPairs_tonum(upper_lim, k): square_lim = int((2 * upper_lim) * * .5) + 1 squares = [n * n for n in range(1, square_lim)] p, s = [], set(squares) for m in range(upper_lim - 1, 1, - 1): for b in squares: if b >= m: break if 2 * m - b in s: p . append([m, m - b]) if len(p) == k: return p
The Sum and The Rest of Certain Pairs of Numbers have to be Perfect Squares (more Challenging)
57aaaada72292d3b8f0001b4
[ "Algorithms", "Mathematics", "Data Structures" ]
https://www.codewars.com/kata/57aaaada72292d3b8f0001b4
5 kyu
You are the owner of a box making company. Your company can produce any equal sided polygon box, but plenty of your customers want to transport circular objects in these boxes. Circles are a very common shape in the consumer industry. Tin cans, glasses, tyres and CD's are a few examples of these. As a result you decide to add this information on your boxes: The largest (diameter) circular object that can fit into a given box.
games
import math def circle_diameter(sides, side_length): return side_length / math . tan(math . pi / sides)
Circles in Polygons
5a026a9cffe75fbace00007f
[ "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/5a026a9cffe75fbace00007f
8 kyu
You are given three integers in the range [0-99]. You must determine if any ordering of the numbers forms a date from the 20th century. - If no ordering forms a date, return the string `"invalid"`. - If multiple distinct orderings form dates, return the string `"ambiguous"`. - If only one ordering forms a date, return that date as a string with format `"YY/MM/DD"`. ## Examples ```python unique_date(13, 12, 77) == '77/12/13' # only the ordering (77, 12, 13) forms a date unique_date(13, 77, 12) == '77/12/13' # argument order is irrelevant unique_date(1, 2, 3) == 'ambiguous' # 01/02/03, 02/01/03, ... unique_date(3, 2, 1) == 'ambiguous' unique_date(50, 40, 60) == 'invalid' # no ordering could form a date unique_date(40, 50, 60) == 'invalid' ``` ## Note This kata was inspired by my encounter with [google.com/foobar](http://www.google.com/foobar)
algorithms
from datetime import date from itertools import permutations def uniqueDate(* args): ds = set() for y, m, d in permutations(args, 3): try: ds . add(date(y + 2000, m, d)) except: pass return 'ambiguous' if len(ds) > 1 else 'invalid' if not ds else ds . pop(). strftime("%y/%m/%d")
Can these three numbers form a date?
582406166cf35b7f93000057
[ "Algorithms", "Date Time", "Permutations" ]
https://www.codewars.com/kata/582406166cf35b7f93000057
6 kyu
Create a function `sierpinski` to generate an ASCII representation of a Sierpinski triangle of order **N**. Seperate each line with `\n`. You don't have to check the input value. The output should look like this: sierpinski(4) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
algorithms
def sierpinski(n): t = ['*'] for _ in range(n): t = [r . center(2 * len(t[- 1]) + 1) for r in t] + [r + ' ' + r for r in t] return '\n' . join(t)
Sierpinski triangle
58add662ea140541a50000f7
[ "Algorithms", "ASCII Art" ]
https://www.codewars.com/kata/58add662ea140541a50000f7
6 kyu
A [binary search tree](https://en.wikipedia.org/wiki/Binary_search_tree) is a binary tree that is ordered. This means that if you were to convert the tree to an array using an in-order traversal, the array would be in sorted order. The benefit gained by this ordering is that when the tree is balanced, searching is a logarithmic time operation, since each node you look at that isn't the one you're searching for lets you discard half of the tree. If you haven't worked with binary trees before or don't understand what a traversal is, you can learn more about that here: https://www.codewars.com/kata/binary-tree-traversal. In this kata, you will write a function that will validate that a given binary tree is a binary search tree. The sort order is not predefined so it should work with either. These are valid binary search trees: 5 / \ 2 7 / \ \ 1 3 9 7 / \ 9 2 while these are not: 1 / \ 2 3 5 / \ 2 9 \ 7 There are several different approaches you can take to solve this kata. If you're not as comfortable with recursion I'd recommend practicing that. Note: no test case tree will contain duplicate numbers.
algorithms
class T: def __init__(self, value, left=None, right=None): self . value = value self . left = left self . right = right def is_bst(node): def extract(node): if node is not None: yield from extract(node . left) yield node . value yield from extract(node . right) gen = extract(node) try: u, v = next(gen), next(gen) except StopIteration: return True cmp = u < v for w in gen: if cmp != (v < w): return False v = w return True
Binary search tree validation
588534713472944a9e000029
[ "Trees", "Recursion", "Data Structures", "Algorithms" ]
https://www.codewars.com/kata/588534713472944a9e000029
5 kyu
You are given two interior angles (in degrees) of a triangle. Write a function to return the 3rd. Note: only positive integers will be tested. https://en.wikipedia.org/wiki/Triangle
reference
def other_angle(a, b): return 180 - a - b
Third Angle of a Triangle
5a023c426975981341000014
[ "Fundamentals" ]
https://www.codewars.com/kata/5a023c426975981341000014
8 kyu
## Task You are at start location `[0, 0]` in mountain area of NxN and you can **only** move in one of the four cardinal directions (i.e. North, East, South, West). Return minimal number of `climb rounds` to target location `[N-1, N-1]`. Number of `climb rounds` between adjacent locations is defined as difference of location altitudes (ascending or descending). Location altitude is defined as an integer number (0-9). ## Path Finder Series: - [#1: can you reach the exit?](https://www.codewars.com/kata/5765870e190b1472ec0022a2) - [#2: shortest path](https://www.codewars.com/kata/57658bfa28ed87ecfa00058a) - [#3: the Alpinist](https://www.codewars.com/kata/576986639772456f6f00030c) - [#4: where are you?](https://www.codewars.com/kata/5a0573c446d8435b8e00009f) - [#5: there's someone here](https://www.codewars.com/kata/5a05969cba2a14e541000129)
algorithms
def path_finder(maze): grid = maze . splitlines() end = h, w = len(grid) - 1, len(grid[0]) - 1 bag, seen = {(0, 0): 0}, set() while bag: x, y = min(bag, key=bag . get) rounds = bag . pop((x, y)) seen . add((x, y)) if (x, y) == end: return rounds for u, v in (- 1, 0), (0, 1), (1, 0), (0, - 1): m, n = x + u, y + v if (m, n) in seen or not (0 <= m <= h and 0 <= n <= w): continue new_rounds = rounds + abs(int(grid[x][y]) - int(grid[m][n])) if new_rounds < bag . get((m, n), float('inf')): bag[m, n] = new_rounds
Path Finder #3: the Alpinist
576986639772456f6f00030c
[ "Algorithms" ]
https://www.codewars.com/kata/576986639772456f6f00030c
3 kyu
## Story Before we dive into the exercise, I would like to show you why these numbers are so important in computer programming today. It all goes back to the time of 19th century. Where computers we know today were non-existing. The first ever **computer program** was for the Analytical Engine to compute **Bernoulli numbers**. A woman named Ada Lovelace wrote the very first program. The sad part is the engine was never fully build so her code was never tested. She also predicted the start of **AI** (artificial intelligence). Computers will be able to compose music by themselves, solve problems (not only numbers) ... So in her honor reproduce what was done back in 1842. The Bernoulli numbers are a sequence of rational numbers with deep connections to number theory. The Swiss mathematician Jakob Bernoulli and the Japanese mathematician Seki Kowa discovered the numbers around the same time at the start of the 18th Century. If you want to read more about her or Bernoulli numbers follow these links: https://en.wikipedia.org/wiki/Ada_Lovelace https://en.wikipedia.org/wiki/Bernoulli_number http://mathworld.wolfram.com/BernoulliNumber.html ## Exercise Your job is to write a function `bernoulli_number(n)` which outputs the n-th Bernoulli number. The input will always be a non-negative integer so you do not need to worry about exceptions. How you will solve the problem is none of my business but here are some guidelines. You can make pascal triangle and then with the basic formula generate all Bernoulli numbers. Look example below. For the sake of floating numbers, just use `Fractions` so there will be no problems with rounding. 0 = 1 + 2b<sub>1</sub> ............................................................... b<sub>1</sub> = - 1/2 0 = 1 + 3b<sub>1</sub> + 3b<sub>2</sub> ................................................... b<sub>2</sub> = 1/6 0 = 1 + 4b<sub>1</sub> + 6b<sub>2</sub> + 4b<sub>3</sub> ....................................... b<sub>3</sub> = 0 0 = 1 + 5b<sub>1</sub> + 10b<sub>2</sub> + 10b<sub>3</sub> + 5b<sub>4</sub> ...................... b<sub>4</sub> = - 1/30 ... and so on. ``` bernoulli_number(0) # return 1 bernoulli_number(1) # return Fraction(-1,2) or Rational(-1,2) or "1/2" bernoulli_number(6) # return Fraction(1,42) or ... bernoulli_number(42) # return Fraction(1520097643918070802691,1806) or ... bernoulli_number(22) # return Fraction(854513,138) or ... "854513/138" ``` ## Note See "Sample Tests" to see the return type for each language. Good luck and happy coding! PS: be careful some numbers might exceed `1000`. If this kata is too hard for you try to solve pascal triangle and something similar to this and then come back :).
algorithms
from fractions import Fraction as frac def ber(): res, m = [], 0 while True: res . append(frac(1, m + 1)) for j in range(m, 0, - 1): res[j - 1] = j * (res[j - 1] - res[j]) yield res[0] m += 1 def bernoulli_number(n): if n == 1: return Fraction(- 1, 2) if n % 2 == 1: return 0 bn2 = [ix for ix in zip(range(n + 2), ber())] bn2 = [b for _, b in bn2] return bn2[n]
Bernoulli numbers
567ffb369f7f92e53800005b
[ "Fundamentals", "Mathematics", "Number Theory", "Algorithms" ]
https://www.codewars.com/kata/567ffb369f7f92e53800005b
4 kyu
**Task** Create class "Package" that represents a package which has a *length*, *width*, *height* (*cm*) and *weight* (*kg*) parameter. Furthermore, the following should always give the current volume of the package: ```python p = Package(0.2, 0.2, 0.2) p.volume # computes 0.2 * 0.2 * 0.2 and returns it ``` But lo and behold! The following constraints must be satisfied for all packages at all time: - 0 < length <= 350 - 0 < width <= 300 - 0 < height <= 150 - 0 < weight <= 40 For example, the following should raise a custom (written-by-you) *DimensionsOutOfBoundError*: ``` python p = Package(351, 0.2, 0.2, 0.2) # raises DimensionsOutOfBoundError with message: # "Package length==351 out of bounds, should be: 0 < length <= 350" ``` Assignments with out-of-bounds values also produce the same error: ``` python p = Package(10, 0.2, 0.2, 0.2) p.length = 351 # raises DimensionsOutOfBoundError with message: # "Package length==351 out of bounds, should be: 0 < length <= 350" ``` **Notes** The error message given when "DimensionsOutOfBoundError" is raised should always follow the exact format: "Package {variable}=={value} out of bounds, should be: {lower} < {variable} <={upper}" where variable is *length*, *width*, *height* or *weight*; value is the out-of-bounds value and lower/upper are lower/upper bound on the variable, respectively.
reference
class Package (object): maxs = {"length": 350, "width": 300, "height": 150, "weight": 40} def __init__(self, l, w, h, wg): self . length = l self . width = w self . height = h self . weight = wg def __setattr__(self, att, v): if v <= 0 or v > Package . maxs[att]: raise DimensionsOutOfBoundError(att, v, Package . maxs[att]) self . __dict__[att] = v @ property def volume(self): return self . length * self . width * self . height class DimensionsOutOfBoundError (Exception): def __init__(self, dim, val, max): self . str = "Package %s==%d out of bounds, should be: 0 < %s <= %d" % ( dim, val, dim, max) def __str__(self): return self . str
Packet Delivery -- Enforcing Constraints
587e1ef6f1a2534bbe0001ef
[ "Fundamentals" ]
https://www.codewars.com/kata/587e1ef6f1a2534bbe0001ef
6 kyu
# Task I have defined (invisible to you) the function "raises_once" that raises an exception if it is called for the first time and returns a magic value the second time it is called. Your job is to call it twice (silencing the exception) and assign the magic value it returns to the variable *magic*. So far, so simple.. now on to the nasty stuff. # Restrictions Your code **must not**... * be longer than one line * contain "def" * contain "lambda" * contain "return" (search is case-insensitive) * contain ";" * contain "class" * contain "import" * contain "eval" * contain more than a single "=" sign # Credits Inspired by [suic](https://www.codewars.com/users/553bfb4e8234ef15340000b9)'s katas. If you enjoy this one, make sure to check his out as well!
games
exec('try: raises_once()\nexcept: magic = raises_once()')
Exception Handling (with restrictions)
586fa9ddc66d18e2e10000ce
[ "Puzzles", "Restricted" ]
https://www.codewars.com/kata/586fa9ddc66d18e2e10000ce
6 kyu
You're given a square consisting of random numbers, like so: ```javascript var square = [ [1,2,3], [4,8,2], [1,5,3]]; ``` Your job is to calculate the minimum total cost when moving from the upper left corner to the coordinate given. You're only allowed to move right or down. In the above example the minimum path would be: ```javascript var square = [ [1,2,3], [_,_,2], [_,_,3]]; ``` Giving a total of 11. Start and end position are included. Note: Coordinates are marked as x horizontally and y vertically.
algorithms
def min_path(grid, x, y): paths = [0] + [float('inf')] * (x + 1) for j in range(y + 1): for i in range(x + 1): paths[i] = grid[j][i] + min(paths[i - 1], paths[i]) return paths[x]
Minimum path in squares
5845e3f680a8cf0bad00017d
[ "Dynamic Programming", "Algorithms" ]
https://www.codewars.com/kata/5845e3f680a8cf0bad00017d
5 kyu
An `non decreasing` number is one containing no two consecutive digits (left to right), whose the first is higer than the second. For example, 1235 is an non decreasing number, 1229 is too, but 123429 isn't. Write a function that finds the number of non decreasing numbers up to `10**N` (exclusive) where N is the input of your function. For example, if `N=3`, you have to count all non decreasing numbers from 0 to 999. You'll definitely need something smarter than brute force for large values of N!
reference
from math import comb def increasing_numbers(digits): return comb(digits + 9, 9)
Increasing Numbers with N Digits
57698ec6dd8944888e000110
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/57698ec6dd8944888e000110
6 kyu
## Summary Implement an algorithm which analyzes a two-color image and determines how many isolated areas of a single color the image contains. ### Islands An "island" is a set of adjacent pixels of one color (`1`) which is surrounded by pixels of a different color (`0`). Pixels are considered adjacent if their coordinates differ by no more than `1` on the `X` or `Y` axis. Below you can see an example with 2 islands: * on the left in the form of a matrix of `1`'s and `0`'s * on the right in an equivalent stringified form using `"X"` and `"~"` characters for better readability ``` [ [0,0,0,0,0,0,0,0,0,0], "~~~~~~~~~~" [0,0,1,1,0,0,0,0,0,0], "~~XX~~~~~~" [0,0,1,1,0,0,0,0,0,0], "~~XX~~~~~~" [0,0,0,0,0,0,0,0,1,0], "~~~~~~~~X~" [0,0,0,0,0,1,1,1,0,0], "~~~~~XXX~~" [0,0,0,0,0,0,0,0,0,0], "~~~~~~~~~~" ] ``` ### Specification Your task is to implement a function which accepts a matrix containing the numbers `0` and `1`. It should return the number of islands as an integer.
algorithms
def count_islands(a): def dfs(x, y): if not (0 <= x < len(a) and 0 <= y < len(a[0]) and a[x][y]): return 0 a[x][y] = 0 for dx in range(- 1, 2): for dy in range(- 1, 2): dfs(x + dx, y + dy) return 1 return sum(dfs(i, j) for i in range(len(a)) for j in range(len(a[0])))
Count the Islands
55a4f1f67157d8cbe200007b
[ "Algorithms", "Graphics", "Arrays" ]
https://www.codewars.com/kata/55a4f1f67157d8cbe200007b
6 kyu
A palindrome is a series of characters that read the same forwards as backwards such as "hannah", "racecar" and "lol". For this Kata you need to write a function that takes a string of characters and returns the length, as an integer value, of longest alphanumeric palindrome that could be made by combining the characters in any order but using each character only once. The function should not be case sensitive. For example if passed "Hannah" it should return 6 and if passed "aabbcc_yYx_" it should return 9 because one possible palindrome would be "abcyxycba".
algorithms
from collections import Counter def longest_palindrome(s): c = Counter(filter(str . isalnum, s . lower())) return sum(v / / 2 * 2 for v in c . values()) + any(v % 2 for v in c . values())
Longest palindrome
5a0178f66f793bc5b0001728
[ "Arrays", "Strings", "Algorithms" ]
https://www.codewars.com/kata/5a0178f66f793bc5b0001728
6 kyu