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 dimens...
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...
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 -> int...
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)...
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(...
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 ...
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 ...
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: ``` ...
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 ...
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 inte...
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 followi...
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 ....
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 ...
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 ...
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` - mos...
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 k...
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%` f...
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,...
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. Exampl...
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 ...
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 '{([])}'...
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). *...
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-banna...
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...
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 undesira...
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...
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...
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']) ...
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...
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] =...
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 ret...
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...
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"}...
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) === ...
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'...
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='...
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 cont...
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</...
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 ar...
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 ...
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(...
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 out...
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: ...
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...
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_f...
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...
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: ``` █████████ ███████████ ███████████████ ███████████████ █████████████████ █████...
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 (cu...
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 i...
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 |__|__|__|...
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 ...
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 di...
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 = i...
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 Factorizat...
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(n...
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...
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])). spli...
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, her...
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 li...
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 ...
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...
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 ...
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") "s...
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...
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: ``` ...
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-hea...
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"> ....+ ........| ............| ...
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...
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 ...
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 substrin...
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...
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 () fi...
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 s...
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: (Inp...
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 overl...
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 o...
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 i...
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 t...
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....
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 `perimete...
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...
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 `i...
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 ...
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 . HEX2TEX...
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 mat...
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 --------- |...|...| |...|...| |...|...| |---+---| |...|...| |...|...| |...|...| -----...
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 t...
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 ...
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' '!#$%&()*+,./:;<=>?@[]...
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, ...
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...
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", "nowa...
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. `cryptogra...
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] ...
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 sa...
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 met...
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(...
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') ==>...
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.p...
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> ....
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`. I...
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 th...
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 ...
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 ...
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...
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 a...
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] == '/': ...
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 rou...
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...
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`. W...
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] ...
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...
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 com...
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::st...
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...
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 g...
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...
Hard Sudoku Solver
5588bd9f28dbb06f43000085
[ "Games", "Algorithms", "Game Solvers", "Puzzles" ]
https://www.codewars.com/kata/5588bd9f28dbb06f43000085
2 kyu