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
You're laying out a rad pixel art mural to paint on your living room wall in homage to [Paul Robertson](http://68.media.tumblr.com/0f55f7f3789a354cfcda7c2a64f501d1/tumblr_o7eq3biK9s1qhccbco1_500.png), your favorite pixel artist. You want your work to be perfect down to the millimeter. You haven't decided on the dimensions of your piece, how large you want your pixels to be, or which wall you want to use. You just know that you want to fit an exact number of pixels. To help decide those things you've decided to write a function, `is_divisible()` that will tell you whether a wall of a certain length can exactly fit an integer number of pixels of a certain length. Your function should take two arguments: the size of the wall in millimeters and the size of a pixel in millimeters. It should return `True` if you can fit an exact number of pixels on the wall, otherwise it should return `False`. For example `is_divisible(4050, 27)` should return `True`, but `is_divisible(4066, 27)` should return `False`. ```if:python Note: you don't need to use an `if` statement here. Remember that in Python an expression using the `==` comparison operator will evaluate to either `True` or `False`: ``` ```python >>> def equals_three(num): >>> return num == 3 >>> equals_three(5) False >>> equals_three(3) True ``` <!-- C# Documentation --> ```if:csharp <h1>Documentation:</h1> <h2>Kata.IsDivisible Method (Int32, Int32)</h2> Returns a boolean representing if the first argument is perfectly divisible by the second argument. <span style="font-size:20px">Syntax</span> <div style="margin-top:-10px;padding:2px;background-color:Grey;position:relative;left:20px;width:600px;"> <div style="background-color:White;color:Black;border:1px;display:block;padding:10px;padding-left:18px;font-family:Consolas,Courier,monospace;"> <span style="color:Blue;">public</span> <span style="color:Blue;">static</span> <span style="color:Blue;">bool</span> IsDivisible(</br> <span style="position:relative;left:62px;">int wallLength,</span></br>   <span style="position:relative;left:62px;">int pixelSize,</span></br>   ) </div> </div> </br> <div style="position:relative;left:20px;"> <strong>Parameters</strong> </br> <i>wallLength</i> </br> <span style="position:relative;left:50px;">Type: <a href="https://msdn.microsoft.com/en-us/library/system.int32(v=vs.110).aspx">System.Int32</a></span></br> <span style="position:relative;left:50px;">The length of the wall in millimeters.</span> </br></br> <i>pixelSize</i> </br> <span style="position:relative;left:50px;">Type: <a href="https://msdn.microsoft.com/en-us/library/system.int32(v=vs.110).aspx">System.Int32</a></span></br> <span style="position:relative;left:50px;">The length of a pixel in millimeters.</span> </br></br> <strong>Return Value</strong> </br> <span>Type: <a href="https://msdn.microsoft.com/en-us/library/system.boolean(v=vs.110).aspx">System.Boolean</a></span></br> A boolean value representing if the first argument is perfectly divisible by the second. </div> ``` <!-- End C# Documentation -->
reference
def is_divisible(wall_length, pixel_size): return wall_length % pixel_size == 0
Thinkful - Number Drills: Pixelart planning
58630e2ae88af44d2b0000ea
[ "Fundamentals" ]
https://www.codewars.com/kata/58630e2ae88af44d2b0000ea
8 kyu
You like the way the Python `+` operator easily handles adding different numeric types, but you need a tool to do that kind of addition without killing your program with a `TypeError` exception whenever you accidentally try adding incompatible types like strings and lists to numbers. You decide to write a function `my_add()` that takes two arguments. If the arguments can be added together it returns the sum. If adding the arguments together would raise an error the function should return `None` instead. For example, `my_add(1, 3.414)` would return `4.414`, but `my_add(42, " is the answer.")` would return `None`. Hint: using a `try` / `except` statement may simplify this kata.
reference
def my_add(a, b): try: return a + b except TypeError: return None
Thinkful - Logic Drills: Graceful addition
58659b1261cbfc8bfc00020a
[ "Fundamentals" ]
https://www.codewars.com/kata/58659b1261cbfc8bfc00020a
7 kyu
Now that we have a [Block](http://www.codewars.com/kata/55b75fcf67e558d3750000a3) let's move on to something slightly more complex: a `Sphere`. ## Arguments for the constructor ```python radius -> integer or float (do not round it) mass -> integer or float (do not round it) ``` ```csharp radius -> integer mass -> integer ``` ## Methods to be defined ```python get_radius() => radius of the Sphere (do not round it) get_mass() => mass of the Sphere (do not round it) get_volume() => volume of the Sphere (rounded to 5 place after the decimal) get_surface_area() => surface area of the Sphere (rounded to 5 place after the decimal) get_density() => density of the Sphere (rounded to 5 place after the decimal) ``` ```csharp GetRadius() => radius of the Sphere GetMass() => mass of the Sphere GetVolume() => volume of the Sphere (a double rounded to 5 place after the decimal) GetSurfaceArea() => surface area of the Sphere (a double rounded to 5 place after the decimal) GetDensity() => density of the Sphere (a double rounded to 5 place after the decimal) ``` ## Example ```python ball = Sphere(2,50) ball.get_radius() -> 2 ball.get_mass() -> 50 ball.get_volume() -> 33.51032 ball.get_surface_area() -> 50.26548 ball.get_density() -> 1.49208 ``` ```csharp Sphere ball = new Sphere(2,50) ball.GetRadius() -> 2 ball.GetMass() -> 50 ball.GetVolume() -> 33.51032 ball.GetSurfaceArea() -> 50.26548 ball.GetDensity() -> 1.49208 ``` Any feedback would be much appreciated
reference
from math import pi class Sphere (object): def __init__(self, radius, mass): self . radius = radius self . mass = mass self . volume = 4 * pi * self . radius * * 3 / 3 self . surface = 4 * pi * self . radius * * 2 def get_radius(self): return self . radius def get_mass(self): return self . mass def get_volume(self): return round(self . volume, 5) def get_surface_area(self): return round(self . surface, 5) def get_density(self): return round(self . mass / self . volume, 5)
Building Spheres
55c1d030da313ed05100005d
[ "Object-oriented Programming", "Fundamentals" ]
https://www.codewars.com/kata/55c1d030da313ed05100005d
7 kyu
Create a program that will return whether an input value is a str, int, float, or bool. Return the name of the value. ### Examples - Input = 23 --> Output = int - Input = 2.3 --> Output = float - Input = "Hello" --> Output = str - Input = True --> Output = bool
bug_fixes
def types(x): return type(x). __name__
Back to Basics
55a89dd69fdfb0d5ce0000ac
[ "Fundamentals" ]
https://www.codewars.com/kata/55a89dd69fdfb0d5ce0000ac
7 kyu
Get ASCII value of a character. For the ASCII table you can refer to http://www.asciitable.com/
reference
def get_ascii(c): return ord(c)
get ascii value of character
55acfc59c3c23d230f00006d
[ "Fundamentals" ]
https://www.codewars.com/kata/55acfc59c3c23d230f00006d
8 kyu
Write a function `count_vowels` to count the number of vowels in a given string. ### Notes: - Return `nil` or `None` for non-string inputs. - Return `0` if the parameter is omitted. ### Examples: ```ruby count_vowels("abcdefg") => 2 count_vowels("aAbcdeEfg") => 4 count_vowels(12) => nil ``` ```python count_vowels("abcdefg") => 2 count_vowels("aAbcdeEfg") => 4 count_vowels(12) => None ```
reference
def count_vowels(s=''): return sum(x . lower() in 'aeoui' for x in s) if type(s) == str else None
count vowels in a string
55b105503da095817e0000b6
[ "Fundamentals", "Strings", "Data Types", "Regular Expressions", "Declarative Programming", "Advanced Language Features", "Programming Paradigms" ]
https://www.codewars.com/kata/55b105503da095817e0000b6
7 kyu
Welcome young Jedi! In this Kata you must create a function that takes an amount of US currency in `cents`, and returns a dictionary/hash which shows the least amount of coins used to make up that amount. The only coin denominations considered in this exercise are: `Pennies (1¢), Nickels (5¢), Dimes (10¢) and Quarters (25¢)`. Therefor the dictionary returned should contain exactly 4 key/value pairs. Notes: * If the function is passed either 0 or a negative number, the function should return the dictionary with all values equal to 0. * If a float is passed into the function, its value should be rounded down, and the resulting dictionary should never contain fractions of a coin. ## Examples ``` loose_change(56) ==> {'Nickels': 1, 'Pennies': 1, 'Dimes': 0, 'Quarters': 2} loose_change(-435) ==> {'Nickels': 0, 'Pennies': 0, 'Dimes': 0, 'Quarters': 0} loose_change(4.935) ==> {'Nickels': 0, 'Pennies': 4, 'Dimes': 0, 'Quarters': 0} ```
reference
import math def loose_change(cents): if cents < 0: cents = 0 cents = int(cents) change = {} change['Quarters'] = cents / / 25 cents = cents % 25 change['Dimes'] = cents / / 10 cents = cents % 10 change['Nickels'] = cents / / 5 cents = cents % 5 change['Pennies'] = cents return change
Loose Change
5571f712ddf00b54420000ee
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5571f712ddf00b54420000ee
6 kyu
Trigrams are a special case of the n-gram, where n is 3. One trigram is a continous sequence of 3 chars in phrase. [Wikipedia](https://en.wikipedia.org/wiki/Trigram) - return all trigrams for the given phrase - replace spaces with underscore (`_`) - return an empty string for phrases shorter than 3 Example: ``` "the quick red" --> "the he_ e_q _qu qui uic ick ck_ k_r _re red"
reference
def trigrams(phrase): phrase = phrase . replace(" ", "_") return " " . join([phrase[i: i + 3] for i in range(len(phrase) - 2)])
Trigrams
55d8dc4c8e629e55dc000068
[ "Fundamentals" ]
https://www.codewars.com/kata/55d8dc4c8e629e55dc000068
7 kyu
Write a function that will take a key of X and place it in the middle of Y repeated N times. Extra challege (not tested): You can complete this with under 70 characters without using regex. Challenge yourself to do this. It wont be best practices but it will work. Rules: If X cannot be placed in the middle, return X. N will always be > 0. Example: ```javascript X = 'A'; Y = '*'; N = 10; Y repeated N times = '**********'; X in the middle of Y repeated N times = '*****A*****'; ```
reference
def middle_me(N, X, Y): if N % 2 == 1: return X else: return Y * (N / / 2) + X + Y * (N / / 2)
Middle Me
59cd155d1a68b70f8e000117
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/59cd155d1a68b70f8e000117
7 kyu
**Simple interest** on a loan is calculated by simply taking the initial amount (the principal, `p`) and multiplying it by a rate of interest (`r`) and the number of time periods (`n`). **Compound interest** is calculated by adding the interest after each time period to the amount owed, then calculating the next interest payment based on the principal PLUS the interest from all previous periods. Given a principal *p*, interest rate *r*, and a number of periods *n*, return an array `[ total owed under simple interest, total owed under compound interest ]` **Notes:** * Round all answers to the nearest integer * Principal will always be an integer between 0 and 9999 * interest rate will be a decimal between 0 and 1 * number of time periods will be an integer between 0 and 50 ## Examples ``` interest(100, 0.1, 1) = [110, 110] interest(100, 0.1, 2) = [120, 121] interest(100, 0.1, 10) = [200, 259] ``` --- More on [Simple interest, compound interest and continuous interest](https://betterexplained.com/articles/a-visual-guide-to-simple-compound-and-continuous-interest-rates/)
reference
def interest(principal, interest, periods): return [round(principal * (1 + interest * periods)), round(principal * (1 + interest) * * periods)]
Simple Interest and Compound Interest
59cd0535328801336e000649
[ "Fundamentals" ]
https://www.codewars.com/kata/59cd0535328801336e000649
7 kyu
The characters of Chima need your help. Their weapons got mixed up! They need you to write a program that accepts the name of a character in Chima then tells which weapon he/she owns. For example: for the character `"Laval"` your program should return the solution `"Laval-Shado Valious"` You must complete the following character-weapon pairs: * Laval-Shado Valious, * Cragger-Vengdualize, * Lagravis-Blazeprowlor, * Crominus-Grandorius, * Tormak-Tygafyre, * LiElla-Roarburn. Return `"Not a character"` for invalid inputs.
reference
def identify_weapon(character): tbl = { "Laval": "Laval-Shado Valious", "Cragger": "Cragger-Vengdualize", "Lagravis": "Lagravis-Blazeprowlor", "Crominus": "Crominus-Grandorius", "Tormak": "Tormak-Tygafyre", "LiElla": "LiElla-Roarburn" } return tbl . get(character, "Not a character")
Re-organize the weapons!
5470ae03304c1250b4000e57
[ "Fundamentals" ]
https://www.codewars.com/kata/5470ae03304c1250b4000e57
7 kyu
For this problem you must create a program that says who ate the last cookie. If the input is a string then "Zach" ate the cookie. If the input is a float or an int then "Monica" ate the cookie. If the input is anything else "the dog" ate the cookie. The way to return the statement is: "Who ate the last cookie? It was (name)!" Ex: Input = "hi" --> Output = "Who ate the last cookie? It was Zach! (The reason you return Zach is because the input is a string) Note: Make sure you return the correct message with correct spaces and punctuation. Please leave feedback for this kata. Cheers!
reference
def cookie(x): return "Who ate the last cookie? It was %s!" % {str: "Zach", float: "Monica", int: "Monica"}. get(type(x), "the dog")
Who ate the cookie?
55a996e0e8520afab9000055
[ "Fundamentals" ]
https://www.codewars.com/kata/55a996e0e8520afab9000055
8 kyu
# Task Given two congruent circles `a` and `b` of radius `r`, return the area of their intersection rounded down to the nearest integer. # Code Limit Javascript: Less than `94` characters. Python: Less than `128` characters. ~~~if:python To remain consistent across version, your code should also not include the 'assignment operator' `:=`. ~~~ # Example For `c1 = [0, 0], c2 = [7, 0] and r = 5`, the output should be `14`.
games
from numpy import * def circleIntersection(a, b, r): return (lambda s: int( max(0, r * r * (s - sin(s)))))(2 * arccos(hypot(* array(a) - b) / 2 / r))
One Line Task: Circle Intersection
5908242330e4f567e90000a3
[ "Puzzles", "Restricted" ]
https://www.codewars.com/kata/5908242330e4f567e90000a3
2 kyu
The factorial of a number, `n!`, is defined for whole numbers as the product of all integers from `1` to `n`. For example, `5!` is `5 * 4 * 3 * 2 * 1 = 120` Most factorial implementations use a recursive function to determine the value of `factorial(n)`. However, this blows up the stack for large values of `n` - most systems cannot handle stack depths much greater than 2000 levels. Write an implementation to calculate the factorial of arbitrarily large numbers, *without recursion.* # Rules * `n < 0` should return `nil`/ `None` * `n = 0` should return `1` * `n > 0` should return `n!` # Note Codewars limits the amount of data it will send back and forth, which may introduce a false ceiling for how high of a value of `n` it will accept. All tests use values less than this limit.
reference
import math def factorial(n): if n >= 0: return math . factorial(n)
Big Factorial
54f0d5447872e8ce9f00013d
[ "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/54f0d5447872e8ce9f00013d
7 kyu
Create a function that takes a string as a parameter and does the following, in this order: 1. Replaces every letter with the letter following it in the alphabet (see note below) 1. Makes any vowels capital 1. Makes any consonants lower case **Note:** * the alphabet should wrap around, so `Z` becomes `A` * in this kata, `y` isn't considered as a vowel. So, for example the string `"Cat30"` would return `"dbU30"` (`Cat30 --> Dbu30 --> dbU30`)
reference
def changer(s): return s . lower(). translate(str . maketrans('abcdefghijklmnopqrstuvwxyz', 'bcdEfghIjklmnOpqrstUvwxyzA'))
Change it up
58039f8efca342e4f0000023
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/58039f8efca342e4f0000023
6 kyu
Write a function that calculates the original product price, without VAT. ## Example If a product price is `200.00` and VAT is `15%`, then the final product price (with VAT) is: `200.00 + 15% = 230.00` Thus, if your function receives `230.00` as input, it should return `200.00` **Notes:** * VAT is *always* `15%` for the purposes of this Kata. * Round the result to 2 decimal places. * If `null` value given then return `-1`
reference
def excludingVatPrice(price): return round(price / 1.15, 2) if price else - 1
Calculate Price Excluding VAT
5890d8bc9f0f422cf200006b
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5890d8bc9f0f422cf200006b
8 kyu
Complete the function that takes a sequence of numbers as single parameter. Your function must return the sum of **the even values** of this sequence. Only numbers without decimals like `4` or `4.0` can be even. The input is a sequence of numbers: integers and/or floats. ### Examples ``` [4, 3, 1, 2, 5, 10, 6, 7, 9, 8] --> 30 # because 4 + 2 + 10 + 6 + 8 = 30 [] --> 0 ```
algorithms
def sum_even_numbers(seq): return sum(n for n in seq if not n % 2)
Sum even numbers
586beb5ba44cfc44ed0006c3
[ "Filtering", "Algorithms" ]
https://www.codewars.com/kata/586beb5ba44cfc44ed0006c3
7 kyu
Write a function `cubeSum(n, m)` that will calculate a sum of cubes of numbers in a given range, starting from the smaller (but not including it) to the larger (including). The first argument is not necessarily the larger number. If both numbers are the same, then the range is empty and the result should be 0. Examples: ```javascript cubeSum(2,3); // => 3^3 = 27 cubeSum(3,2); // => 3^3 = 27 cubeSum(0,4); // => 1^3+2^3+3^3+4^3 = 100 cubeSum(17, 14); // => 15^3+16^3+17^3 = 12384 cubeSum(9, 9); // => 0 ``` ```python cube_sum(2,3); # => 3^3 = 27 cube_sum(3,2); # => 3^3 = 27 cube_sum(0,4); # => 1^3+2^3+3^3+4^3 = 100 cube_sum(17, 14); # => 15^3+16^3+17^3 = 12384 cube_sum(9, 9); # => 0 ``` ```ruby cube_sum(2,3); # => 3^3 = 27 cube_sum(3,2); # => 3^3 = 27 cube_sum(0,4); # => 1^3+2^3+3^3+4^3 = 100 cube_sum(17, 14); # => 15^3+16^3+17^3 = 12384 cube_sum(9, 9); # => 0 ```
reference
def cube_sum(n, m): n, m = sorted([n, m]) return sum(i * * 3 for i in range(n + 1, m + 1))
CubeSummation
550e9fd127c656709400024d
[ "Algorithms", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/550e9fd127c656709400024d
7 kyu
In Bali, as far as I can gather, when ex-pats speak to locals, they basically insert the word 'Pak' as often as possible. I am assured it means something like 'mate' or 'sir' but that could be completely wrong. Anyway, as some basic language education(??) this kata requires you to turn any sentence provided (s) into ex-pat balinese waffle by inserting the word 'pak' between every other word. Simple 8kyu :D Pak should not be the first or last word. Strings of just spaces should return an empty string.
reference
def pak(s): return " pak " . join(s . split(" "))
Holiday VII - Local Talk
57e92812750fcc051800004d
[ "Fundamentals", "Strings", "Arrays" ]
https://www.codewars.com/kata/57e92812750fcc051800004d
7 kyu
Write a function that checks the braces status in a string, and return `True` if all braces are properly closed, or `False` otherwise. Available types of brackets: `()`, `[]`, `{}`. **Please note, you need to write this function without using regex!** ## Examples ```ruby '([[some](){text}here]...)' => true '{([])}' => true '()[]{}()' => true '(...[]...{(..())}[abc]())' => true '1239(df){' => false '[()])' => false ')12[x]34(' => false ``` ```crystal "([[some](){text}here]...)" => true "{([])}" => true "()[]{}()" => true "(...[]...{(..())}[abc]())" => true "1239(df){" => false "[()])" => false ")12[x]34(" => false ``` ```javascript "([[some](){text}here]...)" => true "{([])}" => true "()[]{}()" => true "(...[]...{(..())}[abc]())" => true "1239(df){" => false "[()])" => false ")12[x]34(" => false ``` ```python '([[some](){text}here]...)' => True '{([])}' => True '()[]{}()' => True '(...[]...{(..())}[abc]())' => True '1239(df){' => False '[()])' => False ')12[x]34(' => False ``` Don't forget to rate this kata! Thanks :)
algorithms
brackets = {"}": "{", "]": "[", ")": "("} def braces_status(s): stack = [] for c in s: if c in "[({": stack . append(c) elif c in "])}": if not stack or stack . pop() != brackets[c]: return False return not stack
Braces status
58983deb128a54b530000be6
[ "Algorithms", "Fundamentals", "Logic", "Arrays", "Data Types", "Loops", "Control Flow", "Basic Language Features", "Regular Expressions", "Declarative Programming", "Advanced Language Features", "Programming Paradigms", "Strings" ]
https://www.codewars.com/kata/58983deb128a54b530000be6
6 kyu
# Task Write a function that gets a square of a number without the following: * Your code mustn't contain any `*`s and you cannot use the `pow` function. **Edit: You also cannot use **`__mul__ / imul`** function** * You cannot import any external libraries (unless you are satisfied with `random` being pre-imported). * Only one function can be defined. * Loophole solutions will not be accepted (see below). * If I use `test.expect` in my restriction tests, **that is okay.** This is not an issue. * Input will always be positive or 0 * The code has a length limit: ~~~if:python Your code must be under or equal to **50 characters** (and you already have to use 6 for the function name). ~~~ ~~~if:javascript Your code must be under or equal to **25 characters** (and you already have to use 6 for the function name). ~~~ Example of a loophole solution: ```python square=lambda n:eval(')2,n(wop'[::-1]) ```
games
def square(n): return sum(n for i in range(n))
[Code Golf] Get the Square of a Number without ** or * or pow()
58a8807c5336a3f613000157
[ "Mathematics", "Restricted", "Puzzles" ]
https://www.codewars.com/kata/58a8807c5336a3f613000157
6 kyu
Create a function that changes all the vowels (excluding y) in a string, and changes them all to the same vowel. The first parameter of the function is the string, and the second is the vowel that all the vowels in the string are being changed to. For Example **(input1, vowel) => output**: ``` ("hannah hannah bo-bannah banana fanna fo-fannah fee, fy, mo-mannah. hannah!",'i') => 'hinnih hinnih bi-binnih binini finni fi-finnih fii, fy, mi-minnih. hinnih!' ('adira wants to go to the park', 'o') =>'odoro wonts to go to tho pork' ``` There will never be an uppercase letter as an input.
reference
def vowel_change(s, c): return s . translate(str . maketrans("aiueo", c * 5))
Vowel Changer
597754ba62f8a19c98000030
[ "Fundamentals" ]
https://www.codewars.com/kata/597754ba62f8a19c98000030
7 kyu
Create a function that takes an input String and returns a String, where all the uppercase words of the input String are in front and all the lowercase words at the end. The order of the uppercase and lowercase words should be the order in which they occur. If a word starts with a number or special character, skip the word and leave it out of the result. Input String will not be empty. For an input String: "hey You, Sort me Already!" the function should return: "You, Sort Already! hey me"
reference
def capitals_first(string): return ' ' . join([word for word in string . split() if word[0]. isupper()] + [word for word in string . split() if word[0]. islower()])
Capitals first!
55c353487fe3cc80660001d4
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/55c353487fe3cc80660001d4
7 kyu
A checksum is an algorithm that scans a packet of data and returns a single number. The idea is that if the packet is changed, the checksum will also change, so checksums are often used for detecting transmission errors, validating document contents, and in many other situations where it is necessary to detect undesirable changes in data. For this problem, you will implement a checksum algorithm called Quicksum. A Quicksum packet allows only uppercase letters and spaces. It always begins and ends with an uppercase letter. Otherwise, spaces and uppercase letters can occur in any combination, including consecutive spaces. A Quicksum is the sum of the products of each character’s position in the packet times the character’s value. A space has a value of zero, while letters have a value equal to their position in the alphabet. So, `A = 1`, `B = 2`, etc., through `Z = 26`. Here are example Quicksum calculations for the packets `"ACM"` and `"A C M"`: ``` ACM 1 × 1 + 2 × 3 + 3 × 13 = 46 A C M 1 x 1 + 3 x 3 + 5 * 13 = 75 ``` When the packet doesn't have only uppercase letters and spaces or just spaces the result to quicksum have to be zero (0). ``` AbqTH #5 = 0 ```
reference
def quicksum(packet): result = 0 for idx, char in enumerate(packet, 1): if char . isupper(): result += idx * (ord(char) - 64) elif char == " ": continue else: return 0 return result
Quicksum
569924899aa8541eb200003f
[ "Fundamentals" ]
https://www.codewars.com/kata/569924899aa8541eb200003f
7 kyu
This series of katas will introduce you to basics of doing geometry with computers. `Point` objects have x, y attributes. `Circle` objects have `center` which is a `Point`, and `radius`, which is a number. Write a function calculating circumference of a `Circle`. Tests round answers to 6 decimal places.
reference
from math import pi def circle_circumference(circle): return round(2 * circle . radius * pi, 6)
Geometry Basics: Circle Circumference in 2D
58e43389acfd3e81d5000a88
[ "Geometry", "Fundamentals" ]
https://www.codewars.com/kata/58e43389acfd3e81d5000a88
8 kyu
Create a function that returns the lowest product of 4 **consecutive digits** in a number given as a string. This should only work if the number has 4 digits or more. If not, return "Number is too small". ## Example ```javascript lowestProduct("123456789") --> 24 (1x2x3x4) lowestProduct("35") --> "Number is too small" ``` ```python lowest_product("123456789") --> 24 (1x2x3x4) lowest_product("35") --> "Number is too small" ``` ```ruby lowest_product("123456789") --> 24 (1x2x3x4) lowest_product("35") --> "Number is too small" ```
reference
def lowest_product(input): length = len(input) if length < 4: return "Number is too small" def muller(fourchar): prod = 1 for num in fourchar: prod *= int(num) return prod return min([muller(input[i: i + 4]) for i in range(length - 3)])
Lowest product of 4 consecutive numbers
554e52e7232cdd05650000a0
[ "Fundamentals" ]
https://www.codewars.com/kata/554e52e7232cdd05650000a0
6 kyu
Our fruit guy has a bag of fruit (represented as an array of strings) where some fruits are rotten. He wants to replace all the rotten pieces of fruit with fresh ones. For example, given `["apple","rottenBanana","apple"]` the replaced array should be `["apple","banana","apple"]`. Your task is to implement a method that accepts an array of strings containing fruits should returns an array of strings where all the rotten fruits are replaced by good ones. ### Notes - If the array is null/nil/None or empty you should return empty array (`[]`). - The rotten fruit name will be in this camelcase (`rottenFruit`). - The returned array should be in lowercase.
reference
def remove_rotten(bag_of_fruits): return [x . replace('rotten', ''). lower() for x in bag_of_fruits] if bag_of_fruits else []
Help the Fruit Guy
557af4c6169ac832300000ba
[ "Arrays", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/557af4c6169ac832300000ba
7 kyu
Given an array containing only integers, add all the elements and return the binary equivalent of that sum. If the array contains any non-integer element (e.g. an object, a float, a string and so on), return false. **Note:** The sum of an empty array is zero. ```javascript arr2bin([1,2]) == '11' arr2bin([1,2,'a']) == false ``` ```python arr2bin([1,2]) == '11' arr2bin([1,2,'a']) == False ``` ```ruby arr2bin([1,2]) == '11' arr2bin([1,2,'a']) == false ```
reference
def arr2bin(arr): for x in arr: if (type(x) != int): return False return '{0:b}' . format(sum(arr))
Array2Binary addition
559576d984d6962f8c00003c
[ "Fundamentals" ]
https://www.codewars.com/kata/559576d984d6962f8c00003c
7 kyu
After calling the function `findSum()` with any number of non-negative integer arguments, it should return the sum of all those arguments. If no arguments are given, the function should return 0, if negative arguments are given, it should return -1. ## Example ```javascript findSum(1,2,3,4); // returns 10 findSum(1,-2); // returns -1 findSum(); // returns 0 ``` ```python find_sum(1,2,3,4); # returns 10 find_sum(1,-2); # returns -1 find_sum(); # returns 0 ``` ```ruby find_sum(1,2,3,4); # returns 10 find_sum(1,-2); # returns -1 find_sum(); # returns 0 ``` ```c find_sum(4, 1,2,3,4); // returns 10 find_sum(2, 1,-2); // returns -1 find_sum(0); // returns 0 ``` ```if:javascript **Hint:** research the arguments object on google or read Chapter 4 from Eloquent Javascript ``` ```if:c The first argument `argc` will contain the number of arguments passed to the function. The following arguments will have type `int`. ```
reference
def find_sum(* args): return - 1 if any(x < 0 for x in args) else sum(args)
Sum of numerous arguments
55c5b03f8c28da9a51000045
[ "Fundamentals" ]
https://www.codewars.com/kata/55c5b03f8c28da9a51000045
7 kyu
Given a list of integers values, your job is to return the sum of the values; however, if the same integer value appears multiple times in the list, you can only count it once in your sum. For example: ```python [ 1, 2, 3] ==> 6 [ 1, 3, 8, 1, 8] ==> 12 [ -1, -1, 5, 2, -7] ==> -1 [] ==> None ``` ```ruby [ 1, 2, 3] ==> 6 [ 1, 3, 8, 1, 8] ==> 12 [ -1, -1, 5, 2, -7] ==> -1 [] ==> None ``` ```haskell [ 1, 2, 3] ==> 6 [ 1, 3, 8, 1, 8] ==> 12 [ -1, -1, 5, 2, -7] ==> -1 [] ==> None ``` ```javascript [ 1, 2, 3] ==> 6 [ 1, 3, 8, 1, 8] ==> 12 [ -1, -1, 5, 2, -7] ==> -1 [] ==> null ``` ```csharp Kata.UniqueSum(new List<int> {1, 2, 3}) => 6 Kata.UniqueSum(new List<int> {1, 3, 8, 1, 8}) => 12 Kata.UniqueSum(new List<int> {-1, -1, 5, 2, -7}) => -1 Kata.UniqueSum(new List<int>()) => null ``` Good Luck!
reference
def unique_sum(lst): return sum(set(lst)) if lst else None
Unique Sum
56b1eb19247c01493a000065
[ "Lists", "Logic", "Filtering", "Fundamentals" ]
https://www.codewars.com/kata/56b1eb19247c01493a000065
7 kyu
Given an array of integers of any length, return an array that has 1 added to the value represented by the array. - the array can't be empty - only non-negative, single digit integers are allowed Return `nil` (or your language's equivalent) for invalid inputs. ### Examples **Valid arrays** `[4, 3, 2, 5]` would return `[4, 3, 2, 6]` `[1, 2, 3, 9]` would return `[1, 2, 4, 0]` `[9, 9, 9, 9]` would return `[1, 0, 0, 0, 0]` `[0, 1, 3, 7]` would return `[0, 1, 3, 8]` **Invalid arrays** `[1, -9]` is invalid because `-9` is **not a non-negative integer** `[1, 2, 33]` is invalid because `33` is **not a single-digit integer**
reference
def up_array(a): if not a or any(not 0 <= x < 10 for x in a): return for i in range(1, len(a) + 1): a[- i] = (a[- i] + 1) % 10 if a[- i]: break else: a[: 0] = [1] return a
+1 Array
5514e5b77e6b2f38e0000ca9
[ "Fundamentals", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5514e5b77e6b2f38e0000ca9
6 kyu
In this Kata we will play a classic game of Tug-o'-War! Two teams of 5 members will face off, the strongest of which will prevail. Each team member will be assigned a strength rating (1-9), with the most powerful members having a rating of 9. Your goal is to determine, based on the cumulative strength of the members of each team, which team will win the war. The teams will be represented by an array of arrays: ```javascript [[5,0,3,2,1], [1,6,8,2,9]] // 11 < 26 ; "Team 2 wins!" ``` ```csharp new int[][] { new int[] {5,0,3,2,1}, new int[] {1,6,8,2,9} } // 11 < 26 ; "Team 2 wins!" ``` ```java new int[][]{new int[]{5, 0, 3, 2, 1}, new int[]{1, 6, 8, 2, 9}} // 11 < 26 ; "Team 2 wins!" ``` ```python [[5,0,3,2,1], [1,6,8,2,9]] # 11 < 26 ; "Team 2 wins!" ``` ```ruby [[5,0,3,2,1], [1,6,8,2,9]] # 11 < 26 ; "Team 2 wins!" ``` Your task is to return a string with which team won or if it was a tie. - If team one is stronger, return the string "Team 1 wins!" - If team two is stronger, return the string "Team 2 wins!" If the two teams are of equal strength, the team with the strongest Anchor (the member furthest from the center of the rope (first member for Team 1, last member for Team 2)) will win. In the above example, the member with strength 5 is team one's Anchor and strength 9 is team two's Anchor. - If the teams and the Anchors are both of equal strength, return the string "It's a tie!" The Anchors are members in each end of the rope: ![anchors](http://i.imgur.com/w3MJF2V.jpg?1) more examples: ```javascript [[1,2,3,4,5], [1,2,3,4,5]] // Team 2 has stronger Anchor ; "Team 2 wins!" [[1,2,3,4,5], [5,4,3,2,1]] // Teams & Anchors are tied; "It's a tie!" ``` ```csharp new int[][] { new int[] {1,2,3,4,5}, new int[] {1,2,3,4,5} } // Team 2 has stronger Anchor ; "Team 2 wins!" new int[][] { new int[] {1,2,3,4,5}, new int[] {5,4,3,2,1} } // Teams & Anchors are tied; "It's a tie!" ``` ```java new int[][]{new int[]{1, 2, 3, 4, 5}, new int[]{1, 2, 3, 4, 5}} // Team 2 has stronger Anchor ; "Team 2 wins!" new int[][]{new int[]{1, 2, 3, 4, 5}, new int[]{5, 4, 3, 2, 1}} // Teams & Anchors are tied; "It's a tie!" ``` ```python [[1,2,3,4,5], [1,2,3,4,5]] # Team 2 has stronger Anchor ; "Team 2 wins!" [[1,2,3,4,5], [5,4,3,2,1]] # Teams & Anchors are tied; "It's a tie!" ``` ```ruby [[1,2,3,4,5], [1,2,3,4,5]] # Team 2 has stronger Anchor ; "Team 2 wins!" [[1,2,3,4,5], [5,4,3,2,1]] # Teams & Anchors are tied; "It's a tie!" ``` Good luck!
reference
def tug_o_war(teams): (a, b) = (sum(team) for team in teams) if a == b: a = teams[0][0] b = teams[1][- 1] return "Team 1 wins!" if a > b else "Team 2 wins!" if a < b else "It's a tie!"
Tug-o'-War
547fb94931cce5f5de00024f
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/547fb94931cce5f5de00024f
null
Write a function that removes every lone `9` that is inbetween `7`s. ```javascript "79712312" --> "7712312" "79797" --> "777" ```
reference
def seven_ate9(str_): while str_ . find('797') != - 1: str_ = str_ . replace('797', '77') return str_
SevenAte9
559f44187fa851efad000087
[ "Logic", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/559f44187fa851efad000087
7 kyu
Write a function that takes an array and counts the number of each unique element present. ```ruby count(['james', 'james', 'john']) #=> { 'james' => 2, 'john' => 1} ``` ```javascript count(['james', 'james', 'john']) #=> { 'james': 2, 'john': 1} ``` ```csharp Kata.Count(new List<string> {"James", "James", "John"}) => new Dictionary<string, int> {{"James", 2}, {"John", 1}}; ```
reference
from collections import Counter def count(array): return Counter(array)
Counting Array Elements
5569b10074fe4a6715000054
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5569b10074fe4a6715000054
7 kyu
# Task You are given a string `digits` and an integer `size`(1-9). Your task is to generate a result like this: ``` show("888",1) === - - - | || || | - - - | || || | - - - show("888",2) === -- -- -- | || || | | || || | -- -- -- | || || | | || || | -- -- -- show("1234567890",3) === --- --- --- --- --- --- --- --- | | || || | || || || | | | || || | || || || | | | || || | || || || | --- --- --- --- --- --- --- || | | || | || | || | || | | || | || | || | || | | || | || | || | --- --- --- --- --- --- --- ``` As you can see: - Use '-' represents the horizontal line; Use '|' represents the vertical line. - `size` determines the length of the horizontal line and the height of the vertical line. i.e. If size is 1, the horizontal line is `-`; If size is 2, the horizontal line is `--`. and so on.. - Each row is separated by `"\n"`. - To keep shapes, other places are filled with spaces. Except for the end of each line. - Happy Coding `^_^`
games
def show(digits, size): line = ' ' + '-' * size + ' ' space = ' ' * (size + 2) l_sp = '|' + ' ' * (size + 1) sp_r = ' ' * (size + 1) + '|' l__r = '|' + ' ' * size + '|' level_1 = {str(k): space if str(k) in '14' else line for k in range(10)} level_2 = {str(k): sp_r if str(k) in '1237' else l_sp if str( k) in '56' else l__r for k in range(10)} level_3 = {str(k): space if str(k) in '170' else line for k in range(10)} level_4 = {str(k): sp_r if str(k) in '134579' else l_sp if str( k) in '2' else l__r for k in range(10)} level_5 = {str(k): space if str(k) in '147' else line for k in range(10)} ans = '' . join([level_1[i] for i in digits]) + '\n' + \ ('' . join([level_2[i] for i in digits]) + '\n') * size + \ '' . join([level_3[i] for i in digits]) + '\n' + \ ('' . join([level_4[i] for i in digits]) + '\n') * size + \ '' . join([level_5[i] for i in digits]) while ' \n' in ans: ans = ans . replace(' \n', '\n') while ans[- 1] == ' ': ans = ans[: - 1] return ans
Simple Fun #357: Show The Digits
59cc4c5aaeb284b9a1000089
[ "Puzzles" ]
https://www.codewars.com/kata/59cc4c5aaeb284b9a1000089
5 kyu
The __cartesian product__ of two sets A and B, written __"A × B"__ is equal to the set of all possible combinations of values from both sets. Here's an example, taken from <a href='https://www.mathstopia.net/sets/cartesian-product'>Mathstopia</a> : <a href='https://www.mathstopia.net/sets/cartesian-product'><img src='https://www.mathstopia.net/wp-content/uploads/2021/01/cartesian-products.jpg'></a> <h2>Your task</h2> <p>Implement function <code>cart_prod</code>, which returns the cartesian product (in the form of <code>tuples</code>) of any number of sets passed to it (note the <code>*</code> before <code>sets</code> in the function definition). Also, <ul> <li>The cartesian product A × B × C, where A, B and C are sets, is equal to (A × B) × C. See bottom of description for a concrete e×ample.</li> <li>If no set is passed in, return a set containing an tempty tuple.</li> <li>If a single set is passed in, return a set of tuples of the elements of the set.</li> <li>If any of the sets passed in is empty, return an empty set.</li> </ul> *Note* : You are not allowed to use the word "itertools" in your solution (as in, <code>from itertools import product ¯\\_(ツ)_/¯</code>). <h3>Ecample with three sets</h3> If <code>A = {1, 2}; B = {'x', 'y'}; C = {δ, γ}</code> Then <code>A × B × C = {(1, 'x', δ), (1, 'x', γ), (1, 'y', δ), (1, 'y', γ), (2, 'x', δ), (2, 'x', γ), (2, 'y', δ), (2, 'y', γ)}</code> Note that the cardinality (number of elements) of a cartesian product is always equal to the product of the cardinalities of the sets in the cartesian product (here, |A| = |B| = |C| = 2, therefore |A × B × C| = 8).
algorithms
def cart_prod(* sets): return {()} if not sets else {tuple([x] + list(s)) for x in sets[0] for s in cart_prod(* sets[1:])}
Cartesian product
59ca6fda23dacca1e300003e
[ "Mathematics", "Sets", "Set Theory", "Algorithms" ]
https://www.codewars.com/kata/59ca6fda23dacca1e300003e
6 kyu
### Story > You have serious coding skillz? You wannabe a [scener](https://en.wikipedia.org/wiki/Demoscene)? Complete this mission and u can get in teh crew! You have read a similar message on your favourite [diskmag](https://en.wikipedia.org/wiki/Disk_magazine) back in the early 90s, and got really excited. You contacted the demo crew immediately and they gave you the following job: write a vertical sinus scroller... **for the printer!** ### Your task Write a function that takes three parameters: `text`, `amp` (for [peak amplitude](https://en.wikipedia.org/wiki/Amplitude)) and `period` (or [wavelength](https://en.wikipedia.org/wiki/Wavelength)). Return a string (split into multiple lines) that will display the text as a vertical sine wave. Note: `amp` and `period` are measured in characters and are always positive integers; `text` is never empty. ### Example ```python "Hello World!", 3, 10 --> " H\n e\n l\n l\n o\n \n W\no\nr\n l\n d\n !" ``` Doesn't make much sense? Well, let's print it! ``` H 1 e 2 l 3 l 4 o 5 6 W 7 o 8 r 9 l 10 d 1 ! 2 3210123 ``` (Obviously, the numbers are only shown above to demonstrate `amp` and `period`) Happy coding! *Note:* due to the inevitable use of floats, solutions with slight rounding errors (1 space difference in less than 10% of the output lines) will be accepted. --- ### My other katas If you enjoyed this kata then please try [my other katas](https://www.codewars.com/collections/katas-created-by-anter69)! :-) #### *Translations are welcome!*
algorithms
from math import sin, pi def scroller(text, amp, period): return '\n' . join(' ' * round(amp * (1 + sin((k % period) * 2 * pi / period))) + l for k, l in enumerate(text))
Sinus Scroller
59cabf6baeb28482b8000017
[ "Algorithms" ]
https://www.codewars.com/kata/59cabf6baeb28482b8000017
6 kyu
Check if given numbers are prime numbers.<br> If number N is prime ```return "Probable Prime"``` else ``` return "Composite"```. <br> <b>HINT:</b> Upper bount is <u>really big</u> so you should use an efficient algorithm. <b>Input</b><br> &nbsp; 1 < N ≤ 10<sup style="vertical-align: super;font-size: smaller;">100</sup> <b>Example</b><br> &nbsp; prime_or_composite(2) # should return Probable Prime<br> &nbsp; prime_or_composite(200) # should return Composite
algorithms
from gmpy2 import is_prime as ip def prime_or_composite(n): return ["Composite", "Probable Prime"][ip(n)]
Probable Prime or Composite (Much bigger primes)
5742e725f81ca04d64000c11
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5742e725f81ca04d64000c11
5 kyu
Given two arrays of strings, return the number of times each string of the second array appears in the first array. #### Example ``` array1 = ['abc', 'abc', 'xyz', 'cde', 'uvw'] array2 = ['abc', 'cde', 'uap'] ``` How many times do the elements in `array2` appear in `array1`? * `'abc'` appears twice in the first array (2) * `'cde'` appears only once (1) * `'uap'` does not appear in the first array (0) Therefore, `solve(array1, array2) = [2, 1, 0]` Good luck! If you like this Kata, please try: [Word values](https://www.codewars.com/kata/598d91785d4ce3ec4f000018) [Non-even substrings](https://www.codewars.com/kata/59da47fa27ee00a8b90000b4)
algorithms
def solve(a, b): return [a . count(e) for e in b]
String matchup
59ca8e8e1a68b7de740001f4
[ "Algorithms" ]
https://www.codewars.com/kata/59ca8e8e1a68b7de740001f4
7 kyu
Create a function that interprets code in the esoteric language **Poohbear** ## The Language Poohbear is a stack-based language largely inspired by Brainfuck. It has a maximum integer value of 255, and 30,000 cells. The original intention of Poohbear was to be able to send messages that would, to most, be completely indecipherable: <a href=https://esolangs.org/wiki/Poohbear>Poohbear Wiki</a> * For the purposes of this kata, you will make a version of Poohbear that has **infinite** memory cells in **both directions** (so you do not need to limit cells to 30,000) * Cells have a default value of 0 * Each cell can hold one byte of data. Once a cell's value goes above 255, it wraps around to 0. If a cell's value goes below 0, it wraps to 255. * If the result of an operation isn't an int, round the result down to the nearest one. * Your interpreter should ignore any non-command characters in the code. * If you come to a `W` in the code and the current cell is equal to 0, jump to the corresponding `E`. * If you come to an `E` in the code and the current cell is **not** 0, jump back to the corresponding `W`. Here are the Poohbear commands: | Command | Definition |---| ------------------------- | + | Add 1 to the current cell | - | Subtract 1 from the current cell | > | Move the cell pointer 1 space to the right | < | Move the cell pointer 1 space to the left | c | "Copy" the current cell | p | Paste the "copied" cell into the current cell | W | While loop - While the current cell is not equal to 0 | E | Closing character for loops | P | Output the current cell's value as ascii | N | Output the current cell's value as an integer | T | Multiply the current cell by 2 | Q | Square the current cell | U | Square root the current cell's value | L | Add 2 to the current cell | I | Subtract 2 from the current cell | V | Divide the current cell by 2 | A | Add the copied value to the current cell's value | B | Subtract the copied value from the current cell's value | Y | Multiply the current cell's value by the copied value | D | Divide the current cell's value by the copied value.
algorithms
from operator import add, mul, floordiv as fdiv, pow def poohbear(s): def updateMem(func, v): mem[p] = func(mem . get(p, 0), v) % 256 braces, stack = {}, [] for i, c in enumerate(s): if c == 'W': stack . append(i) if c == 'E': braces[i] = stack[- 1] braces[stack . pop()] = i mem, copy, output = {}, 0, [] p, i = 0, 0 while i < len(s): cmd = s[i] if cmd == '>': p += 1 elif cmd == '<': p -= 1 elif cmd == 'p': mem[p] = copy elif cmd == 'c': copy = mem . get(p, 0) elif cmd == 'W': i = i if bool(mem . get(p, 0)) else braces[i] elif cmd == 'E': i = braces[i] if mem . get(p, 0) else i elif cmd == 'P': output . append(chr(mem . get(p, 0))) elif cmd == 'N': output . append(str(mem . get(p, 0))) elif cmd == '+': updateMem(add, 1) elif cmd == '-': updateMem(add, - 1) elif cmd == 'L': updateMem(add, 2) elif cmd == 'I': updateMem(add, - 2) elif cmd == 'T': updateMem(mul, 2) elif cmd == 'V': updateMem(fdiv, 2) elif cmd == 'Q': updateMem(pow, 2) elif cmd == 'U': updateMem(lambda a, b: int(pow(a, b)), .5) elif cmd == 'A': updateMem(add, copy) elif cmd == 'B': updateMem(add, - copy) elif cmd == 'Y': updateMem(mul, copy) elif cmd == 'D': updateMem(fdiv, copy) i += 1 return '' . join(output)
Esoteric Language: 'Poohbear' Interpreter
59a9735a485a4d807f00008a
[ "Esoteric Languages", "Interpreters", "Algorithms" ]
https://www.codewars.com/kata/59a9735a485a4d807f00008a
5 kyu
Given a certain integer ```n```, we need a function ```big_primefac_div()```, that give an array with the highest prime factor and the highest divisor (not equal to n). Let's see some cases: ```python big_primefac_div(100) == [5, 50] big_primefac_div(1969) == [179, 179] ``` If n is a prime number the function will output an empty list: ```python big_primefac_div(997) == [] ``` If ```n``` is an negative integer number, it should be considered the division with the absolute number of the value. ```python big_primefac_div(-1800) == [5, 900] ``` ~~~if:javascript,python,ruby,julia If ```n``` is a float type, will be rejected if it has a decimal part with some digits different than 0. The output "The number has a decimal part. No Results". But ```n ``` will be converted automatically to an integer if all the digits of the decimal part are 0. ```python big_primefac_div(-1800.00) == [5, 900] big_primefac_div(-1800.1) == "The number has a decimal part. No Results" ``` ~~~ Optimization and fast algorithms are a key factor to solve this kata. Happy coding and enjoy it!
reference
def big_primefac_div(n): bpf, bd = 0, 1 frac = [] if n % 1 != 0: return "The number has a decimal part. No Results" else: n = abs(int(n)) n_copy = n i = 2 while i * i <= n: if n % i == 0: n / /= i frac . append(i) else: i += 1 if n > 1: frac . append(n) bpf = max(frac) bd = n_copy / frac[0] if bpf == 0 or bd == 1: return [] else: return [bpf, bd]
Give The Biggest Prime Factor And The Biggest Divisor Of A Number
5646ac68901dc5c31a000022
[ "Fundamentals", "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/5646ac68901dc5c31a000022
5 kyu
The numbers 12, 63 and 119 have something in common related with their divisors and their prime factors, let's see it. ``` Numbers PrimeFactorsSum(pfs) DivisorsSum(ds) Is ds divisible by pfs 12 2 + 2 + 3 = 7 1 + 2 + 3 + 4 + 6 + 12 = 28 28 / 7 = 4, Yes 63 3 + 3 + 7 = 13 1 + 3 + 7 + 9 + 21 + 63 = 104 104 / 13 = 8, Yes 119 7 + 17 = 24 1 + 7 + 17 + 119 = 144 144 / 24 = 6, Yes ``` There is an obvius property you can see: the sum of the divisors of a number is divisible by the sum of its prime factors. We need the function ```ds_multof_pfs()``` that receives two arguments: ```nMin``` and ```nMax```, as a lower and upper limit (inclusives), respectively, and outputs a sorted list with the numbers that fulfill the property described above. We represent the features of the described function: ```python ds_multof_pfs(nMin, nMax) -----> [n1, n2, ....., nl] # nMin ≤ n1 < n2 < ..< nl ≤ nMax ``` Let's see some cases: ```python ds_multof_pfs(10, 100) == [12, 15, 35, 42, 60, 63, 66, 68, 84, 90, 95] ds_multof_pfs(20, 120) == [35, 42, 60, 63, 66, 68, 84, 90, 95, 110, 114, 119] ``` Enjoy it!!
reference
def ds_multof_pfs(a, b): return [n for n in range(a, b + 1) if divisor_sum(n) % prime_factor_sum(n) == 0] def divisor_sum(n, p=2, s=0): s += 1 + (0 if n == 1 else n) while p * p <= n: if n % p == 0: s += p if n / / p != p: s += n / / p p += 1 return s def prime_factor_sum(n, p=2, s=0): while p * p <= n: while n % p == 0: n / /= p s += p p += 1 if n > 1: s += n return s
When The Sum of The Divisors Is A Multiple Of The Prime Factors Sum
562c04fc8546d8147b000039
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/562c04fc8546d8147b000039
5 kyu
Consider the prime number `23`. If we sum the square of its digits we get: `2^2 + 3^2 = 13`, then for `13: 1^2 + 3^2 = 10`, and finally for `10: 1^2 + 0^2 = 1`. Similarly, if we start with prime number `7`, the sequence is: `7->49->97->130->10->1`. Given a range, how many primes within that range will eventually end up being `1`? The upperbound for the range is `50,000`. A range of `(2,25)` means that: `2 <= n < 25`. Good luck! If you like this Kata, please try: [Prime reversion](https://www.codewars.com/kata/59b46276afcda204ed000094) [Domainant primes](https://www.codewars.com/kata/59ce11ea9f0cbc8a390000ed)
algorithms
from gmpy2 import is_prime as ip def naiHai(n): a = [] while n not in a: a += [n] n = sum(int(i) * * 2 for i in str(n)) if n == 1: return True return False def solve(a, b): return len([i for i in range(a, b) if ip(i) and naiHai(i)])
Prime reduction
59aa6567485a4d03ff0000ca
[ "Algorithms" ]
https://www.codewars.com/kata/59aa6567485a4d03ff0000ca
6 kyu
In this kata, you will create a function, `circle`, that produces a string of some radius, according to certain rules that will be explained shortly. Here is the output of `circle` when passed the integer 10: ``` █████████ ███████████ ███████████████ ███████████████ █████████████████ ███████████████████ ███████████████████ ███████████████████ ███████████████████ ███████████████████ ███████████████████ ███████████████████ ███████████████████ ███████████████████ █████████████████ ███████████████ ███████████████ ███████████ █████████ ``` *(Note: For Python and Ruby users, this will use '#', rather than '█')* The circle consists of spaces, and the character `\u2588`. Note that this is a complete square of characters, so the 'gaps' are filled with spaces. For instance, the last line of the above ends with the five characters `"\u2588 "`; there are five spaces at the end. All characters whose distance from the center is less than the given radius is defined as 'in the circle', hence the character at that position should be filled with `\u2588` rather than spaces. So, for instance, this is a circle of radius 2: ``` ███ ███ ███ ``` Whilst this isn't very circle-y, this is what the rules expect. Here are the edge-case rules; there are examples in the example test cases: - A negative radius should result in an empty string. - A radius of 0 should produce the string `"\n:`. - Any other result should end with `\n`. Please note that the distance metric is Euclidean distance (the most common notion of distance) centered around the middle of a character, where each character is of width and height exactly one. **_(Any translations would be greatly appreciated!)_** ---
algorithms
def circle(radius): return '\n' . join( '' . join('#' if x * * 2 + y * * 2 < radius * * 2 else ' ' for x in range(1 - radius, radius)) for y in range(1 - radius, radius) ) + '\n' * (radius >= 0)
Draw a Circle.
59c804d923dacc6c41000004
[ "Strings", "Geometry", "ASCII Art", "Algorithms" ]
https://www.codewars.com/kata/59c804d923dacc6c41000004
6 kyu
As a strict big brother, I do limit my young brother Vasya on time he spends on computer games. I define a prime-time as a time period till which Vasya have a permission to play computer games. I specify start hour and end hour as pair of integers. I need a function which will take three numbers - a present moment (current hour), a start hour of allowed time period and an end hour of allowed time period. The function should give answer to a question (as a boolean): "Can Vasya play in specified time?" If I say that prime-time is from 12 till 15 that means that at 12:00 it's OK to play computer but at 15:00 there should be no more games. I will allow Vasya to play at least one hour a day.
reference
def can_i_play(now_hour, start_hour, end_hour): return 0 <= (now_hour - start_hour) % 24 < (end_hour - start_hour) % 24
Can I play right now?
59ca888aaeb284bb8f0000aa
[ "Date Time", "Fundamentals" ]
https://www.codewars.com/kata/59ca888aaeb284bb8f0000aa
7 kyu
# Task You are a lonely frog. You live on a coordinate axis. The meaning of your life is to jump and jump.. Two actions are allowed: - `forward`: Move forward 1 unit. - `double`: If you at `x` point, then you can move to `x*2` point. Now, here comes your new task. Your starting point is `x`, the target point is `y`. You need to jump to the target point with `minimal steps`. Please tell me, what's the `minimal steps`? `1 <= x <= 10`, `x < y <= 100000` # Example For `x = 1, y = 8`, the output should be `3`. ``` step from to action 1: 1 --> 2 forward(or double) 2: 2 --> 4 double 3: 4 --> 8 double ``` For `x = 1, y = 17`, the output should be `5`. ``` step from to action 1: 1 --> 2 forward(or double) 2: 2 --> 4 double 3: 4 --> 8 double 4: 8 --> 16 double 5: 16 --> 17 forward ``` For `x = 1, y = 15`, the output should be `6`. ``` step from to action 1: 1 --> 2 forward(or double) 2: 2 --> 3 forward 3: 3 --> 6 double 5: 6 --> 7 forward 6: 7 --> 14 double 7: 14 --> 15 forward ``` For `x = 3, y = 12`, the output should be `2`. ``` step from to action 1: 3 --> 6 double 2: 6 --> 12 double ``` For `x = 3, y = 16`, the output should be `3`. ``` step from to action 1: 3 --> 4 forward 2: 4 --> 8 double 3: 8 --> 16 double ```
algorithms
def jump_to(x, y): n = 0 while y != x: if y % 2 == 0 and y / 2 >= x: y /= 2 else: y -= 1 n += 1 return n
Simple Fun #354: Lonely Frog III
59c9e82ea25c8c05860001aa
[ "Algorithms" ]
https://www.codewars.com/kata/59c9e82ea25c8c05860001aa
6 kyu
Imagine a game level represented as a two dimensional array containing fields which the player can traverse. The player can move up through the rows and sideways through the columns. A 4x4 level might look like this: ``` rows 0 |__|__|__|__| 1 |__|__|PL|__| PL = Player position 2 |__|__|__|__| 3 |__|__|__|__| 0 1 2 3 columns ``` In this example the player is at row: 1, column: 2. As mentioned, you can move straight up (to row: 2, column: 2) or sideways (e.g. to row: 1, column: 3), but never down. <br> OK? Good.<br> It gets more complicated; some of the fields are blocked and the player has to navigate around them (bet you weren't expecting that ay?): ``` rows 0 |__|□□|□□|__| 2 |__|__|__|__| 1 |__|__|PL|□□| □□ = Blocked field 3 |□□|__|__|□□| 0 1 2 3 columns ``` Damn those pesky level designers.. they've asked you to type up some magical algortihm that can check whether a given level is beatable i.e. that there is at least one valid path from the player's position all the way to the top row. An unwinnable level: ``` 0 |__|PL|__|__| 1 |__|__|__|__| "That's bullsh*t!" - Player 2 |□□|□□|□□|□□| 3 |__|__|__|__| 0 1 2 3 ``` Your task is to write a function that will return the number of reachable fields in the last/top row. ```java int GetNumberOfReachableFields(bool[][] grid, int rows, int columns, int startRow, int startColumn) ``` ```python get_number_of_reachable_fields(grid, rows, columns, start_row, start_column) ``` INPUT<br> <u>grid</u>: A 2d array of boolean values; `true` or `1` means a field is traversable, `false` or `0` means it's blocked. Access the array using grid[row][col].<br> <u>rows</u>: Number of rows in the grid/level. (1 <= rows <= 2000)<br> <u>columns</u>: Number of columns in the grid/level. (1 <= columns <= 500)<br> <u>startRow</u>: The row of the player's starting position. (0 <= startRow < rows)<br> <u>startColumn</u>: The column of the player's starting position. (0 <= startColumn < columns)<br> OUTPUT<br> Return, as an integer value greater or equal to zero, the number of unique fields in row: grid[rows-1] that the player can reach using the aforementioned moves (step forward, left or right). More level examples: ``` RE = Reachable field 0 1 2 0 1 2 3 0 1 2 3 0 0 |__|PL|__| 0 |__|□□|__|PL| 0 |□□|□□|__|□□| 0 |PL| 1 |__|__|__| 1 |□□|□□|__|__| 1 |□□|PL|__|__| 1 |__| 2 |__|□□|□□| 2 |__|__|□□|□□| 2 |__|__|□□|□□| 2 |RE| 3 |__|__|__| 3 |□□|__|__|__| 4 |RE|RE|RE| 4 |RE|RE|□□|RE| Output: 3 Output: 0 Output: 3 Output: 1 ``` NOTES<br> • The player cannot step onto a blocked field and diagonal moves are not allowed.<br> • The player will never start on a blocked field - you don't need to validate this.<br> • The grid array will always contain at least one element.<br> • Watch out for performance and note that you don't need to remember the paths the player took. Good luck and happy coding!
algorithms
def get_number_of_reachable_fields(grid, rows, columns, start_row, start_column): reachable, bag, seen = 0, [(start_row, start_column)], { (start_row, start_column)} while bag: x, y = bag . pop() reachable += x == rows - 1 for u, v in (1, 0), (0, 1), (0, - 1): m, n = x + u, y + v if 0 <= m < rows and 0 <= n < columns \ and (m, n) not in seen and grid[m][n]: bag . append((m, n)) seen . add((m, n)) return reachable
Optimized Pathfinding Algorithm
57b4d2dad2a31c75f7000223
[ "Games", "Algorithms", "Puzzles" ]
https://www.codewars.com/kata/57b4d2dad2a31c75f7000223
5 kyu
In this Kata we focus on finding a sum S(n) which is the total number of divisors taken for all natural numbers less or equal to n. More formally, we investigate the sum of n components denoted by d(1) + d(2) + ... + d(n) in which for any i starting from 1 up to n the value of d(i) tells us how many distinct numbers divide i without a remainder. Your solution should work for possibly large values of n without a timeout. Assume n to be greater than zero and not greater than 999 999 999 999 999. Brute force approaches will not be feasible options in such cases. It is fairly simple to conclude that for every n>1 there holds a recurrence S(n) = S(n-1) + d(n) with initial case S(1) = 1. For example:<br/> S(1) = 1<br/> S(2) = 3<br/> S(3) = 5<br/> S(4) = 8<br/> S(5) = 10<br/> But is the fact useful anyway? If you find it is rather not, maybe this will help: <br/> Try to convince yourself that for any natural k, the number S(k) is the same as the number of pairs (m,n) that solve the inequality mn <= k in natural numbers. Once it becomes clear, we can think of a partition of all the solutions into classes just by saying that a pair (m,n) belongs to the class indexed by n. The question now arises if it is possible to count solutions of n-th class. If f(n) stands for the number of solutions that belong to n-th class, it means that S(k) = f(1) + f(2) + f(3) + ... The reasoning presented above leads us to some kind of a formula for S(k), however not necessarily the most efficient one. Can you imagine that all the solutions to inequality mn <= k can be split using sqrt(k) as pivotal item?
algorithms
def count_divisors(n): """Counts the integer points under the parabola xy = n. Because the region is symmetric about x = y, it is only necessary to sum up to that point (at n^{1/2}), and double it. By this method, a square region is counted twice, and thus subtracted off the total. """ r = int(n * * (1 / 2)) return 2 * sum(n / / i for i in range(1, r + 1)) - r * r
Can you really count divisors?
58b16300a470d47498000811
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/58b16300a470d47498000811
4 kyu
Given a list of prime factors, ```primesL```, and an integer, ```limit```, try to generate in order, all the numbers less than the value of ```limit```, that have **all and only** the prime factors of ```primesL``` ## Example ```python primesL = [2, 5, 7] limit = 500 List of Numbers Under 500 Prime Factorization ___________________________________________________________ 70 [2, 5, 7] 140 [2, 2, 5, 7] 280 [2, 2, 2, 5, 7] 350 [2, 5, 5, 7] 490 [2, 5, 7, 7] ``` There are ```5``` of these numbers under ```500``` and the largest one is ```490```. ## Task For this kata you have to create the function ```count_find_num()```, that accepts two arguments: ```primesL``` and ```limit```, and returns the amount of numbers that fulfill the requirements, and the largest number under `limit`. The example given above will be: ```python primesL = [2, 5, 7] limit = 500 count_find_num(primesL, val) == [5, 490] ``` If no numbers can be generated under `limit` then return an empty list: ```python primesL = [2, 3, 47] limit = 200 find_nums(primesL, limit) == [] ``` The result should consider the limit as inclusive: ```python primesL = [2, 3, 47] limit = 282 find_nums(primesL, limit) == [1, 282] ``` Features of the random tests: ``` number of tests = 200 2 <= length_primesL <= 6 // length of the given prime factors array 5000 <= limit <= 1e17 2 <= prime <= 499 // for every prime in primesL ``` Enjoy!
reference
from functools import reduce def count_find_num(primesL, limit): base_num = reduce((lambda a, b: a * b), primesL, 1) if base_num > limit: return [] nums = [base_num] for i in primesL: for n in nums: num = n * i while (num <= limit) and (num not in nums): nums . append(num) num *= i return [len(nums), max(nums)]
Generating Numbers From Prime Factors I
58f9f9f58b33d1b9cf00019d
[ "Algorithms", "Data Structures", "Mathematics", "Dynamic Programming" ]
https://www.codewars.com/kata/58f9f9f58b33d1b9cf00019d
5 kyu
<img src="https://i.imgur.com/ta6gv1i.png?1" title="weekly coding challenge" /> --- # Story Old MacDingle had a farm. It was a free-range chicken farm with a fox problem, as we learned earlier: * Ref: [The Hunger Games - Foxes and Chickens](https://www.codewars.com/kata/the-hunger-games-foxes-and-chickens) So old MacDingle decided to lay fox bait around the farm to poison the foxes. <hr> Foxes ```F``` eat chickens ```C``` When foxes eat fox bait ```X``` they die. Fox bait is harmless to chickens. Chickens in cages ```[]``` are safe (unless a fox has got into the cage with them!) # Kata Task Given the initial configuration of foxes and chickens what will the farm look like the next morning after the hungry foxes have been feasting? # Examples <table> <tr><td rowspan=2 valign=top>Ex1 - chickens outside cages when foxes about<td>Before<td> <pre style='background:black'> CCC[CCC]FCC[CCCCC]CFFFF[CCC]FFFF </pre> </tr> <tr><td>After<td> <pre style='background:black'> ...[CCC]F..[CCCCC].FFFF[CCC]FFFF </pre> </tr> <tr><td rowspan=2 valign=top>Ex2 - a fox in a chicken cage<td>Before<td> <pre style='background:black'> ...[CCC]...[CCCFC].....[CCC].... </pre> </tr> <tr><td>After<td> <pre style='background:black'> ...[CCC]...[...F.].....[CCC].... </pre> </tr> <tr><td rowspan=2 valign=top>Ex3 - foxes are poisoned<td>Before<td> <pre style='background:black'> CCCCC...XCCCCCCCCC....FFF.X..CF </pre> </tr> <tr><td>After<td> <pre style='background:black'> CCCCC...X.................X.... </pre> </tr> <tr><td rowspan=2 valign=top>Ex4 - a bit of everything<td>Before<td> <pre style='background:black'> ...CC...X...[CCC]CCC[CCCXCCCF]CCCC[CFC]FCC </pre> </tr> <tr><td>After<td> <pre style='background:black'> ...CC...X...[CCC]...[CCCX....]....[.F.]... </pre> </tr> </table> # Notes * Anything not a fox, a chicken, fox bait, or a cage is just dirt ``.`` * All cages are intact (not open-ended), and there are no cages inside other cages * The same fox bait can kill any number of foxes * A hungry fox will always eat as many chickens as he can get to, before he is tempted by the bait * Foxes can jump over cages to get to chickens/bait on the other side
algorithms
def hungry_foxes(farm): def eat(s): ps = s . split('X') r = 'X' . join(p . replace('C', '.') if 'F' in p else p for p in ps) return r . replace('F', '.') if len(ps) > 1 else r parts = farm . replace('[', '|['). replace(']', ']|'). split('|') parts[:: 2] = eat('|' . join(parts[:: 2])). split('|') parts[1:: 2] = map(eat, parts[1:: 2]) return '' . join(parts)
The Hunger Games - Foxes and Chickens (Poison)
5916c21917db4a0ad800002d
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/5916c21917db4a0ad800002d
5 kyu
# Task You are a lonely frog. You live on a coordinate axis. The meaning of your life is to jump and jump.. There are only two rules you must follow: - the first and last jumps should be of size 1; - the absolute difference between the lengths of two consecutive jumps should be less than or equal to 1. Now, here comes your new task. Your starting point is `1`, the target point is `n`. You need to jump to the target point with `minimal steps`. Please tell me, what's the `minimal steps`? `1 <= n <= 10^9` # Example For `n = 5`, the output should be `3`. ``` step from to distance 1: 1 --> 2 1 2: 2 --> 4 2 3: 4 --> 5 1 ``` For `n = 14`, the output should be `7`. ``` step from to distance 1: 1 --> 2 1 2: 2 --> 4 2 3: 4 --> 7 3 4: 7 --> 10 3 5: 10 --> 12 2 6: 12 --> 13 1 7: 13 --> 14 1 ```
algorithms
def jump_to(n): return n > 1 and int((4 * n - 6) * * .5)
Simple Fun #353: Lonely Frog II
59c919326bddd238e9000103
[ "Algorithms" ]
https://www.codewars.com/kata/59c919326bddd238e9000103
6 kyu
A chess board is normally played with 16 pawns and 16 other pieces, for this kata a variant will be played with only the pawns. All other pieces will not be on the board. For information on how pawns move, refer [here](http://www.chesscorner.com/tutorial/basic/pawn/pawn.htm) Write a function that can turn a list of pawn moves into a visual representation of the resulting board. A chess move will be represented by a string, ``` "c3" ``` This move represents a pawn moving to `c3`. If it was white to move, the move would represent a pawn from `c2` moving to `c3`. If it was black to move, a pawn would move from `c4` to `c3`, because black moves in the other direction. The first move in the list and every other move will be for white's pieces. The letter represents the column, while the number represents the row of the square where the piece is moving Captures are represented differently from normal moves: ``` "bxc3" ``` represents a pawn on the column represented by 'b' (the second column) capturing a pawn on `c3`. For the sake of this kata a chess board will be represented by a list like this one: ``` [[".",".",".",".",".",".",".","."], ["p","p","p","p","p","p","p","p"], [".",".",".",".",".",".",".","."], [".",".",".",".",".",".",".","."], [".",".",".",".",".",".",".","."], [".",".",".",".",".",".",".","."], ["P","P","P","P","P","P","P","P"], [".",".",".",".",".",".",".","."]] ``` Here is an example of the board with the squares labeled: ``` [["a8","b8","c8","d8","e8","f8","g8","h8"], ["a7","b7","c7","d7","e7","f7","g7","h7"], ["a6","b6","c6","d6","e6","f6","g6","h6"], ["a5","b5","c5","d5","e5","f5","g5","h5"], ["a4","b4","c4","d4","e4","f4","g4","h4"], ["a3","b3","c3","d3","e3","f3","g3","h3"], ["a2","b2","c2","d2","e2","f2","g2","h2"], ["a1","b1","c1","d1","e1","f1","g1","h1"]] ``` White pawns are represented by capital `'P'` while black pawns are lowercase `'p'`. A few examples ``` If the list/array of moves is: ["c3"] >>> [[".",".",".",".",".",".",".","."], ["p","p","p","p","p","p","p","p"], [".",".",".",".",".",".",".","."], [".",".",".",".",".",".",".","."], [".",".",".",".",".",".",".","."], [".",".","P",".",".",".",".","."], ["P","P",".","P","P","P","P","P"], [".",".",".",".",".",".",".","."]] ``` add a few more moves, ``` If the list/array of moves is: ["d4", "d5", "f3", "c6", "f4"] >>> [[".",".",".",".",".",".",".","."], ["p","p",".",".","p","p","p","p"], [".",".","p",".",".",".",".","."], [".",".",".","p",".",".",".","."], [".",".",".","P",".","P",".","."], [".",".",".",".",".",".",".","."], ["P","P","P",".","P",".","P","P"], [".",".",".",".",".",".",".","."]] ``` now to add a capture... ``` If the list/array of moves is: ["d4", "d5", "f3", "c6", "f4", "c5", "dxc5"] >>> [[".",".",".",".",".",".",".","."], ["p","p",".",".","p","p","p","p"], [".",".",".",".",".",".",".","."], [".",".","P","p",".",".",".","."], [".",".",".",".",".","P",".","."], [".",".",".",".",".",".",".","."], ["P","P","P",".","P",".","P","P"], [".",".",".",".",".",".",".","."]] ``` If an invalid move (a move is added that no pawn could perform, a capture where there is no piece, a move to a square where there is already a piece, etc.) is found in the list of moves, return '(move) is invalid'. ```python If the list/array of moves is: ["e6"] >>> "e6 is invalid" ``` ```java If the list/array of moves is: ["e6"] >>> [["e6 is invalid"]] ``` ```python If the list/array of moves is: ["e4", "d5", "exf5"] >>> "exf5 is invalid" ``` ```java If the list/array of moves is: ["e4", "d5", "exf5"] >>> [["exf5 is invalid"]] ``` The list passed to `pawn_move_tracker / PawnMoveTracker.movePawns` will always be a list of strings in the form (regex pattern): `[a-h][1-8]` or `[a-h]x[a-h][1-8]`. <h1>Notes:</h1> * In the case of a capture, the first lowercase letter will always be adjacent to the second in the alphabet, a move like `axc5` will never be passed. * A pawn can move two spaces on its first move * There are no cases with the 'en-passant' rule.
games
LETTERS = 'abcdefgh' # Defining some constants NUMBERS = '87654321' W, B = WB = 'Pp' EMPTY, CAPTURE = '.x' WHITEHOME = '12' BLACKHOME = '87' JUMP = '54' def pawn_move_tracker(moves): board = {letter + number: # Representing board as B if number == BLACKHOME[1] else # a dictionary for easy W if number == WHITEHOME[1] else EMPTY # access for letter in LETTERS for number in NUMBERS} whitemove = True # Move side switcher for move in moves: target = move[- 2:] # Finding target mover = move[0] + str(int(move[- 1]) + 1 - whitemove * 2) # Finding mover if move[- 1] in JUMP[whitemove] and board[mover] == EMPTY: # Mover for the jump mover = move[0] + str(int(move[- 1]) + 2 - whitemove * 4) if (move[- 1] in (BLACKHOME, WHITEHOME)[whitemove] or # Is the move valid? board[target] != (EMPTY, WB[whitemove])[move[1] == CAPTURE] or board[mover] != WB[not whitemove]): return "{} is invalid" . format(move) whitemove = not whitemove # Switching side board[mover] = EMPTY # Empty the source cell board[target] = WB[whitemove] # Fill the target # Return representation return [[board[letter + number] for letter in LETTERS] for number in NUMBERS]
Tracking pawns
56b012bbee8829c4ea00002c
[ "Strings", "Arrays", "Algorithms", "Puzzles" ]
https://www.codewars.com/kata/56b012bbee8829c4ea00002c
4 kyu
Given a lowercase string that has alphabetic characters only and no spaces, return the highest value of consonant substrings. Consonants are any letters of the alphabet except `"aeiou"`. We shall assign the following values: `a = 1, b = 2, c = 3, .... z = 26`. For example, for the word "zodiacs", let's cross out the vowels. We get: "z **~~o~~** d **~~ia~~** cs" ```haskell -- The consonant substrings are: "z", "d" and "cs" and the values are z = 26, d = 4 and cs = 3 + 19 = 22. The highest is 26. solve("zodiacs") = 26 For the word "strength", solve("strength") = 57 -- The consonant substrings are: "str" and "ngth" with values "str" = 19 + 20 + 18 = 57 and "ngth" = 14 + 7 + 20 + 8 = 49. The highest is 57. ``` For C: do not mutate input. More examples in test cases. Good luck! If you like this Kata, please try: [Word values](https://www.codewars.com/kata/598d91785d4ce3ec4f000018) [Vowel-consonant lexicon](https://www.codewars.com/kata/59cf8bed1a68b75ffb000026)
reference
import re def solve(s): return max(sum(ord(c) - 96 for c in subs) for subs in re . split('[aeiou]+', s))
Consonant value
59c633e7dcc4053512000073
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/59c633e7dcc4053512000073
6 kyu
Now we will confect a reagent. There are eight materials to choose from, numbered 1,2,..., 8 respectively. We know the rules of confect: ``` material1 and material2 cannot be selected at the same time material3 and material4 cannot be selected at the same time material5 and material6 must be selected at the same time material7 or material8 must be selected(at least one, or both) ``` # Task You are given a integer array `formula`. Array contains only digits 1-8 that represents material 1-8. Your task is to determine if the formula is valid. Returns `true` if it's valid, `false` otherwise. # Example For `formula = [1,3,7]`, The output should be `true`. For `formula = [7,1,2,3]`, The output should be `false`. For `formula = [1,3,5,7]`, The output should be `false`. For `formula = [1,5,6,7,3]`, The output should be `true`. For `formula = [5,6,7]`, The output should be `true`. For `formula = [5,6,7,8]`, The output should be `true`. For `formula = [6,7,8]`, The output should be `false`. For `formula = [7,8]`, The output should be `true`. # Note - All inputs are valid. Array contains at least 1 digit. Each digit appears at most once. - Happy Coding `^_^`
reference
def isValid(formula): return not ( (1 in formula and 2 in formula) or (3 in formula and 4 in formula) or (5 in formula and not 6 in formula) or (not 5 in formula and 6 in formula) or (not 7 in formula and not 8 in formula))
Simple Fun #352: Reagent Formula
59c8b38423dacc7d95000008
[ "Fundamentals" ]
https://www.codewars.com/kata/59c8b38423dacc7d95000008
8 kyu
In this kata, you will make a function that converts between `camelCase`, `snake_case`, and `kebab-case`. You must write a function that changes to a given case. It must be able to handle all three case types: ```javascript js> changeCase("snakeCase", "snake") "snake_case" js> changeCase("some-lisp-name", "camel") "someLispName" js> changeCase("map_to_all", "kebab") "map-to-all" js> changeCase("doHTMLRequest", "kebab") "do-h-t-m-l-request" js> changeCase("invalid-inPut_bad", "kebab") undefined js> changeCase("valid-input", "huh???") undefined js> changeCase("", "camel") "" ``` ```python py> change_case("snakeCase", "snake") "snake_case" py> change_case("some-lisp-name", "camel") "someLispName" py> change_case("map_to_all", "kebab") "map-to-all" py> change_case("doHTMLRequest", "kebab") "do-h-t-m-l-request" py> change_case("invalid-inPut_bad", "kebab") None py> change_case("valid-input", "huh???") None py> change_case("", "camel") "" ``` ```haskell λ> changeCase "snakeCase" "snake" Just "snake_case" λ> changeCase "some-lisp-name" "camel" Just "someLispName" λ> changeCase "map_to_all" "kebab" Just "map-to-all" λ> changeCase "doHTMLRequest" "kebab" Just "do-h-t-m-l-request" λ> changeCase "invalid-inPut_bad" "kebab" Nothing λ> changeCase "valid-input" "huh???" Nothing λ> changeCase "" "camel" Just "" ``` ```c c> changeCase("snakeCase", "snake") "snake_case" c> changeCase("some-lisp-name", "camel") "someLispName" c> changeCase("map_to_all", "kebab") "map-to-all" c> changeCase("doHTMLRequest", "kebab") "do-h-t-m-l-request" c> changeCase("invalid-inPut_bad", "kebab") NULL c> changeCase("valid-input", "huh???") NULL c> changeCase("", "camel") "" Non-null returns will be free'd. ``` ```cpp cpp> changeCase("snakeCase", "snake") "snake_case" cpp> changeCase("some-lisp-name", "camel") "someLispName" cpp> changeCase("map_to_all", "kebab") "map-to-all" cpp> changeCase("doHTMLRequest", "kebab") "do-h-t-m-l-request" cpp> changeCase("invalid-inPut_bad", "kebab") "" cpp> changeCase("valid-input", "huh???") "" cpp> changeCase("", "camel") "" ``` ```java java> changeCase("snakeCase", "snake") "snake_case" java> changeCase("some-lisp-name", "camel") "someLispName" java> changeCase("map_to_all", "kebab") "map-to-all" java> changeCase("doHTMLRequest", "kebab") "do-h-t-m-l-request" java> changeCase("invalid-inPut_bad", "kebab") null java> changeCase("valid-input", "huh???") null java> changeCase("", "camel") "" ``` Your function must deal with invalid input as shown, though it will only be passed strings. Furthermore, all valid identifiers will be lowercase except when necessary, in other words on word boundaries in `camelCase`. _**(Any translations would be greatly appreciated!)**_
algorithms
import re def change_case(label, target): if ('_' in label) + ('-' in label) + (label != label . lower()) > 1: return if target == 'snake': return re . sub('([A-Z])', r'_\1', label . replace('-', '_')). lower() if target == 'kebab': return re . sub('([A-Z])', r'-\1', label . replace('_', '-')). lower() if target == 'camel': return re . sub('([_-])([a-z])', lambda m: m . group(2). upper(), label)
Convert all the cases!
59be8c08bf10a49a240000b1
[ "Strings", "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/59be8c08bf10a49a240000b1
5 kyu
Given an array, return the difference between the count of even numbers and the count of odd numbers. `0` will be considered an even number. ``` For example: solve([0,1,2,3]) = 0 because there are two even numbers and two odd numbers. Even - Odd = 2 - 2 = 0. ``` Let's now add two letters to the last example: ``` solve([0,1,2,3,'a','b']) = 0. Again, Even - Odd = 2 - 2 = 0. Ignore letters. ``` The input will be an array of lowercase letters and numbers only. In some languages (Haskell, C++, and others), input will be an array of strings: ``` solve ["0","1","2","3","a","b"] = 0 ``` Good luck! If you like this Kata, please try: [Longest vowel chain](https://www.codewars.com/kata/59c5f4e9d751df43cf000035) [Word values](https://www.codewars.com/kata/598d91785d4ce3ec4f000018)
reference
def solve(a): return sum(1 if v % 2 == 0 else - 1 for v in a if type(v) == int)
Even odd disparity
59c62f1bdcc40560a2000060
[ "Fundamentals" ]
https://www.codewars.com/kata/59c62f1bdcc40560a2000060
7 kyu
An array is defined to be `odd-heavy` if it contains at least one odd element and every element whose value is `odd` is greater than every even-valued element. eg. ``` Array [11,4,9,2,8] is odd-heavy, because its odd elements [11,9] are greater than all the even elements [4,2,8] Array [11,4,9,2,3,10] is not odd-heavy, because one of its even elements (10 from [4,2,10]) is greater than two of its odd elements (9 and 3 from [11,9,3]) Array [] is not odd-heavy, because it does not contain any odd numbers Array [3] is odd-heavy, because it does not contain any even numbers. ``` write a function called `isOddHeavy` or `is_odd_heavy` that accepts an integer array and returns `true` if the array is `odd-heavy` else return `false`.
reference
def isOddHeavy(arr): maxEven = max(filter(lambda n: n % 2 == 0, arr), default=float("-inf")) minOdd = min(filter(lambda n: n % 2 == 1, arr), default=float("-inf")) return maxEven < minOdd
Odd-heavy Array
59c7e477dcc40500f50005c7
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/59c7e477dcc40500f50005c7
6 kyu
A camel at the base of a large sand dune wants to get to the top of it to see what is on the other side. The dune distance ```d``` and height ```h``` are as shown below: <hr> <pre style="color:yellow"> ....+ ........| ............| ................| <span style="color:red">h</span> ....................| ........................| <span style="color:white;background:black">Camel</span> ----------------------------+ <span style="color:red">d</span> </pre> <hr> Steep dunes don't worry him because this is a smart camel! When the slope is > 30 degrees, then instead of going straight up he will zig-zag back and forth so the climb is not so steep. <a href="https://imgur.com/POUUose"><img src="https://i.imgur.com/POUUose.png" title="source: imgur.com" /></a> # Kata Task Given ```d``` and ```h``` then what is the shortest amount of walking for our smart camel to get to the top of the sand dune?
games
def zig_zag_camel(d, h): return max([h * 2, (h * * 2 + d * * 2) * * 0.5])
Zig-Zag Camel
582c6b7cfb3179eb6e000027
[ "Mathematics", "Puzzles", "Geometry" ]
https://www.codewars.com/kata/582c6b7cfb3179eb6e000027
6 kyu
An array is called `zero-balanced` if its elements sum to `0` and for each positive element `n`, there exists another element that is the negative of `n`. Write a function named `ìsZeroBalanced` that returns `true` if its argument is `zero-balanced` array, else return `false`. Note that an `empty array` will not sum to `zero`.
reference
from collections import Counter def is_zero_balanced(arr): c = Counter(arr) return bool(arr) and all(c[k] == c[- k] for k in c)
zero-balanced Array
59c6fa6972851e8959000067
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/59c6fa6972851e8959000067
7 kyu
# Solve For X You will be given an equation as a string and you will need to [solve for X](https://www.mathplacementreview.com/algebra/basic-algebra.php#solve-for-a-variable) and return x's value. For example: ```javascript solveForX('x - 5 = 20'); // Should return 25 solveForX('20 = 5 * x - 5'); // Should return 5 solveForX('5 * x = x + 8'); // Should return 2 solveForX('(5 - 3) * x = x + 2'); // Should return 2 ``` ```python solve_for_x('x - 5 = 20') # should return 25 solve_for_x('20 = 5 * x - 5') # should return 5 solve_for_x('5 * x = x + 8') # should return 2 solve_for_x('(5 - 3) * x = x + 2') # should return 2 ``` NOTES: * All numbers will be whole numbers * Don't forget about the [order of operations](https://www.mathplacementreview.com/algebra/basic-algebra.php#order-of-operations). * If the random tests don't pass the first time, just run them again.
reference
from itertools import count def solve_for_x(equation): return next(x for n in count(0) for x in [n, - n] if eval(equation . replace("x", str(x)). replace("=", "==")))
Solve For X
59c2e2a36bddd2707e000079
[ "Algorithms", "Puzzles", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/59c2e2a36bddd2707e000079
5 kyu
The vowel substrings in the word `codewarriors` are `o,e,a,io`. The longest of these has a length of 2. Given a lowercase string that has alphabetic characters only (both vowels and consonants) and no spaces, return the length of the longest vowel substring. Vowels are any of `aeiou`. Good luck! If you like substring Katas, please try: [Non-even substrings](https://www.codewars.com/kata/59da47fa27ee00a8b90000b4) [Vowel-consonant lexicon](https://www.codewars.com/kata/59cf8bed1a68b75ffb000026)
reference
import re def solve(s): return len(max(re . findall(r"[aeiou]+", s), key=len, default=""))
Longest vowel chain
59c5f4e9d751df43cf000035
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/59c5f4e9d751df43cf000035
7 kyu
Complete the function that returns an array of length `n`, starting with the given number `x` and the squares of the previous number. If `n` is negative or zero, return an empty array/list. ## Examples ``` 2, 5 --> [2, 4, 16, 256, 65536] 3, 3 --> [3, 9, 81] ```
reference
def squares(x, n): return [x * * (2 * * i) for i in range(n)]
Squares sequence
5546180ca783b6d2d5000062
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5546180ca783b6d2d5000062
7 kyu
Write a function `sumTimesTables` which sums the result of the sums of the elements specified in `tables` multiplied by all the numbers in between `min` and `max` including themselves. For example, for `sumTimesTables([2,5],1,3)` the result should be the same as ``` 2*1 + 2*2 + 2*3 + 5*1 + 5*2 + 5*3 ``` i.e. the table of two from 1 to 3 plus the table of five from 1 to 3 All the numbers are integers but you must take in account: * `tables` could be empty. * `min` could be negative. * `max` could be really big.
reference
def sum_times_tables(table, a, b): return sum(table) * (a + b) * (b - a + 1) / / 2
Sum Times Tables
551e51155ed5ab41450006e1
[ "Fundamentals" ]
https://www.codewars.com/kata/551e51155ed5ab41450006e1
7 kyu
Find the first character that repeats in a String and return that character. ```javascript firstDup('tweet') => 't' firstDup('like') => undefined ``` ```python first_dup('tweet') => 't' first_dup('like') => None ``` ```haskell firstDup "tweet" `shouldBe` Just 't' firstDup (repeat ()) `shouldBe` Just () firstDup [] `shouldBe` Nothing firstDup [1..10] `shouldBe` Nothing firstDup [2,46,3,1,1,2] `shouldBe` 2 ``` ```ruby first_dup('tweet') => 't' first_dup('like') => nil ``` *This is not the same as finding the character that repeats first.* *In that case, an input of 'tweet' would yield 'e'.* Another example: In `'translator'` you should return `'t'`, not `'a'`. ``` v v translator ^ ^ ``` While second `'a'` appears before second `'t'`, the first `'t'` is before the first `'a'`.
algorithms
def first_dup(s): for x in s: if s . count(x) > 1: return x return None
first character that repeats
54f9f4d7c41722304e000bbb
[ "Algorithms" ]
https://www.codewars.com/kata/54f9f4d7c41722304e000bbb
6 kyu
Create a function that takes an argument `n` and sums even Fibonacci numbers up to `n`'s index in the Fibonacci sequence. Example: ```c sum_fibs(5) == 2 // (0, 1, 1, 2, 3, 5); // 2 is the only even number in the sequence // and doesn't have another number in the sequence // to get added to in the indexed Fibonacci sequence. ``` ```javascript sumFibs(5) === 2 // (0, 1, 1, 2, 3, 5);2 is the only even number in the sequence and doesn't have another number in the sequence to get added to in the indexed Fibonacci sequence. ``` ```ruby sum_fibs(5) == 2 # (0, 1, 1, 2, 3, 5); 2 is the only even number in the sequence and doesn't have another number in the sequence to get added to in the indexed Fibonacci sequence. ``` ```python sum_fibs(5) == 2 # (0, 1, 1, 2, 3, 5); 2 is the only even number in the sequence and doesn't have another number in the sequence to get added to in the indexed Fibonacci sequence. ``` ```julia sumfibs(5) == 2 # (0, 1, 1, 2, 3, 5) 2 is the only even number in the sequence and doesn't have another number in the sequence to get added to in the indexed Fibonacci sequence. ``` Example: ```c sum_fibs(9) == 44; // (0, 1, 1, 2, 3, 5, 8, 13, 21, 34) // 2 + 8 + 34 = 44; ``` ```javascript sumFibs(9) === 44; // (0, 1, 1, 2, 3, 5, 8, 13, 21, 34) // 2 + 8 + 34 = 44; ``` ```ruby sum_fibs(9) == 44 # (0, 1, 1, 2, 3, 5, 8, 13, 21, 34); # 2 + 8 + 34 = 44; ``` ```python sum_fibs(9) == 44 # (0, 1, 1, 2, 3, 5, 8, 13, 21, 34) # 2 + 8 + 34 = 44 ``` ```julia sumfibs(9) == 44 # (0, 1, 1, 2, 3, 5, 8, 13, 21, 34) # 2 + 8 + 34 = 44 ```
algorithms
def sum_fibs(n): res, x, y = 0, 2, 0 for _ in range(n / / 3): res, x, y = res + x, 4 * x + y, x return res
SumFibs
56662e268c0797cece0000bb
[ "Algorithms" ]
https://www.codewars.com/kata/56662e268c0797cece0000bb
6 kyu
Your team is writing a fancy new text editor and you've been tasked with implementing the line numbering. Write a function which takes a list of strings and returns each line prepended by the correct number. The numbering starts at 1. The format is `n: string`. Notice the colon and space in between. **Examples: (Input --> Output)** ``` [] --> [] ["a", "b", "c"] --> ["1: a", "2: b", "3: c"] ```
reference
def number(lines): return ['%d: %s' % v for v in enumerate(lines, 1)]
Testing 1-2-3
54bf85e3d5b56c7a05000cf9
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/54bf85e3d5b56c7a05000cf9
7 kyu
Create a method **each_cons** that accepts a list and a number **n**, and returns cascading subsets of the list of size **n**, like so: each_cons([1,2,3,4], 2) #=> [[1,2], [2,3], [3,4]] each_cons([1,2,3,4], 3) #=> [[1,2,3],[2,3,4]] As you can see, the lists are cascading; ie, they overlap, but never out of order.
reference
def each_cons(lst, n): return [lst[i: i + n] for i in range(len(lst) - n + 1)]
Enumerable Magic #20 - Cascading Subsets
545af3d185166a3dec001190
[ "Fundamentals", "Lists", "Data Structures", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/545af3d185166a3dec001190
8 kyu
I was working with some time series data in Python today and came across this problem and thought it would make a nice little kata for beginners. ### The problem: You have a time series in Pandas or whatever, indexed by datetime objects. For any date in the time series, you want to find the **date** of the beginning of the week that it is in (Monday in the case of Python) or the end of the week that it is in (Sunday in the case of python). You may use datetime module where necessary.
reference
from datetime import timedelta def week_start_date(dt): return dt - timedelta(days=dt . weekday()) def week_end_date(dt): return dt + timedelta(days=6 - dt . weekday())
Every beginning has an end (Dates)
56f19a230cd8bc5814001047
[ "Date Time", "Fundamentals" ]
https://www.codewars.com/kata/56f19a230cd8bc5814001047
7 kyu
In this kata, you need to make your own `map` function. The way `map` works is that it accepts two arguments: the first one is a function, the second one is an array, a tuple, or a string. It goes through the array, applying the function to each element of an array and storing the result in a new array. The new array is the result of the `map` function. You may read more on the `map` function [here](https://docs.python.org/2/library/functions.html#map). You should return a list (python 2 style) instead of a generator (python 3). *Note:* as Python already has a built-in `map` function, that is disabled. ### Examples ```python map(sum, [[1, 2, 3], [4, 5], [6, 7, 8]]) ==> [6, 9, 21] map(str, [1, 2, 3]) ==> ['1', '2', '3'] map(int, ['34', '23']) ==> [34, 23] ```
algorithms
def map(f, xs): return [f(x) for x in xs]
Write your own map function.
587c37897f7dc251a0000001
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/587c37897f7dc251a0000001
7 kyu
I want to know the size of the longest consecutive elements of X in Y. You will receive two arguments: `items` and `key`. Return the length of the longest segment of consecutive `keys` in the given `items`. **Notes:** * The items and the key will be either an integer or a string (consisting of **letters only**) * If the key does not appear in the items, return `0` ### Examples ``` 90000, 0 --> 4 "abcdaaadse", "a" --> 3 "abcdaaadse", "z" --> 0 ```
reference
from itertools import groupby def get_consective_items(items, key): items, key = str(items), str(key) return max((len(list(l)) for k, l in groupby(items) if k == key), default=0)
Consecutive Count
59c3e819d751df54e9000098
[ "Fundamentals" ]
https://www.codewars.com/kata/59c3e819d751df54e9000098
6 kyu
```if:javascript Your task is to create a function called `addArrays`, which takes two arrays consisting of integers, and returns the sum of those two arrays. ``` ```if:python Your task is to create a function called `sum_arrays()`, which takes two arrays consisting of integers, and returns the sum of those two arrays. ``` ```if:ruby Your task is to create a function called `sum_arrays()`, which takes two arrays consisting of integers, and returns the sum of those two arrays. ``` ```if:rust Your task is to create a function called `add_arrays()`, which takes two arrays consisting of integers, and returns the sum of those two arrays. ``` ```if:java Your task is to create a method called `addArrays` which takes two integer arrays and returns the sum of those two arrays. ``` ```if:c,cpp,nasm Your task is to create a function called `add_arrays` which takes two integer arrays and returns the sum of those two arrays. ``` The twist is that (for example) `[3,2,9]` does not equal `3 + 2 + 9`, it would equal `'3' + '2' + '9'` converted to an integer for this kata, meaning it would equal `329`. The output should be an array of the sum in a similar fashion to the input (for example, if the sum is `341`, you would return `[3,4,1]`). Examples are given below of what two arrays should return. ```python [3,2,9],[1,2] --> [3,4,1] [4,7,3],[1,2,3] --> [5,9,6] [1],[5,7,6] --> [5,7,7] ``` ```ruby [3,2,9],[1,2] --> [3,4,1] [4,7,3],[1,2,3] --> [5,9,6] [1],[5,7,6] --> [5,7,7] ``` ```rust [3, 2, 9], [1, 2] // [3, 4, 1] [4, 7, 3], [1, 2, 3] // [5, 9, 6] [1], [5, 7, 6] // [5, 7, 7] ``` ```java {3,2,9} + {1,2} = {3,4,1} {4,7,3} + {1,2,3} = {5,9,6} {1} + {5,7,6} = {5,7,7} ``` ```c {3,2,9} + {1,2} = {3,4,1} {4,7,3} + {1,2,3} = {5,9,6} {1} + {5,7,6} = {5,7,7} ``` ```cpp {3,2,9} + {1,2} = {3,4,1} {4,7,3} + {1,2,3} = {5,9,6} {1} + {5,7,6} = {5,7,7} ``` ```nasm {3,2,9} + {1,2} = {3,4,1} {4,7,3} + {1,2,3} = {5,9,6} {1} + {5,7,6} = {5,7,7} ``` If both arrays are empty, return an empty array. In some cases, there will be an array containing a negative number as the first index in the array. In this case treat the whole number as a negative number. See below: ```python [3,2,6,6],[-7,2,2,8] --> [-3,9,6,2] # 3266 + (-7228) = -3962 ``` ```ruby [3,2,6,6],[-7,2,2,8] --> [-3,9,6,2] # 3266 + (-7228) = -3962 ``` ```rust [3, 2, 6, 6], [-7, 2, 2, 8] // [-3, 9, 6, 2] as 3266 + (-7228) = -3962 ``` ```java {3,2,6,6} + {-7,2,2,8} = {-3,9,6,2} // 3266 + (-7228) = -3962 ``` ```c {3,2,6,6} + {-7,2,2,8} = {-3,9,6,2} // 3266 + (-7228) = -3962 ``` ```cpp {3,2,6,6} + {-7,2,2,8} = {-3,9,6,2} // 3266 + (-7228) = -3962 ``` ```nasm {3,2,6,6} + {-7,2,2,8} = {-3,9,6,2} // 3266 + (-7228) = -3962 ```
algorithms
def sum_arrays(array1, array2): if not array1: return array2 if not array2: return array1 num = sum(map(lambda x: int('' . join(map(str, x))), [array1, array2])) lst = list(map(int, str(abs(num)))) if num < 0: lst[0] *= - 1 return lst
Sum two arrays
59c3e8c9f5d5e40cab000ca6
[ "Algorithms" ]
https://www.codewars.com/kata/59c3e8c9f5d5e40cab000ca6
6 kyu
The drawing shows 6 squares the sides of which have a length of 1, 1, 2, 3, 5, 8. The perimeter of the overall rectangle is `42`. Could you give the perimeter of a rectangle when there are n + 1 squares disposed in the same manner as in the drawing: ![Alt text](http://i.imgur.com/EYcuB1wm.jpg) The function `perimeter` has the parameter `n` where `n + 1` is the number of squares (they are numbered from 0 to n), and returns the perimeter of the overall rectangle (*not* of its component squares). ~~~if:javascript **JS: The result of the random tests can go up to 210 digits. So, return the result in the form of BigInt.** ~~~ Credit: this kata is a twist on [Perimeter of squares in a rectangle](https://www.codewars.com/kata/perimeter-of-squares-in-a-rectangle).
reference
def perimeter(n: int) - > int: a, b = 0, 1 for i in range(n): a, b = b, a + b return b * 2 + (a + b) * 2
Perimeter of Fibonacci Rectangle
59c35ba16bddd219ee000082
[ "Algorithms", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/59c35ba16bddd219ee000082
6 kyu
# Pythagorean Triples A Pythagorean triplet is a set of three numbers a, b, and c where `a^2 + b^2 = c^2`. In this Kata, you will be tasked with finding the Pythagorean triplets whose product is equal to `n`, the given argument to the function `pythagorean_triplet`. ## Your task In this Kata, you will be tasked with finding the Pythagorean triplets whose product is equal to `n`, the given argument to the function, where `0 < n < 10000000` ## Examples One such triple is `3, 4, 5`. For this challenge, you would be given the value `60` as the argument to your function, and then it would return the Pythagorean triplet in an array `[3, 4, 5]` which is returned in increasing order. `3^2 + 4^2 = 5^2` since `9 + 16 = 25` and then their product (`3 * 4 * 5`) is `60`. More examples: | **argument** | **returns** | | ---------|---------| | 60 | [3, 4, 5] | | 780 | [5, 12, 13] | | 2040 | [8, 15, 17] |
algorithms
def pythagorean_triplet(n): for a in range(3, n): for b in range(a + 1, n): c = (a * a + b * b) * * 0.5 if a * b * c > n: break if c == int(c) and a * b * c == n: return [a, b, c]
Pythagorean Triplets
59c32c609f0cbce0ea000073
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/59c32c609f0cbce0ea000073
6 kyu
### Task: A magician in the subway showed you a trick, he put an ice brick in a bottle to impress you. The brick's length and width are equal, forming a square; its height may be different. Just for fun and also to impress the magician and people around, you decided to calculate the brick's volume. Write a function `iceBrickVolume` that will accept these parameters: - `radius` - bottle's radius (always > 0); - `bottleLength` - total bottle length (always > 0); - `rimLength` - length from bottle top to brick (always < `bottleLength`); And return volume of ice brick that magician managed to put into a bottle. ![illustration](https://i.imgur.com/vU2zzm4.png) ### Note: All inputs are integers. Assume no irregularities to the cuboid brick. You may assume the bottle is shaped like a cylinder. The brick cannot fit inside the rim. The ice brick placed into the bottle is the largest possible cuboid that could actually fit inside the inner volume. ### Example 1: ```c radius = 1 bottle_length = 10 rim_length = 2 volume = 16 ``` ### Example 2: ```c radius = 5 bottle_length = 30 rim_length = 7 volume = 1150 ```
algorithms
def ice_brick_volume(radius, bottle_length, rim_length): return (bottle_length - rim_length) * 2 * radius * * 2
For Twins: 2. Math operations
59c287b16bddd291c700009a
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/59c287b16bddd291c700009a
8 kyu
In order to bamboozle your friends, you decide to encode your communications in hexadecimal, using an ASCII to hexadecimal table. At first, none of them can understand your messages. But quickly enough, one of your cleverer friends uncovers your trick and starts sending messages in hexadecimal himself. To stay one (or shall we say, *n*) step(s) ahead of your friend, you decide to go one step further : you'll apply the ASCII to hexadecimal conversion more than once. ## Your Task Implement 2 functions for encoding and decoding text as described above. There's a preloaded dictionary `TEXT2HEX` which maps ASCII characters to their corresponding hexadecimal codes, e.g. `'a'` maps to `'61'`. Happy bamboozlin'!
algorithms
class HexCipher: HEX2TEXT = {h: c for c, h in TEXT2HEX . items()} @ classmethod def encode(cls, s, n): for _ in range(n): s = '' . join(TEXT2HEX[c] for c in s) return s @ classmethod def decode(cls, s, n): for _ in range(n): s = '' . join(HexCipher . HEX2TEXT[s[i: i + 2]] for i in range(0, len(s), 2)) return s
Hex cipher
59c191df4f98a8a70b00001e
[ "Cryptography", "Object-oriented Programming", "Ciphers", "Algorithms" ]
https://www.codewars.com/kata/59c191df4f98a8a70b00001e
6 kyu
### Prolog: This kata series was created for friends of mine who just started to learn programming. Wish you all the best and keep your mind open and sharp! ### Task: Write a function that will accept two parameters: `variable` and `type` and check if type of `variable` is matching `type`. Return `true` if types match or `false` if not. ### Examples: ```javascript 42, "number" --> true "42", "number" --> false ``` ```python 42, "int" --> True "42", "int" --> False ```
reference
def type_validation(variable, _type): return type(variable). __name__ == _type
For Twins: 1. Types
59c1302ecb7fb48757000013
[ "Fundamentals" ]
https://www.codewars.com/kata/59c1302ecb7fb48757000013
8 kyu
Make me a window. I'll give you a number (N). You return a window. Rules: The window will always be 2 x 2. The window needs to have N number of periods across and N number of periods vertically in each pane. Example: ``` N = 3 --------- |...|...| |...|...| |...|...| |---+---| |...|...| |...|...| |...|...| --------- ``` Note: there should be no trailing new line characters at the end.
reference
def make_a_window(n): top = '-' * (2 * n + 3) middle = f"| { '-' * n } + { '-' * n } |" glasses = [f"| { '.' * n } | { '.' * n } |"] * n return '\n' . join([top, * glasses, middle, * glasses, top])
Make A Window
59c03f175fb13337df00002e
[ "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/59c03f175fb13337df00002e
6 kyu
A **pandigital number** is one that has its digits from ```1``` to ```9``` occuring only once (they do not have the digit 0). The number ```169```, is the first pandigital square, higher than ```100```, having its square root, ```13```, pandigital too. The number ```1728``` is the first pandigital cubic, higher than ```1000```, having its cubic root, ```12```, pandigital too. Make the function ```pow_root_pandigit()```, that receives three arguments: - a minimum number, ```val``` - the exponent of the n-perfect powers to search, ```n``` - ```k```, maximum amount of terms that we want in the output The function should output a 2D-array with an amount of k pairs of numbers(or an array of an only pair if we have this case). Each pair has a nth-perfect power pandigital higher than val with its respective nth-root that is pandigital, too. The function should work in this way: ```python pow_root_pandigit(val, n, k) = [[root1, pow1], [root2, pow2], ...., [rootk, powk]] """ root1 < root2 <.....< rootk val < pow1 < pow2 < ....< powk root1 ^ n = pow1 // root2 ^ n = pow2 //........// rootk ^ n = powk all pairs rooti, powi are pandigitals """ ``` Let's see some examples: ```python pow_root_pandigit(388, 2, 3)== [[23, 529], [24, 576], [25, 625]] # 3 pairs (k = 3) ``` For a different power: ```python pow_root_pandigit(1750, 3, 5) == [[13, 2197], [17, 4913], [18, 5832], [19, 6859], [21, 9261]] # 5 pairs (k = 5) ``` The output in not inclusive for val. ```python pow_root_pandigit(1728, 3, 4) == [[13, 2197], [17, 4913], [18, 5832], [19, 6859]] # ∛1728 = 12 ``` The result may have less terms than the required: ```python pow_root_pandigit(600000000, 2, 5) == [25941, 672935481] # If the result has an only one pair, the output is an array ``` Furthermore, if the minimum value, ```val``` is high enough, the result may be an empty list: ```python pow_root_pandigit(900000000, 2, 5) == [] ``` You may suposse that the input ```val```, ```n``` will be always: ```val > 10``` and ```n > 2```. Enjoy it!!
reference
def is_pandigital(n): s = str(n) return not '0' in s and len(set(s)) == len(s) def pow_root_pandigit(val, n, k): res = [] current = int(round(val * * (1.0 / n), 5)) + 1 while len(res) < k and current <= 987654321 * * (1.0 / n): if is_pandigital(current): p = current * * n if is_pandigital(p): res += [[current, p]] current += 1 return res if len(res) != 1 else res[0]
Pandigital Powers
572a0fd8984419070e000491
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic", "Strings" ]
https://www.codewars.com/kata/572a0fd8984419070e000491
5 kyu
[BasE91](http://base91.sourceforge.net/) is a method for encoding binary as ASCII characters. It is more efficient than Base64 and needs 91 characters to represent the encoded data. The following ASCII charakters are used: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' '!#$%&()*+,./:;<=>?@[]^_`{|}~"' Create two functions that encode strings to basE91 string and decodes the other way round. b91encode('test') = 'fPNKd' b91decode('fPNKd') = 'test' b91decode('>OwJh>Io0Tv!8PE') = 'Hello World!' b91encode('Hello World!') = '>OwJh>Io0Tv!8PE' Input strings are valid.
algorithms
import base91 import pip pip . main(['install', 'base91']) def b91decode(s): return base91 . decode(s). decode() def b91encode(s): return base91 . encode(s . encode())
BasE91 encoding & decoding
58a57c6bcebc069d7e0001fe
[ "Algorithms" ]
https://www.codewars.com/kata/58a57c6bcebc069d7e0001fe
4 kyu
Your collegue wrote an simple loop to list his favourite animals. But there seems to be a minor mistake in the grammar, which prevents the program to work. Fix it! :) If you pass the list of your favourite animals to the function, you should get the list of the animals with orderings and newlines added. For example, passing in: ```python animals = [ 'dog', 'cat', 'elephant' ] ``` will result in: ```python list_animals(animals) == '1. dog\n2. cat\n3. elephant\n' ```
bug_fixes
def list_animals(animals): list = '' for i in range(len(animals)): list += str(i + 1) + '. ' + animals[i] + '\n' return list
Fix the loop!
55ca43fb05c5f2f97f0000fd
[ "Debugging", "Fundamentals" ]
https://www.codewars.com/kata/55ca43fb05c5f2f97f0000fd
8 kyu
<i>Special thanks to <b>SteffenVogel_79</b> for the idea</i>. ```if:c Challenge: Given a null-terminated string and a pre-allocated buffer that has enough memory to store the full null-terminated copy of the passed string, copy the entire string into the buffer with its vowels' case swapped, and return the pointer to the beginning of the copied string (buffer). ``` ```if-not:c Challenge: Given a string, return a copy of the string with the vowels' case swapped. ``` For this kata, assume that vowels are in the set `"aeouiAEOUI"`. ```if:c Example: Given a string `"C is alive!"` and a buffer of size `strlen("C is alive!") + 1`, after the call to swapCase(), the function should return the pointer to the buffer which now contains `"C Is AlIvE!"` and is properly null-terminated. ``` ```if-not:c Example: Given a string `"C is alive!"`, your function should return `"C Is AlIvE!"` ``` Addendum: Your solution is only required to work for the ASCII character set. Please make sure you only swap cases for the vowels. ```if:c Your solution should not allocate or de-allocate any memory. The buffer has already been pre-allocated before the call. Dont forget to NUL-terminate the output string. The buffer has enough memory to hold the passed string and its null terminator entirely. ```
reference
def swap_vowel_case(st): return "" . join(x . swapcase() if x in "aeiouAEIOU" else x for x in st)
Strings: swap vowels' case
5803c0c6ab6c20a06f000026
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5803c0c6ab6c20a06f000026
7 kyu
Challenge: Given two null-terminated strings in the arguments "string" and "prefix", determine if "string" starts with the "prefix" string. Return true or false. Example: ``` startsWith("hello world!", "hello"); // should return true startsWith("hello world!", "HELLO"); // should return false startsWith("nowai", "nowaisir"); // should return false ``` Addendum: For this problem, an empty "prefix" string should always return true for any value of "string". If the length of the "prefix" string is greater than the length of the "string", return false. The check should be case-sensitive, i.e. startsWith("hello", "HE") should return false, whereas startsWith("hello", "he") should return true. The length of the "string" as well as the "prefix" can be defined by the formula: <i>0 <= length < +Infinity</i> No characters should be ignored and/or omitted during the test, e.g. whitespace characters should not be ignored.
reference
def starts_with(st, prefix): return st . startswith(prefix)
Strings: starts with
5803a6d8db07c59fff00015f
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5803a6d8db07c59fff00015f
7 kyu
# Introduction The Condi (Consecutive Digraphs) cipher was introduced by G4EGG (Wilfred Higginson) in 2011. The cipher preserves word divisions, and is simple to describe and encode, but it's surprisingly difficult to crack. # Encoding Algorithm The encoding steps are: - Start with an `initial key`, e.g. `cryptogram` - Form a `key`, remove the key duplicated letters except for the first occurrence - Append to it, in alphabetical order all letters which do not occur in the `key`. The example produces: `cryptogambdefhijklnqsuvwxz` - Number the `key alphabet` starting with 1. ```python 1 2 3 4 5 6 7 8 9 10 11 12 13 c r y p t o g a m b d e f 14 15 16 17 18 19 20 21 22 23 24 25 26 h i j k l n q s u v w x z ``` - One of the inputs to encoding algorithm is an `initial shift`, say `10` - Encode the first letter of your `message` by moving 10 places to the right from the letter's position in the key alphabet. If the first letter were say `o` then the letter 10 places to the right in the `key alphabet` is `j`, so `o` would be encoded as `j`. If you move past the end of the key alphabet you wrap back to the beginning. For example if the first letter were `s` then counting 10 places would bring you around to `t`. - Use the position of the previous plaintext letter as the number of places to move to encode the next plaintext number. If you have just encoded an `o` (position 6) , and you now want to encode say `n`, then you move 6 places to the right from `n` which brings you to `x`. - Keep repeating the previous step until all letters are encoded. Decoding is the reverse of encoding - you move to the left instead of to the right. # Task Create two functions - `encode`/`Encode` and `decode`/`Decode` which implement Condi cipher encoding and decoding. # Inputs - `message` - a string to encode/decode - `key` - a key consists of only lower case letters - `initShift` - a non-negative integer representing the initial shift # Notes - Don't forget to remove the duplicated letters from the `key` except for the first occurrence - Characters which do not exist in the `key alphabet` should be coppied to the output string exactly like they appear in the `message` string - Check the test cases for samples
algorithms
# from string import ascii_lowercase as LOWER LOWER = "abcdefghijklmnopqrstuvwxyz" def encode(message, key, shift, encode=True): key = sorted(LOWER, key=f" { key }{ LOWER } " . index) result = [] for char in message: if char in key: i = key . index(char) char = key[(i + shift) % 26] shift = i + 1 if encode else - (key . index(char) + 1) result . append(char) return "" . join(result) def decode(message, key, shift): return encode(message, key, - shift, encode=False)
Condi cipher
59bf6b73bf10a4c8e5000047
[ "Ciphers", "Strings", "Algorithms" ]
https://www.codewars.com/kata/59bf6b73bf10a4c8e5000047
6 kyu
Consider the following: * The divisors of `6` are: `1, 2, 3 & 6` and their sum is `12`. Now, `12/6 = 2`. * The divisors of `28` are `1, 2, 4, 7, 14 & 28` and their sum is `56`. Now, `56/28 = 2`. * The divisors of `496` are `1, 2, 4, 8, 16, 31, 62, 124, 248, 496` and their sum is `992`. Now, `992/496 = 2`. We shall say that `(6,28,496)` is a grouping with a ratio of `2`. Similarly, consider the grouping `(30,140)`: * The divisors of `30` are: `1, 2, 3, 5, 6, 10, 15 & 30` and their sum is `72`. Now, `72/30 = 12/5 = 2.4`. * The divisors of `140` are `1, 2, 4, 5, 7, 10, 14, 20, 28, 35, 70, 140` and their sum is `336`. Now, `336/140 = 12/5 = 2.4`. We shall say that `(30,140)` is a grouping with a ratio of `12/5`. `(6,28)` and `(30,140)` are the only groupings in which `every member of a group is 0 <= n < 200`. The sum of the smallest members of each group is `6 + 30 = 36`. Given a `range(a,b),` return the sum of the smallest members of each group. As illustrated above: * every member of a group must be greater than or equal to `a` and less than `b`. * a group must have `2` or more members. ``` Examples: solve(1,200) = 36, the sum of [6,30] as explained above solve(1,250) = 168, the sum of [6, 12, 30, 40, 80] solve(1,500) = 498, the sum of [6, 12, 30, 40, 66, 78, 80, 84, 102] As you can see, for "solve(1,500)", we do not include all (6,28) & (6,496) & (28,496). We count the group once by including 6 only. ``` If there are no groups, return `0`. Upper limit is `2000`. Good luck! if you like this Kata, please try: [Simple division](https://www.codewars.com/kata/59ec2d112332430ce9000005) [Sub-array division](https://www.codewars.com/kata/59eb64cba954273cd4000099)
algorithms
import collections def solve(a, b): d = collections . defaultdict(list) for n in range(a, b): d[(sum(k + n / / k for k in range(1, int(n * * 0.5) + 1) if n % k == 0) - (int(n * * 0.5) if int(n * * 0.5) == n * * 0.5 else 0)) / n]. append(n) return sum(v[0] for v in d . values() if len(v) > 1)
Divisor harmony
59bf97cd4f98a8b1cd00007e
[ "Algorithms" ]
https://www.codewars.com/kata/59bf97cd4f98a8b1cd00007e
6 kyu
Imagine you have a large project where is suddenly going something very messy. You are not able to guess what it is and don't want to debug all the code through. Your project has one base class. In this kata you will write metaclass Meta for your base class, which will collect data about all attribute accesses and method calls in all project classes. From this data you can then better guess what is happening or which method call is bottleneck of your app. We will use class Debugger to store the data. Method call collection should look like this: ```python Debugger.method_calls.append({ 'class': ..., # class object, not string 'method': ..., # method name, string 'args': args, # all args, including self 'kwargs': kwargs }) ``` Attribute access collection should look like this: ```python Debugger.attribute_accesses.append({ 'action': 'set', # set/get 'class': ..., # class object, not string 'attribute': ..., # name of attribute, string 'value': value # actual value }) ``` You should NOT log calls of getter/setter methods that you might create by meta class. See the tests if in doubts.
reference
from time import time class Debugger (object): attribute_acceses = [] method_calls = [] class Meta (type): def __new__(cls, name, bases, atts): for k, v in atts . items(): if callable(v): atts[k] = wrapped_method(cls, v) atts['__getattribute__'] = wrapped_getattribute(cls) atts['__setattr__'] = wrapped_setattr(cls) return type . __new__(cls, name, bases, atts) def wrapped_method(c, f): def w(* args, * * kwargs): a = time() r = f(* args, * * kwargs) b = time() Debugger . method_calls . append( {'class': c, 'mehod': f . __name__, 'args': args, 'kwargs': kwargs, 'time': b - a}) return w def wrapped_setattr(c): def s(self, k, v): object . __setattr__(self, k, v) Debugger . attribute_acceses . append( {'action': 'set', 'class': c, 'attribute': k, 'value': v}) return s def wrapped_getattribute(c): def g(self, k): v = object . __getattribute__(self, k) Debugger . attribute_acceses . append( {'action': 'get', 'class': c, 'attribute': k, 'value': v}) return v return g
Debugger
54bebed0d5b56c5b2600027f
[ "Metaprogramming" ]
https://www.codewars.com/kata/54bebed0d5b56c5b2600027f
2 kyu
Let's assume we need "clean" strings. Clean means a string should only contain letters `a-z`, `A-Z` and spaces. We assume that there are no double spaces or line breaks. Write a function that takes a string and returns a string without the unnecessary characters. ### Examples ```python remove_chars('.tree1') ==> 'tree' remove_chars("that's a pie$ce o_f p#ie!") ==> 'thats a piece of pie' remove_chars('john.dope@dopington.com') ==> 'johndopedopingtoncom' remove_chars('my_list = ["a","b","c"]') ==> 'mylist abc' remove_chars('1 + 1 = 2') ==> ' ' (string with 4 spaces) remove_chars("0123456789(.)+,|[]{}=@/~;^$'<>?-!*&:#%_") ==> '' (empty string) ``` ```javascript removeChars('.tree1') ==> 'tree' removeChars("that's a pie$ce o_f p#ie!") ==> 'thats a piece of pie' removeChars('john.dope@dopington.com') ==> 'johndopedopingtoncom' removeChars('my_list = ["a","b","c"]') ==> 'mylist abc' removeChars('1 + 1 = 2') ==> ' ' (string with 4 spaces) removeChars("0123456789(.)+,|[]{}=@/~;^$'<>?-!*&:#%_") ==> '' (empty string) ```
reference
import re def remove_chars(s): return re . sub(r'[^a-zA-Z ]', '', s)
letters only, please!
59be6bdc4f98a8a9c700007d
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/59be6bdc4f98a8a9c700007d
7 kyu
Removed due to copyright infringement. <!--- # Task Imagine a standard chess board with only two white and two black knights placed in their standard starting positions: the white knights on b1 and g1; the black knights on b8 and g8. ![](https://codefightsuserpics.s3.amazonaws.com/tasks/whoseTurn/img/initial_pos.png?_tm=1473954690809) There are two players: one plays for `white`, the other for `black`. During each move, the player picks one of his knights and moves it to an unoccupied square according to standard chess rules. Thus, a knight on d5 can move to any of the following squares: b6, c7, e7, f6, f4, e3, c3, and b4, as long as it is not occupied by either a friendly or an enemy knight. ![](https://codefightsuserpics.s3.amazonaws.com/tasks/whoseTurn/img/knight.jpg?_tm=1473954691265) The players take turns in making moves, starting with the white player. Given the configuration `positions` of the knights after an unspecified number of moves, determine whose turn it is. # Example For `positions = "b1;g1;b8;g8"`, the output should be `true`. The configuration corresponds to the initial state of the game. Thus, it's white's turn. # Input/Output - `[input]` string `positions` The positions of the four knights, starting with white knights, separated by a semicolon, in the chess notation. - `[output]` a boolean value `true` if white is to move, `false` otherwise. --->
games
def whose_turn(positions): return sum(ord(c) for c in positions . replace(";", "")) % 2 == 0
Chess Fun #5: Whose Turn?
5897e572948beb7858000089
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/5897e572948beb7858000089
6 kyu
Task. Calculate area of given triangle. Create a function t_area that will take a string which will represent triangle, find area of the triangle, one space will be equal to one length unit. The smallest triangle will have one length unit. Hints Ignore dots. All triangles will be right isoceles. Example: .</br> .&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; . &nbsp; </br> .&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; . &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; . &nbsp;&nbsp;&nbsp;&nbsp; ---> should return 2.0 .</br> .&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; . &nbsp; </br> .&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; . &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; . &nbsp;&nbsp;&nbsp;&nbsp; </br> .&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; . &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; . &nbsp;&nbsp;&nbsp;&nbsp; . &nbsp;&nbsp;&nbsp;&nbsp; ---> should return 4.5
reference
def t_area(s): return (s . count('\n') - 2) * * 2 / 2
Triangle area
59bd84b8a0640e7c49002398
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/59bd84b8a0640e7c49002398
7 kyu
A western man is trying to find gold in a river. To do that, he passes a bucket through the river's soil and then checks if it contains any gold. However, he could be more productive if he wrote an algorithm to do the job for him. So, you need to check if there is gold in the bucket, and if so, return `True`/`true`. If not, return `False`/`false`.
reference
def check_the_bucket(bucket): return 'gold' in bucket
Man in the west
59bd5dc270a3b7350c00008b
[ "Fundamentals" ]
https://www.codewars.com/kata/59bd5dc270a3b7350c00008b
8 kyu
# Magpies are my favourite birds Baby ones even more so... <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/0b/Magpie_samcem05.jpg/220px-Magpie_samcem05.jpg"/> It is a little known fact^ that the black & white colours of baby magpies differ by **at least** one place and **at most** two places from the colours of the mother magpie. So now you can work out if any two magpies may be related. *...and Quardle oodle ardle wardle doodle the magpies said* # Kata Task Given the colours of two magpies, determine if one is a possible **child** or **grand-child** of the other. # Notes * Each pair of birds being compared will have same number of colour areas * `B` = Black * `W` = White # Example Given these three magpies <pre style='font-size:6em;line-height:90px;'> <span style='font-size:20px;'>Magpie 1 </span><span style='background:black'>B</span><span style='background:white;color:black'>W</span><span style='background:black'>B</span><span style='background:white;color:black'>W</span><span style='background:black'>B</span><span style='background:white;color:black'>W</span> <span style='font-size:20px;'>Magpie 2 </span><span style='background:black'>B</span><span style='background:white;color:black'>W</span><span style='background:black'>B</span><span style='background:white;color:black'>W</span><span style='background:black'>B</span><span style='background:black;color:brown'>B</span> <span style='font-size:20px;'>Magpie 3 </span><span style='background:white;color:brown'>W</span><span style='background:white;color:black'>W</span><span style='background:white;color:brown'>W</span><span style='background:white;color:black'>W</span><span style='background:black'>B</span><span style='background:black'>B</span> </pre> You can see: * Magpie 2 may be a child of Magpie 1 because there is only one difference * Magpie 3 may be child of Magpie 2 because there are two differences * So Magpie 3 may be a grand-child of Magpie 1 * On the other hand, Magpie 3 cannot be a child of Magpie 1 because there are three differences --- DM :-) ^ <span style='font-size:0.8em;'>*This fact is little known because I just made it up*</span>
algorithms
def diffs(bird1, bird2): return sum(c1 != c2 for c1, c2 in zip(bird1, bird2)) def child(bird1, bird2): return diffs(bird1, bird2) in [1, 2] def grandchild(bird1, bird2): return diffs(bird1, bird2) in [0, 1, 2, 3, 4] if len(bird1) > 1 else bird1 == bird2
Baby Magpies
59bb02f5623654a0dc000119
[ "Algorithms" ]
https://www.codewars.com/kata/59bb02f5623654a0dc000119
6 kyu
An acrostic is a text in which the first letter of each line spells out a word. It is also a quick and cheap way of writing a poem for somebody, as exemplified below : <a href='http://treasuredpoem.com/Acrostic-Poem.html'><img src='http://treasuredpoem.com/images/cynthia_acrostic.jpg'></a> Write a program that reads an acrostic to identify the "hidden" word. Specifically, your program will receive a list of words (reprensenting an acrostic) and will need to return a <code>string</code> corresponding to the word that is spelled out by taking the first letter of each word in the acrostic.
reference
def read_out(acrostic): return "" . join(word[0] for word in acrostic)
Acrostic reader
59b843b58bcb7766660000f6
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/59b843b58bcb7766660000f6
7 kyu
I will give you two strings. I want you to transform stringOne into stringTwo one letter at a time. Example: ```javascript stringOne = 'bubble gum'; stringTwo = 'turtle ham'; Result: bubble gum tubble gum turble gum turtle gum turtle hum turtle ham ```
reference
def mutate_my_strings(s1, s2): return '\n' . join([s1] + [s2[: i] + s1[i:] for i, (a, b) in enumerate(zip(s1, s2), 1) if a != b]) + '\n'
Mutate My Strings
59bc0059bf10a498a6000025
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/59bc0059bf10a498a6000025
7 kyu
Define a "prime prime" number to be a rational number written as one prime number over another prime number: `primeA / primeB` (e.g. `7/31`) Given a whole number `N` / `n`, generate the number of "prime prime" rational numbers less than 1, using only prime numbers between `0` and `N` / `n`(non inclusive). Return the count of these "prime primes", and the integer part of their sum. ## Example ```python N = 6 # The "prime primes" less than 1 are: 2/3, 2/5, 3/5 # count: 3 2/3 + 2/5 + 3/5 = 1.6667 # integer part: 1 Thus, the function should return 3 and 1. ``` ```ruby n = 6 # The "prime primes" less than 1 are: 2/3, 2/5, 3/5 # count: 3 2/3 + 2/5 + 3/5 = 1.6667 # integer part: 1 thus, the function should return 3 and 1. ``` ```javascript N = 6 // The "prime primes" less than 1 are: 2/3, 2/5, 3/5 // count: 3 2/3 + 2/5 + 3/5 = 1.6667 // integer part: 1 Thus, the function should return [3, 1]. ```
algorithms
from bisect import bisect_left def sieve(n): sieve, primes = [0] * (n + 1), [] for i in range(2, n + 1): if not sieve[i]: primes . append(i) for j in range(i * * 2, n + 1, i): sieve[j] = 1 return primes PRIMES = sieve(100000) def prime_primes(n): lst = PRIMES[: bisect_left(PRIMES, n)] divs = [p / q for i, p in enumerate(lst) for q in lst[i + 1:]] return len(divs), int(sum(divs))
Prime Primes
57ba58d68dcd97e98c00012b
[ "Algorithms" ]
https://www.codewars.com/kata/57ba58d68dcd97e98c00012b
6 kyu
<img src="https://i.imgur.com/ta6gv1i.png?1"/> --- You receive the following letter in the mail... >Dear Valued Customer, > > >*Thank you for your recent visit to the <span style='color:red;'>Nut Farm</span> - https://www.codewars.com/kata/nut-farm* > >* *You came* >* *You saw* >* *You harvested our nuts* > >*I am pleased to advise that more trees have recently come into season.* > >*Looking forward to seeing you again soon.* > >*Your Sincerely,*<br/> >*D.M. (CEO) Nut Co.* </span> Barely able to contain your excitement you jump in the car and head straight back to the Nut Farm. # To Recap Harvesting nuts is very easy. We just shake the trees and the nuts fall out! As they fall down the nuts might hit branches: * Sometimes they bounce left. * Sometimes they bounce right. * Sometimes they get stuck in the tree and don't fall out at all. ## Legend * `o` = a nut * `\` = branch. A nut hitting this branch bounces right * `/` = branch. A nut hitting this branch bounces left * `.` = leaves, which have no effect on falling nuts * `|` = tree trunk, which has no effect on falling nuts * ` ` = empty space, which has no effect on falling nuts # Kata Task Shake the tree and count where the nuts land. **Output** - An array (same width as the tree) which indicates how many nuts fell at each position ^ ^ See the example tests Notes * The nuts may be anywhere in the canopy of the tree * Nuts do not affect the falling patterns of other nuts * Falling nuts are only affected by the branches **beneath** them * There is not always space for nuts to fall between branches * A left/right bouncing nut may continue hitting other branches that bounces it further in that direction * If a nut bouncing in one direction bounces backwards then it will become stuck in the tree * There are no branches at the extreme left/right edges of the tree so it is not possible for a nut to fall "out of bounds" # Example <pre style='font-size:20px;line-height:22px;'> <span style='background:green'>.</span>\<span style='background:green'>.</span><span style='background:green'>.</span>\<span style='background:green'>.</span><span style='background:green'>.</span>o//<span style='background:green'>.</span>o<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>\o<span style='background:green'>.</span> <span style='background:green'>.</span>\<span style='background:green'>.</span>/\\<span style='background:green'>.</span>///<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>\<span style='background:green'>.</span>o\<span style='background:green'>.</span> <span style='background:green'>.</span>oo<span style='background:green'>.</span>\<span style='background:green'>.</span><span style='background:green'>.</span>o/\<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>\\o/<span style='background:green'>.</span> <span style='background:green'>.</span><span style='background:green'>.</span>o<span style='background:green'>.</span>o\\//<span style='background:green'>.</span>o/<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span> <span style='background:green'>.</span>\/<span style='background:green'>.</span>\/<span style='background:green'>.</span>\<span style='background:green'>.</span>o\oo\o<span style='background:green'>.</span>oo<span style='background:green'>.</span> <span style='background:green'>.</span>/<span style='background:green'>.</span>/<span style='background:green'>.</span><span style='background:green'>.</span>//o<span style='background:green'>.</span><span style='background:green'>.</span>o<span style='background:green'>.</span><span style='background:green'>.</span>oo\o<span style='background:green'>.</span> <span style='background:green'>.</span>\<span style='background:green'>.</span>o\oo/\<span style='background:green'>.</span>o<span style='background:green'>.</span>o<span style='background:green'>.</span><span style='background:green'>.</span>\<span style='background:green'>.</span>\<span style='background:green'>.</span> <span style='background:green'>.</span>\<span style='background:green'>.</span>\<span style='background:green'>.</span><span style='background:green'>.</span>o/oo\<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span>//<span style='background:green'>.</span><span style='background:green'>.</span><span style='background:green'>.</span> <span style='background:brown'> </span><span style='background:brown'> </span><span style='background:brown'> </span><span style='background:brown'> </span> <span style='background:brown'> </span><span style='background:brown'> </span><span style='background:brown'> </span><span style='background:brown'> </span> <span style='background:brown'> </span><span style='background:brown'> </span><span style='background:brown'> </span><span style='background:brown'> </span> <span style='background:brown'> </span><span style='background:brown'> </span><span style='background:brown'> </span><span style='background:brown'> </span> 0000112013052200106 </pre>
algorithms
def shake_tree(tree): nuts, tree = [0 for _ in tree[0]], [a . replace('\\/', '__') for a in tree] for r, c in [(r, c) for r, row in enumerate(tree) for c, v in enumerate(row) if v == 'o']: for k in range(r, len(tree)): while tree[k][c] == '\\': c += 1 while tree[k][c] == '/': c -= 1 if tree[k][c] == '_': break else: nuts[c] += 1 return nuts
Nut Farm 2
59b24a2158ef58966e00005e
[ "Algorithms" ]
https://www.codewars.com/kata/59b24a2158ef58966e00005e
5 kyu
# Overview For a simple watch face we want the current time spelled out in english. Write a function `getTimeText(hour, minute)` (or `get_time_text(cls, h, m)` for Python) that takes the time as two integers and returns the spelled out time as written below. We would like the text to be simple to read, so we will round the current time to the next full 5 minutes (Definitely more convenient for the user than rounding down...). We will use a 12-hour clock (e.g. 13:00 is "one". For this particular clock we will not use "AM" and "PM", just the time (and let the user guess which half of the day it is ;-) ) The time will be passed in a 24-hour format, and may contain `(0, 0)` as well as `(24, 0)`. # Examples | Time | Expected String | | --- | --- | | 00:00 | "midnight" | | 12:01 | "five past noon" | | 01:05 | "five past one" | | 13:06 | "ten past one" | | 16:29 | "half past four" | | 22:34 | "twenty-five to eleven"| | 06:44 | "quarter to seven" | | 07:56 | "eight" | # English time representation As a reminder for all who are not that familiar with english names for the time: During the first 30 minutes of an hour (_m_ < 30), the time is measured from the current hour (_m_ past _h_), afterwards we measure to the next hour (_60-m_ to _h_). 00:00 is called midnight, 12:00 is called noon. Hour names: | Hour | Name | | --- | --- | | 00:00 | midnight | | 01:00 | one | | 02:00 | two | | ... | ... | | 12:00 | noon | | 13:00 | one | | 14:00 | two | | ... | ... | | 24:00 | midnight | Minute names: | Minute | Name | | --- | --- | | xx:00 | - | | xx:05 | five | | xx:10 | ten | | xx:15 | *quarter* | | xx:20 | twenty | | xx:25 | twenty-five | | xx:30 | *half* |
reference
class WorldClock (object): SPEAKER_H = ['midnight', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'noon'] JOINER = [" past ", " to "] SPEAKER_M = {0: '', 5: "five", 10: "ten", 15: 'quarter', 20: 'twenty', 25: 'twenty-five', 30: 'half'} @ classmethod def get_time_text(cls, h, m): x, y = divmod(m, 5) m = (x + bool(y)) * 5 # Round to the five minutes upper isTo = m > 30 # Differentiate past/to ("half" is "past") if isTo: m = 60 - m # Retro-reading of the minute h += 1 # increase hour by one # Reduce the hour to 12, but keeping the special case of noon h %= (12 + (h == 12)) sH = cls . SPEAKER_H[h] sM = cls . SPEAKER_M[m] jn = cls . JOINER[isTo] return jn . join([sM, sH]) if sM else sH
Speaking clock
56d2f73854d686eb1c00062b
[ "Fundamentals", "Dates/Time", "Data Types" ]
https://www.codewars.com/kata/56d2f73854d686eb1c00062b
6 kyu
Consider the range `0` to `10`. The primes in this range are: `2, 3, 5, 7`, and thus the prime pairs are: `(2,2), (2,3), (2,5), (2,7), (3,3), (3,5), (3,7),(5,5), (5,7), (7,7)`. Let's take one pair `(2,7)` as an example and get the product, then sum the digits of the result as follows: `2 * 7 = 14`, and `1 + 4 = 5`. We see that `5` is a prime number. Similarly, for the pair `(7,7)`, we get: `7 * 7 = 49`, and `4 + 9 = 13`, which is a prime number. You will be given a range and your task is to return the number of pairs that revert to prime as shown above. In the range `(0,10)`, there are only `4` prime pairs that end up being primes in a similar way: `(2,7), (3,7), (5,5), (7,7)`. Therefore, `solve(0,10) = 4)` Note that the upperbound of the range will not exceed `10000`. A range of `(0,10)` means that: `0 <= n < 10`. Good luck! If you like this Kata, please try [Simple Prime Streaming](https://www.codewars.com/kata/5a908da30025e995880000e3) [Prime reduction](https://www.codewars.com/kata/59aa6567485a4d03ff0000ca) [Dominant primes](https://www.codewars.com/kata/59ce11ea9f0cbc8a390000ed)
reference
import itertools def solve(a, b): primes = set([2] + [n for n in range(3, b, 2) if all(n % r for r in range(3, int(n * * 0.5) + 1, 2))]) return sum(sum(map(int, str(x * y))) in primes for x, y in itertools . combinations_with_replacement([p for p in primes if a <= p < b], 2))
Prime reversion
59b46276afcda204ed000094
[ "Fundamentals" ]
https://www.codewars.com/kata/59b46276afcda204ed000094
6 kyu
# Task Aliens send messages to our planet, but they use a very strange language. Try to decode the messages!
reference
CODE = dict(zip(['__', '/\\', ']3', '(', '|)', '[-', '/=', '(_,', '|-|', '|', '_T', '/<', '|_', '|\\/|', '|\\|', '()', '|^', '()_', '/?', '_\\~', '~|~', '|_|', '\\/', '\\/\\/', '><', '`/', '~/_'], ' abcdefghijklmnopqrstuvwxyz')) def decode(m): return '' . join(CODE[c] for c in reversed(m . replace(m[0], ' '). split()))
Message from Aliens
598980a41e55117d93000015
[ "Puzzles", "Fundamentals" ]
https://www.codewars.com/kata/598980a41e55117d93000015
6 kyu
### Different lists? Here are two lists. They each represent a sample of observations of some value taken from some larger population of values: ```python g1 = [124, 118, 78, 123, 124, 124] g2 = [127, 125, 125, 125, 172, 125] ``` ```r g1 <- c(124, 118, 78, 123, 124, 124) g2 <- c(127, 125, 125, 125, 172, 125) ``` Did these come from the same population? It's hard to say. We don't know what they are. Maybe the number of people enrolled in an introductory statistics class? Maybe systolic blood pressure measurements? Maybe my golf scores? ### Some things to notice You'll notice the smallest value in g2 is larger than the biggest in g1, but the variance of each sample is pretty big, so again, it's hard to say. Let's focus on the mean values: the mean of g1 is about `117.17`, for g2 it's `136.5`, and the absolute difference is about `19.33`. ### Don't do it this way We could compute a two-sided t-test on the sample means, but we'd be out on a limb with that one, since, again, we can't say anything about the distribution of the values in the population they come from. Lets do that (**DON'T DO THAT**): assuming equal variances (they're about equal), we get a p-value of `0.1265`. So they look a little different, but really not that different, and not different enough to satisfy the good folks at Guinness in 1908. ### Do it this way Lets try this: if they are from the same population, i.e., _if the measurement is independent of the group assignment_, then we can assign measurement values to whichever group we'd like. It's like probability with counting. We can partition the 12 measurements above, 6 in group g1 and 6 in g2, in all the different ways possible, and then _count how many times the sample statistic (absolute difference between sample means) is equal or greater than the sample statistic (absolute difference between sample means) in observation we were given to begin with_. This is what is known as a [permutation test](https://en.wikipedia.org/wiki/Resampling_%28statistics%29#Permutation_tests). Do that. Make it exact. # Task: Write a function, `exact_p(g1, g2)` that takes two samples g1 and g2, and computes a p-value for the difference in sample means using a permutation test. #### Some things to remember: 1. Given all possible partitions of the data into equal size groups, `p` is the proportion of those partitions with an ABSOLUTE difference in sample means EQUAL or GREATER than the original partition. 2. As implied by item 1, `0 < p < 1` 3. As with the example, samples g1 and g2 will always have the same length, have non-overlapping ranges, and you can assume equal variances. 4. Your function will be tested with samples of length 2 to 9 (no empty lists, no lists of length 1) 5. Results are rounded to 4 decimal places when tested, so I suppose you have a chance with a Monte Carlo approach. # Examples ```python exact_p([124, 118, 78, 123, 124, 124], [127, 125, 125, 125, 172, 125]) => 0.0021645021645021645 exact_p([12705, 12264, 12003, 12536], [13524, 13478, 12845, 13351]) => 0.02857142857142857 ``` ```r exact_p(c(124, 118, 78, 123, 124, 124), c(127, 125, 125, 125, 172, 125)) [1] 0.002164502 exact_p(c(12705, 12264, 12003, 12536), c(13524, 13478, 12845, 13351)) [1] 0.02857143 ``` Note: rounding the result may result in some random tests expecting a value of 0. That doesn't mean it expects your p value to be 0, it just expects it to be less than 0.00005. The p value of an exact permutation test can never be 0. Understanding that will help you solve this kata! If you want to try finding an exact p for two groups with overlapping ranges, try this one [Exact p](https://www.codewars.com/kata/59baf6676a9b6053950007b1)
reference
from math import factorial def exact_p(g1, g2): l = len(g1) full = l * 2 """ g, total = g1 + g2, sum(g1) + sum(g2) combos = [combo for combo in combinations(g, l)] # brute force - timeout baseStat = abs(sum(g1) / l - sum(g2) / l) testStat = [abs(sum(combo) / l - (total - sum(combo)) / l) for combo in combos] return sum(ts >= baseStat for ts in testStat) / len(combos) # brute force plus simplification - still timeout baseStat = abs(sum(g1) - sum(g2)) return sum(abs(sum(combo) * 2 - total) >= baseStat for combo in combos)\ / len(combos) # if g1 < g2, then only those combos with sum <= g1 or >= g2 are relevant # for combo with sum <= g1, the other half must be a combo with sum >= g2 # hence answer = 2 * (number of combos with sum <= g1). # with non-overlapping ranges, answer = 2 """ totalCombos = factorial(full) / factorial(l) * * 2 return 2 / totalCombos
Minimum exact p
59b8a1bc4f98a8f844000087
[ "Mathematics", "Statistics", "Fundamentals", "Permutations", "Probability" ]
https://www.codewars.com/kata/59b8a1bc4f98a8f844000087
6 kyu
# Connect Four Take a look at wiki description of Connect Four game: [Wiki Connect Four](https://en.wikipedia.org/wiki/Connect_Four) The grid is 6 row by 7 columns, those being named from A to G. You will receive a list of strings showing the order of the pieces which dropped in columns: ```cpp std::vector<std::string> pieces_position_list { "A_Red", "B_Yellow", "A_Red", "B_Yellow", "A_Red", "B_Yellow", "G_Red", "B_Yellow" } ``` ```csharp List<string> myList = new List<string>() { "A_Red", "B_Yellow", "A_Red", "B_Yellow", "A_Red", "B_Yellow", "G_Red", "B_Yellow" }; ``` ```java List<String> myList = new ArrayList<String>(Arrays.asList( "A_Red", "B_Yellow", "A_Red", "B_Yellow", "A_Red", "B_Yellow", "G_Red", "B_Yellow" )); ``` ```javascript piecesPositionList = ["A_Red", "B_Yellow", "A_Red", "B_Yellow", "A_Red", "B_Yellow", "G_Red", "B_Yellow"] ``` ```ruby pieces_position_list = ["A_Red", "B_Yellow", "A_Red", "B_Yellow", "A_Red", "B_Yellow", "G_Red", "B_Yellow"] ``` ```python pieces_position_list = ["A_Red", "B_Yellow", "A_Red", "B_Yellow", "A_Red", "B_Yellow", "G_Red", "B_Yellow"] ``` ```php $piecesPositionList = ["A_Red", "B_Yellow", "A_Red", "B_Yellow", "A_Red", "B_Yellow", "G_Red", "B_Yellow"]; ``` The list may contain up to 42 moves and shows the order the players are playing. The first player who connects four items of the same color is the winner. You should return "Yellow", "Red" or "Draw" accordingly.
reference
COLUMNS, ROWS = 'ABCDEFG', range(6) LINES = [{(COLUMNS[i + k], ROWS[j]) for k in range(4)} for i in range(len(COLUMNS) - 3) for j in range(len(ROWS))] \ + [{(COLUMNS[i], ROWS[j + k]) for k in range(4)} for i in range(len(COLUMNS)) for j in range(len(ROWS) - 3)] \ + [{(COLUMNS[i + k], ROWS[j + k]) for k in range(4)} for i in range(len(COLUMNS) - 3) for j in range(len(ROWS) - 3)] \ + [{(COLUMNS[i + k], ROWS[j - k]) for k in range(4)} for i in range(len(COLUMNS) - 3) for j in range(3, len(ROWS))] def who_is_winner(pieces_positions): players = {} board = dict . fromkeys(COLUMNS, 0) for position in pieces_positions: column, player = position . split('_') pos = (column, board[column]) board[column] += 1 players . setdefault(player, set()). add(pos) if any(line <= players[player] for line in LINES): return player return "Draw"
Connect Four
56882731514ec3ec3d000009
[ "Fundamentals" ]
https://www.codewars.com/kata/56882731514ec3ec3d000009
4 kyu
There are several difficulty of sudoku games, we can estimate the difficulty of a sudoku game based on how many cells are given of the 81 cells of the game. - Easy sudoku generally have over 32 givens - Medium sudoku have around 30–32 givens - Hard sudoku have around 28–30 givens - Very Hard sudoku have less than 28 givens Note: The minimum of givens required to create a unique (with no multiple solutions) sudoku game is 17. A hard sudoku game means that at start no cell will have a single candidates and thus require guessing and trial and error. A very hard will have several layers of multiple candidates for any empty cell. # Task: Write a function that solves sudoku puzzles of any difficulty. The function will take a sudoku grid and it should return a 9x9 array with the proper answer for the puzzle. Or it should raise an error in cases of: invalid grid (not 9x9, cell with values not in the range 1~9); multiple solutions for the same puzzle or the puzzle is unsolvable ```if:java ___Java users:___ throw an `IllegalArgumentException` for unsolvable or invalid puzzles or when a puzzle has mutliple solutions. ``` ```if:python ___Python users:___ python 2 has been disabled. ```
games
from copy import deepcopy import itertools as it import numpy as np class SudokuError (Exception): pass class Sudoku (object): def __init__(self, board): self . board = board @ classmethod def from_square(cls, board): for cell in it . chain(* board): if not isinstance(cell, int): raise SudokuError('Puzzle contain non digit charcters') cube = [[set(range(1, 10)) if cell == 0 else set([cell]) for cell in row] for row in board] return cls(cube) def rank(self): """ A completely solved board is of rank 0""" return sum(map(len, it . chain(* self . board))) - 9 * 9 @ property def is_solved(self): return self . rank() == 0 def guess(self): min_cell, min_row, min_col = set(range(1, 10)), 0, 0 for i, row in enumerate(self . board): for j, cell in enumerate(row): if len(min_cell) > len(cell) >= 2: min_cell, min_row, min_col = cell, i, j for option in min_cell: new_board = deepcopy(self . board) new_board[min_row][min_col]. clear() new_board[min_row][min_col]. add(option) new_sudoku = Sudoku(new_board) yield new_sudoku def square(self): """ Return the sudoko as readable 2D list of integers: """ return [[list(cell). pop() if len(cell) == 1 else 0 for cell in row] for row in self . board] def reduce_possibilities(self): """ Given a sudoko solution reduce the number of possiblities per cell""" while True: before = self . rank() # Rows: for row in self . board: self . reduce_row(row) # Coloumns: for row in zip(* self . board): self . reduce_row(row) # Boxes: boxes_to_rows = [] for i, j in it . product([0, 1, 2], [0, 1, 2]): boxes_to_rows . append([cell for row in self . board[3 * i: 3 * i + 3] for cell in row[3 * j: 3 * j + 3]]) for row in boxes_to_rows: self . reduce_row(row) # Break test after = self . rank() if before == after: break def reduce_row(self, row): """ Minimize number of options for each cell for every row """ # len 1 sets are known, longer sets are unknown: known = [cell . copy(). pop() for cell in row if len(cell) == 1] known_set = set(known) if len(known_set) != len(known): raise SudokuError("Repeating Value") unknown = [cell for cell in row if len(cell) > 1] uknown_set = set(range(1, 10)). difference(known_set) # All known options are remove from the unknown sets: for cell in unknown: cell . difference_update(known_set) if not cell: raise SudokuError("Cell without possibilities") # Some more immidate deductions for speedup: for k in [1, 2]: for nums in it . combinations(uknown_set, k): option_counter = 0 aditional_options = False cell_ref = [] for cell in unknown: if set(nums). issubset(cell): option_counter += 1 cell_ref . append(cell) elif set(nums). intersection(cell): aditional_options = True if option_counter == k and not aditional_options: for cell in cell_ref: cell . clear() cell . update(nums) def solve(sudoku): # breakout if sudoko is unsolvable: try: sudoku . reduce_possibilities() except SudokuError: return # or complete solution have been found: if sudoku . is_solved: return sudoku # Recurse over following options: solution = None for next_guess in sudoku . guess(): result = solve(next_guess) if result: if solution: raise SudokuError("More than one solution") else: solution = result return solution def sudoku_solver(puzzle): sudoku = Sudoku . from_square(puzzle) solution = solve(sudoku) if solution is None: raise SudokuError("No valid solution is possible") else: return solution . square()
Hard Sudoku Solver
5588bd9f28dbb06f43000085
[ "Games", "Algorithms", "Game Solvers", "Puzzles" ]
https://www.codewars.com/kata/5588bd9f28dbb06f43000085
2 kyu