description
stringlengths
38
154k
category
stringclasses
5 values
solutions
stringlengths
13
289k
name
stringlengths
3
179
id
stringlengths
24
24
tags
listlengths
0
13
url
stringlengths
54
54
rank_name
stringclasses
8 values
This kata is about singly-[linked lists](http://en.wikipedia.org/wiki/Linked_list). A linked list is an ordered set of data elements, each containing a link to its successor (and sometimes its predecessor, known as a double linked list). You are you to implement an algorithm to find the kth to last element. `k` will ...
algorithms
# pass in the linked list # to access the head of the linked list # linked_list.head def search_k_from_end(linked_list, k): head = linked_list . head vals = [] while head: vals . append(head . data) head = head . next return vals[- k] if k <= len(vals) else None
Node Mania
5567e7d0adb11174c50000a7
[ "Linked Lists", "Algorithms", "Data Structures" ]
https://www.codewars.com/kata/5567e7d0adb11174c50000a7
6 kyu
Calculate the number of items in a vector that appear at the same index in each vector, with the same value. ```clojure (vector-affinity [1 2 3 4 5] [1 2 2 4 3]) ; => 0.6 (vector-affinity [1 2 3] [1 2 3]) ; => 1.0 ``` ```python vector_affinity([1, 2, 3, 4, 5], [1, 2, 2, 4, 3]) # => 0.6 vector_affinity([1, 2...
algorithms
def vector_affinity(a, b): longer = len(a) if len(a) > len(b) else len(b) return len([i for i, j in zip(a, b) if i == j]) / float(longer) if longer > 0 else 1.0
Vector Affinity
5498505a43e0fd83620010a9
[ "Data Structures", "Algorithms" ]
https://www.codewars.com/kata/5498505a43e0fd83620010a9
6 kyu
We define the score of permutations of combinations, of an integer number (the function to obtain this value:```sc_perm_comb```) as the total sum of all the numbers obtained from the permutations of all the possible combinations of its digits. For example we have the number 348. ```python sc_perm_comb(348) = 3 + 4 + 8 ...
reference
from itertools import permutations def sc_perm_comb(num): sNum = str(num) return sum({int('' . join(p)) for d in range(1, len(sNum) + 1) for p in permutations(sNum, d)})
Score From Permutations Of Combinations of an Integer
5676ffaa8da527f234000025
[ "Fundamentals", "Mathematics", "Permutations" ]
https://www.codewars.com/kata/5676ffaa8da527f234000025
6 kyu
A vector operation takes two or more vectors, applies an operation to each set of elements, and returns a vector of the results. For example, if `x = [1, 2]` and `y = [6, 4]`, then `x + y = [1 + 6, 2 + 4]`, or `[7, 6]`. Your task has two parts. In Part 1, you'll define a higher order funciton, `vector_op`, that can ex...
reference
from functools import partial, reduce from operator import eq, mul def vector_op(f, * vs): return list(map(f, zip(* vs))) iter_mult = partial(reduce, mul) iter_eq = partial(reduce, eq)
Vector Operations and Functionals
59a8dc83ba7b60426b000059
[ "Mathematics", "Linear Algebra", "Fundamentals" ]
https://www.codewars.com/kata/59a8dc83ba7b60426b000059
6 kyu
Hi! Welcome to my first kata. In this kata the task is to take a list of integers (positive and negative) and split them according to a simple rule; those ints greater than or equal to the key, and those ints less than the key (the itself key will always be positive). However, in this kata the goal is to sort the num...
reference
from itertools import groupby def group_ints(lst, key=0): return [list(g) for _, g in groupby(lst, lambda a: a < key)] # PEP8: function name should use snake_case groupInts = group_ints
Sorting Integers into a nested list
583fe48ca20cfc3a230009a1
[ "Fundamentals", "Algorithms", "Sorting" ]
https://www.codewars.com/kata/583fe48ca20cfc3a230009a1
6 kyu
The purpose of this kata is to write a program that can do some algebra. Write a function `expand` that takes in an expression with a single, one character variable, and expands it. The expression is in the form `(ax+b)^n` where `a` and `b` are integers which may be positive or negative, `x` is any single character va...
algorithms
import re P = re . compile(r'\((-?\d*)(\w)\+?(-?\d+)\)\^(\d+)') def expand(expr): a, v, b, e = P . findall(expr)[0] if e == '0': return '1' o = [int(a != '-' and a or a and '-1' or '1'), int(b)] e, p = int(e), o[:] for _ in range(e - 1): p . append(0) p = [o[0] * co...
Binomial Expansion
540d0fdd3b6532e5c3000b5b
[ "Mathematics", "Algebra", "Algorithms" ]
https://www.codewars.com/kata/540d0fdd3b6532e5c3000b5b
3 kyu
Normally, we decompose a number into binary digits by assigning it with powers of 2, with a coefficient of `0` or `1` for each term: `25 = 1*16 + 1*8 + 0*4 + 0*2 + 1*1` The choice of `0` and `1` is... not very binary. We shall perform the *true* binary expansion by expanding with powers of 2, but with a coefficient o...
algorithms
def true_binary(n): return [- 1 if x == '0' else 1 for x in bin(n)[1: - 1]]
The Binary Binary Expansion
59a818191c55c44f3900053f
[ "Algorithms" ]
https://www.codewars.com/kata/59a818191c55c44f3900053f
5 kyu
<img src="https://static1.squarespace.com/static/56a1a14b05caa7ee9f26f47d/t/5719c5d91d07c0bcdda31d01/1464935309584/ant_bridge_TS.jpg"/> # Background My pet bridge-maker ants are marching across a terrain from left to right. If they encounter a gap, the first one stops and then next one climbs over him, then the next...
algorithms
def ant_bridge(ants, terrain): n_ants = len(ants) terrain = terrain . replace('-.', '..') terrain = terrain . replace('.-', '..') count = terrain . count('.') % n_ants return ants[- count:] + ants[: - count]
Ant Bridge
599385ae6ca73b71b8000038
[ "Algorithms" ]
https://www.codewars.com/kata/599385ae6ca73b71b8000038
5 kyu
# The President's phone is broken He is not very happy. The only letters still working are uppercase ```E```, ```F```, ```I```, ```R```, ```U```, ```Y```. An angry tweet is sent to the department responsible for presidential phone maintenance. # Kata Task Decipher the tweet by looking for words with known meaning...
algorithms
def fire_and_fury(tweet): if not all(c in 'EFIRUY' for c in tweet): return 'Fake tweet.' s = [0] for i in range(0, len(tweet) - 3): if tweet[i: i + 4] == 'FIRE': if s[- 1] > 0: s[- 1] += 1 else: s . append(1) elif tweet[i: i + 4] == 'FURY': if s[- 1] < ...
FIRE and FURY
59922ce23bfe2c10d7000057
[ "Regular Expressions", "Strings", "Algorithms" ]
https://www.codewars.com/kata/59922ce23bfe2c10d7000057
6 kyu
Calculate how many times a number can be divided by a given number. ### Example For example the number `6` can be divided by `2` two times: ```py 1. 6 / 2 = 3 2. 3 / 2 = 1 remainder = 1 ``` `100` can be divided by `2` six times: ```py 1. 100 / 2 = 50 2. 50 / 2 = 25 3. 25 / 2 = 12 remainder 1 4. 12 / 2 = 6 5. 6 / 2 =...
algorithms
from math import log def divisions(n, divisor): return int(log(n, divisor))
Number of Divisions
5913152be0b295cf99000001
[ "Algorithms" ]
https://www.codewars.com/kata/5913152be0b295cf99000001
7 kyu
A simple kata, my first. simply tranform an array into a string, like so: ```javascript transform([4, -56, true, "box"]) => "4-56truebox" ``` ```haskell transform [ 5, 7, 8, 9, 0, 5 ] -> "578905" ``` have fun coding!
reference
def transform(s): return '' . join(map(str, s))
transform an array into a string
59a602dc57019008d900004e
[ "Fundamentals" ]
https://www.codewars.com/kata/59a602dc57019008d900004e
null
Write a program that will take a string of digits and give you all the possible consecutive slices of length `n` in that string. Raise an error if `n` is larger than the length of the string. ## Examples For example, the string `"01234"` has the following 2-digit slices: ``` [0, 1], [1, 2], [2, 3], [3, 4] ``` The...
algorithms
def series_slices(digits, n): if n > len(digits): raise ValueError else: return [[int(digit) for digit in digits[i: i + n]] for i in range(0, len(digits) - n + 1)]
Slices of a Series of Digits
53f9a36864b19d8be7000609
[ "Algorithms", "Data Structures" ]
https://www.codewars.com/kata/53f9a36864b19d8be7000609
6 kyu
In most languages, division immediately produces decimal values, and therefore, adding two fractions gives a decimal result: ```ruby (1/2) + (1/4) #=> 0.75 ``` But what if we want to be able to add fractions and get a fractional result? ```ruby (1/2) + (1/4) #=> 3/4 ``` #### Task: Your job here is to implement a fun...
reference
from fractions import Fraction def add_fracs(* args): return str(sum(Fraction(a) for a in args)) if args else ''
Adding Fractions
5816f2580e80c5e075000a4f
[ "Fundamentals" ]
https://www.codewars.com/kata/5816f2580e80c5e075000a4f
6 kyu
Your task is to build a model<sup>1</sup> which can predict y-coordinate.<br> You can pass tests if predicted y-coordinates are inside error margin.<br><br> You will receive train set which should be used to build a model. <br> After you build a model tests will call function ```predict``` and pass x to it. <br><br> ...
algorithms
from functools import reduce class Datamining: def __init__(self, train_set): self . p = train_set[: 5] def lagrange_interp(self, x): return sum(reduce(lambda p, n: p * n, [(x - xi) / (xj - xi) for (i, (xi, yi)) in enumerate(self . p) if j != i], yj) for (j, (xj, yj)) in enumerate(self . p)...
Data mining #2
591748b3f014a2593d0000d9
[ "Mathematics", "Machine Learning", "Algorithms", "Data Science" ]
https://www.codewars.com/kata/591748b3f014a2593d0000d9
4 kyu
Math hasn't always been your best subject, and these programming symbols always trip you up! I mean, does `**` mean _"Times, Times"_ or _"To the power of"_? Luckily, you can create the function to write out the expressions for you! The operators you'll need to use are: ``` "+" --> "Plus" "-" --> "Minus" "*" -...
reference
NUMBERS = 'Zero One Two Three Four Five Six Seven Eight Nine Ten' . split() def expression_out(exp): x, op, y = exp . split() x, y = NUMBERS[int(x)], NUMBERS[int(y)] op = OPERATORS . get(op, "That's not an operator!") return '%s %s%s' % (x, op, y) if op[- 1] != '!' else op
Write out expression!
57e2afb6e108c01da000026e
[ "Fundamentals" ]
https://www.codewars.com/kata/57e2afb6e108c01da000026e
7 kyu
Your task is to build a model<sup>1</sup> which can predict y-coordinate.<br> You can pass tests if predicted y-coordinates are inside error margin.<br><br> You will receive train set which should be used to build a model. <br> After you build a model tests will call function ```predict``` and pass x to it. <br><br> ...
algorithms
from statistics import variance, mean class Datamining: def __init__(self, train_set): # This is a simple linear regression model. # Notice we're computing the covariance but from Python 3.10 # the statistics module includes a function for that. avg_x = mean(x for x, _ in train...
Data mining #1
58f89357d13bab79dc000208
[ "Mathematics", "Machine Learning", "Algorithms", "Data Science" ]
https://www.codewars.com/kata/58f89357d13bab79dc000208
5 kyu
## Background A simple statistical analysis of a series of samples can be done with a [Five Figure Summary](http://en.wikipedia.org/wiki/Five-number_summary). The five figure summary gives the lower extreme, upper extreme, lower quartile, median, and upper quartile, all derived from the supplied sample data. Confusi...
algorithms
class StatisticalSummary (object): def __init__(self, seq): self . seq = list(seq) for i in reversed(range(len(self . seq))): if not isinstance(self . seq[i], (int, float, complex)) or isinstance(self . seq[i], bool): self . seq . pop(i) # Discard every value that is not a number self . s...
Intro to Statistics - Part 1: A Five figure summary
555c7fa8d8cb57834a000028
[ "Statistics", "Algorithms", "Data Science" ]
https://www.codewars.com/kata/555c7fa8d8cb57834a000028
5 kyu
The objective of this Kata is to write a function that creates a dictionary of factors for a range of numbers. The key for each list in the dictionary should be the number. The list associated with each key should possess the factors for the number. If a number possesses no factors (only 1 and the number itself), the...
reference
def factorsRange(n, m): res = {} for num in range(n, m + 1): factors = [] for div in range(2, num / / 2 + 1): if num % div == 0: factors . append(div) if len(factors) == 0: factors = ['None'] res[num] = factors return res
Dictionary of Factors
58bf3cd9c4492d942a0000de
[ "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/58bf3cd9c4492d942a0000de
6 kyu
Mr. Khalkhoul, an amazing teacher, likes to answer questions sent by his students via e-mail, but he often doesn't have the time to answer all of them. In this kata you will help him by making a program that finds some of the answers. You are given a `question` which is a string containing the question and some `infor...
algorithms
def answer(question, information): score, info = max((sum(word in info . lower(). split( ) for word in question . lower(). split()), info) for info in information) return None if not score else info
Answer the students' questions!
59476f9d7325addc860000b9
[ "Algorithms" ]
https://www.codewars.com/kata/59476f9d7325addc860000b9
6 kyu
In this kata your mission is to rotate matrix counter - clockwise N-times. So, you will have 2 inputs: 1)matrix 2)a number, how many times to turn it And an output is turned matrix. Example: matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, ...
algorithms
import numpy as np def rotate_against_clockwise(matrix, times): return np . rot90(matrix, times). tolist()
Rotate matrix counter - clockwise N - times!
5919f3bf6589022915000023
[ "Algorithms", "Matrix" ]
https://www.codewars.com/kata/5919f3bf6589022915000023
6 kyu
You're given a string of dominos. For each slot, there are 3 options: * "|" represents a standing domino * "/" represents a knocked over domino * " " represents a space where there is no domino For example: ``` "||| ||||//| |/" ``` Tipping a domino will cause the next domino to its right to fall over as wel...
reference
def domino_reaction(s): return s . replace("|", "/", min(len(s . split(" ")[0]), len(s . split("/")[0])))
Domino Reaction
584cfac5bd160694640000ae
[ "Fundamentals" ]
https://www.codewars.com/kata/584cfac5bd160694640000ae
6 kyu
Write a function which receives 4 digits and returns the latest time of day that can be built with those digits. The time should be in `HH:MM` format. Examples: ``` digits: 1, 9, 8, 3 => result: "19:38" digits: 9, 1, 2, 5 => result: "21:59" (19:25 is also a valid time, but 21:59 is later) ``` ### Notes - Result sho...
games
def late_clock(* a): for h in range(23, - 1, - 1): for m in range(59, - 1, - 1): x = f' { h :0 2 } ' y = f' { m :0 2 } ' s = list(map(int, list(x + y))) if sorted(s) == sorted(a): return f' { x } : { y } '
The latest clock
58925dcb71f43f30cd00005f
[ "Date Time", "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/58925dcb71f43f30cd00005f
6 kyu
Write a function that solves an algebraic expression given as a string. * The expression can include only sums and products. * The numbers in the expression are in standard notation (NOT scientific). * In contrast, the function should return a string with the calculated value given in scientific notation with 5 de...
reference
def sum_prod(strexpression): return "%.5e" % (eval(strexpression))
Algebraic string
5759513c94aba6a30900094d
[ "Fundamentals", "Strings", "Parsing" ]
https://www.codewars.com/kata/5759513c94aba6a30900094d
6 kyu
# Task For a given non-empty list of sets `l` return a dictionary where 1. keys are the unique elements across all sets 2. the value is a number of sets in which the key appears. The sets are empty or contains only integers. Don't modify the input list and sets ## Example: ```python # Input: [{1,2,3}, {2,3,4}] # ...
games
def short(l): return __import__( "collections"). Counter(e for m in l for e in m)
Keep it short (with restrictions)
5851aae410200111f70006c0
[ "Puzzles", "Restricted" ]
https://www.codewars.com/kata/5851aae410200111f70006c0
5 kyu
We have an array with string digits that occurrs more than once, for example, ```arr = ['1', '2', '2', '2', '3', '3']```. How many different string numbers can be generated taking the 6 elements at a time? We present the list of them below in an unsorted way: ``` ['223213', '312322', '223312', '222133', '312223', '22...
reference
from operator import mul from math import factorial from functools import reduce from collections import Counter def proc_arr(arr): s = '' . join(sorted(arr)) return [factorial(len(arr)) / / reduce(mul, map(factorial, Counter(arr). values())), int(s), int(s[:: - 1])]
Generating Numbers From Digits #1
584d05422609c8890f0000be
[ "Fundamentals", "Data Structures", "Algorithms", "Mathematics", "Logic", "Strings" ]
https://www.codewars.com/kata/584d05422609c8890f0000be
6 kyu
In this kata, you've to count lowercase letters in a given string and return the letter count in a hash with 'letter' as key and count as 'value'. The key must be 'symbol' instead of string in Ruby and 'char' instead of string in Crystal. Example: ```javascript letter_count('arithmetics') //=> {"a": 1, "c": 1, "e": ...
reference
from collections import Counter def letter_count(s): return Counter(s)
Count letters in string
5808ff71c7cfa1c6aa00006d
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5808ff71c7cfa1c6aa00006d
6 kyu
Let's just place tokens on a connect four board. <img src="http://tinyurl.com/js6vz2v" alt="Connect Four Example" style="width: 250px;"/> ** INPUT ** Provided as input the list of columns where a token is placed, from 0 to 6 included. The first player starting is the yellow one (marked with `Y`), then the red (marke...
reference
def connect_four_place(columns): player, board, placed = 1, [['-'] * 7 for _ in range(6)], [- 1] * 7 for c in columns: player ^= 1 board[placed[c]][c] = "YR" [player] placed[c] -= 1 return board
Connect Four - placing tokens
5864f90473bd9c4b47000057
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5864f90473bd9c4b47000057
6 kyu
For all x in the range of integers [0, 2 ** n), let y[x] be the binary exclusive-or of x and x // 2. Find the sum of all numbers in y. Write a function sum_them that, given n, will return the value of the above sum. This can be implemented a simple loop as shown in the initial code. But once n starts getting to highe...
games
def sum_them(n): return 2 * * (n - 1) * (2 * * n - 1)
Summing Large Amounts of Numbers
549c7ae26d86c7c3ed000b87
[ "Binary", "Puzzles" ]
https://www.codewars.com/kata/549c7ae26d86c7c3ed000b87
6 kyu
This kata aims to show the vulnerabilities of hashing functions for short messages. When provided with a SHA-256 hash, return the value that was hashed. You are also given the characters that make the expected value, but in alphabetical order. The returned value is less than 10 characters long. Return `nil` for Ruby ...
games
from hashlib import sha256 from itertools import permutations def sha256_cracker(hash, chars): for p in permutations(chars, len(chars)): current = '' . join(p) if sha256(current . encode('utf-8')). hexdigest() == hash: return current
SHA-256 Cracker
587f0abdd8730aafd4000035
[ "Security", "Algorithms", "Puzzles" ]
https://www.codewars.com/kata/587f0abdd8730aafd4000035
6 kyu
Your task is to ___find the next higher number (int) with same '1'- Bits___. I.e. as much `1` bits as before and output next higher than input. Input is always an int in between 1 and 1<<30 (inclusive). No bad cases or special tricks... ### Some easy examples: ``` Input: 129 => Output: 130 (10000001 => 10000010) I...
algorithms
def next_higher(value): s = f'0 { value : b } ' i = s . rfind('01') s = s[: i] + '10' + '' . join(sorted(s[i + 2:])) return int(s, 2)
Basics 08: Find next higher number with same Bits (1's)
56bdd0aec5dc03d7780010a5
[ "Fundamentals", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/56bdd0aec5dc03d7780010a5
6 kyu
# Story Old MacDingle had a farm... ...and on that farm he had * horses * chickens * rabbits * some apple trees * a vegetable patch Everything is idylic in the MacDingle farmyard **unless somebody leaves the gates open** Depending which gate was left open then... * horses might run away * horses might eat the...
algorithms
from itertools import groupby def shut_the_gate(farm): who_eats_whom = {'H': ['A', 'V'], 'R': ['V'], 'C': []} runaway_back, runaway_front, farm = [], [], [ "" . join(j) for k, j in groupby(farm)] def doSomeFarm(i=0): def do(j, s=False): while (j >= 0 if s else j < len(farm)) and...
The Hunger Games - Shut the gate
59218bf66034acb9b7000040
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/59218bf66034acb9b7000040
5 kyu
Tolkein's publisher wishes to implement an online store for the "Lord of the Rings" and "The Hobbit" books. Each book costs $10. However, if 2 titles are purchased, a 5% discount will be received, i.e. purchasing "Fellowship of the Ring" and "Two Towers" will cost $19. If 3 different titles are purchased, a 10% discoun...
algorithms
from collections import Counter def calculate_cart_total(contents): return sum(p * n for p, (_, n) in zip((10, 9, 8, 5), Counter(contents). most_common()))
Tolkien's Book Cart
59a2666349ae65ea69000051
[ "Algorithms" ]
https://www.codewars.com/kata/59a2666349ae65ea69000051
6 kyu
You wrote a program that can calculate the sum of all the digits of a non-negative integer. However, it's not fast enough. Can you make it faster? --- ### Input size ~~~if:haskell Haskell: - 50 random tests of `n <= 2^64` - 50 random tests of `n <= 2^200000` ~~~ ~~~if:python Python: - 50 random tests of `n <= 2^64...
reference
def digit_sum(n): return sum(map(int, str(n)))
Micro Optimization: Digit Sum
59a2af923203e8220b00008f
[ "Fundamentals" ]
https://www.codewars.com/kata/59a2af923203e8220b00008f
6 kyu
You are given two arrays `arr1` and `arr2`, where `arr2` always contains integers. Write a function such that: For `arr1 = ['a', 'a', 'a', 'a', 'a']`, `arr2 = [2, 4]` the function returns `['a', 'a']` For `arr1 = [0, 1, 5, 2, 1, 8, 9, 1, 5]`, `arr2 = [1, 4, 7]` the function returns `[1, 1, 1]` For `arr1 = [0, 3, 4]...
games
def find_array(arr1, arr2): return [arr1[i] for i in arr2 if i < len(arr1)]
Find array
59a2a3ba5eb5d4e609000055
[ "Puzzles" ]
https://www.codewars.com/kata/59a2a3ba5eb5d4e609000055
7 kyu
Write a function that returns a list of all the integers from `lower` ( inclusive ) to `upper` ( exclusive ) in a such way that no two adjacent numbers in the list are numerically adjacent ( e.g. `5` cannot be next to `4` or `6` ). The maximum sequence length tested is 10<sup>7</sup>. The minimum sequence length teste...
algorithms
def generate_sequence(lower, upper): return list(range(lower + 1, upper, 2)) + list(range(lower, upper, 2))
No adjacent integers sequence generator
59a20f283203e8bd8c000006
[ "Algorithms" ]
https://www.codewars.com/kata/59a20f283203e8bd8c000006
6 kyu
You will be given the number of angles of a shape with equal sides and angles, and you need to return the number of its sides, and the measure of the interior angles. Should the number be equal or less than `2`, return: ``` "this will be a line segment or a dot" ``` Otherwise return the result in the following format...
games
def describe_the_shape(n): return "this will be a line segment or a dot" if n < 3 else \ "This shape has %s sides and each angle measures %s" % (n, (n - 2) * 180 / / n)
Describe the shape
59a1ea8b70e25ef8e3002992
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/59a1ea8b70e25ef8e3002992
7 kyu
The `Stanton` measure of an array is computed as follows: count the number of occurences for value `1` in the array. Let this count be `n`. The `Stanton` measure is the number of times that `n` appears in the array. Write a function which takes an integer array and returns its `Stanton` measure. #### Examples The St...
reference
def stanton_measure(arr): return arr . count(arr . count(1))
Stanton measure
59a1cdde9f922b83ee00003b
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/59a1cdde9f922b83ee00003b
7 kyu
The number `198` has the property that `198 = 11 + 99 + 88, i.e., if each of its digits is concatenated twice and then summed, the result will be the original number`. It turns out that `198` is the only number with this property. However, the property can be generalized so that each digit is concatenated `n` times and...
reference
def check_concatenated_sum(n, r): return abs(n) == sum(int(e * r) for e in str(abs(n)) if r)
Concatenated Sum
59a1ec603203e862bb00004f
[ "Fundamentals" ]
https://www.codewars.com/kata/59a1ec603203e862bb00004f
7 kyu
A happy number is a number defined by the following process: starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this pro...
algorithms
def is_happy(n): seen = set() while n != 1: n = sum(int(d) * * 2 for d in str(n)) if n not in seen: seen . add(n) else: return False return True
Happy numbers
5464cbfb1e0c08e9b3000b3e
[ "Algorithms" ]
https://www.codewars.com/kata/5464cbfb1e0c08e9b3000b3e
6 kyu
An array is defined to be `inertial`if the following conditions hold: ``` a. it contains at least one odd value b. the maximum value in the array is even c. every odd value is greater than every even value that is not the maximum value. ``` eg:- ``` So [11, 4, 20, 9, 2, 8] is inertial because a. it contains at leas...
reference
def is_inertial(arr): mx = max(arr, default=1) miO = min((x for x in arr if x % 2 == 1), default=float("-inf")) miE2 = max((x for x in arr if x % 2 == 0 and x != mx), default=float("-inf")) return mx % 2 == 0 and miE2 < miO
Inertial Array
59a151c53f64cdd94c00008f
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/59a151c53f64cdd94c00008f
7 kyu
You'll be given a string of random characters (numbers, letters, and symbols). To decode this string into the key we're searching for: (1) count the number occurences of each ascii lowercase letter, and (2) return an ordered string, 26 places long, corresponding to the number of occurences for each corresponding le...
reference
from collections import Counter from string import ascii_lowercase def decrypt(test_key): cnt = Counter(test_key) return '' . join(str(cnt[a]) for a in ascii_lowercase)
Simple decrypt algo
58693136b98de0e4910001ab
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/58693136b98de0e4910001ab
6 kyu
This kata builds on [Number Climber](http://www.codewars.com/kata/number-climber). For every positive number N there exists a unique sequence starting at 1 and ending at N, where each number in the sequence is either the double of the previous number or the double plus one. For example, if N = 13, then the sequence is...
reference
def multiply(x, y): s = zero while y: s += y & one and x y >>= one x <<= one return s
Write your own multiplication function
55988922d24a02ccd0000063
[ "Fundamentals" ]
https://www.codewars.com/kata/55988922d24a02ccd0000063
6 kyu
In genetic algorithms, a crossover allows 2 chromosomes to exchange part of their genes. For more details, you can visit these wikipedia links : <a href="https://en.wikipedia.org/wiki/Genetic_algorithm">Genetic algorithm</a> and <a href="https://en.wikipedia.org/wiki/Crossover_(genetic_algorithm)">Crossover</a>. A c...
reference
def crossover(ns, xs, ys): for i in sorted(set(ns)): xs, ys = xs[: i] + ys[i:], ys[: i] + xs[i:] return xs, ys
N-Point Crossover
57339a5226196a7f90001bcf
[ "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/57339a5226196a7f90001bcf
6 kyu
Create an SQLite3 database `/tmp/movies.db` Your database should have a table named `MOVIES` that contains the following data: <table> <thead> <tr> <th>Name</th> <th>Year</th> <th>Rating</th> </tr> </thead> <tbody> <tr> <td>Rise of the Planet of the Apes </td> <td>2011</td> <td>77</td> </tr> <tr> <td>D...
reference
import sqlite3 from contextlib import closing with sqlite3 . connect('/tmp/movies.db') as db: with closing(db . cursor()) as cursor: cursor . execute(''' CREATE TABLE MOVIES(id INTEGER PRIMARY KEY, Name TEXT unique, Year INTEGER, Rating INTEGER) ''') movies = [("Rise of the Planet of t...
I Liked the SQL Better...
53d2c97d7152a59b64001033
[ "SQL", "Databases", "Fundamentals" ]
https://www.codewars.com/kata/53d2c97d7152a59b64001033
6 kyu
Write a ```timer()``` decorator that validates if a function it decorates is executed within *(less than)* a given ```seconds``` interval and returns a boolean ```True``` or ```False``` accordingly. Example: ``` from time import sleep @timer(1) def foo(): sleep(0.1) @timer(1) def bar(): sleep(1.1) >>>...
reference
from time import time from functools import wraps def timer(limit): def dec(func): @ wraps(func) def time_func(* args, * * kwargs): time_start = time() func(* args, * * kwargs) return time() - time_start < limit return time_func return dec
Timer Decorator
56f84d093b164c2e490013cb
[ "Fundamentals", "Design Patterns", "Object-oriented Programming", "Date Time" ]
https://www.codewars.com/kata/56f84d093b164c2e490013cb
6 kyu
Let's look at the following generator: ``` def gen(): for i in range(2): for j in range(3): yield (i, j) ``` If we print all yielded values, we'll get ``` (0, 0) (0, 1) (0, 2) (1, 0) (1, 1) (1, 2) ``` For a given parameter list N you must return an iterator, which goes through all possible tu...
reference
from itertools import product def multiiter(* args): return product(* map(range, args))
Multirange iterator
56bc72f866a2ab1890000be0
[ "Iterators", "Fundamentals" ]
https://www.codewars.com/kata/56bc72f866a2ab1890000be0
6 kyu
How many days are we represented in a foreign country? My colleagues make business trips to a foreign country. We must find the number of days our company is represented in a country. Every day that one or more colleagues are present in the country is a day that the company is represented. A single day cannot count fo...
reference
def days_represented(a): return len({i for x, y in a for i in range(x, y + 1)})
How many days are we represented in a foreign country?
58e93b4706db4d24ee000096
[ "Lists", "Fundamentals" ]
https://www.codewars.com/kata/58e93b4706db4d24ee000096
7 kyu
Part 2/3 of my kata series. [Part 1](http://www.codewars.com/kata/riemann-sums-i-left-side-rule) The description changes little in this second part. Here we simply want to improve our approximation of the integral by using trapezoids instead of rectangles. The left/right side rules have a serious bias and the trapezoi...
reference
def riemann_trapezoidal(f, n, a, b): dx = (b - a) / n return round(sum(f(a + i * dx) + f(a + (i + 1) * dx) for i in range(n)) * dx / 2, 2)
riemann sums II (trapezoidal rule)
5562b6de2f508f1adc000089
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5562b6de2f508f1adc000089
6 kyu
The aim of this kata is to determine the number of sub-function calls made by an unknown function. You have to write a function named `count_calls` which: * takes as parameter a function and its arguments (args, kwargs) * calls the function * returns a tuple containing: * the number of function calls made inside it...
reference
import sys def count_calls(func, * args, * * kwargs): """Count calls in function func""" calls = [- 1] def tracer(frame, event, arg): if event == 'call': calls[0] += 1 return tracer sys . settrace(tracer) rv = func(* args, * * kwargs) return calls[0], rv
Counting inner calls in an unknown function.
53efc28911c36ff01e00012c
[ "Recursion", "Language Features" ]
https://www.codewars.com/kata/53efc28911c36ff01e00012c
4 kyu
In your class, you have started lessons about geometric progression. Since you are also a programmer, you have decided to write a function that will print first `n` elements of the sequence with the given constant `r` and first element `a`. Result should be separated by comma and space. ### Example ```python geometr...
reference
def geometric_sequence_elements(a, r, n): return ", " . join(str(a * r * * i) for i in range(n))
Geometric Progression Sequence
55caef80d691f65cb6000040
[ "Fundamentals" ]
https://www.codewars.com/kata/55caef80d691f65cb6000040
7 kyu
Implement a function `reverse_list` which takes a singly-linked list of nodes and returns a matching list in the reverse order. Assume the presense of a class `Node`, which exposes the property `value`/`Value` and `next`/`Next`. `next` must either be set to the next `Node` in the list, or to `None` (or `null`) to indi...
algorithms
def reverse_list(node): res = None while node: res = Node(node . value, res) node = node . next return res
Reverse a singly-linked list
57262ca48565846f33001365
[ "Algorithms" ]
https://www.codewars.com/kata/57262ca48565846f33001365
6 kyu
The [Linear Congruential Generator (LCG)](https://en.wikipedia.org/wiki/Linear_congruential_generator) is one of the oldest pseudo random number generator functions. The algorithm is as follows: ## X<sub>n+1</sub>=(aX<sub>n</sub> + c) mod m where: * `a`/`A` is the multiplier (we'll be using `2`) * `c`/`C` is the incr...
algorithms
class LCG (object): def __init__(self, x): self . _seed = x def random(self): self . _seed = (2 * self . _seed + 3) % 10 return self . _seed / 10
PRNG: Linear Congruential Generator
594979a364becbc1ab00003a
[ "Algorithms" ]
https://www.codewars.com/kata/594979a364becbc1ab00003a
7 kyu
Write a function name `nextPerfectSquare` / ```next_perfect_square``` that returns the first perfect square that is greater than its integer argument. A `perfect square` is a integer that is equal to some integer squared. For example 16 is a perfect square because `16=4*4`. ``` example n next perfect square 6 9...
reference
def next_perfect_square(n): return n >= 0 and (int(n * * 0.5) + 1) * * 2
nextPerfectSquare
599f403119afacf9f1000051
[ "Fundamentals" ]
https://www.codewars.com/kata/599f403119afacf9f1000051
7 kyu
This is the Performance version of [simple version](http://www.codewars.com/kata/574be65a974b95eaf40008da). If your code runs more than 7000ms, please optimize your code or try the [simple version](http://www.codewars.com/kata/574be65a974b95eaf40008da) ## Task A game I played when I was young: Draw 4 cards from playin...
games
from itertools import permutations import math def equal_to_24(* aceg): ops = '+-*/' OPS = { '+': lambda a, b: a + b, '-': lambda a, b: a - b, '*': lambda a, b: a * b, '/': lambda a, b: a / b if b else math . inf } for b in ops: for d in ops: for...
Fastest Code : Equal to 24
574e890e296e412a0400149c
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/574e890e296e412a0400149c
2 kyu
This kata explores writing an AI for a two player, turn based game called *NIM*. The Board -------------- The board starts out with several piles of straw. Each pile has a random number of straws. ``` Pile 0: |||| Pile 1: || Pile 2: ||||| Pile 3: | Pile 4: |||||| ...or more concisely: [4,2,5,1,6] ``` The Rule...
games
from operator import xor def choose_move(game_state): """Chooses a move to play given a game state""" x = reduce(xor, game_state) for i, amt in enumerate(game_state): if amt ^ x < amt: return (i, amt - (amt ^ x))
NIM the game
54120de842dff35232000195
[ "Mathematics", "Games", "Puzzles" ]
https://www.codewars.com/kata/54120de842dff35232000195
4 kyu
Imagine that you are given two sticks. You want to end up with three sticks of equal length. You are allowed to cut either or both of the sticks to accomplish this, and can throw away leftover pieces. Write a function, maxlen, that takes the lengths of the two sticks (L1 and L2, both positive values), that will return...
reference
def maxlen(s1, s2): sm, lg = sorted((s1, s2)) return min(max(lg / 3, sm), lg / 2)
Three sticks
57c1f22d8fbb9fd88700009b
[ "Fundamentals" ]
https://www.codewars.com/kata/57c1f22d8fbb9fd88700009b
7 kyu
It's important day today: the class has just had a math test. You will be given a list of marks. Complete the function that will: * Calculate the average mark of the whole class and round it to 3 decimal places. * Make a dictionary/hash with keys `"h", "a", "l"` to make clear how many `h`igh, `a`verage and `l`ow marks...
reference
from statistics import mean def test(r): dct = {'l': 0, 'a': 0, 'h': 0} for n in r: dct['lah' [(n > 6) + (n > 8)]] += 1 return [round(mean(r), 3), dct] + ['They did well'] * (sum(dct . values()) == dct['h'])
Test's results
599db0a227ca9f294b0000c8
[ "Fundamentals", "Lists" ]
https://www.codewars.com/kata/599db0a227ca9f294b0000c8
7 kyu
From [Wikipedia](https://en.wikipedia.org/wiki/N-back): "The n-back task is a continuous performance task that is commonly used as an assessment in cognitive neuroscience to measure a part of working memory and working memory capacity. \[...\] The subject is presented with a sequence of stimuli, and the task consists o...
reference
def count_targets(n, sequence): return sum(a == b for a, b in zip(sequence, sequence[n:]))
n-back
599c7f81ca4fa35314000140
[ "Fundamentals" ]
https://www.codewars.com/kata/599c7f81ca4fa35314000140
6 kyu
<img src="https://i.imgur.com/ta6gv1i.png?1" title="source: imgur.com" /> The code provided is supposed return a person's **Full Name** given their ```first``` and ```last``` names. But it's not working properly. # Notes The first and/or last names are never null, but may be empty. # Task Fix the bug so we can al...
bug_fixes
class Dinglemouse (object): def __init__(self, first_name, last_name): self . first_name = first_name self . last_name = last_name def get_full_name(self): return (self . first_name + ' ' + self . last_name). strip()
FIXME: Get Full Name
597c684822bc9388f600010f
[ "Debugging" ]
https://www.codewars.com/kata/597c684822bc9388f600010f
7 kyu
Create a function to determine whether or not two circles are colliding. You will be given the position of both circles in addition to their radii: ```javascript function collision(x1, y1, radius1, x2, y2, radius2) { // collision? } ``` ```c bool IsCollision(float x1, float y1, float r1, float x2, float y2, float r2...
reference
from math import dist def collision(x1, y1, radius1, x2, y2, radius2): return radius1 + radius2 >= dist((x1, y1), (x2, y2))
Collision Detection
599da159a30addffd00000af
[ "Fundamentals" ]
https://www.codewars.com/kata/599da159a30addffd00000af
7 kyu
# Background I drink too much coffee. Eventually it will probably kill me. *Or will it..?* Anyway, there's no way to know. *Or is there...?* # The Discovery of the Formula I proudly announce my discovery of a formula for measuring the life-span of coffee drinkers! For * ```h``` is a health number assigned to ...
games
def coffee_limits(year, month, day): h = int(f' { year :0 4 }{ month :0 2 }{ day :0 2 } ') return [limit(h, 0xcafe), limit(h, 0xdecaf)] def limit(h, c): for i in range(1, 5000): h += c if 'DEAD' in f' { h : X } ': return i return 0
Death by Coffee
57db78d3b43dfab59c001abe
[ "Puzzles" ]
https://www.codewars.com/kata/57db78d3b43dfab59c001abe
6 kyu
# Task You are a spy. You lurk in the enemy's control zone. Your task is to get the length data of a railway, accurate to meters. Although you have taken all kinds of technical measures, you still haven't finished your task. Now, You can only use the last method: Take the train, record the sounds you hear, and then ...
reference
def length_of_railway(sounds): sounds = sounds . replace('呜呜呜', 'a'). replace('哐当', 'b') result = 0 speed = 10 for sound in sounds: if sound == 'a': speed = 20 if speed != 20 else 10 elif sound == 'b': result += speed return result
Happy Coding : a Spy On the Train
599cf86d01a4108584000064
[ "Fundamentals" ]
https://www.codewars.com/kata/599cf86d01a4108584000064
6 kyu
How much bigger is a 16-inch pizza compared to an 8-inch pizza? A more pragmatic question is: How many 8-inch pizzas "fit" in a 16-incher? The answer, as it turns out, is exactly four 8-inch pizzas. For sizes that don't correspond to a round number of 8-inchers, you must <strong>round</strong> the number of <em>slices...
reference
def how_many_pizzas(n): return 'pizzas: {}, slices: {}' . format(* divmod(n * n / / 8, 8))
8 inch pizza equivalence
599bb194b7a047b04d000077
[ "Geometry", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/599bb194b7a047b04d000077
6 kyu
Write a function that takes a string which has integers inside it separated by spaces, and your task is to convert each integer in the string into an integer and return their sum. ### Example ```python summy("1 2 3") ==> 6 ``` ```rust summy("1 2 3") -> 6 ``` ```julia summy("1 2 3") --> 6 ``` Good luck!
algorithms
def summy(string_of_ints): return sum(map(int, string_of_ints . split()))
Summy
599c20626bd8795ce900001d
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/599c20626bd8795ce900001d
7 kyu
Your friend asks you to explain the difference between the python string methods, `isdecimal()`, `isdigit()`, and `isnumeric()`. Create two lists to show the difference. The first list: `digits_not_decimals` should be a list with all the Unicode characters that are digits, but not decimals. The second list: `numer...
reference
from sys import maxunicode as mu digits_not_decimals = [chr(c) for c in range( mu + 1) if chr(c). isdigit() and not chr(c). isdecimal()] numeric_not_digits = [chr(c) for c in range( mu + 1) if chr(c). isnumeric() and not chr(c). isdigit()]
So many kinds of numbers!
599b4e682b862b8498000021
[ "Fundamentals" ]
https://www.codewars.com/kata/599b4e682b862b8498000021
7 kyu
Write a function that, given a string of text (possibly with punctuation and line-breaks), returns an array of the top-3 most occurring words, in descending order of the number of occurrences. Assumptions: ------------ - A word is a string of letters (A to Z) optionally containing one or more apostrophes (`'`) in ASC...
algorithms
from collections import Counter import re def top_3_words(text): c = Counter(re . findall( r"[a-z']+", re . sub(r" '+ ", " ", text . lower()))) return [w for w, _ in c . most_common(3)]
Most frequently used words in a text
51e056fe544cf36c410000fb
[ "Strings", "Filtering", "Algorithms", "Regular Expressions" ]
https://www.codewars.com/kata/51e056fe544cf36c410000fb
4 kyu
An integer partition of `n` is a weakly decreasing list of positive integers which sum to `n`. For example, there are 7 integer partitions of 5: ```python [5], [4,1], [3,2], [3,1,1], [2,2,1], [2,1,1,1], [1,1,1,1,1]. ``` Write a function which returns the number of integer partitions of `n`. The function should be abl...
algorithms
def partitions(n, k=1, cache={}): if k > n: return 0 if n == k: return 1 if (n, k) in cache: return cache[n, k] return cache . setdefault((n, k), partitions(n, k + 1) + partitions(n - k, k))
Number of integer partitions
546d5028ddbcbd4b8d001254
[ "Mathematics", "Algorithms", "Discrete Mathematics" ]
https://www.codewars.com/kata/546d5028ddbcbd4b8d001254
4 kyu
The palindromic number `595` is interesting because it can be written as the sum of consecutive squares: `6^2 + 7^2 + 8^2 + 9^2 + 10^2 + 11^2 + 12^2 = 595`. There are exactly eleven palindromes below one-thousand that can be written as consecutive square sums. Note that `1 = 0^2 + 1^2` has not been included as this pr...
algorithms
def values(n): pal = set() for i in range(1, int(n * * 0.5)): sos = i * i while sos < n: i += 1 sos += i * i if str(sos) == str(sos)[:: - 1] and sos < n: pal . add(sos) return len(pal)
Palindrome integer composition
599b1a4a3c5292b4cc0000d5
[ "Performance", "Algorithms" ]
https://www.codewars.com/kata/599b1a4a3c5292b4cc0000d5
5 kyu
## Task You're given an integer `n` (`0 <= n <= 10000`). You need to create a function which returns: 1. `Fizz` when `n` is divisible by `3` 2. `Buzz` when `n` is divisible by `5` 3. `Fizz Buzz` when `n` is divisible by both `3` and `5` 4. Otherwise it should return the string representation of `n` ## Restrictions ...
games
dic = { (0, 0): 'Fizz Buzz', (0, 1): 'Fizz', (1, 0): 'Buzz', (1, 1): 0 } def fizz_buzz(x): return ( dic[(min(x % 3, 1), min(x % 5, 1))] or '{}' . format(x))
Fizz Buzz (with restrictions)
584911a20d8b8f5b70000149
[ "Restricted", "Puzzles" ]
https://www.codewars.com/kata/584911a20d8b8f5b70000149
5 kyu
It's March and you just can't seem to get your mind off brackets. However, it is not due to basketball. You need to extract statements within strings that are contained within brackets. You have to write a function that returns a list of statements that are contained within brackets given a string. If the value entere...
reference
import re REGEX = re . compile(r'\[(.*?)\]') def bracket_buster(strng): try: return REGEX . findall(strng) except TypeError: return 'Take a seat on the bench.'
Bracket Buster
56ff322e79989cff16000e39
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/56ff322e79989cff16000e39
6 kyu
## Description We have a big list of jobs to do, and all of the jobs have been assigned a difficulty rating. Difficulties will be an integer, and they may be positive, negative or zero. Jim and Bob have the job of doing all the jobs, but we need to find the position in the container where we can make a cut so that J...
algorithms
def split_workload(workload): if not workload: return None, None diff = sum(workload) best_i, best_diff = None, float('inf') for i, work in enumerate(workload): if abs(diff) < best_diff: best_i, best_diff = i, abs(diff) # For each shift in the workload # the differen...
Evening up a workload
56431c04ed1454a35d00003b
[ "Lists", "Algorithms" ]
https://www.codewars.com/kata/56431c04ed1454a35d00003b
6 kyu
You're going on a trip with some students and it's up to you to keep track of how much money each Student has. A student is defined like this: ```ruby class Student attr_reader :name attr_reader :fives attr_reader :tens attr_reader :twenties def initialize(name, fives, tens, twenties) @name = name ...
algorithms
def most_money(students): total = [] for student in students: total . append((student . fives * 5) + (student . tens * 10) + (student . twenties * 20)) if min(total) == max(total) and len(students) > 1: return "all" else: return students[total . index(max(total))...
Who has the most money?
528d36d7cc451cd7e4000339
[ "Object-oriented Programming", "Algorithms" ]
https://www.codewars.com/kata/528d36d7cc451cd7e4000339
6 kyu
In this kata, we simply want to expand a matrix with some padding. For simplicity, we will take a square nxn matrix and expand it to a 2nx2n matrix. By expand I mean: ``` .------ n .------------------2n | | | fill | | | ===> | | | | | .--...
reference
def expand(maze, fill): unit = len(maze) / 2 brick = [fill] * unit block = [4 * brick] * unit return block + [brick + row + brick for row in maze] + block
matrix expanding
5568c4ed1597b393b6000066
[ "Arrays", "Fundamentals", "Matrix" ]
https://www.codewars.com/kata/5568c4ed1597b393b6000066
6 kyu
The built-in print function for Python class instances is not very entertaining. In this kata, we will implement a function ```show_me(instance)``` that takes an instance as parameter and returns the string ```"Hi, I'm one of those (classname)s! Have a look at my (attrs)."``` , where (classname) is the class name and ...
reference
def show_me(instname): classname = instname . __class__ . __name__ attrs = " and" . join(", " . join(attr for attr in sorted( instname . __dict__ . keys())). rsplit(",", 1)) return f"Hi, I'm one of those { classname } s! Have a look at my { attrs } ."
You look like a classy instance! Show me what you've got! - Part 1
561f9d37e4786544e0000035
[ "Data Structures", "Strings", "Lists", "Fundamentals", "Object-oriented Programming" ]
https://www.codewars.com/kata/561f9d37e4786544e0000035
6 kyu
<font size=1px>Description overhauled by V</font> --- I've invited some kids for my son's birthday, during which I will give to each kid some amount of candies. Every kid hates receiving less amount of candies than any other kids, and I don't want to have any candies left - giving it to my kid would be bad for his t...
algorithms
from math import lcm def candies_to_buy(amount_of_kids_invited): return lcm(* range(1, amount_of_kids_invited + 1))
Kids and candies
56cca888a9d0f25985000036
[ "Algorithms" ]
https://www.codewars.com/kata/56cca888a9d0f25985000036
6 kyu
In recreational mathematics, a magic square is an arrangement of distinct numbers (i.e., each number is used once), usually integers, in a square grid, where the numbers in each row, and in each column, and the numbers in the main and secondary diagonals, all add up to the same number, called the "magic constant." For...
reference
def is_magical(sq): return sum(sq[2: 7: 2]) == sum(sq[:: 4]) == sum(sq[:: 3]) == sum(sq[1:: 3]) == sum(sq[2:: 3]) == sum(sq[: 3]) == sum(sq[3: 6]) == sum(sq[6:])
Magic Square Validator
57be6a612eaf7cc3af000178
[ "Fundamentals" ]
https://www.codewars.com/kata/57be6a612eaf7cc3af000178
7 kyu
*Recreation of [Project Euler problem #6](https://projecteuler.net/problem=6)* Find the difference between the sum of the squares of the first `n` natural numbers `(1 <= n <= 100)` and the square of their sum. ## Example For example, when `n = 10`: * The square of the sum of the numbers is: (1 + 2 + 3 + 4 + 5 + 6...
reference
def difference_of_squares(x): r = range(1, x + 1, 1) return (sum(r) * * 2) - (sum(z * * 2 for z in r))
Difference Of Squares
558f9f51e85b46e9fa000025
[ "Fundamentals" ]
https://www.codewars.com/kata/558f9f51e85b46e9fa000025
7 kyu
[Currying and partial application](http://www.2ality.com/2011/09/currying-vs-part-eval.html) are two ways of transforming a function into another function with a generally smaller arity. While they are often confused with each other, they work differently. The goal is to learn to differentiate them. ## Currying > Is ...
reference
class CurryPartial: def __init__(self, func, * args): self . func = func self . args = args def __call__(self, * args): return CurryPartial(self . func, * (self . args + args)) def __eq__(self, other): try: return self . func(* self . args) == other except TypeError: ...
Currying vs. Partial Application
53cf7e37e9876c35a60002c9
[ "Functional Programming" ]
https://www.codewars.com/kata/53cf7e37e9876c35a60002c9
4 kyu
The Ulam sequence `U` is defined by `u0 = u`, `u1 = v`, with the general term `uN` for `N > 2` given by the least integer expressible uniquely as the sum of two distinct earlier terms. In other words, the next number is always the smallest, unique sum of any two previous terms. Complete the function that creates an Ul...
algorithms
from itertools import combinations from collections import defaultdict def ulam_sequence(u0, u1, n): seq = [u0, u1, u0 + u1] while len(seq) < n: candidates = defaultdict(int) for a, b in combinations(seq, 2): candidates[a + b] += 1 for num, pairs in sorted(candidates . items()): ...
Ulam Sequences
5995ff073acba5fa3a00011d
[ "Number Theory", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5995ff073acba5fa3a00011d
6 kyu
The Stern-Brocot sequence is much like the Fibonacci sequence and has some cool implications. Let's learn about it: It starts with `[1, 1]` and adds **two** new terms every iteration: `nextTerm` which is the sum of a previous pair; and `termAfterThat` which is the second term of this previous pair. Here is how to find...
algorithms
seq = [1, 1] for i in range(10 * * 4): a, b = seq[i: i + 2] seq . extend([a + b, b]) stern_brocot = seq . index
Stern-Brocot Sequence Part I
59986011d85bdd7fd7000621
[ "Number Theory", "Algorithms" ]
https://www.codewars.com/kata/59986011d85bdd7fd7000621
6 kyu
Consider the following series: `0,1,2,3,4,5,6,7,8,9,10,22,11,20,13,24...`There is nothing special between numbers `0` and `10`. Let's start with the number `10` and derive the sequence. `10` has digits `1` and `0`. The next possible number that does not have a `1` or a `0` is `22`. All other numbers between `10` and...
algorithms
masks = [0] * 10 for i in range(10 * * 4): for c in str(i): masks[int(c)] |= 1 << i def find_num(n): seq, x = 1, 0 for j in range(n): M = seq for m in masks: if x & m: M |= m x = ~ M & (M + 1) seq |= x return x . bit_length() - 1
Unique digits sequence
599688d0e2800dda4e0001b0
[ "Algorithms" ]
https://www.codewars.com/kata/599688d0e2800dda4e0001b0
5 kyu
The Abundancy (A) of a number `n` is defined as: ## (sum of divisors of n) / n For example: ```python A(8) = (1 + 2 + 4 + 8) / 8 = 15/8 A(25) = (1 + 5 + 25) / 25 = 31/25 ``` Friendly Pairs are pairs of numbers (m, n), such that their abundancies are equal: A(n) = A(m). Write a function that returns `"Friendly!"` ...
algorithms
from fractions import Fraction def getDivisors(x): for n in range(1, int(x * * .5) + 1): if not x % n: yield n if n != x / / n: yield x / / n def friendlyNumbers(m, n): a, b = sum(getDivisors(m)), sum(getDivisors(n)) return "Friendly!" if a / m == b / n else "{} {}" . ...
Friendly Pairs I
59974515b4c40be3cc000263
[ "Number Theory", "Algorithms" ]
https://www.codewars.com/kata/59974515b4c40be3cc000263
6 kyu
Consider the following series: `1, 2, 4, 8, 16, 22, 26, 38, 62, 74, 102, 104, 108, 116, 122` It is generated as follows: * For single digit integers, add the number to itself to get the next element. * For other integers, multiply all the non-zero digits and add the result to the original number to get the next elem...
algorithms
from operator import mul from functools import reduce def genSequence(n): yield n while True: n += reduce(mul, [int(d) for d in str(n) if d != '0']) if n > 9 else n yield n def extract(seq, v): return sorted(seq). index(v) def convergence(n): gen1, genN = genSequence(1), ...
Sequence convergence
59971e64bfccc70748000068
[ "Algorithms" ]
https://www.codewars.com/kata/59971e64bfccc70748000068
6 kyu
A [rock-paper-scissors](https://en.wikipedia.org/wiki/Rock%E2%80%93paper%E2%80%93scissors) robo player paticipates regularly in the same knockout tournament but almost always without succes. Can you improve this robo player and make it a tournament winner? <img style="height:200px" src="https://web.archive.org/web/201...
algorithms
from itertools import cycle class Player (RockPaperScissorsPlayer): STRATEGIES = { 'Vitraj Bachchan': 'R', 'Sven Johanson': 'RRSPPR', 'Max Janssen': 'P', 'Bin Jinhao': 'RPRSPS', 'Jonathan Hughes': 'SRP', } def __init__(self): self . cycle = None ...
RPS Knockout Tournament Winner
58691792a44cfcf14700027c
[ "Games", "Algorithms", "Game Solvers", "Design Patterns", "Object-oriented Programming" ]
https://www.codewars.com/kata/58691792a44cfcf14700027c
6 kyu
Write a function that accepts two parameters (sum and multiply) and find two numbers [x, y], where x + y = sum and x * y = multiply. Example: sum = 12 and multiply = 32 In this case, x equals 4 and y equals 8. x = 4 y = 8 Because x + y = 4 + 8 = 12 = sum x \* y = 4 \* 8 = 32 = multiply The result should be [4,...
algorithms
def sum_and_multiply(sum, multiply): for x in range(sum + 1): if x * (sum - x) == multiply: return [x, sum - x]
Sum and Multiply
59971206e06bbf4407002382
[ "Algorithms" ]
https://www.codewars.com/kata/59971206e06bbf4407002382
7 kyu
Since there are lots of katas requiring you to round numbers to 2 decimal places, you decided to extract the method to ease out the process. And you can't even get this right! Quick, fix the bug before everyone in CodeWars notices that you can't even round a number correctly!
bug_fixes
from decimal import Decimal, ROUND_HALF_UP def round_by_2_decimal_places(n): return n . quantize(Decimal('.01'), rounding=ROUND_HALF_UP)
Round and Round
5996eb39cdc8eb39f80000a0
[ "Fundamentals", "Debugging" ]
https://www.codewars.com/kata/5996eb39cdc8eb39f80000a0
6 kyu
## Task Generate a sorted list of all possible IP addresses in a network. For a subnet that is not a valid IPv4 network return `None`. ## Examples ``` ipsubnet2list("192.168.1.0/31") == ["192.168.1.0", "192.168.1.1"] ipsubnet2list("213.256.46.160/28") == None ```
reference
import ipaddress as ip def ipsubnet2list(subnet): try: return list(map(str, ip . ip_network(subnet). hosts())) except: pass
IPv4 subnet to list
5980d4e258a9f5891e000062
[ "Networks", "Fundamentals" ]
https://www.codewars.com/kata/5980d4e258a9f5891e000062
6 kyu
In this Kata, you will create a function that converts a string with letters and numbers to the inverse of that string (with regards to Alpha and Numeric characters). So, e.g. the letter `a` will become `1` and number `1` will become `a`; `z` will become `26` and `26` will become `z`. Example: `"a25bz"` would become `...
games
import re def AlphaNum_NumAlpha(s): return re . sub(r'[0-9]+|[a-z]', lambda x: alphabet[(int(x . group()) - 1) % 26] if x . group(). isdigit() else str(alphabet . index(x . group()) + 1), s)
Alpha to Numeric and Numeric to Alpha
5995ceb5d4280d07f6000822
[ "Algorithms", "Strings" ]
https://www.codewars.com/kata/5995ceb5d4280d07f6000822
6 kyu
Write a code that receives an array of numbers or strings, goes one by one through it while taking one value out, leaving one value in, taking, leaving, and back again to the beginning until all values are out. It's like a circle of people who decide that every second person will leave it, until the last person is th...
algorithms
from collections import deque def yes_no(arr): d, result = deque(arr), [] while d: result . append(d . popleft()) d . rotate(- 1) return result
Yes No Yes No
573c84bf0addf9568d001299
[ "Algorithms" ]
https://www.codewars.com/kata/573c84bf0addf9568d001299
6 kyu
When provided with a String, capitalize all vowels For example: Input : "Hello World!" Output : "HEllO WOrld!" Note: Y is not a vowel in this kata.
reference
def swap(st): tr = str . maketrans('aeiou', 'AEIOU') return st . translate(tr)
Changing letters
5831c204a31721e2ae000294
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/5831c204a31721e2ae000294
7 kyu
# Regular Expression for Binary Numbers Divisible by n Create a function that will return a regular expression string that is capable of evaluating binary strings (which consist of only `1`s and `0`s) and determining whether the given string represents a number divisible by `n`. ## Tests Inputs `1 <= n <= 18` will b...
algorithms
def regex_divisible_by(n): if n == 1: return '^[01]*$' G = {(i, (2 * i + j) % n): str(j) for i in range(n) for j in (0, 1)} for k in range(n - 1, 0, - 1): loop = '' if (k, k) not in G else G[(k, k)] + '*' I = {i for i, j in G if i != k and j == k} J = {j for i, j in G if i == k and j ...
Regular Expression for Binary Numbers Divisible by n
5993c1d917bc97d05d000068
[ "Algorithms", "Puzzles", "Regular Expressions", "Strings" ]
https://www.codewars.com/kata/5993c1d917bc97d05d000068
1 kyu
Create a function that converts a given ASCII string to its hexadecimal SHA-256 hash. ``` sha256("Hello World!") => "7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069" ```
algorithms
from hashlib import sha256 def to_sha256(s): return sha256(s . encode('utf-8')). hexdigest()
SHA-256
587fb57e12fc6eadf200009b
[ "Strings", "Cryptography", "Algorithms" ]
https://www.codewars.com/kata/587fb57e12fc6eadf200009b
6 kyu
Write a function that verifies provided argument is either an integer or a floating-point number, returning true if it is or false otherwise. *__Pointers__* * Numeric quantities are _signed_ (optionally when positive, e.g. "+5" is valid notation) * Floats less than 1 (___not considering possible exponent!___) can be...
games
def i_or_f(arr): # Your code here (and maybe somewhere else? Hint, hint) try: float(arr) return True except: return False
Float or Integer verifier
541a9774204d12252f00045d
[ "Regular Expressions", "Puzzles" ]
https://www.codewars.com/kata/541a9774204d12252f00045d
6 kyu
Implement a function `k_permutations_of_n` that accepts a list of elements `lst` and an integer `k`, and returns all permutations of elements from the list `lst`. Permutations should be a list containing all unique lists of `k` elements from `lst`, in any order. For example, if `lst == [1,2,3]` and `k == 2` the result...
algorithms
from itertools import permutations def k_permutations_of_n(lst: list, k: int) - > list: return [list(p) for p in permutations(lst, k)]
k-permutations of n
5592890bb4af624e930000b5
[ "Algorithms", "Recursion", "Permutations" ]
https://www.codewars.com/kata/5592890bb4af624e930000b5
6 kyu
Return the secret integer in a range based on the response from the `guess_bot`. You are given a low and high range (inclusive) and an instance of `GuessBot` (`guess_bot`). You are only to interact with `guess_bot` by its method: `guess_number(num)` which returns a string. `guess_bot` is a bit of an asshole and only...
algorithms
def find_secret_number(low, high, f): while low <= high: mid = (low + high) / / 2 r = f . guess_number(mid) if r == 'Larger': low = mid + 1 elif r == 'Smaller': high = mid - 1 else: return mid
Guess the secret integer (binary search)
5749b2fc8bf8b6fbd3001ff3
[ "Algorithms" ]
https://www.codewars.com/kata/5749b2fc8bf8b6fbd3001ff3
6 kyu
Passer ratings are the generally accepted standard for evaluating NFL quarterbacks. I knew a rating of 100 is pretty good, but never knew what makes up the rating. So out of curiosity I took a look at the wikipedia page and had an idea or my first kata: https://en.wikipedia.org/wiki/Passer_rating ## Formula There are...
algorithms
def passer_rating(att, yds, comp, td, ints): def limit(x): return min(max(x, 0), 2.375) att = float(att) # for python 2 compatibility A = ((comp / att) - .3) * 5 B = ((yds / att) - 3) * .25 C = (td / att) * 20 D = 2.375 - ((ints / att) * 25) A, B, C, D = map(limit, (A, B, C, D)) ...
NFL Passer Ratings
59952e17f902df0e5f000078
[ "Algorithms" ]
https://www.codewars.com/kata/59952e17f902df0e5f000078
7 kyu
The `mystery` function is defined over the non-negative integers. The more common name of this function is concealed in order to not tempt you to search the Web for help in solving this kata, which most definitely would be a very dishonorable thing to do. Assume `n` has `m` bits. Then `mystery(n)` is the number whose ...
reference
def mystery(n): return n ^ (n >> 1) def mystery_inv(n): mask = n >> 1 while mask != 0: n = n ^ mask mask = mask >> 1 return n def name_of_mystery(): return "Gray code"
Mystery Function
56b2abae51646a143400001d
[ "Fundamentals" ]
https://www.codewars.com/kata/56b2abae51646a143400001d
4 kyu
Please write a function that sums a list, but ignores any duplicate items in the list. For instance, for the list [3, 4, 3, 6] , the function should return 10.
reference
def sum_no_duplicates(l): return sum(n for n in set(l) if l . count(n) == 1)
Sum a list but ignore any duplicates
5993fb6c4f5d9f770c0000f2
[ "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/5993fb6c4f5d9f770c0000f2
7 kyu
You are provided with a skeleton of the class 'Fraction', which accepts two arguments (numerator, denominator). EXAMPLE: ```python fraction1 = Fraction(4, 5) ``` ```csharp Fraction fraction1 = new Fraction(4, 5); ``` ```haskell fraction1 = fraction 4 5 ``` ```java Fraction fraction1 = new Fraction(4, 5); ``` Your tas...
reference
# Something goes Here ... class Fraction: def __init__(self, numerator, denominator): g = gcd(numerator, denominator) self . top = numerator / g self . bottom = denominator / g # Equality test def __eq__(self, other): first_num = self . top * other . bottom second_num = other ...
Fractions class
572bbd7c72a38bd878000a73
[ "Fundamentals", "Object-oriented Programming" ]
https://www.codewars.com/kata/572bbd7c72a38bd878000a73
6 kyu
Convert a hash into an array. Nothing more, Nothing less. ``` {name: 'Jeremy', age: 24, role: 'Software Engineer'} ``` should be converted into ``` [["age", 24], ["name", "Jeremy"], ["role", "Software Engineer"]] ``` ```if:python,javascript,crystal **Note**: The output array should be sorted alphabetically by key na...
reference
def convert_hash_to_array(hash): return sorted(map(list, hash . items()))
Convert Hash To An Array
59557b2a6e595316ab000046
[ "Arrays", "Lists", "Fundamentals" ]
https://www.codewars.com/kata/59557b2a6e595316ab000046
7 kyu