description stringlengths 38 154k | category stringclasses 5
values | solutions stringlengths 13 289k | name stringlengths 3 179 | id stringlengths 24 24 | tags listlengths 0 13 | url stringlengths 54 54 | rank_name stringclasses 8
values |
|---|---|---|---|---|---|---|---|
Another Fibonacci... yes but with other kinds of result.
The function is named `aroundFib` or `around_fib`, depending of the language.
Its parameter is `n` (positive integer).
First you have to calculate `f` the value of `fibonacci(n)` with `fibonacci(0) --> 0` and
`fibonacci(1) --> 1` (see: <https://en.wikipedia.org/... | reference | def around_fib(n):
a, b = 0, 1
for i in range(n - 1):
a, b = b, a + b
fib = str(b)
lst = len(fib) % 25
if lst == 0:
lst = 25
maxcnt = 0
digit = - 1
for i in '0123456789':
c = fib . count(i)
if c > maxcnt:
maxcnt = c
digit = i
return "Last chunk {}; Max is ... | Around Fibonacci: chunks and counts | 59bf943cafcda28e31000130 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/59bf943cafcda28e31000130 | 5 kyu |
Given a certain number, how many multiples of three could you obtain with its digits?
Suposse that you have the number 362. The numbers that can be generated from it are:
```
362 ----> 3, 6, 2, 36, 63, 62, 26, 32, 23, 236, 263, 326, 362, 623, 632
```
But only:
```3, 6, 36, 63``` are multiple of three.
We need a fun... | reference | from itertools import permutations
def find_mult_3(num):
num_list = tuple(map(int, str(num)))
poss = set()
for i in range(1, len(num_list) + 1):
poss |= set(permutations(num_list, i))
res = set()
for p in poss:
if p[0] != 0 and sum(p) % 3 == 0:
res . add(p)
res = ... | Find All the Possible Numbers Multiple of 3 with the Digits of a Positive Integer. | 5828b9455421a4a4e8000007 | [
"Fundamentals",
"Data Structures",
"Algorithms",
"Mathematics",
"Logic",
"Strings",
"Permutations"
] | https://www.codewars.com/kata/5828b9455421a4a4e8000007 | 5 kyu |
Given a string, remove any characters that are unique from the string.
Example:
input: "abccdefee"
output: "cceee"
| algorithms | def only_duplicates(string):
return "" . join([x for x in string if string . count(x) > 1])
| Only Duplicates | 5a1dc4baffe75f270200006b | [
"Fundamentals",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5a1dc4baffe75f270200006b | 6 kyu |
# Task
Given a person, trace their ancestory and create a <a href=https://en.wikipedia.org/wiki/Pedigree_chart>Pedigree Chart</a>
Return the chart as a string.
# Example
Pedigree Chart for: XXXXX
```
|16 _______
|08 _______
... | algorithms | from itertools import islice
from collections import deque
result = (
" |16 {15}\n" +
" |08 {7}\n" +
" | |17 {16}\n" +
" |04 {3}\n" +
" | | |18 {17}\n" +
" | |09 {8}\n" +
" | |19 {18}\n" +
" |02 {1}\n" +
" | | |20 {19}\n" +
" | | |10 {9}\n" +
" | | | |21 {20}\n" +
" | |05... | Family Tree - Ancestors | 5871690ba44cfc0834000303 | [
"Algorithms"
] | https://www.codewars.com/kata/5871690ba44cfc0834000303 | 5 kyu |
For this kata, we're given an image in which some object of interest (e.g. a face, or a license plate, or an aircraft) appears as a large block of contiguous pixels all of the same colour. (Probably some image-processing has already occurred to achieve this, but we needn't worry about that.) We want to find the **centr... | reference | class Central_Pixels_Finder (Image):
def central_pixels(self, colour):
size = self . width * self . height
depths = [0] * size
internal = []
for position, pcolour in enumerate(self . pixels):
if pcolour == colour:
depths[position] = 1
if (position > self . width and
po... | Centre of attention | 58c8c723df10450b21000024 | [
"Algorithms",
"Arrays"
] | https://www.codewars.com/kata/58c8c723df10450b21000024 | 3 kyu |
<blockquote style="max-width:360px;min-width:200px;border-color:#777;background-color:#111;font-family:Georgia,Verdana,serif"><strong>“Do you bite your thumb at us, sir?”</strong><br/><p style="text-align:right;font-family:serif"><i>Romeo and Juliet</i> Act I: Sc. 1</p></blockquote>
<p>Prince Escalus and t... | algorithms | from decimal import Decimal
from math import ceil
DECI = Decimal(10)
def tug_of_war(n, arr):
n /= Decimal(2)
pos = fm = fc = elapsed = 0
f = 0
for c_m, t in ((c / DECI - m / DECI, t) for c, m, t in arr):
delta = f * t
if abs(pos + delta) >= n:
break
pos += delta
elapsed += t
f ... | Shakespearean Tug of War | 5a1a46ef80171fc2b0000064 | [
"Algorithms"
] | https://www.codewars.com/kata/5a1a46ef80171fc2b0000064 | 6 kyu |
Write a method that takes a number and returns a string of that number in English.
Your method should be able to handle any number between 0 and 99999. If the given number is outside of that range or not an integer, the method should return an empty string.
## Examples
```
0 --> "zero"
27 --> "twenty seven... | algorithms | def number_to_english(n):
z = '''zero one two three four five six seven eight nine ten eleven twelve
thirteen fourteen fifteen sixteen seventeen eighteen nineteen'''
D = {i: w for i, w in enumerate(z . split())}
for i, w in enumerate('twenty thirty forty fifty sixty seventy eighty ninety' . split(), 2... | Ninety Nine Thousand Nine Hundred Ninety Nine | 5463c8db865001c1710003b2 | [
"Strings",
"Parsing",
"Algorithms"
] | https://www.codewars.com/kata/5463c8db865001c1710003b2 | 5 kyu |
# Count distinct elements in every window of size k
Given an array of size `n`, and an integer `k`, return the count of distinct contiguous numbers for all windows of size `k`.
`k` will always be lower than or equal to `n`.
## Example
```
Input: array = {1, 2, 1, 3, 4, 2, 3}
k = 4
Since we have n = 7 and k ... | algorithms | from collections import Counter
def count_contiguous_distinct(k, arr):
counts = Counter(arr[: k])
distinct = len(counts)
windows = [distinct]
for i in range(k, len(arr)):
counts[arr[i - k]] -= 1
if not counts[arr[i - k]]:
distinct -= 1
if not counts[arr[i]]:
distinct +=... | Distinct contiguous elements in every window of size k | 5945f0c207693bc53100006b | [
"Arrays",
"Performance",
"Algorithms"
] | https://www.codewars.com/kata/5945f0c207693bc53100006b | 5 kyu |
When you were little, your mother used to make the most delicious cookies, which you could not resist. So, every now and then, when your mother didn't see you, you sneaked into the kitchen, climbed onto a stool to reach the cookie jar, and stole a cookie or two. However, sometimes while doing this, you would hear foot ... | reference | from contextlib import contextmanager
@ contextmanager
def SelfClosing(jar):
try:
jar . open_jar()
yield jar
finally:
jar . close_jar()
| Self-closing Cookie Jar | 583b33786e3994f54e000142 | [
"Object-oriented Programming",
"Fundamentals"
] | https://www.codewars.com/kata/583b33786e3994f54e000142 | 5 kyu |
Evaluate the given string with the given conditons.
The conditions will be passed in an array and will be formatted like this:
```
{symbol or digit}{comparison operator}{symbol or digit}
```
Return the results in an array.
The characters in the conditions will always be in the string. Characters in the string are ch... | algorithms | from collections import Counter
from operator import le, lt, ge, gt, eq, ne
def string_evaluation(s, conditions):
cnt = Counter(s)
ops = {'<=': le, '<': lt, '>=': ge, '>': gt, '==': eq, '!=': ne}
result = []
for condition in conditions:
left = condition[0]
right = condition[- 1]
... | String Evaluation | 57f548337763f20e02000114 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/57f548337763f20e02000114 | 6 kyu |
Your task is to validate rhythm with a meter.
_________________________________________________
Rules:
1. Rhythmic division requires that in one whole note (1) there are two half notes (2) or four quarter notes (4) or eight eighth notes (8).
<pre>Examples: 1 = 2 + 2, 1 = 4 + 4 + 4 + 4 ...
Note that: 2 = 4 + 4, 4 = ... | reference | from fractions import Fraction
VALID_CHARS = {"1", "2", "4", "8"}
def note_sum(s):
return sum(Fraction(1, x) for x in map(int, s))
def validate_rhythm(meter, score):
if meter[1] not in [1, 2, 4, 8]:
return "Invalid rhythm"
ss = score . split("|")
if not all(s and all(x in VALID_CHA... | #02 - Music Theory - Validate rhythm | 57091b473f1008c03f001a2a | [
"Logic",
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/57091b473f1008c03f001a2a | 6 kyu |
The task is very simple.
You must to return pyramids. Given a number ```n``` you print a pyramid with ```n``` floors
For example , given a ```n=4``` you must to print this pyramid:
```
/\
/ \
/ \
/______\
```
Other example, given a ```n=6``` you must to print this pyramid:
```
/\
/ \
... | games | def pyramid(n):
return '\n' . join("/{}\\" . format(" _" [r == n - 1] * r * 2). center(2 * n). rstrip() for r in range(n)) + '\n'
| Return pyramids | 5a1c28f9c9fc0ef2e900013b | [
"Strings",
"Algorithms",
"ASCII Art",
"Puzzles"
] | https://www.codewars.com/kata/5a1c28f9c9fc0ef2e900013b | 7 kyu |
In a game of chess, a queen is the most powerful piece on the board. She can move an unlimited number of squares in a straight line in any of 8 directions (forwards, backwards, left, right, and each of the four diagonals in between).
The diagram below shows the queen's influence from her current position - she would b... | reference | def check(board):
for x, line in enumerate(board):
for y, c in enumerate(line):
if c == 'q':
xq, yq = x, y
elif c == 'k':
xk, yk = x, y
return yk == yq or xk == xq or abs(xq - xk) == abs(yq - yk)
| Check by Queen | 5a1cae0832b8b99e2900000c | [
"Fundamentals"
] | https://www.codewars.com/kata/5a1cae0832b8b99e2900000c | 6 kyu |
You are given an array of integers. Your task is to sort odd numbers within the array in ascending order, and even numbers in descending order.
Note that zero is an even number. If you have an empty array, you need to return it.
For example:
```
[5, 3, 2, 8, 1, 4] --> [1, 3, 8, 4, 5, 2]
odd numbers ascending: [... | reference | def sort_array(xs):
es = sorted(x for x in xs if x % 2 == 0)
os = sorted((x for x in xs if x % 2 != 0), reverse=True)
return [(es if x % 2 == 0 else os). pop() for x in xs]
| Sort odd and even numbers in different order | 5a1cb5406975987dd9000028 | [
"Arrays",
"Fundamentals",
"Sorting"
] | https://www.codewars.com/kata/5a1cb5406975987dd9000028 | 6 kyu |
<h1>Happy traveller [Part 2]</h1>
<p>In the <a href="https://www.codewars.com/kata/happy-traveller-number-1">previous part</a> we calculated possible ways to reach point <b>X</b>.</p>
<p>For this time you become a treasure hunter! On each step you can get the reward. But in some points you can meet robbers or thieves.... | algorithms | def count_cash(MAP, coords):
lenY, (r, c) = len(MAP), coords
s = [float("-inf")] * (len(MAP[0]) - c + 1)
s[1] = 0
for x in range(r, - 1, - 1):
for i in range(1, len(s)):
s[i] = max(s[i - 1], s[i]) + MAP[x][c + i - 1]
return s[- 1]
| Happy traveller [#2] | 586e2bc03f3675a4e70000e1 | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/586e2bc03f3675a4e70000e1 | 5 kyu |
Write a function generator that will generate the first `n` primes grouped in tuples of size `m`. If there are not enough primes for the last tuple it will have the remaining values as `None`.
## Examples
```python
For n = 11 and m = 2:
(2, 3), (5, 7), (11, 13), (17, 19), (23, 29), (31, None)
For n = 11 and m = 3:
... | reference | from gmpy2 import next_prime as np
def get_primes(h, g):
a = 2
while h > 0:
m, f = g, []
while m > 0:
a, f, m, h = np(a), f + [a] if h > 0 else f + [None], m - 1, h - 1
yield tuple(f)
| Group prime numbers | 593e8d839335005b42000097 | [
"Algorithms",
"Fundamentals"
] | https://www.codewars.com/kata/593e8d839335005b42000097 | 6 kyu |
### Story
You are a h4ck3r n00b: you "acquired" a bunch of password hashes, and you want to decypher them. Based on the length, you already guessed that they must be SHA-1 hashes. You also know that these are weak passwords: maximum 5 characters long and use only lowercase letters (`a-z`), no other characters.
Happy ... | algorithms | import hashlib
import itertools
def password_cracker(hash):
for length in range(6):
for candidate in map("" . join, itertools . product("abcdefghijklmnopqrstuvwxyz", repeat=length)):
if hashlib . sha1(candidate . encode()). hexdigest() == hash:
return candidate
| Real Password Cracker | 59146f7b4670ba520900000a | [
"Security",
"Cryptography",
"Algorithms"
] | https://www.codewars.com/kata/59146f7b4670ba520900000a | 6 kyu |
# Minesweeper
Write a program that adds the numbers to a minesweeper board
Minesweeper is a popular game where the user has to find the mines using
numeric hints that indicate how many mines are directly adjacent
(horizontally, vertically, diagonally) to a square.
In this exercise you have to create some code that c... | games | def board(inp):
return ["" . join([ret(i, k, z) for k, z in enumerate(j)]) for i, j in enumerate(inp)]
def ret(i, j, s):
if s in {"+", "-", "|", "*"}:
return s
t = sum(1 for m in range(j - 1, j + 2)
for l in range(i - 1, i + 2) if inp[l][m] == "*")
return str(t) if t else " ... | Minesweeper | 587b2ddb87264729e6000128 | [
"Algorithms",
"Puzzles"
] | https://www.codewars.com/kata/587b2ddb87264729e6000128 | 6 kyu |
Section numbers are strings of dot-separated integers. The highest level sections (chapters) are numbered 1, 2, 3, etc. Second level sections are numbered 1.1, 1.2, 1.3, 2.1, 2.2, 2.3, etc. Next level sections are numbered 1.1.1, 1.1.2, 1.1.2, 1.2.1, 1.2.2, erc. There is no bound on the number of sections a document ma... | reference | def compare(s1, s2):
v1, v2 = version(s1), version(s2)
return - 1 if v1 < v2 else 1 if v1 > v2 else 0
def version(s):
v = [int(n) for n in s . split(".")]
while (v[- 1] == 0):
v = v[0: - 1]
return v
| Compare section numbers | 5829c6fe7da141bbf000021b | [
"Strings",
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/5829c6fe7da141bbf000021b | 6 kyu |
Everyday we go to different places to get our things done. Those places can be represented by specific location points `[ [<lat>, <long>], ... ]` on a map. I will be giving you an array of arrays that contain coordinates of the different places I had been on a particular day. Your task will be to find `peripheries (out... | reference | def box(coords):
lat, long = zip(* coords)
return {"nw": [max(lat), min(long)], "se": [min(lat), max(long)]}
| Northwest and Southeast corners | 58ed139326f519019a000053 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/58ed139326f519019a000053 | 6 kyu |
The local transport authority is organizing an online picture contest.
Participants must take pictures of transport means in an original way, and then post the picture on Instagram using a specific ```hashtag```.
The local transport authority needs your help. They want you to take out the ```hashtag``` from the posted... | reference | def omit_hashtag(message, hashtag):
return message . replace(hashtag, "", 1)
| Picture Contest - Extract the message | 5a06238a80171f824300003c | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5a06238a80171f824300003c | 7 kyu |
Same as [the original](https://www.codewars.com/kata/simple-fun-number-258-is-divisible-by-6) (same rules, really, go there for example and I strongly recommend completing it first), but with more than one asterisk (but always at least one).
For example, `"*2"` should return `["12", "42", "72"]`.
Similarly, `"*2*"` s... | reference | from itertools import product
def is_divisible_by_6(s):
if s[- 1] in '13579':
return []
ss = s . replace('*', '{}')
return [v for v in (ss . format(* p) for p in product(* (['0123456789'] * s . count('*')))) if not int(v) % 6]
| Is Divisible By 6 Mk II | 5a1a8b7ec374cbea92000086 | [
"Permutations",
"Strings",
"Combinatorics",
"Number Theory",
"Fundamentals"
] | https://www.codewars.com/kata/5a1a8b7ec374cbea92000086 | 6 kyu |
Two students are giving each other test answers during a test. They don't want to be caught so they are sending each other coded messages.
For example one student is sending the following message: `"Answer to Number 5 Part b"`. He starts with a square grid (in this example a 5x5 grid) and he writes the message down, i... | games | def decipherMessage(s):
ll = int(len(s) * * 0.5)
return '' . join(s[i:: ll] for i in range(ll))
| Decipher Student Messages | 5a1a144f8ba914bbe800003f | [
"Strings",
"Ciphers"
] | https://www.codewars.com/kata/5a1a144f8ba914bbe800003f | 6 kyu |
Your task is to write a function ```angle_planes(lstPts)``` that calculates the [angle between two planes](http://www.vitutor.com/geometry/distance/angle_planes.html), each of them being defined by a [tuple of three points](http://www.had2know.com/academics/equation-plane-through-3-points.html).
Input:
> lstPts – lis... | algorithms | import numpy as np
def angle_planes(lstPts):
vectPlans = [np . cross(np . subtract(p1, p2), np . subtract(p1, p3))
for p1, p2, p3 in [lstPts[: 3], lstPts[3:]]]
n1, n2, vp = map(np . linalg . norm, vectPlans + [np . cross(* vectPlans)])
return round(np . arcsin(vp / (n1 * n2)), 2)
| Angle between two planes | 57de888c758d9ebfd7000061 | [
"Geometry",
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/57de888c758d9ebfd7000061 | 6 kyu |
Given an array containing only zeros and ones, find the index of the zero that, if converted to one, will make the longest sequence of ones.
For instance, given the array:
```
[1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1]
```
replacing the zero at index 10 (counting from 0) forms a sequence of 9 ones:
`... | algorithms | def replace_zero(arr):
m, im, i, lst = 0, - 1, - 1, '' . join(map(str, arr)). split('0')
for a, b in zip(lst, lst[1:]):
i += len(a) + 1
candidate = len(a) + len(b) + 1
if m <= candidate:
im, m = i, candidate
return im
| Zeros and Ones | 5a00a8b5ffe75f8888000080 | [
"Puzzles",
"Logic",
"Algorithms"
] | https://www.codewars.com/kata/5a00a8b5ffe75f8888000080 | 6 kyu |
A person's _Life Path Number_ is calculated by adding each individual number in that person's date of birth, until it is reduced to a single digit number.
Complete the function that accepts a date of birth (as a string) in the following format: `"yyyy-mm-dd"`. The function shall return a one digit integer between 1 an... | reference | def life_path_number(s):
return int(s . replace("-", "")) % 9 or 9
| Life Path Number | 5a1a76c8a7ad6aa26a0007a0 | [
"Recursion",
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/5a1a76c8a7ad6aa26a0007a0 | 7 kyu |
Given a sequence of integers, return the sum of all the integers that have an even index (odd index in COBOL), multiplied by the integer at the last index.
Indices in sequence start from 0.
If the sequence is empty, you should return 0.
| reference | def even_last(numbers):
return sum(numbers[:: 2]) * numbers[- 1] if numbers else 0
| Evens times last | 5a1a9e5032b8b98477000004 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/5a1a9e5032b8b98477000004 | 7 kyu |
# Context
According to <a href="https://en.wikipedia.org/wiki/Seventh_son_of_a_seventh_son">Wikipedia</a> : "The seventh son of a seventh son is a concept from folklore regarding special powers given to, or held by, such a son. **The seventh son must come from an unbroken line with no female siblings born between, and... | reference | import json
def f(data, level):
if level == 0:
yield data['name']
return
children = data['children']
if len(children) >= 7 and all(child['gender'] == 'male' for child in children[: 7]):
yield from f(children[6], level - 1)
for child in children:
yield from f(child, 2)
... | Seventh JSON of a seventh JSON | 5a15b54bffe75f31990000e0 | [
"JSON",
"Recursion",
"Fundamentals"
] | https://www.codewars.com/kata/5a15b54bffe75f31990000e0 | 6 kyu |
Complete the function that counts the number of unique consonants in a string (made up of printable ascii characters).
Consonants are letters used in English other than `"a", "e", "i", "o", "u"`.
Remember, your function needs to return the number of unique consonants - disregarding duplicates. For example, if the st... | algorithms | CONSONANTS = set('bcdfghjklmnpqrstvwxyz')
def count_consonants(text):
return len(CONSONANTS . intersection(text . lower()))
| How Many Unique Consonants? | 5a19226646d843de9000007d | [
"Strings",
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/5a19226646d843de9000007d | 7 kyu |
In this Kata, you will be given an array and your task will be to determine if an array is in ascending or descending order and if it is rotated or not.
Consider the array `[1,2,3,4,5,7,12]`. This array is sorted in `Ascending` order. If we rotate this array once to the left, we get `[12,1,2,3,4,5,7]` and twice-rotat... | algorithms | def solve(arr):
if sorted(arr) == arr:
return "A"
if sorted(arr)[:: - 1] == arr:
return "D"
return "RA" if arr[0] > arr[- 1] else "RD"
| Simple array rotation | 5a16cab2c9fc0e09ce000097 | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/5a16cab2c9fc0e09ce000097 | 6 kyu |
Calculate the trace of a square matrix. A square matrix has `n` rows and `n` columns, where `n` is any integer > 0. The entries of the matrix can contain any number of integers. The function should return the calculated trace of the matrix, or `nil/None` if the array is empty or not square; you can otherwise assume the... | algorithms | def trace(matrix):
if not matrix or len(matrix) != len(matrix[0]):
return None
return sum(matrix[i][i] for i in range(len(matrix)))
| Matrix Trace | 55208f16ecb433c5c90001d2 | [
"Linear Algebra",
"Mathematics",
"Matrix",
"Algorithms"
] | https://www.codewars.com/kata/55208f16ecb433c5c90001d2 | 6 kyu |
In this Kata, you will be given an array of integers whose elements have both a negative and a positive value, except for one integer that is either only negative or only positive. Your task will be to find that integer.
Examples:
`[1, -1, 2, -2, 3] => 3`
`3` has no matching negative appearance
`[-3, 1, 2, 3, -1, ... | algorithms | def solve(arr): return sum(set(arr))
| Array element parity | 5a092d9e46d843b9db000064 | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/5a092d9e46d843b9db000064 | 7 kyu |
<h1>Coffee Vending Machine Problems [Part 1]</h1>
You have a vending machine, but it can not give the change back. You decide to implement this functionality. First of all, you need to know the minimum number of coins for this operation (i'm sure you don't want to return 100 pennys instead of 1$ coin).
So, find an opt... | algorithms | def optimal_number_of_coins(n, coins):
dp = [0 if not i else float("inf") for i in range(n + 1)]
for i in range(1, n + 1):
for j in range(len(coins)):
if coins[j] <= i:
temp = dp[i - coins[j]]
if temp != float("inf") and temp + 1 < dp[i]:
dp[i] = temp + 1
return dp[n]
| Vending Machine Problems [#1] | 586b1b91c66d181c2c00016f | [
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/586b1b91c66d181c2c00016f | 6 kyu |
A special type of prime is generated by the formula `p = 2^m * 3^n + 1` where `m` and `n` can be any non-negative integer.
The first `5` of these primes are `2, 3, 5, 7, 13`, and are generated as follows:
```
2 = 2^0 * 3^0 + 1
3 = 2^1 * 3^0 + 1
5 = 2^2 * 3^0 + 1
7 = 2^1 * 3^1 + 1
13 = 2^2 * 3^1 + 1
..and so on
```
Yo... | algorithms | sb_primes = [2, 3, 5, 7, 13, 17, 19, 37, 73, 97, 109, 163, 193, 257, 433, 487, 577, 769, 1153, 1297, 1459, 2593, 2917, 3457, 3889, 10369,
12289, 17497, 18433, 39367, 52489, 65537, 139969, 147457, 209953, 331777, 472393, 629857, 746497, 786433, 839809, 995329, 1179649, 1492993]
def solve(x, y):
r... | Stone bridge primes | 5a1502db46d84395ab00008a | [
"Algorithms"
] | https://www.codewars.com/kata/5a1502db46d84395ab00008a | 6 kyu |
This kata is definitely harder than the first one. See the last one here: http://www.codewars.com/kata/the-unknown-but-known-variables-addition
This one is a programming problem as well as a puzzle. And this is one of those annoying puzzles that is going to seem impossible, as the answer is not like a riddle, but some... | games | def score(c):
return abs(ord(c) - ord('n'))
def the_var(s):
a, b = s . split("*")
return score(a) * score(b)
| The U-n-KNOWN but known variables: Multiplication | 571a8920b29485b065000582 | [
"Puzzles"
] | https://www.codewars.com/kata/571a8920b29485b065000582 | 6 kyu |
# Linked List
Implement a doubly linked list
Like an array, a linked list is a simple linear data structure. Several
common data types can be implemented using linked lists, like queues,
stacks, and associative arrays.
A linked list is a collection of data elements called *nodes*. In a
*singly linked list* each node... | algorithms | from collections import deque
class DoublyLinkedList (deque):
push, shift, unshift = deque . append, deque . popleft, deque . appendleft
| Doubly Linked List | 58901ac726bd581274000096 | [
"Data Structures",
"Algorithms",
"Fundamentals"
] | https://www.codewars.com/kata/58901ac726bd581274000096 | 6 kyu |
When multiple master devices are connected to a single bus (https://en.wikipedia.org/wiki/System_bus), there needs to be an arbitration in order to choose which of them can have access to the bus (and 'talk' with a slave).
We implement here a very simple model of bus mastering. Given `n`, a number representing the num... | reference | def arbitrate(s, n):
i = s . find('1') + 1
return s[: i] + '0' * (n - i)
| Bus mastering - Who is the most prioritary? | 5a0366f12b651dbfa300000c | [
"Strings",
"Fundamentals",
"Bits"
] | https://www.codewars.com/kata/5a0366f12b651dbfa300000c | 7 kyu |
Implement a function to calculate the sum of the numerical values in a nested list. For example :
```python
sum_nested([1, [2, [3, [4]]]]) -> 10
```
```javascript
sumNested([1, [2, [3, [4]]]]) => 10
``` | reference | def sum_nested(lst):
return sum(sum_nested(x) if isinstance(x, list) else x for x in lst)
| Sum of a nested list | 5a15a4db06d5b6d33c000018 | [
"Recursion",
"Lists",
"Algorithms",
"Fundamentals"
] | https://www.codewars.com/kata/5a15a4db06d5b6d33c000018 | 7 kyu |
In this Kata, you will write a function `doubles` that will remove double string characters that are adjacent to each other.
For example:
`doubles('abbcccdddda') = 'aca'`, because, from left to right:
```Haskell
a) There is only one 'a' on the left hand side, so it stays.
b) The 2 b's disappear because we are removin... | algorithms | def doubles(s):
cs = []
for c in s:
if cs and cs[- 1] == c:
cs . pop()
else:
cs . append(c)
return '' . join(cs)
| String doubles | 5a145ab08ba9148dd6000094 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5a145ab08ba9148dd6000094 | 7 kyu |
Chocolate factory produces unusual chocolate. Chocolate bars come in the form of **_long tiles 1 × N_**, which consists of N squares. Each square shows the portrait of one of the famous N confectioners of this company. Different chocolates have the same N confectioners' portraits, but in a different order.
# Task
Writ... | algorithms | def chocolate(n, first_bar, second_bar):
return len(set(zip(first_bar, first_bar[1:])) - set(zip(second_bar, second_bar[1:])))
| Chocolate problem | 559a9a9ed391015e0700010f | [
"Algorithms",
"Logic",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/559a9a9ed391015e0700010f | 6 kyu |
Sam wants to know how many times the variable `i` gets incremented after `n` seconds,
but he has no idea how to stop the loop.
Help him so that the function can return `i` after `n` seconds.
```
0 <= n <= 3
(Artifacts for the delay is allowed up to 0.5 seconds)
```
NB: The value `i` is not so important in this kat... | bug_fixes | import time
def increment_loop(n):
start = time . time()
i = 0
while time . time() - start < n:
i += 1
return i
| Stop the loop after n seconds | 5a147735ffe75f1c75000199 | [
"Date Time",
"Debugging"
] | https://www.codewars.com/kata/5a147735ffe75f1c75000199 | 7 kyu |
The business has been suffering for years under the watch of Homie the Clown. Every time there is a push to production it requires 500 hands-on deck, a massive manual process, and the fire department is on stand-by along with Fire Marshall Bill the king of manual configuration management. He is called a Fire Marshall b... | reference | def nkotb_vs_homie(requirements):
return ["{}! Homie dont play that!" . format(a[8: - 5]. title())
for b in requirements for a in b] + \
["{} monitoring objections, {} automation, {} deployment pipeline, {} cloud, and {} microservices." .
format(* (len(x) for x in requirements))]
| DevOps New Kids On The Block VS Homie The Clown | 58b497914c5d0af407000049 | [
"Fundamentals"
] | https://www.codewars.com/kata/58b497914c5d0af407000049 | 7 kyu |
My 6th kata, implement a lexicographic sort order to make longer items go **before** any of their prefixes.
In Python, write a function (`custom_sort`) that takes an input list (`lst`) of strings. The function should return a new list of strings sorted lexiographically but with longer items before their prefixes. The ... | algorithms | import functools
def cmp(a, b):
for x, y in zip(a, b):
if x < y:
return - 1
if y < x:
return 1
if len(a) > len(b):
return - 1
if len(b) > len(a):
return 1
return 0
def custom_sort(lst):
return sorted(lst, key=functools . cmp_to_key(cmp))
| Lexographic sort with a twist | 5901b2f47591f339b5000059 | [
"Algorithms",
"Arrays",
"Sorting",
"Data Structures"
] | https://www.codewars.com/kata/5901b2f47591f339b5000059 | 6 kyu |
You have `n` dices each one having `s` sides numbered from 1 to `s`.
How many outcomes add up to a specified number `k`?
For example if we roll four normal six-sided dices we
have four outcomes that add up to 5.
(1, 1, 1, 2)
(1, 1, 2, 1)
(1, 2, 1, 1)
(2, 1, 1, 1)
There are 100 random tests with:
- `0 <= n <= 10`
- ... | reference | from numpy . polynomial import polynomial
def outcome(n, s, k):
try:
return polynomial . polypow([0] + [1] * s, n)[k]
except IndexError:
return 0
| Sum of dices | 58ff61d2d6b38ee5270000bc | [
"Algorithms",
"Fundamentals"
] | https://www.codewars.com/kata/58ff61d2d6b38ee5270000bc | 6 kyu |
Hi guys, welcome to introduction to DocTesting.
The kata is composed of two parts; in part (1) we write three small functions, and in part (2) we write a few doc tests for those functions.
Lets talk about the functions first...
The reverse_list function takes a list and returns the reverse of it.
If given an... | reference | def reverse_list(x):
"""Takes an list and returns the reverse of it.
If x is empty, return [].
>>> reverse_list([1, 2, 3, 4])
[4, 3, 2, 1]
>>> reverse_list([])
[]
"""
return x[:: - 1]
def sum_list(x):
"""Takes a list, and returns the sum of that list.
If x is empty list... | An Introduction to DocTesting... | 58e4033b5600a17be1000103 | [
"Fundamentals"
] | https://www.codewars.com/kata/58e4033b5600a17be1000103 | 7 kyu |
Let's say that in a hypothetical platform that resembles Codewars there is a clan with 2 warriors. The 2nd one in ranking (lets call him **D**) wants to at least reach the honor score of his ally (lets call her **M**).
*(Let's say that there is no antagonism here, he just wants to prove his ally that she should be pro... | reference | def get_honor_path(score, target):
return {'1kyus': (target - score) / / 2, '2kyus': (target - score) % 2} if target > score else {}
| Help your fellow warrior! | 5660aa6fa60f03856c000045 | [
"Fundamentals",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5660aa6fa60f03856c000045 | 7 kyu |
A company is opening a bank, but the coder who is designing the user class made some errors. They need <strong> you </strong> to help them.
You <strong>must</strong> include the following:<br/>
<strong>Note: These are NOT steps to code the class</strong>
- A withdraw method
- Subtracts money from balance
- One p... | reference | class User (object):
def __init__(self, name, balance, checking_account):
self . name = name
self . balance = balance
self . checking_account = checking_account
def withdraw(self, v):
if v > self . balance:
raise ValueError()
self . balance -= v
return "{} has {}." . for... | User class for Banking System | 5a03af9606d5b65ff7000009 | [
"Fundamentals",
"Object-oriented Programming"
] | https://www.codewars.com/kata/5a03af9606d5b65ff7000009 | 7 kyu |
You get an input list of 10 random integers between 0 and 100 (`0 <= x <= 100`).
Your task is to return the **integer** used to initialize the random number generator (the "seed") (`0 <= n < 10000`)
## Examples
```python
input: [17, 72, 97, 8, 32, 15, 63, 97, 57, 60]
expected: 1
input: [99, 56, 14, 0, 11, 74, 4, 85,... | reference | from random import seed, randint
def find_random_seed(A):
for s in range(10000):
seed(s)
if [randint(0, 100) for _ in range(10)] == A:
return s
| Find the random seed | 5a106ce7ffe75f4c200000f7 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a106ce7ffe75f4c200000f7 | 7 kyu |
An array is a data structure in which a collection of different data stored continuously in memory. This collection is usually accessed by a numerical index and allows near instant access to all of the data held by the array as opposed to other structures such as binary search trees or linked lists, where the computer ... | reference | def element_location(begin: int, end: int, index: int, size: int) - > int:
out = begin + index * size
if out < begin or out >= end:
raise IndexError
return out
| Where's my Elements at? | 5a0ec343c374cb6da0000006 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/5a0ec343c374cb6da0000006 | 7 kyu |
<h1>Statistics puzzle</h1>
Your function will receive an array of 10000 integer values randomly selected from a uniform distribution (a range of values with equal selection probability). Your function will also receive the minimum and maximum possible values in the range (inclusive). A constant has been added to every... | games | def find_constant(arr, lb, ub):
return min(arr) - lb
| Crouching Distribution, Hidden Constant | 5a0da79b32b8b98b8d000097 | [
"Statistics",
"Mathematics",
"Puzzles"
] | https://www.codewars.com/kata/5a0da79b32b8b98b8d000097 | 7 kyu |
When it's spring Japanese cherries blossom, it's called "sakura" and it's admired a lot. The petals start to fall in late April.
Suppose that the falling speed of a petal is 5 centimeters per second (5 cm/s), and it takes 80 seconds for the petal to reach the ground from a certain branch.
Write a function that receiv... | algorithms | def sakura_fall(v):
return 400 / v if v > 0 else 0
| The falling speed of petals | 5a0be7ea8ba914fc9c00006b | [
"Algorithms"
] | https://www.codewars.com/kata/5a0be7ea8ba914fc9c00006b | 8 kyu |
Krazy King BlackJack is just like blackjack, with one difference: the kings!
Instead of the kings being simply worth 10 points, kings are worth either 10 points or some other number of points announced by the dealer at the start of the game. Whichever value yields the best hand is the one that plays (much like how ace... | algorithms | from itertools import product
def krazy_king_blackjack(hand, king_value):
VALUE = {str(n): (n,) for n in range(1, 11)}
VALUE . update(
{'J': (10,), 'Q': (10,), 'K': (10, king_value), 'A': (1, 11)})
possible = [sum(comb) for comb in product(* (VALUE[card]
... | Krazy King Blackjack | 57bb798756449dea77000020 | [
"Algorithms",
"Logic",
"Games"
] | https://www.codewars.com/kata/57bb798756449dea77000020 | 5 kyu |
Let us define a function `f`such as:
- (1) for k positive odd integer > 2 :
<img src="https://latex.codecogs.com/gif.latex?\bg_green&space;f(k)&space;=&space;\sum_{n=1}^{nb}1/n^{k}" title="\bg_green f(k) = \sum_{n=1}^{nb}1/n^{k}"
/>
- (2) for k positive even integer >= 2 :
<img src="https://latex.codecogs.co... | reference | from fractions import Fraction as F
from math import factorial, tau
B = [1, F(1, 2), F(1, 6), 0, - F(1, 30), 0, F(1, 42), 0, - F(1, 30), 0, F(5, 66), 0, - F(691, 2730), 0, F(7, 6), 0, - F(3617, 510), 0, F(43867, 798),
0, - F(174611, 330), 0, F(854513, 138), 0, - F(236364091, 2730), 0, F(8553103, 6), 0, - F(2374... | Getting along with Bernoulli's numbers | 5a02cf76c9fc0ee71d0000d5 | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/5a02cf76c9fc0ee71d0000d5 | 5 kyu |
Christmas is coming, and Santa has a long list to go through, to find who deserves presents for the big day. Go through a list of children, and return a list containing every child who appeared on Santa's list. Do not add any child more than once. Output should be sorted.
~~~if:java
For java, use Lists.
~~~
Comparison... | reference | def find_children(santas_list, children):
return sorted(set(santas_list) & set(children))
| Santa's Naughty List | 5a0b4dc2ffe75f72f70000ef | [
"Lists",
"Sorting",
"Fundamentals"
] | https://www.codewars.com/kata/5a0b4dc2ffe75f72f70000ef | 7 kyu |
Program the function distance(p1, p2) which returns the distance between the points p1 and p2 in n-dimensional space. p1 and p2 will be given as arrays.
Your program should work for all lengths of arrays, and should return -1 if the arrays aren't of the same length or if both arrays are empty sets.
If you don't know ... | reference | def distance(p1, p2):
return sum((a - b) * * 2 for a, b in zip(p1, p2)) * * 0.5 if len(p1) == len(p2) > 0 else - 1
| Distance between two points | 5a0b72484bebaefe60001867 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a0b72484bebaefe60001867 | 7 kyu |
You have been speeding on a motorway and a police car had to stop you. The policeman is a funny guy that likes to play games. Before issuing penalty charge notice he gives you a choice to change your penalty.
Your penalty charge is a combination of numbers like: speed of your car, speed limit in the area, speed of th... | algorithms | # return str of the smallest value of the combined numbers in a_list
def penalty(a_list):
return '' . join(sorted(a_list, key=lambda n: n + n[: 1]))
| Penalty for speeding | 5a05a4d206d5b61ba70000f9 | [
"Algorithms"
] | https://www.codewars.com/kata/5a05a4d206d5b61ba70000f9 | 5 kyu |
Timothy (age: 16) really likes to smoke. Unfortunately, he is too young to buy his own cigarettes and that's why he has to be extremely efficient in smoking.
It's now your task to create a function that calculates how many cigarettes Timothy can smoke out of the given amounts of `bars` and `boxes`:
- a bar has 10 box... | algorithms | def start_smoking(bars, boxes):
return int(22.5 * (10 * bars + boxes) - 0.5)
| Smoking Timmy | 5a0aae48ba2a14cfa600016d | [
"Algorithms",
"Fundamentals"
] | https://www.codewars.com/kata/5a0aae48ba2a14cfa600016d | 7 kyu |
Were you ever interested in the phenomena of <i>astrology, star signs, tarot, voodoo </i>? (ok not voodoo that's too spooky)...<br>
<font size="4" color="#25B6CC">Task:</font><br>
Your job for today is to finish the <code>star_sign</code> function by finding the astrological sign, given the birth details as a <code>D... | games | def star_sign(date):
limits = ['', 20, 19, 20, 20, 21, 21, 22, 23, 23, 23, 22, 21]
signs = ['Aquarius', 'Pisces', 'Aries', 'Taurus', 'Gemini', 'Cancer',
'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius', 'Capricorn']
if date . day > limits[date . month]:
return signs[date . month - 1... | It is written in the stars | 5888a57cbf87c25c840000c6 | [
"Date Time",
"Puzzles"
] | https://www.codewars.com/kata/5888a57cbf87c25c840000c6 | 7 kyu |
An element in an array is dominant if it is greater than all elements to its right. You will be given an array and your task will be to return a list of all dominant elements. For example:
```
solve([1,21,4,7,5]) = [21,7,5] because 21, 7 and 5 are greater than elments to their right.
solve([5,4,3,2,1]) = [5,4,3,2,1]
... | reference | def solve(arr):
r = []
for v in arr[:: - 1]:
if not r or r[- 1] < v:
r . append(v)
return r[:: - 1]
| Dominant array elements | 5a04133e32b8b998dc000089 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/5a04133e32b8b998dc000089 | 7 kyu |
In this Kata, you will be given an array of unique elements, and your task is to rearrange the values so that the first max value is followed by the first minimum, followed by second max value then second min value, etc.
For example:
```javascript
solve([15,11,10,7,12]) = [15,7,12,10,11]
```
```csharp
Kata.Solve(new ... | reference | def solve(arr):
arr = sorted(arr, reverse=True)
res = []
while len(arr):
res . append(arr . pop(0))
if len(arr):
res . append(arr . pop())
return res
| Max-min arrays | 5a090c4e697598d0b9000004 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/5a090c4e697598d0b9000004 | 7 kyu |
This kata requires you to convert minutes (`int`) to hours and minutes in the format `hh:mm` (`string`).
If the input is `0` or negative value, then you should return `"00:00"`
**Hint:** use the modulo operation to solve this challenge. The modulo operation simply returns the remainder after a division. For example t... | reference | def timeConvert(m):
return '{:02d}:{:02d}' . format(* divmod(max(int(m), 0), 60))
| Easy Time Convert | 5a084a098ba9146690000969 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a084a098ba9146690000969 | 7 kyu |
In music, if you double (or halve) the pitch of any note you will get to the same note again.
"Concert A" is fixed at 440 Hz, and every other note is defined based on that. 880 Hz is also an A, as is 1760 Hz, as is 220 Hz.
There are 12 notes in Western music: A, A#, B, C, C#, D, D#, E, F, F#, G, G#. You are given a p... | reference | notes = {
440: "A",
466.16: "A#",
493.88: "B",
523.25: "C",
554.37: "C#",
587.33: "D",
622.25: "D#",
659.25: "E",
698.46: "F",
739.99: "F#",
783.99: "G",
830.61: "G#"
}
def get_note(pitch):
for note in notes:
if note >= pitch and note % pitch... | Pitches and Notes | 5a0599908ba914a6cf000138 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a0599908ba914a6cf000138 | 7 kyu |
Get the number n to return the sequence from n to 1.
The number n can be negative and also large number. (See the range as the following)
```
Example :
n=5 >> [5,4,3,2,1]
n=-1 >> [-1,0,1]
Range :
Python -9999 < n < 9999
Javascript -9999 < n < 9999
c++ -9999 < n < 9999
Crystal -9999 < n < 9999
Ruby ... | reference | def seq_to_one(n):
step = (- 1) * * (n >= 1)
return list(range(n, 1 + step, step))
| Sequence to 1 | 5a05fe8a06d5b6208e00010b | [
"Fundamentals"
] | https://www.codewars.com/kata/5a05fe8a06d5b6208e00010b | 7 kyu |
Let `n` be an integer coprime with `10`, e.g. `7`.
`1/7 = 0.142857 142857 142857 ...`.
We see that the decimal part has a cycle: `142857`. The length of this cycle is `6`. In the same way:
`1/11 = 0.09 09 09 ...`. Cycle length is `2`.
#### Task
Given an integer `n (n > 1)` the function `cycle(n)` returns the lengt... | reference | import math
def cycle(n):
if n % 2 == 0 or n % 5 == 0:
return - 1
k = 1
while pow(10, k, n) != 1:
k += 1
return k
| 1/n- Cycle | 5a057ec846d843c81a0000ad | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/5a057ec846d843c81a0000ad | 6 kyu |
I need some help with my math homework. I have a number of problems I need to return the derivative for.
They will all be of the form: `ax^b`, where `a` and `b` are both integers, but can be positive or negative.
**Notes:**
- if `b` is 1, then the equation will be `ax`
- if `b` is 0, then the equation will be ... | reference | def get_derivative(s):
if '^' in s:
f, t = map(int, s . split('x^'))
return '{}x' . format(f * t) if t == 2 else '{}x^{}' . format(f * t, t - 1)
elif 'x' in s:
return s[: - 1]
else:
return '0'
| Calculate Derivative #1 - Single Integer Equation | 5a0350c380171ffd7b00012a | [
"Fundamentals",
"Mathematics",
"Algorithms",
"Logic",
"Numbers"
] | https://www.codewars.com/kata/5a0350c380171ffd7b00012a | 7 kyu |
The aim of the kata is to decompose `n!` (factorial n) into its prime factors.
Examples:
```
n = 12; decomp(12) -> "2^10 * 3^5 * 5^2 * 7 * 11"
since 12! is divisible by 2 ten times, by 3 five times, by 5 two times and by 7 and 11 only once.
n = 22; decomp(22) -> "2^19 * 3^9 * 5^4 * 7^3 * 11^2 * 13 * 17 * 19"
n = 25;... | reference | from collections import defaultdict
def dec(n):
decomp = defaultdict(lambda: 0)
i = 2
while n > 1:
while n % i == 0:
n /= i
decomp[i] += 1
i += 1
return decomp
def decomp(n):
ans = defaultdict(lambda: 0)
for i in range(2, n + 1):
for key, value in dec(i).... | Factorial decomposition | 5a045fee46d843effa000070 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a045fee46d843effa000070 | 5 kyu |
Implement the validate_args decorator, which raises an error **(InvalidArgument)** when the decorated function is called with arguments of the wrong type. Validate_args takes in a sequence of argument types as a variable number of arguments. You do not have to check that the number of arguments matches, only their type... | reference | from functools import wraps
def validate_args(* types):
def decorator(func):
@ wraps(func)
def wrapper(* args):
if all(map(isinstance, args, types)):
return func(* args)
else:
raise InvalidArgument
return wrapper
return decorator
| @validate_args | 5a0001a606d5b68a5a000013 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a0001a606d5b68a5a000013 | 5 kyu |
Implement the "memoize" decorator, which adds memoization capabilities to a function in order to make it more efficient. In short, memoization means storing computed values instead of recomputing every time. In the example below, this means that you only calculate fib(n) once for every n.
The decorated function must r... | reference | from functools import wraps
def memoize(func):
cache = {}
@ wraps(func)
def wrapper(* args):
if args in cache:
return cache[args]
else:
return cache . setdefault(args, func(* args))
return wrapper
| @memoize | 59ffef8246d8434b0700001d | [
"Fundamentals"
] | https://www.codewars.com/kata/59ffef8246d8434b0700001d | 6 kyu |
Implement the functools.wraps decorator, which is used to preserve the name and docstring of a decorated function. Your decorator must not modify the behavior of the decorated function. Here's an example :
```python
def identity(func):
@wraps(func)
def wrapper(*args, **kwargs):
"""Wraps func"""
return func... | reference | def wraps(wrapped):
def wrapper(func):
for attr in ('__module__', '__name__', '__qualname__', '__doc__', '__annotations__'):
try:
value = getattr(wrapped, attr)
except AttributeError:
pass
else:
setattr(func, attr, value)
func . __dict__ . update(getattr(wrapped, attr, {}))
... | @wraps | 5a010ee3ba2a14f4940001df | [
"Fundamentals"
] | https://www.codewars.com/kata/5a010ee3ba2a14f4940001df | 6 kyu |
Implement the htmlize decorator, which takes in a string argument and uses it to wrap a function's return value in html tags. Your decorator must be composable (i.e., it must be possible to do several decorations in a row) and well-behaved (i.e., your decorator must not change the name or docstring of the decorated fun... | reference | from functools import wraps
def htmlize(tag):
def wrapper(f):
@ wraps(f)
def fexec(* args, * * kwds):
return '<{0}>{1}</{0}>' . format(tag, f(* args, * * kwds))
return fexec
return wrapper
| @htmlize | 5a0117798ba9143a64000073 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a0117798ba9143a64000073 | 6 kyu |
Implement the "count" decorator, which adds an attribute "call_count" to a function passed in to it, and increments it every time the function is called.
The behavior of the decorated function must be the same as before. Your decorator must be well-behaved, i.e. the returned function must have the same name and docstr... | reference | from functools import wraps
def count_calls(func):
@ wraps(func)
def wrapper(* args, * * kwds):
wrapper . call_count += 1
return func(* args, * * kwds)
wrapper . call_count = 0
return wrapper
| @count_calls | 59ffe8bbffe75f6d94000016 | [
"Fundamentals"
] | https://www.codewars.com/kata/59ffe8bbffe75f6d94000016 | 6 kyu |
Observe the process with the array given below and the tracking of the sums of each corresponding array.
```
[5, 3, 6, 10, 5, 2, 2, 1] (34) ----> [5, 3, 6, 10, 2, 1] ----> (27) ------> [10, 6, 5, 3, 2, 1] ----> [4, 1, 2, 1, 1] (9) -----> [4, 1, 2] (7)
```
The tracked sums are : `[34, 27, 9, 7]`. We do not register o... | games | def track_sum(arr):
a = arr
b = sorted(set(a), reverse=True)
c = [(x - y) for (x, y) in zip(b, b[1:])]
d = sorted(set(c), key=c . index)
return [list(map(sum, [a, b, c, d])), d]
| Tracking Sums in a Process | 56dbb6603e5dd6543c00098d | [
"Fundamentals",
"Data Structures",
"Algorithms",
"Mathematics",
"Logic",
"Sorting",
"Puzzles"
] | https://www.codewars.com/kata/56dbb6603e5dd6543c00098d | 6 kyu |
Create a function that accepts 3 inputs, a string, a starting location, and a length. The function needs to simulate the string endlessly repeating in both directions and return a substring beginning at the starting location and continues for length.
Example:
```python
endless_string('xyz', -23, 6) == 'yzxyzx'
```
To... | reference | from itertools import cycle, islice
def endless_string(stg, i, l):
i = min(i, i + l) % len(stg) + (l < 0)
j = i + abs(l)
return "" . join(islice(cycle(stg), i, j))
| Endless String | 57048c1275263af10b00063e | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/57048c1275263af10b00063e | 6 kyu |
There are several (or no) spiders, butterflies, and dragonflies.
In this kata, a spider has eight legs. A dragonfly or a butterfly has six legs. A __dragonfly__ has __two__ pairs of wings, while a __butterfly__ has __one__ pair of wings. _I am not sure whether they are biologically correct, but the values apply here.... | algorithms | # system of equations:
# h = s + b + d
# l = 8*s + 6*b + 6*d
# w = 0*s + 1*b + 2*d
#
# get third equation in terms of b
# b = w - 2d
#
# replace b in other equations:
# h = s + (w - 2d) + d
# l = 8*s + 6*(w - 2d) + 6*d
#
# get first equation in terms of s
# s = h - w + d
#
# replace in remaining equation:
# l = 8*(h - ... | Jungerstein's Math Training Room: 2. How many bugs? | 58cf479f87c2e967250000e4 | [
"Algorithms"
] | https://www.codewars.com/kata/58cf479f87c2e967250000e4 | 7 kyu |
You are given a binary tree. Implement the method findMax which returns the maximal node value in the tree.
For example, maximum in the following Tree is 11.
```
7
/ \
/ \
5 2
\ \
6 11
/\ /
... | algorithms | def find_max(root):
v = root . value
if root . left:
v = max(v, find_max(root . left))
if root . right:
v = max(v, find_max(root . right))
return v
| Find Max Tree Node | 5a04450c8ba914083700000a | [
"Algorithms",
"Recursion",
"Binary Search Trees",
"Binary"
] | https://www.codewars.com/kata/5a04450c8ba914083700000a | 7 kyu |
Write a function that replaces 'two', 'too' and 'to' with the number '2'. Even if the sound is found mid word (like in octopus) or not in lowercase grandma still thinks that should be replaced with a 2. Bless her.
```text
'I love to text' becomes 'I love 2 text'
'see you tomorrow' becomes 'see you 2morrow'
'look at th... | reference | import re
def textin(txt):
return re . sub(r'(two|too|to)', '2', txt, flags=re . I)
| Grandma learning to text | 5a043fbef3251a5a2b0002b0 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a043fbef3251a5a2b0002b0 | 7 kyu |
Write a function that takes a list of at least four elements as an argument and returns a list of the middle two or three elements in reverse order. | reference | def reverse_middle(lst):
l = len(lst) / / 2 - 1
return lst[l: - l][:: - 1]
| Slice the middle of a list backwards | 5a043724ffe75fbab000009f | [
"Lists",
"Fundamentals"
] | https://www.codewars.com/kata/5a043724ffe75fbab000009f | 7 kyu |
# Story
The citizens of Bytetown, could not stand that the candidates in the mayoral election campaign have been placing their electoral posters at all places at their whim. The city council has finally decided to build an electoral wall for placing the posters and introduce the following rules:
```
Every candidate c... | reference | def count_visible(posters):
wall = [0] * 1000
for i, (x, y) in enumerate(posters, 1):
wall[x - 1: y] = [i] * (y - x + 1)
wall = set(wall)
wall . discard(0)
return len(wall)
| Simple Fun #376: The Visible Posters | 5a028001ba2a14346b0000d4 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a028001ba2a14346b0000d4 | 7 kyu |
Find the total sum of internal angles (in degrees) in an n-sided simple polygon. N will be greater than 2. | reference | def angle(n):
return 180 * (n - 2)
| Sum of angles | 5a03b3f6a1c9040084001765 | [
"Geometry",
"Fundamentals"
] | https://www.codewars.com/kata/5a03b3f6a1c9040084001765 | 7 kyu |
Your task is to return an array of the first `n` abundant numbers, sorted by their abundance. If the abundance is the same for multiple numbers, sort them numbers from smallest to largest.
"An abundant number or excessive number is a number for which the sum of its proper divisors is greater than the number itself. Th... | algorithms | def abundance(n):
l, i = [], 2
while len(l) < n:
i += 1
a = sum(k for k in range(2, i / / 2 + 1) if i % k == 0) - i
if a > 0:
l . append((a, i))
return [a for _, a in sorted(l)]
| Abundant Array | 5811cb19d8a4dadcb8000037 | [
"Fundamentals",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5811cb19d8a4dadcb8000037 | 6 kyu |
<h1>Happy traveller [Part 1]</h1>
There is a play grid NxN; Always square!
<pre>
0 1 2 3
0 [o, o, o, X]
1 [o, o, o, o]
2 [o, o, o, o]
3 [o, o, o, o]
</pre><br>
<p>
You start from a random point. I mean, you are given the coordinates of your start position in format (row, col).
</p>
<p>And your <b>TASK is to de... | algorithms | from math import comb
def count_paths(N, coords):
n, m = coords[0], N - coords[1] - 1
return comb(n + m, n) if n + m > 0 else 0
| Happy traveller [#1] | 586d9a71aa0428466d00001c | [
"Algorithms"
] | https://www.codewars.com/kata/586d9a71aa0428466d00001c | 6 kyu |
The aim of this kata is to write function ```drawACross``` / ```draw_a_cross``` which returns a cross shape with 'x' characters on a square grid of size and height of our sole input n. All non-'x' characters in the grid should be filled with a space character (" ").
For example for ```drawACross(7)``` / ```draw_a_cros... | games | def draw_a_cross(n: int) - > str:
if n < 3:
return "Not possible to draw cross for grids less than 3x3!"
if n % 2 == 0:
return "Centered cross not possible!"
lines = [('x' + ' ' * i + 'x'). center(n) for i in range(n - 2, 0, - 2)]
return '\n' . join(lines + ['x' . center(n)] + lines[:: - 1... | Drawing a Cross! | 5a036ecb2b651d696f00007c | [
"Fundamentals",
"Algorithms",
"Games",
"ASCII Art"
] | https://www.codewars.com/kata/5a036ecb2b651d696f00007c | 7 kyu |
Create a function that takes any sentence and redistributes the spaces (and adds additional spaces if needed) so that each word starts with a vowel. The letters should all be in the same order but every vowel in the sentence should be the start of a new word. The first word in the new sentence may start without a vowel... | algorithms | from re import sub
def vowel_start(st):
return sub(r'(?<=.)([aeiou])', r' \1', sub(r'[^a-z0-9]', '', st . lower()))
| Start with a Vowel | 5a02e9c19f8e2dbd50000167 | [
"Regular Expressions",
"Algorithms"
] | https://www.codewars.com/kata/5a02e9c19f8e2dbd50000167 | 7 kyu |
Farmer Bob have a big farm, where he growths chickens, rabbits and cows. It is very difficult to count the number of animals for each type manually, so he diceded to buy a system to do it. But he bought a cheap system that can count only total number of heads, total number of legs and total number of horns of animals o... | algorithms | def get_animals_count(legs, heads, horns):
cows = horns / / 2
rabbits = legs / / 2 - cows - heads
chickens = heads - cows - rabbits
return dict(cows=cows, rabbits=rabbits, chickens=chickens)
| Help the farmer to count rabbits, chickens and cows | 5a02037ac374cbab41000089 | [
"Fundamentals",
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/5a02037ac374cbab41000089 | 7 kyu |
Given the number n, return a string which shows the minimum number of moves to complete the tower of Hanoi consisting of n layers.
Tower of Hanoi : https://en.wikipedia.org/wiki/Tower_of_Hanoi
Example - 2 layered Tower of Hanoi
Input: n=2
Start
[[2, 1], [], []]
Goal
[[], [], [2, 1]]
Expected Output : '[[2, 1], []... | algorithms | def hanoiArray(n):
A, B, C = list(range(n, 0, - 1)), [], []
res = [str([A, C, B])]
def rec(n, X, Y, Z):
if not n:
return
rec(n - 1, X, Z, Y)
Y . append(X . pop())
res . append(str([A, C, B]))
rec(n - 1, Z, Y, X)
rec(n, A, B, C)
return '\n' . join(res)
| Hanoi Tower Array | 5a02a758ffe75f8da5000030 | [
"Algorithms"
] | https://www.codewars.com/kata/5a02a758ffe75f8da5000030 | 6 kyu |
Hello, your test today is to create an algorithm. You do not have a description of what it should do, all you have are the inputs and outputs. All inputs are strings and all outputs are required to be.
#### Example 1:
Input: `abcdefghijklmnopqrstuvwxyz`
Output:
```text
xxxxxxxxxxxxxxxxxxxxxxxxw
y ... | algorithms | from itertools import cycle
def spiralize(word):
x, y, dirs, spiral = 0, 0, cycle([(1, 0), (0, 1), (- 1, 0), (0, - 1)]), {}
for c in word:
dx, dy = next(dirs)
for _ in range(ord(c) - 96):
x, y = x + dx, y + dy
spiral[(x, y)] = c
miX, maX = min(spiral . keys(), key=lambda t: t[0... | Word Spiral | 583726b8aa6717a718000002 | [
"Algorithms"
] | https://www.codewars.com/kata/583726b8aa6717a718000002 | 5 kyu |
This the second part part of the kata:
https://www.codewars.com/kata/the-sum-and-the-rest-of-certain-pairs-of-numbers-have-to-be-perfect-squares
In this part we will have to create a faster algorithm because the tests will be more challenging.
The function ```n_closestPairs_tonum()```, (Javascript: ```nClosestPairsT... | algorithms | def n_closestPairs_tonum(upper_lim, k):
square_lim = int((2 * upper_lim) * * .5) + 1
squares = [n * n for n in range(1, square_lim)]
p, s = [], set(squares)
for m in range(upper_lim - 1, 1, - 1):
for b in squares:
if b >= m:
break
if 2 * m - b in s:
p . append([m, m - b]... | The Sum and The Rest of Certain Pairs of Numbers have to be Perfect Squares (more Challenging) | 57aaaada72292d3b8f0001b4 | [
"Algorithms",
"Mathematics",
"Data Structures"
] | https://www.codewars.com/kata/57aaaada72292d3b8f0001b4 | 5 kyu |
You are the owner of a box making company.
Your company can produce any equal sided polygon box, but plenty of your customers want to transport circular objects in these boxes. Circles are a very common shape in the consumer industry. Tin cans, glasses, tyres and CD's are a few examples of these.
As a result you deci... | games | import math
def circle_diameter(sides, side_length):
return side_length / math . tan(math . pi / sides)
| Circles in Polygons | 5a026a9cffe75fbace00007f | [
"Mathematics",
"Puzzles"
] | https://www.codewars.com/kata/5a026a9cffe75fbace00007f | 8 kyu |
You are given three integers in the range [0-99]. You must determine if any ordering of the numbers forms a date from the 20th century.
- If no ordering forms a date, return the string `"invalid"`.
- If multiple distinct orderings form dates, return the string `"ambiguous"`.
- If only one ordering forms a date, retu... | algorithms | from datetime import date
from itertools import permutations
def uniqueDate(* args):
ds = set()
for y, m, d in permutations(args, 3):
try:
ds . add(date(y + 2000, m, d))
except:
pass
return 'ambiguous' if len(ds) > 1 else 'invalid' if not ds else ds . pop(). strftime("%y... | Can these three numbers form a date? | 582406166cf35b7f93000057 | [
"Algorithms",
"Date Time",
"Permutations"
] | https://www.codewars.com/kata/582406166cf35b7f93000057 | 6 kyu |
Create a function `sierpinski` to generate an ASCII representation of a Sierpinski triangle of order **N**.
Seperate each line with `\n`. You don't have to check the input value.
The output should look like this:
sierpinski(4)
*
* *
... | algorithms | def sierpinski(n):
t = ['*']
for _ in range(n):
t = [r . center(2 * len(t[- 1]) + 1) for r in t] + [r + ' ' + r for r in t]
return '\n' . join(t)
| Sierpinski triangle | 58add662ea140541a50000f7 | [
"Algorithms",
"ASCII Art"
] | https://www.codewars.com/kata/58add662ea140541a50000f7 | 6 kyu |
A [binary search tree](https://en.wikipedia.org/wiki/Binary_search_tree) is a binary tree that is ordered. This means that if you were to convert the tree to an array using an in-order traversal, the array would be in sorted order. The benefit gained by this ordering is that when the tree is balanced, searching is a lo... | algorithms | class T:
def __init__(self, value, left=None, right=None):
self . value = value
self . left = left
self . right = right
def is_bst(node):
def extract(node):
if node is not None:
yield from extract(node . left)
yield node . value
yield from extract(node . right)
... | Binary search tree validation | 588534713472944a9e000029 | [
"Trees",
"Recursion",
"Data Structures",
"Algorithms"
] | https://www.codewars.com/kata/588534713472944a9e000029 | 5 kyu |
You are given two interior angles (in degrees) of a triangle.
Write a function to return the 3rd.
Note: only positive integers will be tested.
https://en.wikipedia.org/wiki/Triangle | reference | def other_angle(a, b):
return 180 - a - b
| Third Angle of a Triangle | 5a023c426975981341000014 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a023c426975981341000014 | 8 kyu |
## Task
You are at start location `[0, 0]` in mountain area of NxN and you can **only** move in one of the four cardinal directions (i.e. North, East, South, West). Return minimal number of `climb rounds` to target location `[N-1, N-1]`. Number of `climb rounds` between adjacent locations is defined as difference of lo... | algorithms | def path_finder(maze):
grid = maze . splitlines()
end = h, w = len(grid) - 1, len(grid[0]) - 1
bag, seen = {(0, 0): 0}, set()
while bag:
x, y = min(bag, key=bag . get)
rounds = bag . pop((x, y))
seen . add((x, y))
if (x, y) == end:
return rounds
for u, v in (- 1, 0)... | Path Finder #3: the Alpinist | 576986639772456f6f00030c | [
"Algorithms"
] | https://www.codewars.com/kata/576986639772456f6f00030c | 3 kyu |
## Story
Before we dive into the exercise, I would like to show you why these numbers are so important in computer programming today.
It all goes back to the time of 19th century. Where computers we know today were non-existing. The first ever **computer program** was for the Analytical Engine to compute **Bernoulli ... | algorithms | from fractions import Fraction as frac
def ber():
res, m = [], 0
while True:
res . append(frac(1, m + 1))
for j in range(m, 0, - 1):
res[j - 1] = j * (res[j - 1] - res[j])
yield res[0]
m += 1
def bernoulli_number(n):
if n == 1:
return Fraction(- 1, 2)
if n... | Bernoulli numbers | 567ffb369f7f92e53800005b | [
"Fundamentals",
"Mathematics",
"Number Theory",
"Algorithms"
] | https://www.codewars.com/kata/567ffb369f7f92e53800005b | 4 kyu |
**Task**
Create class "Package" that represents a package which has a *length*, *width*, *height* (*cm*) and *weight* (*kg*) parameter.
Furthermore, the following should always give the current volume of the package:
```python
p = Package(0.2, 0.2, 0.2)
p.volume # computes 0.2 * 0.2 * 0.2 and returns it
```
But lo... | reference | class Package (object):
maxs = {"length": 350, "width": 300, "height": 150, "weight": 40}
def __init__(self, l, w, h, wg):
self . length = l
self . width = w
self . height = h
self . weight = wg
def __setattr__(self, att, v):
if v <= 0 or v > Package . maxs[att]:
raise... | Packet Delivery -- Enforcing Constraints | 587e1ef6f1a2534bbe0001ef | [
"Fundamentals"
] | https://www.codewars.com/kata/587e1ef6f1a2534bbe0001ef | 6 kyu |
# Task
I have defined (invisible to you) the function "raises_once"
that raises an exception if it is called for the first time and returns a magic value the second time it is called.
Your job is to call it twice (silencing the exception) and assign the magic value it returns to the variable *magic*.
So far, so si... | games | exec('try: raises_once()\nexcept: magic = raises_once()')
| Exception Handling (with restrictions) | 586fa9ddc66d18e2e10000ce | [
"Puzzles",
"Restricted"
] | https://www.codewars.com/kata/586fa9ddc66d18e2e10000ce | 6 kyu |
You're given a square consisting of random numbers, like so:
```javascript
var square = [
[1,2,3],
[4,8,2],
[1,5,3]];
```
Your job is to calculate the minimum total cost when moving from the upper left corner to the coordinate given. You're only allowed to move right or down.
In the above example the minim... | algorithms | def min_path(grid, x, y):
paths = [0] + [float('inf')] * (x + 1)
for j in range(y + 1):
for i in range(x + 1):
paths[i] = grid[j][i] + min(paths[i - 1], paths[i])
return paths[x]
| Minimum path in squares | 5845e3f680a8cf0bad00017d | [
"Dynamic Programming",
"Algorithms"
] | https://www.codewars.com/kata/5845e3f680a8cf0bad00017d | 5 kyu |
An `non decreasing` number is one containing no two consecutive digits (left to right), whose the first is higer than the second. For example, 1235 is an non decreasing number, 1229 is too, but 123429 isn't.
Write a function that finds the number of non decreasing numbers up to `10**N` (exclusive) where N is the input... | reference | from math import comb
def increasing_numbers(digits):
return comb(digits + 9, 9)
| Increasing Numbers with N Digits | 57698ec6dd8944888e000110 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/57698ec6dd8944888e000110 | 6 kyu |
## Summary
Implement an algorithm which analyzes a two-color image and determines how many isolated areas of a single color the image contains.
### Islands
An "island" is a set of adjacent pixels of one color (`1`) which is surrounded by pixels of a different color (`0`). Pixels are considered adjacent if their coor... | algorithms | def count_islands(a):
def dfs(x, y):
if not (0 <= x < len(a) and 0 <= y < len(a[0]) and a[x][y]):
return 0
a[x][y] = 0
for dx in range(- 1, 2):
for dy in range(- 1, 2):
dfs(x + dx, y + dy)
return 1
return sum(dfs(i, j) for i in range(len(a)) for j in range(len(a[0])))
| Count the Islands | 55a4f1f67157d8cbe200007b | [
"Algorithms",
"Graphics",
"Arrays"
] | https://www.codewars.com/kata/55a4f1f67157d8cbe200007b | 6 kyu |
A palindrome is a series of characters that read the same forwards as backwards such as "hannah", "racecar" and "lol".
For this Kata you need to write a function that takes a string of characters and returns the length, as an integer value, of longest alphanumeric palindrome that could be made by combining the charact... | algorithms | from collections import Counter
def longest_palindrome(s):
c = Counter(filter(str . isalnum, s . lower()))
return sum(v / / 2 * 2 for v in c . values()) + any(v % 2 for v in c . values())
| Longest palindrome | 5a0178f66f793bc5b0001728 | [
"Arrays",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5a0178f66f793bc5b0001728 | 6 kyu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.