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 |
|---|---|---|---|---|---|---|---|
Given two different positions on a chess board, find the least number of moves it would take a knight to get from one to the other.
The positions will be passed as two arguments in algebraic notation.
For example, `knight("a3", "b5")` should return 1.
The knight is not allowed to move off the board.
The board is 8x8.
... | algorithms | from collections import deque
moves = ((1, 2), (1, - 2), (- 1, 2), (- 1, - 2),
(2, 1), (2, - 1), (- 2, 1), (- 2, - 1))
def knight(p1, p2):
x, y = ord(p2[0]) - 97, int(p2[1]) - 1
left, seen = deque([(ord(p1[0]) - 97, int(p1[1]) - 1, 0)]), set()
while left:
i, j, v = left . popleft()
... | Shortest Knight Path | 549ee8b47111a81214000941 | [
"Algorithms"
] | https://www.codewars.com/kata/549ee8b47111a81214000941 | 4 kyu |
In [Geometry A-1](http://www.codewars.com/kata/554c8a93e466e794fe000001) kata, `point_vs_vector(point, vector)` function was defined. This function allows to check whether a point is in the right subplane, in the left subplane, or at the line of the vector.
However, that function was not required to check for zero-len... | refactoring | def point_vs_vector_v2(p, v):
EPS = 10 * * - 9
(x, y), ((x1, y1), (x2, y2)) = p, v
res = (x - x1) * (y2 - y1) - (y - y1) * (x2 - x1)
return (- 1) * * (res < 0) * (abs(res) > EPS) if abs(x1 - x2) + abs(y1 - y2) > EPS else None
| [Geometry A-1.1] Modify point location detector to handle zero-length vectors and precision errors [DRY] | 5550f37131caf073b8000025 | [
"Geometry",
"Refactoring"
] | https://www.codewars.com/kata/5550f37131caf073b8000025 | 6 kyu |
# Binary Search Trees
A `Tree` consists of a root, which is of type `Node`, possibly a left subtree of type `Tree`, and possibly a right subtree of type `Tree`. If the left subtree is present, then all its nodes are less than the parent tree's root; if the right tree is present, then all its nodes are greater than the... | reference | class Tree (object):
def __init__(self, root, left=None, right=None):
assert root and isinstance(root, Node)
assert left is None or isinstance(
left, Tree) and left . _max(). root < root
assert right is None or isinstance(
right, Tree) and root < right . _min(). root
self . le... | Binary Search Trees | 571a551a196bb0567f000603 | [
"Object-oriented Programming",
"Algorithms",
"Data Structures"
] | https://www.codewars.com/kata/571a551a196bb0567f000603 | 5 kyu |
A generalization of Bézier surfaces, called the S-patch, uses an interesting scheme for indexing its control points.
In the case of an n-sided surface of degree d, each index has n non-negative integers that sum to d, and all possible configurations are used.
For example, for a 3-sided quadratic (degree 2) surface th... | algorithms | def gen(n, d):
if d == 0 or n == 1:
yield [d] * n
else:
for x in range(d + 1):
for y in gen(n - 1, d - x):
yield [x] + y
def indices(n, d):
return list(gen(n, d))
| Fixed-length integer partitions | 553291f451ab4fbcdc0001c6 | [
"Algorithms"
] | https://www.codewars.com/kata/553291f451ab4fbcdc0001c6 | 5 kyu |
A function receives a certain numbers of integers ```n1, n2, n3 ..., np```(all positive and different from 0) and a factor ```k, k > 0```
The function rearranges the numbers ```n1, n2, ..., np``` in such order that generates the minimum number concatenating the digits and this number should be divisible by ```k```.
T... | algorithms | from itertools import permutations
def rearranger(k, * args):
perms = permutations(map(str, args), len(args))
divisible_by_k = filter(lambda x: int('' . join(x)) % k == 0, perms)
try:
rearranged = min(divisible_by_k, key=lambda x: int('' . join(x)))
return 'Rearrangement: {} generates: {} ... | Rearrangement of Numbers to Have The Minimum Divisible by a Given Factor | 569e8353166da6908500003d | [
"Fundamentals",
"Mathematics",
"Sorting",
"Logic",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/569e8353166da6908500003d | 5 kyu |
### Description
Here is a rope with a length of `x cm`. We will cut it in the following way: each `m cm` to make a mark, and then each `n cm` to make a mark. Finally, We cut the rope from the marked place. Please calculate that we have a total of several kinds of length of the rope, and how many of each kind of rope?
... | games | from collections import Counter
from itertools import pairwise
def cut_rope(length, m, n):
cuts = sorted([0, * range(m, length, m), * range(n, length, n), length])
return {f' { k } cm': v for k, v in Counter(b - a for a, b in pairwise(cuts)). items() if k}
| T.T.T.39: Cut rope | 57b2a9631fae8a30fa000013 | [
"Puzzles",
"Games"
] | https://www.codewars.com/kata/57b2a9631fae8a30fa000013 | 6 kyu |
You have been tasked with converting a number from base i (sqrt of -1) to base 10.
Recall how bases are defined:
abcdef = a * 10^5 + b * 10^4 + c * 10^3 + d * 10^2 + e * 10^1 + f * 10^0
Base i follows then like this:
... i^4 + i^3 + i^2 + i^1 + i^0
The only numbers in any place will be 1 or 0
Examples:
... | algorithms | def convert(n):
ds = list(map(int, reversed(str(n))))
return [sum(ds[:: 4]) - sum(ds[2:: 4]), sum(ds[1:: 4]) - sum(ds[3:: 4])]
| Imaginary Base Conversion | 583a47342fb0ba1418000060 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/583a47342fb0ba1418000060 | 6 kyu |
In mathematics, a <a href="https://en.wikipedia.org/wiki/Matrix_%28mathematics%29">matrix</a> (plural matrices) is a rectangular array of numbers. Matrices have many applications in programming, from <a href="http://www.mathplanet.com/education/geometry/transformations/transformation-using-matrices">performing transfor... | algorithms | import numpy as np
def get_matrix_product(a, b):
try:
return np . array(a). dot(np . array(b)). tolist()
except:
return None
| Matrix Multiplier | 573248f48e531896770001f9 | [
"Matrix",
"Algorithms",
"Linear Algebra",
"Mathematics"
] | https://www.codewars.com/kata/573248f48e531896770001f9 | 6 kyu |
# Task
You are given integer `n` determining set S = {1, 2, ..., n}. Determine if the number of k-element subsets of S is `ODD` or `EVEN` for given integer k.
# Example
For `n = 3, k = 2`, the result should be `"ODD"`
In this case, we have 3 2-element subsets of {1, 2, 3}:
`{1, 2}, {1, 3}, {2, 3}`
For `n = ... | games | def subsets_parity(n, k):
return 'EVEN' if ~ n & k else 'ODD'
| Simple Fun #119: Sub Sets Parity | 589d5c80c31aa590e300006b | [
"Puzzles"
] | https://www.codewars.com/kata/589d5c80c31aa590e300006b | 4 kyu |
For a given 2D point with coordinates presented as `[x, y]`, determine if it belongs to a vector presented as `[[x1, y1],[x2, y2]]`, and return `True` if point belongs to the vector (including vector's ends) or `False` if not.
Vector may have a zero length (i. e. start and end in the same point).
Random test cases w... | algorithms | class Point:
__slots__ = ['x', 'y']
def __init__(self, x, y):
self . x = x
self . y = y
def colinear(self, p, q):
t1 = (self . x - p . x) * (self . y - q . y)
t2 = (self . x - q . x) * (self . y - p . y)
return abs(t1 - t2) <= 1e-9
def within(self, p, q):
if p . x <= ... | [Geometry A-3] Does point belong to the vector? [DRY] | 554e5ef27daf4082f6000071 | [
"Geometry",
"Algorithms"
] | https://www.codewars.com/kata/554e5ef27daf4082f6000071 | 6 kyu |
> When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said
# Description:
In this Kata, we have to try to create a mysterious pattern.
Given a positive integer `m`, you can generate a Fibonacci sequence with a length of `m`:
``... | games | def mysterious_pattern(m, n):
rows = [[' '] * m for _ in range(n)]
a, b = 1, 1
for i in range(m):
rows[a % n][i] = 'o'
a, b = b, a + b
rows = ['' . join(r). rstrip() for r in rows]
return '\n' . join(rows). strip('\n')
| Mysterious Pattern | 580ec64394291d946b0002a1 | [
"ASCII Art",
"Puzzles"
] | https://www.codewars.com/kata/580ec64394291d946b0002a1 | 6 kyu |
An array is called *zero-plentiful* if it contains multiple zeros, and **every** sequence of zeros is at least 4 items long.
Your task is to return the number of zero sequences if the given array is *zero-plentiful*, oherwise `0`.
## Examples
```python
[0, 0, 0, 0, 0, 1] --> 1
# 1 group of 5 zeros (>= 4), thus the... | reference | from itertools import groupby
def zero_plentiful(arr):
r = [len(list(g)) > 3 for k, g in groupby(arr) if k == 0]
return all(r) * len(r)
| Zero-plentiful Array | 59e270da7997cba3d3000041 | [
"Fundamentals"
] | https://www.codewars.com/kata/59e270da7997cba3d3000041 | 6 kyu |
## Screen Locking Patterns
You might already be familiar with many smartphones that allow you to use a geometric pattern as a security measure. To unlock the device, you need to connect a sequence of dots/points in a grid by swiping your finger **without lifting it** as you trace the pattern through the screen.
The i... | algorithms | EQUIV_PTS = {same: src for src, seq in (
('A', 'CGI'), ('B', 'DFH')) for same in seq}
ALL = set('ABCDEFGHI')
LINKED_TO = {'A': ('BC', 'DG', 'EI', 'F', 'H'),
'B': ('A', 'C', 'D', 'EH', 'F', 'G', 'I'),
'C': ('BA', 'D', 'EG', 'FI', 'H'),
'D': ('A', 'B', 'C', 'EF', 'G', 'H... | Screen Locking Patterns | 585894545a8a07255e0002f1 | [
"Mathematics",
"Combinatorics",
"Geometry",
"Algorithms",
"Graph Theory"
] | https://www.codewars.com/kata/585894545a8a07255e0002f1 | 3 kyu |
<img src="http://bestanimations.com/Science/Gears/loadinggears/loading-gears-animation-6-4.gif"/>
# Kata Task
You are given a list of cogs in a <a href ="https://en.wikipedia.org/wiki/Gear_train">gear train</a>
Each element represents the number of teeth of that cog
e.g. `[100, 75]` means
* 1st cog has 100 teeth ... | reference | def cog_RPM(l):
return (- 1 + len(l) % 2 * 2) * l[0] / l[- 1]
| Cogs | 59e1b9ce7997cbecb9000014 | [
"Fundamentals"
] | https://www.codewars.com/kata/59e1b9ce7997cbecb9000014 | 7 kyu |
Two integers are coprimes if the their only greatest common divisor is 1.
## Task
In this kata you'll be given a number ```n >= 2``` and output a list with all positive integers less than ```gcd(n, k) == 1```, with ```k``` being any of the output numbers.
The list cannot include duplicated entries and has to be sorte... | algorithms | from fractions import gcd
def coprimes(n):
return [i for i in range(1, n + 1) if gcd(n, i) == 1]
| Coprimes up to N | 59e0dbb72a7acc3610000017 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/59e0dbb72a7acc3610000017 | 6 kyu |
Given a string (`str`) containing a base-10 integer between `0` and `10000`, convert the integer to its binary representation. At that point, obtain a count of the maximum amount of consecutive 0s. From there, return the count in written form with a capital letter.
```ruby
max_consec_zeros("9") => "Two"
max_consec_zer... | reference | import re
ls = ["Zero", "One", "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen"]
def max_consec_zeros(n):
return ls[max(map(lambda x: len(x), re . findall(r'0*', bin(int(n))[2:])))]
| Most Consecutive Zeros of a Binary Number | 59decdf40863c76ae3000080 | [
"Fundamentals",
"Mathematics",
"Strings"
] | https://www.codewars.com/kata/59decdf40863c76ae3000080 | 6 kyu |
# Letterss of Natac
In a game I just made up that doesn’t have anything to do with any other game that you may or may not have played, you collect resources on each turn and then use those resources to build things like roads, settlements and cities. If you would like to try other kata about this game, they can be foun... | reference | from collections import Counter
def play_if_enough(hand, play):
h = Counter(hand)
p = Counter(play)
if p & h == p:
h . subtract(p)
return (True, "" . join(h . elements()))
return (False, hand)
| Letterss of Natac | 59e0069781618a7950000995 | [
"Fundamentals"
] | https://www.codewars.com/kata/59e0069781618a7950000995 | 5 kyu |
Imagine two arrays/lists where elements are linked by their positions in the array. For example:
```
HowMany = [ 1 , 6 , 5 , 0 ];
Type = ['house', 'car','pen','jeans'];
```
Means I have 1 house, 6 cars,5 pens and 0 jeans.
Now if we sort one array we lose the connectivity. The goal is to create a sorting func... | algorithms | def linked_sort(a, b, key=str):
a[:], b[:] = zip(* sorted(zip(a, b), key=key))
return a
| 2 Arrays 1 Sort | 546b22225874d24fbd00005b | [
"Arrays",
"Algorithms",
"Sorting"
] | https://www.codewars.com/kata/546b22225874d24fbd00005b | 6 kyu |
We have the following function of two variables x, y (values of x, y are in determined ranges of values):
<a href="http://imgur.com/0HdIVic"><img src="http://i.imgur.com/0HdIVic.png?1" title="source: imgur.com" /></a>
The function above is studied for ```x, y```, positive integers, and ```x ≠ y```.
```⌊ ⌋``` - rep... | reference | from math import pow, floor
def max_val_f(range1, range2, hMax, k):
m, n = range1[0], range1[1]
p, q = range2[0], range2[1]
res = []
for x in range(m, n + 1):
for y in range(p, q + 1):
if x != y:
ab = float(abs(x - y))
val = pow(floor((x + y) / ab), ab)
if val <= hMax:
... | Finding the Closest Maximum Values of a Function to an Upper Limit | 56085481f82c1672d000001f | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/56085481f82c1672d000001f | 5 kyu |
This kata is a very basic introduction to compression.
Your task is to make a program which **takes in a sentence** and returns a string which shows the **unique position** of each word in the sentence. If a word appears more than once in the sentence, your string should
return the position of the **first occurrence**... | algorithms | def compress(sentence):
ref = []
for i in sentence . lower(). split():
if i not in ref:
ref . append(i)
return '' . join([str(ref . index(n)) for n in sentence . lower(). split()])
| Compress sentences | 59de469cfc3c492da80000c5 | [
"Lists",
"Algorithms"
] | https://www.codewars.com/kata/59de469cfc3c492da80000c5 | 7 kyu |
It happened decades before Snapchat, years before Twitter and even before Facebook. Targeted advertising was a bit of a challenge back then. One day, the marketing professor at my university told us a story that I am yet to confirm using reliable sources. Nevertheless, I retold the story to dozens of my students alread... | reference | def remove_bmw(string):
try:
return string . translate(str . maketrans('', '', "BMWbmw"))
except AttributeError:
raise TypeError("This program only works for text.")
| Remove B M W | 59de795c289ef9197f000c48 | [
"Fundamentals",
"Strings",
"Regular Expressions"
] | https://www.codewars.com/kata/59de795c289ef9197f000c48 | 7 kyu |
Your task is to create a magic square for any positive odd integer `N`. The magic square contains the integers from `1` to `N * N`, arranged in an `NxN` matrix, such that the columns, rows and both main diagonals add up to the same number.
**Note**: use have to use the [Siamese method](https://en.wikipedia.org/wiki/Si... | games | def magicSquare(n):
if n % 2:
square = [[0] * n for _ in range(n)]
for i in range(n * * 2):
x, y = (2 * (i / / n) - i) % n, (n / / 2 + i - i / / n) % n
square[x][y] = i + 1
return square
else:
return "Please enter an odd integer."
| Odd Magic Square | 570b69d96731d4cf9c001597 | [
"Puzzles",
"Arrays",
"Mathematics"
] | https://www.codewars.com/kata/570b69d96731d4cf9c001597 | 6 kyu |
You need to write a function, that returns the first non-repeated character in the given string.
If all the characters are unique, return the first character of the string.
If there is no unique character, return `null` in JS or Java, `None` in Python, `'\0'` in C.
You can assume, that the input string has always... | reference | def first_non_repeated(s):
for c in s:
if s . count(c) == 1:
return c
| The First Non Repeated Character In A String | 570f6436b29c708a32000826 | [
"Algorithms",
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/570f6436b29c708a32000826 | 7 kyu |
## Task
```if:haskell
Create a function `eqAll` that determines if all elements of a `list` are equal.
`list` can be any `Foldable` structure, of any `Eq` instance, and may be infinite. Return value is a `Bool`.
```
```if:javascript
Create a function `eqAll` that determines if all elements of a `list` are equal.
`... | reference | from itertools import islice, groupby
def eq_all(iterable):
return not next(islice(groupby(iterable), 1, None), False)
| Are all elements equal? (Infinity version) | 59dce15af703c42af6000035 | [
"Fundamentals"
] | https://www.codewars.com/kata/59dce15af703c42af6000035 | 6 kyu |
Two strings ```a``` and b are called isomorphic if there is a one to one mapping possible for every character of ```a``` to every character of ```b```. And all occurrences of every character in ```a``` map to same character in ```b```.
## Task
In this kata you will create a function that return ```True``` if two give... | algorithms | def isomorph(a, b):
return [a . index(x) for x in a] == [b . index(y) for y in b]
| Check if two words are isomorphic to each other | 59dbab4d7997cb350000007f | [
"Algorithms"
] | https://www.codewars.com/kata/59dbab4d7997cb350000007f | 6 kyu |
## A Knight's Tour
A knight's tour is a sequence of moves of a knight on a chessboard such that the knight visits every square only once.
https://en.wikipedia.org/wiki/Knight%27s_tour
Traditional chess boards are 8x8 grids, but for this kata we are interested in generating tours for any square board sizes.
You will... | algorithms | def knights_tour(start, size):
MOVES = [(- 2, 1), (- 2, - 1), (- 1, - 2), (1, - 2),
(2, - 1), (2, 1), (1, 2), (- 1, 2)]
def genNeighs(pos): return ((pos[0] + dx, pos[1] + dy)
for dx, dy in MOVES if (pos[0] + dx, pos[1] + dy) in Warnsdorf_DP)
def travel... | A Knight's Tour | 5664740e6072d2eebe00001b | [
"Algorithms"
] | https://www.codewars.com/kata/5664740e6072d2eebe00001b | 4 kyu |
# What's in a name?
...Or rather, what's a name in? For us, a particular string is where we are looking for a name.
## Task
Write a function, taking two strings in parameter, that tests whether or not the first string contains all of the letters of the second string, in order.
The function should return `true` if t... | reference | def name_in_str(str, name):
it = iter(str . lower())
return all(c in it for c in name . lower())
| What's A Name In? | 59daf400beec9780a9000045 | [
"Fundamentals"
] | https://www.codewars.com/kata/59daf400beec9780a9000045 | 6 kyu |
We have three numbers: ```123489, 5, and 67```.
With these numbers we form the list from their digits in this order ```[1, 5, 6, 2, 7, 3, 4, 8, 9]```. It shouldn't take you long to figure out what to do to achieve this ordering.
Furthermore, we want to put a limit to the number of terms of the above list.
Instead of... | reference | from itertools import permutations
def make_array_from_args(* args: int) - > list[int]:
its = [iter(f' { arg } ') for arg in args]
result_array = []
for it in its:
try:
value = int(next(it))
except StopIteration:
continue
else:
its . append(it)
if value not in resu... | Great Total Additions of All Possible Arrays from a List. | 568f2d5762282da21d000011 | [
"Fundamentals",
"Mathematics",
"Permutations"
] | https://www.codewars.com/kata/568f2d5762282da21d000011 | 4 kyu |
We need a function, closest_points3D() that may give an accurate result to find the closest pair or pairs of points that are contained in cube volumes of size l. The function will receive a list of variable number of points in a list (each point represented with cartesian coordinates(x, y, z)). All the values of x, y a... | reference | from itertools import combinations
def closest_points3D(points):
pairs = list(set([tuple(sorted(p)) for p in combinations(points, 2)]))
dists = [round(sum((i - j) * * 2 for i, j in zip(a, b)) * * 0.5, 5) for a, b in pairs]
mdist = min(dists)
return [len(points), sorted([[pairs[i][0], pairs[i][1... | Closest Neighbouring Points II | 55e47815d7055e1a97000128 | [
"Fundamentals",
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/55e47815d7055e1a97000128 | 5 kyu |
We need a function, closest_points() that may give an accurate result to find the closest pair or pairs of points that are contained in square areas of size l. The function will receive a list of variable number of points in a list (each point represented with cartesian coordinates) and should display the results in th... | reference | from collections import defaultdict
from itertools import combinations as combo
def closest_points(l):
d = defaultdict(list)
for (x1, y1), (x2, y2) in combo(sorted(l), 2):
d[(x2 - x1) * * 2 + (y2 - y1) * * 2]. append([(x1, y1), (x2, y2)])
return [len(l), sorted(d[min(d)]), round(min(d) * * .5,... | Closest Neighbouring Points I | 55e4419eb589793709000044 | [
"Fundamentals",
"Mathematics",
"Data Structures",
"Algorithms"
] | https://www.codewars.com/kata/55e4419eb589793709000044 | 5 kyu |
#Task:
Write a function `get_member_since` which accepts a username from someone at Codewars and returns an string containing the month and year separated by a space that they joined CodeWars.
###If you want/don't want your username to be in the tests, ask me in the discourse area. There can't be too many though becau... | reference | from urllib . request import urlopen
from bs4 import BeautifulSoup as bs
def get_member_since(username):
html = urlopen(f'https://www.codewars.com/users/ { username } ')
soup = bs(html . read(), "html.parser")
tags = soup . find_all("div", {"class": "stat"})
member_tag = [x . text for x in tag... | Scraping: Get the Year a CodeWarrior Joined | 58ab2ed1acbab2eacc00010e | [
"Strings",
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/58ab2ed1acbab2eacc00010e | 5 kyu |
> When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process -- myjinxin2015 said
## Description:
In a dark, deserted night, a thief entered a shop. There are some items in the room, and the items have different weight (in kg) and price (in $).
The t... | algorithms | from preloaded import Item
# 0/1 Knapsack Problem
def greedy_thief(items: list[Item], n: int) - > list[Item]:
dp = [(0, []) for _ in range(n + 1)]
for item in items:
for w in range(n, 0, - 1):
if item . weight <= w:
x, y = dp[w - item . weight]
if x + item . price > dp[w][0]:
dp... | Greedy thief | 58296c407da141e2c7000271 | [
"Algorithms",
"Puzzles"
] | https://www.codewars.com/kata/58296c407da141e2c7000271 | 4 kyu |
# Task
You are given a positive integer `n`. Now we want to choose some numbers from 1 to n, and then doing some addition and subtraction(or doing nothing), all these numbers are used at most once. Eventually, all the numbers from 1 to n can be calculated.
Your task is to find the minimum amount of numbers you need ... | algorithms | from itertools import count
def fewest_numbers(target):
top, n = 1, 1
for d in count(1):
if n >= target:
return d
top = 2 * n + 1
n += top
| Simple Fun #360: Calculate 1 to n Using The Fewest Numbers | 59dad2177997cb2a1300008d | [
"Algorithms"
] | https://www.codewars.com/kata/59dad2177997cb2a1300008d | 6 kyu |
Given a string of integers, return the number of odd-numbered substrings that can be formed.
For example, in the case of `"1341"`, they are `1, 1, 3, 13, 41, 341, 1341`, a total of `7` numbers.
`solve("1341") = 7`. See test cases for more examples.
Good luck!
If you like substring Katas, please try
[Longest vo... | reference | def solve(s):
return sum(i + 1 for i, d in enumerate(list(s)) if d in '13579')
| Non-even substrings | 59da47fa27ee00a8b90000b4 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/59da47fa27ee00a8b90000b4 | 6 kyu |
Consider the word `"abode"`. We can see that the letter `a` is in position `1` and `b` is in position `2`. In the alphabet, `a` and `b` are also in positions `1` and `2`. Notice also that `d` and `e` in `abode` occupy the positions they would occupy in the alphabet, which are positions `4` and `5`.
Given an array of ... | reference | def solve(arr):
return [sum(c == chr(97 + i) for i, c in enumerate(w[: 26]. lower())) for w in arr]
| Alphabet symmetry | 59d9ff9f7905dfeed50000b0 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/59d9ff9f7905dfeed50000b0 | 7 kyu |
Create a function that takes a list of one or more non-negative integers, and arranges them such that they form the largest possible number.
Examples:
`largestArrangement([4, 50, 8, 145])` returns 8504145 (8-50-4-145)
`largestArrangement([4, 40, 7])` returns 7440 (7-4-40)
`largestArrangement([4, 46, 7])` returns 74... | reference | from functools import cmp_to_key
def cmp(a, b): return int('%i%i' % (b, a)) - int('%i%i' % (a, b))
def largest_arrangement(n): return int('' . join(str(i)
for i in sorted(n, key=cmp_to_key(cmp))))
| Largest Number Arrangement | 59d902f627ee004281000160 | [
"Permutations",
"Fundamentals"
] | https://www.codewars.com/kata/59d902f627ee004281000160 | 6 kyu |
Alex is a devoted fan of snooker Masters and in particular, he recorded results of all matches. Help Alex to know the score of matches.
<i>Hint:</i><br>
A string with a score presented as follows: <b>"24-79(72); 16-101(53); ..."</b><br>
"24" - Points scored the first player;<br>
"79" - the number of points of the seco... | algorithms | import re
def frame(score):
frames = [0, 0]
for s1, _, s2 in re . findall(r'(\d+)(\([\d,]+\))?-(\d+)', score):
frames[int(s1) < int(s2)] += 1
return frames
| Alex & snooker: scores. | 58b28e5830473070e5000007 | [
"Statistics",
"Arrays",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/58b28e5830473070e5000007 | 6 kyu |
We have the following sequence:
```python
f(0) = 0
f(1) = 1
f(2) = 1
f(3) = 2
f(4) = 4;
f(n) = f(n-1) + f(n-2) - f(n-3) + f(n-4) - f(n-5);
```
The first term of the sequence that has its last nine digits forms a prime number is the value, 8480150779 (total of 10 digits), and corresponds to the 92-th term, because 48015... | reference | from gmpy2 import is_prime
def k_thlastDigPrime(k):
result = [0, 1, 1, 2, 4, 6, 8, 11, 15, 20, 26, 34, 44, 57, 73, 94, 120, 154, 196, 251, 319, 408, 518, 662, 840, 1073, 1361, 1738, 2204, 2814, 3568, 4555, 5775, 7372, 9346, 11930, 15124, 19305, 24473, 31238, 39600, 50546, 64076, 81787, 103679, 132336, 167758,... | Primes in the Last Digits of Huge Numbers | 55e61967663140aafb0001d6 | [
"Fundamentals",
"Mathematics",
"Algorithms",
"Data Structures"
] | https://www.codewars.com/kata/55e61967663140aafb0001d6 | 5 kyu |
## Task
You are given an array of positive integers. While the array has more than one element you can choose two elements and replace them with their sum or product.
Your task is to find the maximum possible number that can remain in the array after multiple such operations.
## Example
For `arr = [1, 3, 2]`, th... | games | import math
from collections import Counter
def sum_or_product(arr):
if len(arr) == 1:
return arr[0]
cs = Counter(arr)
while cs[1]:
cs[1] -= 1
m = int(cs[2] > 1) + \
1 if cs[1] > 0 else min(k for k in cs . keys() if k > 1)
cs[m] -= 1
cs[m + 1] += 1
return math . prod(x ... | Simple Fun #118: Sum Or Product | 589d581680458f695200008e | [
"Puzzles"
] | https://www.codewars.com/kata/589d581680458f695200008e | 5 kyu |
## Story
Eight men fell in love with a woman at the same time. Oh~~ A lucky woman and eight unfortunate men ;-). The 8 men are ready to fight a duel of life and death.
```
The names of eight men:
[
"Asda Btry","Csrt Dks","Gjhgj Hewr","Kewrwe Lhgj",
"Osdf Psde","Mretb Njhk","Isdf Jjhkhj","Eyui Ferd"
]
```
The duel ta... | games | from itertools import accumulate
from operator import add
def duel(people, guns):
p = [first_name[0] + last_name[0]
for first_name, last_name in map(str . split, people)]
initials = {initial: full_name for initial, full_name in zip(p, people)}
matrix = [(man, [(i + (guns . index(man) - k)... | T.T.T.53: Fighting for love! Knights of the round | 57c3a4431170a30b4e00017f | [
"Puzzles",
"Games"
] | https://www.codewars.com/kata/57c3a4431170a30b4e00017f | 6 kyu |
Quite recently it happened to me to join some recruitment interview, where my first task was to write own implementation of built-in split function. It's quite simple, is it not?
However, there were the following conditions:
* the function **cannot** use, in any way, the original `split` or `rsplit` functions,
* the ... | reference | import re
def my_very_own_split(string, delimiter=None):
if delimiter == '':
raise ValueError('empty delimiter')
if delimiter == None:
delimiter = '\s+'
else:
delimiter = re . escape(delimiter)
pos = 0
for m in re . finditer(delimiter, string):
yield string[... | My Very Own Python's Split Function | 55e0467217adf9c3690000f9 | [
"Strings"
] | https://www.codewars.com/kata/55e0467217adf9c3690000f9 | 5 kyu |
Math geeks and computer nerds love to anthropomorphize numbers and assign emotions and personalities to them. Thus there is defined the concept of a "happy" number. A happy number is defined as an integer in which the following sequence ends with the number 1.
* Start with the number itself.
* Calculate the sum of the... | algorithms | def is_happy(n):
seen = set()
while n not in seen:
seen . add(n)
n = sum(int(d) * * 2 for d in str(n))
return n == 1
def happy_numbers(n):
return [x for x in range(1, n + 1) if is_happy(x)]
| Happy Numbers | 59d53c3039c23b404200007e | [
"Recursion",
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/59d53c3039c23b404200007e | 6 kyu |
## Story
There are four warriors, they need to go through a dark tunnel. Tunnel is very narrow, every time only can let two warriors through, and there are lot of dangerous traps. Fortunately, they have a lamp that can illuminate the tunnel to avoid being trapped by the trap.
In order to pass this tunnel, they need f... | games | def shortest_time(speed):
a, b, c, d = sorted(speed)
return a + b + d + min(2 * b, a + c)
| T.T.T.51: Four warriors and a lamp | 57bff92049324c0fd00012fd | [
"Puzzles",
"Games"
] | https://www.codewars.com/kata/57bff92049324c0fd00012fd | 6 kyu |
## Description
In this kata, the problem is: Give you a range of number, Calculate the sum of the each digits. For example:
```
range:1-10
all numbers in the range is:12345678910
the sum of each digits is:1+2+3+4+5+6+7+8+9+1+0=46
range:1-20
all numbers in the range is:1234567891011121314151617181920
the sum of each ... | games | def sum_of_digits(a, b):
def f(n):
d, m, s = 0, 1, 0
while n:
n, r = divmod(n, 10)
s += r * 9 * d * 10 * * d / / 2 + r * (r - 1) / / 2 * 10 * * d + r * m
m += r * 10 * * d
d += 1
return s
return f(b) - f(max(a - 1, 0))
| T.T.T.38: The sum of each digits | 57b1f617b69bfc08cf00042a | [
"Puzzles",
"Games"
] | https://www.codewars.com/kata/57b1f617b69bfc08cf00042a | 5 kyu |
> ## Previous [Cartesian neighbors](https://www.codewars.com/kata/cartesian-neighbors) kata
In previous kata we have been searching for all the neighboring points in a Cartesian coordinate system. As we know each point in a coordinate system has eight neighboring points when we search it by range equal to 1, but now ... | reference | def cartesian_neighbors_distance(x, y, r):
return {(m * m + n * n) * * 0.5 for m in range(1, r + 1) for n in range(m + 1)}
| Cartesian neighbors distance | 59cd39a7a25c8c117d00020c | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/59cd39a7a25c8c117d00020c | 6 kyu |
This is the second part of this kata series. First part is [here](https://www.codewars.com/kata/simple-assembler-interpreter/).
We want to create an interpreter of assembler which will support the following instructions:
- ```mov x, y``` - copy y (either an integer or the value of a register) into register x.
- ```in... | refactoring | from operator import add, sub, mul, floordiv as div, lt, le, eq, ne, ge, gt
import re
TOKENIZER = re . compile(r"('.*?'|-?\w+)[:,]?\s*")
SKIP_COMMENTS = re . compile("\s*;")
SPLIT_PROG = re . compile(r'\n\s*')
CMP_FUNCS = {'jmp': lambda x, y: True, 'jne': ne,
'je': eq, 'jge': ge, 'jg': gt, 'jle': l... | Assembler interpreter (part II) | 58e61f3d8ff24f774400002c | [
"Interpreters",
"Refactoring"
] | https://www.codewars.com/kata/58e61f3d8ff24f774400002c | 2 kyu |
### Story
You have a list of domain names from a log file, indicating the number of times the computer accessed those sites. However, the list shows subdomains too, but you want to see only the main sites and the total number of accesses. For example `6.clients-channel.google.com` and `apis.google.com` should be count... | algorithms | import re
from collections import defaultdict
PATTERN = re . compile(r'([^.\n]+(\.com?)?\.\w*)\s+(\d+)')
def count_domains(domains, min_hits=0):
d_dct = defaultdict(int)
for k, _, v in PATTERN . findall(domains):
d_dct[k] += int(v)
sortedAndFilteredItems = sorted([it for it in d_dct . items(
... | Count the Domain Names | 595120ac5afb2e5c1d000001 | [
"Algorithms"
] | https://www.codewars.com/kata/595120ac5afb2e5c1d000001 | 5 kyu |
I will give you an integer (N) and a string. Break the string up into as many substrings of N as you can without spaces. If there are leftover characters, include those as well.
```javascript
Example:
N = 5;
String = "This is an example string";
Return value:
Thisi
sanex
ample
strin
g
Return value as a string: 'T... | reference | def string_breakers(n, st):
s = st . replace(' ', '')
return '\n' . join(s[i: i + n] for i in range(0, len(s), n))
| String Breakers | 59d398bb86a6fdf100000031 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/59d398bb86a6fdf100000031 | 6 kyu |
Each composed integer may have a prime factorization.
If n is the integer, it will be:
<a href="http://imgur.com/M5n0WCg"><img src="http://i.imgur.com/M5n0WCg.png?1" title="source: imgur.com" /></a>
and k1, k2, k3....., kn are the exponents corresponding to each prime in the factorization.
The radical of n, Rad(n), ... | reference | def hash_radSeq(n, k):
rads = [0] + [1] * n
for i in range(2, n + 1):
if rads[i] == 1:
for j in range(i, n + 1, i):
rads[j] *= i
return sorted((r, i) for i, r in enumerate(rads))[k][1]
| A Challenging Sequence. | 55e84ce709a1e37e420000df | [
"Algorithms",
"Data Structures",
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/55e84ce709a1e37e420000df | 5 kyu |
<strong>Introduction</strong>
<a href="https://en.wikipedia.org/wiki/Brainfuck">Brainfuck</a> is one of the most well-known esoteric programming languages. But it can be hard to understand any code longer that 5 characters. In this kata you have to solve that problem.
<strong>Description</strong>
In this kata you ha... | reference | import re
def brainfuck_to_c(source):
# remove comments
source = re . sub('[^+-<>,.\[\]]', '', source)
# remove redundant code
before = ''
while source != before:
before = source
source = re . sub('\+-|-\+|<>|><|\[\]', '', source)
# check braces status
braces = re .... | Brainfuck Translator | 58924f2ca8c628f21a0001a1 | [
"Esoteric Languages",
"Strings"
] | https://www.codewars.com/kata/58924f2ca8c628f21a0001a1 | 4 kyu |
In this Kata you will be playing <a href="https://en.wikipedia.org/wiki/Clock_Patience">Clock Patience</a> which is a single-player card game of chance requiring zero skill.
## Input
* ```cards``` a shuffled deck of 52 playing cards represented as a string array
* card values are ```A```,```2```,```3```,```4```,```5... | algorithms | def patience(cards):
clock, h = [cards[i:: 13] for i in range(13)], 13 - 1
while len(clock[h]):
h = ['A', '2', '3', '4', '5', '6', '7', '8', '9',
'10', 'J', 'Q', 'K']. index(clock[h]. pop())
return sum(len(h) for h in clock)
| Clock Patience | 58e8f020fd89eaa1cf0000c2 | [
"Algorithms"
] | https://www.codewars.com/kata/58e8f020fd89eaa1cf0000c2 | 6 kyu |
### Description
[Do you know Collatz conjecture? Click here, You can read some details..](https://en.wikipedia.org/wiki/Collatz_conjecture)
Given the following algorithm (Collatz conjecture):
```
If number x is even, x = x / 2
else if x is odd, x = x * 3 + 1
```
Find all the possible numbers(x) which resolve to... | games | def reversal_collatz(step, y):
bag = {y}
for _ in range(step):
bag = {z for x in bag for z in [2 * x] + [(x - 1) / / 3] * (x % 6 == 4)}
return sorted(bag)
| T.T.T.37: Reversal of Collatz | 57b1d750b69bfcf231000204 | [
"Puzzles",
"Games"
] | https://www.codewars.com/kata/57b1d750b69bfcf231000204 | 6 kyu |
Convert a number to a binary coded decimal (BCD).
You can assume input will always be an integer. If it is a negative number then simply place a minus sign in front of the output string. Output will be a string with each digit of the input represented as 4 bits (0 padded) with a space between each set of 4 bits.
Ex.
... | algorithms | def to_bcd(n):
return '-' * (n < 0) + ' ' . join(bin(x)[2:]. zfill(4) for x in map(int, str(abs(n))))
| Binary Coded Decimal | 5521d84b95c172461d0000a4 | [
"Algorithms"
] | https://www.codewars.com/kata/5521d84b95c172461d0000a4 | 6 kyu |
In Western music, a major chord (major third) starts at a root note and adds the note 4 semitones and 7 semitones above it.
A minor chord (minor third) starts at a root note and adds the note 3 semitones and 7 semitones above it.
Given a root note `root`, please return an array of the major chord and the minor chord ... | reference | notes = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
def chords(root):
index = notes . index(root)
major = [notes[index], notes[(index + 4) % 12], notes[(index + 7) % 12]]
minor = [notes[index], notes[(index + 3) % 12], notes[(index + 7) % 12]]
return [major, minor]
| Chords | 59d2fc6c23dacca182000068 | [
"Fundamentals"
] | https://www.codewars.com/kata/59d2fc6c23dacca182000068 | 7 kyu |
Given a string as input, move all of its vowels to the end of the string, in the same order as they were before.
Vowels are (in this kata): `a, e, i, o, u`
Note: all provided input strings are lowercase.
## Examples
```python
"day" ==> "dya"
"apple" ==> "pplae"
``` | reference | def move_vowels(s):
return '' . join(sorted(s, key=lambda k: k in 'aeiou'))
| Move all vowels | 56bf3287b5106eb10f000899 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/56bf3287b5106eb10f000899 | 7 kyu |
In his publication *Liber Abaci* Leonardo Bonacci, aka Fibonacci, posed a problem involving a population of idealized rabbits. These rabbits bred at a fixed rate, matured over the course of one month, had unlimited resources, and were immortal.
Create a function that determines the number of pairs of mature rabbits af... | algorithms | def fib_rabbits(n, b):
x, y = 0, 1
for i in range(n):
x, y = y, y + b * x
return x
| Fibonacci Rabbits | 5559e4e4bbb3925164000125 | [
"Algorithms"
] | https://www.codewars.com/kata/5559e4e4bbb3925164000125 | 6 kyu |
# Introduction
Take a list of `n` numbers `a1, a2, a3, ..., aN` to start with.
**Arithmetic mean** (or average) is the sum of these numbers divided by `n`.
**Geometric mean** (or average) is the product of these numbers taken to the `n`th root.
### Example
List of numbers: `1, 3, 9, 27, 81`
- `n = 5`
- Arithmetic... | algorithms | from functools import reduce
from operator import mul
def geo_mean(nums, mean):
nums . append(mean * (len(nums) + 1) - sum(nums))
return reduce(mul, nums) * * (1 / len(nums))
| Mean Means | 57c6b44f58da9ea6c20003da | [
"Mathematics",
"Algorithms",
"Algebra"
] | https://www.codewars.com/kata/57c6b44f58da9ea6c20003da | 7 kyu |
Your task is to write a function, which takes two arguments and returns a sequence. First argument is a sequence of values, second is multiplier. The function should filter all non-numeric values and multiply the rest by given multiplier. | algorithms | def multiply_and_filter(seq, multiplier):
return [num * multiplier for num in seq if type(num) in (int, float)]
| Multiply array values and filter non-numeric | 55ed875819ae85ca8b00005c | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/55ed875819ae85ca8b00005c | 7 kyu |
Check that a number is a valid number that has been given to 2 decimal places. The number passed to the function will be given as a string. If the number satisfies the criteria below, the function should return true, else it should return false.
Please check the criteria for a valid number:
optional + or - symbol... | reference | import re
def valid_number(input_str):
return re . match(r"""
[+-]? # optional +/- sign
\d* # optional digits
\. # decimal point
\d\d # two digits
$ # end of string
""", input_str, re . VERBOSE) is not None
| Valid number to 2 decimal places | 55f9064161541a9e01000001 | [
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/55f9064161541a9e01000001 | 7 kyu |
A very passive-aggressive co-worker of yours was just fired. While he was gathering his things, he quickly inserted a bug into your system which renamed everything to what looks like jibberish. He left two notes on his desk, one reads: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" while the other reads: "Uif u... | games | alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
correct = 'ZABCDEFGHIJKLMNOPQRSTUVWXYzabcdefghijklmnopqrstuvwxy'
def one_down(txt):
return "Input is not a string" if type(txt) != str else txt . translate(str . maketrans(alpha, correct))
| One down | 56419475931903e9d1000087 | [
"Strings",
"Algorithms",
"Cryptography",
"Puzzles"
] | https://www.codewars.com/kata/56419475931903e9d1000087 | 6 kyu |
Oh no! You have stumbled upon a mysterious signal consisting of beeps of various lengths, and it is of utmost importance that you find out the secret message hidden in the beeps. There are long and short beeps, the longer ones roughly three times as long as the shorter ones. Hmm... that sounds familiar.
That's righ... | algorithms | def decode(s):
return '' . join(TOME . get(w, ' ') for w in s . split(' ')) if s else ''
| Decode Morse | 54b0306c56f22d0bf9000ffb | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/54b0306c56f22d0bf9000ffb | 6 kyu |
Write a function that takes a string and returns an array of the repeated characters (letters, numbers, whitespace) in the string.
If a charater is repeated more than once, only show it once in the result array.
Characters should be shown **by the order of their first repetition**. Note that this may be different fro... | algorithms | def remember(str_):
seen = set()
res = []
for i in str_:
res . append(i) if i in seen and i not in res else seen . add(i)
return res
| Remember | 55a243393fb3e87021000198 | [
"Logic",
"Strings",
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/55a243393fb3e87021000198 | 6 kyu |
In this kata you must take an input string, reverse the order of the words, and reverse the order of the letters within the words.
But, as a bonus, every test input will end with a punctuation mark (! ? .) and the output should be returned with the mark at the end.
A few examples should help clarify:
```python
esrev... | reference | def esrever(s):
return s[: - 1][:: - 1] + s[- 1] if s else ''
| esrever esreveR! | 57e0206335e198f82b00001d | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/57e0206335e198f82b00001d | 7 kyu |
Array Exchange and Reversing
It's time for some array exchange! The objective is simple: exchange the elements of two arrays in-place in a way that their new content is also reversed.
```ruby
# before
my_array = ['a', 'b', 'c']
other_array = [1, 2, 3]
my_array.exchange_with!(other_array)
# after
my_array == [3, 2, ... | reference | def exchange_with(a, b):
a[:], b[:] = b[:: - 1], a[:: - 1]
| Array Exchange | 5353212e5ee40d4694001114 | [
"Arrays",
"Algorithms",
"Fundamentals"
] | https://www.codewars.com/kata/5353212e5ee40d4694001114 | 6 kyu |
# Your task should you chose to accept...
Build a deck of playing cards by generating 52 strings representing cards. There are no jokers.
Each card string will have the format of:
```
"ace of hearts"
"ace of spades"
"ace of diamonds"
"ace of clubs"
```
And will consist of the following ranks:
```
ace two three four ... | reference | def deck_of_cards(): return [card + " of " + suit for card in ["ace", "two", "three", "four", "five", "six",
"seven", "eight", "nine", "ten", "jack", "queen", "king"] for suit in ["hearts", "spades", "diamonds", "clubs"]]
| A functional deck of cards.... | 535742c7e727388cdc000297 | [
"Functional Programming",
"Fundamentals"
] | https://www.codewars.com/kata/535742c7e727388cdc000297 | 6 kyu |
The Menger Sponge is a three-dimensional fractal, first described by Karl Menger in 1926.

###### _An illustration of the iterative construction of a Menger sponge_
A method of constructing a Menger Sponge can be visualized as follows:
1. Start from a cube ... | algorithms | def calc_ms(n):
return 20 * * n
| Count cubes in a Menger Sponge | 59d28768a25c8c51a6000057 | [
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/59d28768a25c8c51a6000057 | 7 kyu |
##### _This kata is inspired by [davazp's one](https://www.codewars.com/kata/break-the-pieces)_
<hr>
## Context
So, here we go again:
You are given an ASCII diagram, containing minus signs `"-"`, plus signs `"+"`, vertical bars `"|"` and whitespaces `" " `. Your task is to write a function which will break the di... | games | USE_BREAK_DISPLAY = True
def v(c): return {(c[0] + 1, c[1]), (c[0] - 1, c[1])}
def h(c): return {(c[0], c[1] + 1), (c[0], c[1] - 1)}
def neig(c): return {(c[0] + 1, c[1]), (c[0] - 1, c[1]),
(c[0], c[1] + 1), (c[0], c[1] - 1)}
def neig2(c): return {(c[0] + i, c[1] + j)
... | Break the pieces (Evilized Edition) | 591f3a2a6368b6658800020e | [
"Games",
"Algorithms",
"Puzzles"
] | https://www.codewars.com/kata/591f3a2a6368b6658800020e | 1 kyu |
## Check Digits
Some numbers are more important to get right during data entry than others: a common example is product codes.
To reduce the possibility of mistakes, product codes can be crafted in such a way that simple errors are detected. This is done by calculating a single-digit value based on the product number... | algorithms | from itertools import cycle
def add_check_digit(number):
fact = cycle([2, 3, 4, 5, 6, 7])
r = sum(int(c) * next(fact) for c in number[:: - 1]) % 11
return number + ('0' if not r else 'X' if r == 1 else str(11 - r))
| Modulus 11 - Check Digit | 568d1ee43ee6afb3ad00001d | [
"Algorithms"
] | https://www.codewars.com/kata/568d1ee43ee6afb3ad00001d | 6 kyu |
_This is the performance verison of [KenKamau](https://www.codewars.com/users/KenKamau)'s kata: "__[Unique digit sequence](https://www.codewars.com/kata/599688d0e2800dda4e0001b0)__". If you did not complete it yet, you should begin there._
<hr>
<br>
<h1>Sequence detail:</h1>
Consider a serie that has the following se... | refactoring | from itertools import combinations, count
from string import digits
def digitalize(n): return frozenset(str(n))
seq, used = [0], {0}
def filter_gen(forbidden_digits):
for n in count():
if not (n in used or
digitalize(n) & forbidden_digits):
yield n
gens = {c: filter_gen(... | Unique digit sequence II - Optimization problem | 599846fbc2bd3a62a4000031 | [
"Memoization",
"Refactoring",
"Algorithms"
] | https://www.codewars.com/kata/599846fbc2bd3a62a4000031 | 3 kyu |
### Task
Your goal is to find two numbers(`>= 0`), the greatest common divisor of which is `divisor` and the number of iterations taken by Euclid's algorithm is `iterations`.
### Euclid's GCD
```cs
BigInteger FindGCD(BigInteger a, BigInteger b) {
// Swapping `a` and `b`
if (a < b)
{
var tmp = a;
a = b;... | algorithms | def find_initial_numbers(divisor, iterations):
if not iterations:
return divisor, 0
a, b = divisor, divisor
for _ in range(iterations):
a, b = a + b, a
return a, b
| Reversing Euclid's GCD. Parameters out of results | 58cd7f6914e656400100005a | [
"Algorithms"
] | https://www.codewars.com/kata/58cd7f6914e656400100005a | 6 kyu |
If we alternate the vowels and consonants in the string `"have"`, we get the following list, arranged alphabetically:
`['ahev', 'aveh', 'ehav', 'evah', 'have', 'heva', 'vahe', 'veha']`. These are the only possibilities in which vowels and consonants are alternated. The first element, `ahev`, is alphabetically lowest.
... | algorithms | def solve(s):
vowels = sorted(c for c in s if c in "aeiou")
consonants = sorted(c for c in s if c not in "aeiou")
part1, part2 = sorted((vowels, consonants), key=len, reverse=True)
part2 . append('')
if len(part1) > len(part2):
return "failed"
return "" . join(a + b for a, b in zip(pa... | Vowel-consonant lexicon | 59cf8bed1a68b75ffb000026 | [
"Strings",
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/59cf8bed1a68b75ffb000026 | 6 kyu |
Given a string, capitalize the letters that occupy even indexes and odd indexes separately, and return as shown below. Index `0` will be considered even.
For example, `capitalize("abcdef") = ['AbCdEf', 'aBcDeF']`. See test cases for more examples.
The input will be a lowercase string with no spaces.
Good luck!
If y... | reference | def capitalize(s):
s = '' . join(c if i % 2 else c . upper() for i, c in enumerate(s))
return [s, s . swapcase()]
| Alternate capitalization | 59cfc000aeb2844d16000075 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/59cfc000aeb2844d16000075 | 7 kyu |
Given a string and an array of integers representing indices, capitalize all letters at the given indices.
For example:
* `capitalize("abcdef",[1,2,5]) = "aBCdeF"`
* `capitalize("abcdef",[1,2,5,100]) = "aBCdeF"`. There is no index 100.
The input will be a lowercase string with no spaces and an array of digits.
Goo... | reference | def capitalize(s, ind):
ind = set(ind)
return '' . join(c . upper() if i in ind else c for i, c in enumerate(s))
| Indexed capitalization | 59cfc09a86a6fdf6df0000f1 | [
"Fundamentals"
] | https://www.codewars.com/kata/59cfc09a86a6fdf6df0000f1 | 7 kyu |
It involves implementing a program that sums the digits of a non-negative integer. For example, the sum of 3433 digits is 13.
```if:javascript
Digits can be a number, a string, or undefined. In case of `undefined` return an empty string `''`.
```
```if:python
Digits can be a number, a string, or `None`. In case of `N... | reference | def sum_of_digits(digits):
d = str(digits)
return "" if digits is None else f' { " + " . join ( x for x in d )} = { sum ( map ( int , d ))} '
| Sum of digits | 59cf805aaeb28438fe00001c | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/59cf805aaeb28438fe00001c | 7 kyu |
Define a function that generates medial values between two coordinates and returns them in an array from start to target.
For example, if the starting point is `[1,1]` and the target point is `[3,2]` then the shortest route from start to target would be `[[1,1], [2,2], [3,2]]`. The route should go only through integral... | reference | def tick_toward(start, target):
(x, y), (tx, ty), path = start, target, [start]
while (x, y) != target:
x = x + (1 if x < tx else - 1 if tx < x else 0)
y = y + (1 if y < ty else - 1 if ty < y else 0)
path . append((x, y))
return path
| Tick Toward | 54bd06539f075cece0000feb | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/54bd06539f075cece0000feb | 6 kyu |
You're given a mystery `puzzlebox` object. Examine it to make the tests pass and solve this kata. | games | def answer(puzzlebox):
return 42
| Thinkful - Object Drills: Puzzlebox | 587f0871f297a6df780000cd | [
"Puzzles"
] | https://www.codewars.com/kata/587f0871f297a6df780000cd | 6 kyu |
You are given a list of directions in the form of a list:
goal = ["N", "S", "E", "W"]
Pretend that each direction counts for 1 step in that particular direction.
Your task is to create a function called directions, that will return a reduced list that will get you to the same point.The order of directions must be re... | reference | def directions(goal):
y = goal . count("N") - goal . count("S")
x = goal . count("E") - goal . count("W")
return ["N"] * y + ["S"] * (- y) + ["E"] * x + ["W"] * (- x)
| Shorter Path | 56a14f18005af7002f00003f | [
"Fundamentals"
] | https://www.codewars.com/kata/56a14f18005af7002f00003f | 6 kyu |
<h3 style='color:#ffffaa'>Task:</h3>
<p style='color:#ffff00'>Make a function that converts a word to pig latin. The rules of pig latin are:</p>
```
If the word has more than 3 letters:
1. Take the first letter of a word and move it to the end
2. Add -ay to the word
Otherwise leave the word alone.
```
Example: `h... | reference | def pig_latin(word):
return word[1:] + word[0] + 'ay' if len(word) > 3 else word
| Pig Atinlay | 58702c0ca44cfc50dc000245 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/58702c0ca44cfc50dc000245 | 7 kyu |
You're putting together contact information for all the users of your website to ship them a small gift. You queried your database and got back a list of users, where each user is another list with up to two items: a string representing the user's name and their shipping zip code. Example data might look like:
```pyth... | reference | def user_contacts(data):
return {contact[0]: contact[1] if len(contact) > 1 else None
for contact in data}
| Thinkful - Dictionary Drills: User contacts | 586f61bdfd53c6cce50004ee | [
"Fundamentals"
] | https://www.codewars.com/kata/586f61bdfd53c6cce50004ee | 7 kyu |
You're running an online business and a big part of your day is fulfilling orders. As your volume picks up that's been taking more of your time, and unfortunately lately you've been running into situations where you take an order but can't fulfill it.
You've decided to write a function `fillable()` that takes three ar... | reference | def fillable(stock, merch, n):
return stock . get(merch, 0) >= n
| Thinkful - Dictionary drills: Order filler | 586ee462d0982081bf001f07 | [
"Fundamentals"
] | https://www.codewars.com/kata/586ee462d0982081bf001f07 | 8 kyu |
The goal of this Kata is to remind/show you, how Z-algorithm works and test your implementation.
For a string str[0..n-1], Z array is of same length as string. An element Z[i] of Z array stores length of the longest substring starting from str[i] which is also a prefix of str[0..n-1]. The first entry of Z array is mea... | algorithms | def prefix1(a, b):
cnt = 0
for i, j in zip(a, b):
if i == j:
cnt += 1
else:
return cnt
return cnt
def prefix2(a, b, num):
for i in range(num, - 1, - 1):
if b . startswith(a[: i]):
return i
def zfunc(str_):
z = []
k = len(str_)
for i in range(len... | Z-algorithm | 56d30dadc554829d55000578 | [
"Algorithms"
] | https://www.codewars.com/kata/56d30dadc554829d55000578 | 5 kyu |
We know the formula to find the solutions of an equation of second degree with only one variable:
<a href="http://imgur.com/jXO5HA9"><img src="http://i.imgur.com/jXO5HA9.jpg?1" title="source: imgur.com" /></a>
We need the function ```sec_deg_solver()/secDegSolver()```, that accepts three arguments, ```a```, ```b``` a... | reference | from math import sqrt
MSG = {
# a == 0
0: "It is a first degree equation. Solution: {}", # b != 0 and c != 0
1: "The equation is indeterminate", # b == 0 and c == 0
2: "Impossible situation. Wrong entries", # b == 0 and c != 0
3: "It is a first degree equation. Solution: 0.0", # b != 0 and... | One Variable Second Degree Equation Solver | 560ae2027dc9033b5e0000c2 | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/560ae2027dc9033b5e0000c2 | 6 kyu |
Given an array of numbers, return the difference between the largest and smallest values.
For example:
`[23, 3, 19, 21, 16]` should return `20` (i.e., `23 - 3`).
`[1, 434, 555, 34, 112]` should return `554` (i.e., `555 - 1`).
The array will contain a minimum of two elements. Input data range guarantees that `max-m... | algorithms | def between_extremes(numbers):
return max(numbers) - min(numbers)
| Between Extremes | 56d19b2ac05aed1a20000430 | [
"Algorithms",
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/56d19b2ac05aed1a20000430 | 7 kyu |
How sexy is your name?
Write a program that calculates how sexy one's name is according to the criteria below.
There is a preloaded dictionary of letter scores called `SCORES`(Python & JavaScript) / `$SCORES` (Ruby). Add up the letters (case-insensitive) in your name to get your sexy score. Ignore other characters.
... | reference | def sexy_name(name):
name_score = sum(SCORES . get(a, 0) for a in name . upper())
if name_score >= 600:
return 'THE ULTIMATE SEXIEST'
elif name_score >= 301:
return 'VERY SEXY'
elif name_score >= 61:
return 'PRETTY SEXY'
return 'NOT TOO SEXY'
| How sexy is your name? | 571b2ee08d8c9c0d160014ec | [
"Fundamentals"
] | https://www.codewars.com/kata/571b2ee08d8c9c0d160014ec | 7 kyu |
The Monty Hall problem is a probability puzzle base on the American TV show "Let's Make A Deal".
In this show, you would be presented with 3 doors: One with a prize behind it, and two without (represented with goats).
After choosing a door, the host would open one of the other two doors which didn't include a prize, ... | reference | def monty_hall(door, guesses):
return round(100.0 * (len(guesses) - guesses . count(door)) / len(guesses))
| Monty Hall Problem | 54f9cba3c417224c63000872 | [
"Fundamentals"
] | https://www.codewars.com/kata/54f9cba3c417224c63000872 | 7 kyu |
As a member of the editorial board of the prestigous scientific Journal _Proceedings of the National Academy of Sciences_, you've decided to go back and review how well old articles you've published stand up to modern publication best practices. Specifically, you'd like to re-evaluate old findings in light of recent li... | reference | def categorize_study(p_value, requirements):
study_value = p_value * (2 * * (6 - requirements))
if study_value < 0.05 and requirements != 0:
return "Fine"
elif study_value < 0.05 and requirements == 0:
return "Needs review"
elif study_value > 0.05 and study_value < 0.15:
return "Nee... | Thinkful - Logic Drills: Hacking p-hackers | 5864af6739c5ab26e80000bf | [
"Fundamentals"
] | https://www.codewars.com/kata/5864af6739c5ab26e80000bf | 7 kyu |
Old Greg likes to count his 31 fish on just one hand.
To do this he holds his right hand up, palm facing toward him, fist closed and then counts in binary using his fingers.
First he sticks his thumb out which makes 1, then just his index finger which makes 10 (decimal 2), then Index and thumb which makes 11 (decimal... | games | def binary_fingers(s): return [["Pinkie", "Ring", "Middle", "Index", "Thumb"][i]
for i, d in enumerate(s . zfill(5)) if int(d)]
| Old Greg's Binary Fingers | 565f1bd8f97d3e59c400014a | [
"Puzzles"
] | https://www.codewars.com/kata/565f1bd8f97d3e59c400014a | 7 kyu |
You're playing a game with a friend involving a bag of marbles. In the bag are ten marbles:
* 1 smooth red marble
* 4 bumpy red marbles
* 2 bumpy yellow marbles
* 1 smooth yellow marble
* 1 bumpy green marble
* 1 smooth green marble
You can see that the probability of picking a smooth red marble from the bag is `1 / ... | reference | def color_probability(color, texture):
marbles = {"smooth": {"red": 1, "yellow": 1, "green": 1, "total": 3},
"bumpy": {"red": 4, "yellow": 2, "green": 1, "total": 7}}
return "{}" . format(marbles[texture][color] / marbles[texture]["total"])[: 4]
| Thinkful - Logic Drills: Red and bumpy | 5864cdc483f7e6df980001c8 | [
"Fundamentals"
] | https://www.codewars.com/kata/5864cdc483f7e6df980001c8 | 6 kyu |
In your class, you have started lessons about [arithmetic progression](https://en.wikipedia.org/wiki/Arithmetic_progression). Since you are also a programmer, you have decided to write a function that will return the first `n` elements of the sequence with the given common difference `d` and first element `a`. Note tha... | reference | def arithmetic_sequence_elements(a, r, n):
return ", " . join((str(a + r * i) for i in range(n)))
| Arithmetic progression | 55caf1fd8063ddfa8e000018 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/55caf1fd8063ddfa8e000018 | 7 kyu |
Given two numbers `m` and `n`, such that `0 ≤ m ≤ n` :
- convert all numbers from `m` to `n` (inclusive) to binary
- sum them as if they were in base 10
- convert the result to binary
- return as a string
## Example
```javascript
1, 4 --> 1111010
because:
1 // 1 in binary is 1
+ 10 // 2 in binary is 10
+... | reference | def binary_pyramid(m, n):
return bin(sum(int(bin(i)[2:]) for i in range(m, n + 1)))[2:]
| Binary Pyramid 101 | 5596700a386158e3aa000011 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/5596700a386158e3aa000011 | 7 kyu |
# Task
You are given a string `s`. Your task is to count the number of each letter (A-Z), and make a vertical histogram as result. Look at the following examples to understand the rules.
# Example
For `s = "XXY YY ZZZ123ZZZ AAA BB C"`, the output should be:
```
*
*
*
* * *
* * *... | reference | from collections import Counter
def verticalHistogramOf(s):
def buildLine(h):
return ' ' . join(h and ' *' [cnts[k] >= h] or k for k in keys). rstrip()
cnts = Counter(filter(str . isupper, s))
keys = sorted(cnts)
m = max(cnts . values(), default=0)
return '\n' . join(map(buildLine... | Simple Fun #358: Vertical Histogram Of Letters | 59cf0ba5d751dffef300001f | [
"Fundamentals"
] | https://www.codewars.com/kata/59cf0ba5d751dffef300001f | 5 kyu |
Attention Agent.
The White House is currently developing a mobile app that it can use to issue instructions to its undercover agents.
Part of the functionality of this app is to have messages that can be read only once, and are then destroyed.
As our best undercover developer, we need you to implement a `SecureList`... | reference | class SecureList (list):
def __getitem__(self, key):
ret = list(self)[key]
del self[key]
return ret
def __repr__(self):
ret = list(self). __repr__()
del self[:]
return ret
def __str__(self):
ret = list(self). __str__()
del self[:]
return ret
| Only-Readable-Once list | 53f17f5b59c3fcd589000390 | [
"Lists"
] | https://www.codewars.com/kata/53f17f5b59c3fcd589000390 | 5 kyu |
One suggestion to build a satisfactory password is to start with a memorable phrase or sentence and make a password by extracting the first letter of each word.
Even better is to replace some of those letters with numbers (e.g., the letter `O` can be replaced with the number `0`):
* instead of including `i` or `I` p... | reference | SWAP = {'i': '1', 'I': '1', 'o': '0', 'O': '0', 's': '5', 'S': '5'}
def make_password(phrase):
return '' . join(SWAP . get(a[0], a[0]) for a in phrase . split())
| Password maker | 5637b03c6be7e01d99000046 | [
"Strings",
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/5637b03c6be7e01d99000046 | 7 kyu |
The prime number sequence starts with: `2,3,5,7,11,13,17,19...`. Notice that `2` is in position `one`.
`3` occupies position `two`, which is a prime-numbered position. Similarly, `5`, `11` and `17` also occupy prime-numbered positions. We shall call primes such as `3,5,11,17` dominant primes because they occupy prime... | reference | n = 500000
sieve, PRIMES = [0] * (n / / 2 + 1), [0, 2]
for i in range(3, n + 1, 2):
if not sieve[i / / 2]:
PRIMES . append(i)
for j in range(i * * 2, n + 1, i * 2):
sieve[j / / 2] = 1
DOMINANTS = []
for p in PRIMES:
if p >= len(PRIMES):
break
DOMINANTS . append(PRI... | Dominant primes | 59ce11ea9f0cbc8a390000ed | [
"Fundamentals"
] | https://www.codewars.com/kata/59ce11ea9f0cbc8a390000ed | 6 kyu |
# Problem
In China,there is an ancient mathematical book, called "The Mathematical Classic of Sun Zi"(《孙子算经》). In the book, there is a classic math problem: “今有物不知其数,三三数之剩二,五五数之剩三,七七数之剩二,问物几何?”
Ahh, Sorry. I forgot that you don't know Chinese. Let's translate it to English:
There is a unkown positive integer `n`. W... | algorithms | def find_unknown_number(x, y, z):
return (x * 70 + y * 21 + z * 15) % 105 or 105
| Algorithm Fun: Find The Unknown Number - Part I | 59cdb2b3a25c8c6d56000005 | [
"Algorithms"
] | https://www.codewars.com/kata/59cdb2b3a25c8c6d56000005 | 7 kyu |
### Buddy pairs
You know what divisors of a number are. The divisors of a positive integer `n` are said to be `proper` when you consider only the divisors other than `n` itself. In the following description, divisors will mean `proper` divisors. For example for `100` they are `1, 2, 4, 5, 10, 20, 25, and 50`.
Let `... | reference | def div_sum(n):
divs = set()
for x in range(2, int(n * * 0.5) + 1):
if n % x == 0:
divs . add(x)
divs . add(n / / x)
return sum(divs)
def buddy(start, limit):
for n in range(start, limit + 1):
buddy = div_sum(n)
if buddy > n and div_sum(buddy) == n:
return [n, ... | Buddy Pairs | 59ccf051dcc4050f7800008f | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/59ccf051dcc4050f7800008f | 5 kyu |
Transpose means is to interchange rows and columns of a two-dimensional array matrix.
[A<sup>T</sup>]<sub>ij</sub>=[A]<sub>ji</sub>
ie:
Formally, the i th row, j th column element of AT is the j th row, i th column element of A:
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Matrix_transpose.gif... | reference | def transpose(arr):
return [list(i) for i in zip(* arr)]
| Transpose of a Matrix | 559656796d8fb52e17000003 | [
"Linear Algebra",
"Matrix",
"Data Structures",
"Mathematics",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/559656796d8fb52e17000003 | 6 kyu |
Julie is x years older than her brother, and she is also y times as old as him.
Given x and y calculate Julie's age using the function age(x, y).
For example:
```javascript
Age(6, 3) // returns 9
```
```coffeescript
age 6, 3 # returns 9
```
```python
age(6, 3) #returns 9
```
Note also that x can be negative, and y ca... | algorithms | def age(x, y):
return (x * y) / (y - 1)
| Calculate Julie's Age | 558445a88826e1376b000011 | [
"Algebra",
"Algorithms"
] | https://www.codewars.com/kata/558445a88826e1376b000011 | 7 kyu |
Given a string, return true if the first instance of "x" in the string is immediately followed by the string "xx".
```
"abraxxxas" → true
"xoxotrololololololoxxx" → false
"softX kitty, warm kitty, xxxxx" → true
"softx kitty, warm kitty, xxxxx" → false
```
Note :
- capital X's do not count as an occurrence of "x".
... | reference | def triple_x(s: str) - > bool:
return 0 <= s . find("x") == s . find("xxx")
| L2: Triple X | 568dc69683322417eb00002c | [
"Strings",
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/568dc69683322417eb00002c | 7 kyu |
# Escape the room
You are creating an "Escape the room" game. The first step is to create a hash table called `rooms` that contains all of the rooms of the game. There should be at least 3 rooms inside it, each being a hash table with at least three properties (e.g. `name`, `description`, `completed`). | reference | rooms = {"Room_1": {"Guest_Name": "Hardik", "Room_Number": "69", "Hotel": "Royal Inn"},
"Room_2": {"Guest_Name": "Hridhik", "Room_Number": "369", "Hotel": "Sandesh The Prince"},
"Room_3": {"Guest_Name": "Pratham", "Room_Number": "96", "Hotel": "The Quorum"},
"Room_4": {"Guest_Name": "Rutur... | Grasshopper - Create the rooms | 56a29b237e9e997ff2000048 | [
"Fundamentals"
] | https://www.codewars.com/kata/56a29b237e9e997ff2000048 | 8 kyu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.