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 |
|---|---|---|---|---|---|---|---|
In this kata, your task is to implement what I call **Iterative Rotation Cipher (IRC)**. To complete the task, you will create an object with two methods, `encode` and `decode`. (For non-JavaScript versions, you only need to write the two functions without the enclosing dict)
<h2 style='color:#f66'>Input</h2>
<p>The <... | algorithms | def shift(string, step):
i = (step % len(string)) if string else 0
return f" { string [ - i :]}{ string [: - i ]} "
def encode(n, string):
for _ in range(n):
shifted = shift(string . replace(" ", ""), n)
l = [len(word) for word in string . split(" ")]
string = " " . join(
shi... | Iterative Rotation Cipher | 5a3357ae8058425bde002674 | [
"Strings",
"Ciphers",
"Algorithms"
] | https://www.codewars.com/kata/5a3357ae8058425bde002674 | 5 kyu |

In this kata, your task is to implement what I call **Interlaced Spiral Cipher (ISC)**.
*Encoding* a string using ISC is achieved with the following steps:
1. Form a square large enough to fit all the string characters
2. Starting with the top-left corner, place str... | algorithms | def interlaced_spiral(s):
n = int((s - 1) * * .5) + 1
for x, r in enumerate(range(n, 0, - 2)):
for y in range(x, x + r - (r > 1)):
for _ in range(4):
yield x * n + y
if r == 1:
return
x, y = y, n - x - 1
def encode(s):
table = {j: i for i, j in enumerate(interlaced_... | Interlaced Spiral Cipher | 5a24a35a837545ab04001614 | [
"Ciphers",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5a24a35a837545ab04001614 | 5 kyu |
The prime `149` has 3 permutations which are also primes: `419`, `491` and `941`.
There are 3 primes below `1000` with three prime permutations:
```python
149 ==> 419 ==> 491 ==> 941
179 ==> 197 ==> 719 ==> 971
379 ==> 397 ==> 739 ==> 937
```
```javascript
149 ==> 419 ==> 491 ==> 941
179 ==> 197 ==> 719 ==> 971
379 ==... | algorithms | from collections import Counter
def permutational_primes(n_max, k_perms):
print(n_max, k_perms)
# list of primes
P = [2] + [n for n in range(2, n_max) if all(n % i != 0 for i in range(2, int(n * * (0.5)) + 2))]
A = ["" . join(sorted(str(p))) for p in P] # convert e.g. 839 to 389
B = Counter(A). i... | Permutational Primes | 55eec0ee00ae4a8fa0000075 | [
"Algorithms",
"Sorting",
"Permutations",
"Mathematics",
"Memoization",
"Data Structures"
] | https://www.codewars.com/kata/55eec0ee00ae4a8fa0000075 | 4 kyu |
# Task
Here are 10 ribbons. The length of each ribbon is 11 units with a unique pattern (number 0-9). Now let's put these ribbons on a 11x11 table. Every time a ribbon is placed, horizontal or vertical. The next ribbon and the last one are in different directions, and ensure that any two ribbons are not completely ove... | reference | from collections import Counter
def the_order_of(ribbons):
def extractH(row): return next(
(d for d, n in Counter(row). items() if n > 1 and d != '.'), None)
horz = {d for d in map(extractH, ribbons . split('\n')) if d}
cnt = Counter(filter(str . isdigit, ribbons))
tic = max(cnt . ... | Simple Fun #389: The Order Of Ribbons | 5a4adff7e626c53463000015 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a4adff7e626c53463000015 | 5 kyu |
Complete the function that takes a list of numbers (`nums`), as the only argument to the function. Take each number in the list and *square* it if it is even, or *square root* the number if it is odd. Take this new list and return the *sum* of it, rounded to two decimal places.
The list will never be empty and will on... | reference | def sum_square_even_root_odd(nums):
return round(sum(n * * 2 if n % 2 == 0 else n * * 0.5 for n in nums), 2)
| Sum - Square Even, Root Odd | 5a4b16435f08299c7000274f | [
"Fundamentals"
] | https://www.codewars.com/kata/5a4b16435f08299c7000274f | 7 kyu |
<img src="https://i.imgur.com/ta6gv1i.png?1" />
<!-- Featured 9/6/2021 -->
---
# Background
If your phone buttons have letters, then it is easy remember long phone numbers by making words from the substituted digits.
https://en.wikipedia.org/wiki/Phoneword
<img src="https://i.imgur.com/VJU55cg.png" title="source:... | algorithms | from collections import defaultdict
TABLE = str . maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"22233344455566677778889999")
NUMS = defaultdict(list)
for w in WORDS:
NUMS[w . translate(TABLE)]. append(w)
def check1800(s):
num = s[6:]. replace('-', ''). translate(TABLE)
ret... | 1-800-CODE-WAR | 5a3267b2ee1aaead3d000037 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5a3267b2ee1aaead3d000037 | 5 kyu |
You are stacking some boxes containing gold weights on top of each other. If a box contains more weight than the box below it, it will crash downwards and combine their weights. e.g. If we stack `[2]` on top of `[1]`, it will crash downwards and become a single box of weight `[3]`.
```
[2]
[1] --> [3]
```
Given an ar... | reference | from functools import reduce
def crashing_weights(weights):
return reduce(lambda a, b: [a1 + b1 if a1 > b1 else b1 for a1, b1 in zip(a, b)], weights)
| Crashing Boxes | 5a4a167ad8e1453a0b000050 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a4a167ad8e1453a0b000050 | 6 kyu |
Similarly to the [previous kata](https://www.codewars.com/kata/string-subpattern-recognition-i/), you will need to return a boolean value if the base string can be expressed as the repetition of one subpattern.
This time there are two small changes:
* if a subpattern has been used, it will be present at least twice, ... | reference | from collections import Counter
from functools import reduce
from math import gcd
def has_subpattern(string):
return reduce(gcd, Counter(string). values()) != 1
| String subpattern recognition II | 5a4a391ad8e145cdee0000c4 | [
"Strings",
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/5a4a391ad8e145cdee0000c4 | 6 kyu |
In this kata you need to build a function to return either `true/True` or `false/False` if a string can be seen as the repetition of a simpler/shorter subpattern or not.
For example:
```cpp,java
hasSubpattern("a") == false; //no repeated pattern
hasSubpattern("aaaa") == true; //created repeating "a"
hasSubpattern("ab... | reference | def has_subpattern(string):
return (string * 2). find(string, 1) != len(string)
| String subpattern recognition I | 5a49f074b3bfa89b4c00002b | [
"Strings",
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/5a49f074b3bfa89b4c00002b | 6 kyu |
The Catalan Numbers are defined by the formula:
<a href="http://imgur.com/dpDsgz2"><img src="http://i.imgur.com/dpDsgz2.png?1" title="source: imgur.com" /></a>
The first nine Catalan Numbers are:
```
Catalan Number Ordinal Term
1 0
1 1
2 2
5 ... | reference | s, n = [], 1
for i in range(200):
s . append(n)
n = 2 * n * (2 * i + 1) / / (i + 2)
def hankel_matrix_maker (n ): return [s [i : i + n ] for i in range ( n )] | #10 Matrices: Creating Hankel Matrices | 5a48c7e1e626c56fb7000092 | [
"Fundamentals",
"Mathematics",
"Arrays",
"Matrix"
] | https://www.codewars.com/kata/5a48c7e1e626c56fb7000092 | 6 kyu |
Each test case will generate a variable whose value is 777. Find the name of the variable. | games | def find_variable():
return next(k for k, v in globals(). items() if v == 777)
| Find the name of the lucky variable | 5a47d5ddd8e145ff6200004e | [
"Puzzles"
] | https://www.codewars.com/kata/5a47d5ddd8e145ff6200004e | 7 kyu |
In the sys module there is a function ```sys.setrecursionlimit``` and ```sys.getrecursionlimit```. These two functions set and get the recursion limit. If function calls stack is larger than this limit it will raise a ```RuntimeError```
Examples of these two functions:
```python
import sys
sys.setrecursionlimit(905)
s... | reference | def fetch_recursion_limit():
try:
return 1 + fetch_recursion_limit()
except RuntimeError:
return 2
| Get recursion limit | 5a1e1b69697598459d000057 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a1e1b69697598459d000057 | 6 kyu |
We'll think that a "mirror" section in an array is a group of contiguous elements ( > 1) such that somewhere in the array, the same group appears in reverse order. For example, the largest mirror section in [1, 2, 3, 8, 9, 3, 2, 1] is length 3 (the ...```1, 2, 3```... part). Return the length of the largest mirror sect... | algorithms | def max_mirror(arr):
n, r_arr = len(arr), arr[:: - 1]
for i in range(n, 1, - 1):
s1, s2 = set(), set()
for j in range(n - i + 1):
s1 . add(tuple(arr[j: j + i]))
s2 . add(tuple(r_arr[j: j + i]))
if s1 & s2:
return i
return 0
| The largest "mirror" | 5a3f61bab6cfd7acbc000001 | [
"Algorithms",
"Arrays"
] | https://www.codewars.com/kata/5a3f61bab6cfd7acbc000001 | 6 kyu |
In this kata, we want to discover a small property of numbers.
We say that a number is a **dd** number if it contains d occurences of a digit d, (d is in [1,9]).
## Examples
* 664444309 is a **dd** number, as it contains 4 occurences of the number 4
* 30313, 122 are **dd** numbers as they respectively contain 3 occu... | reference | from collections import Counter
def is_dd(n):
return any(value == count for value, count in Counter(int(x) for x in str(n)). items())
| Numbers with d occurences of digit d | 5a40fc7ce1ce0e34440000a3 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a40fc7ce1ce0e34440000a3 | 7 kyu |
The citizens of Codeland read each word from right to left, meaning that lexicographical comparison works differently in their language. Namely, string ```a``` is <i>lexicographically smaller</i> than string ```b``` if either: ```a``` is a suffix of ```b``` (in common sense, i.e. ```b``` ends with a substring equal to ... | algorithms | def unusual_lex_order(a):
return sorted(a, key=lambda k: k[:: - 1])
| Unusual Lex Order | 5a438bc1e1ce0e129100005a | [
"Algorithms",
"Fundamentals"
] | https://www.codewars.com/kata/5a438bc1e1ce0e129100005a | 7 kyu |
In input string ```word```(1 word):
* replace the vowel with the nearest left consonant.
* replace the consonant with the nearest right vowel.
P.S. To complete this task imagine the alphabet is a circle (connect the first and last element of the array in the mind). For example, 'a' replace with 'z', 'y' with 'a', etc.... | reference | def replace_letters(word):
return word . translate(str . maketrans('abcdefghijklmnopqrstuvwxyz', 'zeeediiihooooonuuuuutaaaaa'))
| Replace letters | 5a4331b18f27f2b31f000085 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/5a4331b18f27f2b31f000085 | 6 kyu |
For an integer ```k``` rearrange all the elements of the given array in such way, that:
all elements that are less than ```k``` are placed before elements that are not less than ```k```;<br>
all elements that are less than ```k``` remain in the same order with respect to each other;<br>
all elements that are not less ... | algorithms | def split_by_value(k, elements):
return sorted(elements, key=lambda x: x >= k)
| Split By Value | 5a433c7a8f27f23bb00000dc | [
"Algorithms"
] | https://www.codewars.com/kata/5a433c7a8f27f23bb00000dc | 7 kyu |
Given an `array` of numbers, return a new array of length `number` containing the last even numbers from the original array (in the same order). The original array will be not empty and will contain at least "number" even numbers.
For example:
```
([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) => [4, 6, 8]
([-22, 5, 3, 11, 26, -6, ... | reference | def even_numbers(arr, n):
return [i for i in arr if i % 2 == 0][- n:]
| Even numbers in an array | 5a431c0de1ce0ec33a00000c | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/5a431c0de1ce0ec33a00000c | 7 kyu |
## Task
**_Given_** *an array of integers* , **_Find_** **_the maximum product_** *obtained from multiplying 2 adjacent numbers in the array*.
____
# Notes
* **_Array/list_** size is *at least 2*.
* **_Array/list_** numbers could be a *mixture of positives, negatives also zeroes* .
___
# Input >> Output Examples
`... | reference | def adjacent_element_product(array):
return max(a * b for a, b in zip(array, array[1:]))
| Maximum Product | 5a4138acf28b82aa43000117 | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/5a4138acf28b82aa43000117 | 7 kyu |
Given a string, return the minimal number of parenthesis reversals needed to make balanced parenthesis.
For example:
```if-not:rust
~~~
solve(")(") = 2 Because we need to reverse ")" to "(" and "(" to ")". These are 2 reversals.
solve("(((())") = 1 We need to reverse just one "(" parenthesis to make it balanced.
sol... | reference | def solve(s):
if len(s) % 2:
return - 1
# imagine a simple symmetric random walk; '(' is a step up and ')' is a step down. We must stay above the original position
height = 0
counter = 0
for x in s:
if x == '(':
height += 1
else:
height -= 1
if height < 0:
counter += ... | Simple reversed parenthesis | 5a3f2925b6cfd78fb0000040 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a3f2925b6cfd78fb0000040 | 6 kyu |
# Task
Christmas is coming. In the [previous kata](https://www.codewars.com/kata/5a405ba4e1ce0e1d7800012e), we build a custom Christmas tree with the specified characters and the specified height.
Now, we are interested in the center of the Christmas tree.
Please imagine that we build a Christmas tree with `chars =... | reference | def center_of(chars):
if not chars:
return ''
res, ln, nxt, step = [chars[0]], len(chars), 4, 4
while len(res) < len(chars) or len(res) % 2 or res[: len(res) / / 2] != res[len(res) / / 2:]:
res . append(chars[nxt % ln])
step += 4
nxt += step
ind = next(k for k in range(1, len... | Custom Christmas Tree III: the center of leaves | 5a4076f3e1ce0ee6d4000010 | [
"Puzzles",
"Strings",
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/5a4076f3e1ce0ee6d4000010 | 6 kyu |
This is a simplified version of [Racing #2: Accelerated Drag Race](https://www.codewars.com/kata/5a42c4cf8f27f25c3700009f).
Anna and Bob are good friends, but also rival drag racers.
Bob just got his engine reconditioned and wants to prove that he is the fastest of the two.
In this kata, you will simulate a drag race... | reference | def drag_race(d, * cars):
def fullTime(car): return d / car . speed + car . reaction_time
t1, t2 = map(fullTime, cars)
return ("It's a draw" if abs(t1 - t2) < 1e-10 else
"{} is the winner" . format("Anna" if t1 < t2 else "Bob"))
| Racing #1: Simplified Drag Race | 5a40f5b01f7f70ed7600001e | [
"Games",
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/5a40f5b01f7f70ed7600001e | 7 kyu |
You drop a ball from a given height. After each bounce, the ball returns to some fixed proportion of its previous height. If the ball bounces to height 1 or less, we consider it to have stopped bouncing. Return the number of bounces it takes for the ball to stop moving.
```
bouncingBall(initialHeight, bouncingProporti... | reference | def bouncing_ball(initial, proportion):
count = 0
while initial > 1:
initial = initial * proportion
count = count + 1
return count
| Bouncing Ball | 5a40c250c5e284a76400008c | [
"Fundamentals"
] | https://www.codewars.com/kata/5a40c250c5e284a76400008c | 7 kyu |
# Task
Christmas is coming, and your task is to build a custom Christmas tree with the specified characters and the specified height.
# Inputs:
- `chars`: the specified characters.
- `n`: the specified height. A positive integer greater than 2.
# Output:
- A multiline string. Each line is separated by `\n`. A tree ... | games | def custom_christmas_tree(chars, n):
from itertools import cycle
it = cycle(chars)
tree = [' ' . join(next(it) for j in range(i)). center(
2 * n). rstrip() for i in range(1, n + 1)]
tree . extend('|' . center(2 * n). rstrip() for _ in range(n / / 3))
return '\n' . join(tree)
| Custom Christmas Tree | 5a405ba4e1ce0e1d7800012e | [
"Strings",
"ASCII Art",
"Puzzles"
] | https://www.codewars.com/kata/5a405ba4e1ce0e1d7800012e | 6 kyu |
In this Kata, you will be given a expression string and your task will be to remove all braces as follows:
```
solve("x-(y+z)") = "x-y-z"
solve("x-(y-z)") = "x-y+z"
solve("u-(v-w-(x+y))-z") = "u-v+w+x+y-z"
solve("x-(-y-z)") = "x+y+z"
```
There are no spaces in the expression. Only two operators are given: `"+" or "-"... | algorithms | from functools import reduce
def solve(st):
res, s, k = [], "", 1
for ch in st:
if ch == '(':
res . append(k)
k = 1
elif ch == ')':
res . pop()
k = 1
elif ch == '-':
k = - 1
elif ch == '+':
k = 1
else:
s += '-' + ch if (reduce(lambda ... | Simple parenthesis removal | 5a3bedd38f27f246c200005f | [
"Strings",
"Logic",
"Algorithms"
] | https://www.codewars.com/kata/5a3bedd38f27f246c200005f | 5 kyu |
In this Kata your task will be to return the count of pairs that have consecutive numbers as follows:
```Haskell
pairs([1,2,5,8,-4,-3,7,6,5]) = 3
The pairs are selected as follows [(1,2),(5,8),(-4,-3),(7,6),5]
--the first pair is (1,2) and the numbers in the pair are consecutive; Count = 1
--the second pair is (5,8) an... | reference | def pairs(ar):
res = 0
for i in range(1, len(ar), 2):
if abs(ar[i] - ar[i - 1]) == 1:
res += 1
return res
| Simple consecutive pairs | 5a3e1319b6486ac96f000049 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/5a3e1319b6486ac96f000049 | 7 kyu |
The first input array is the key to the correct answers to an exam, like `["a", "a", "b", "d"]`. The second one contains a student's submitted answers.
The two arrays are not empty and are the same length. Return the score for this array of answers, giving `+4` for each correct answer, `-1` for each incorrect answer,... | reference | def check_exam(arr1, arr2):
return max(0, sum(4 if a == b else - 1 for a, b in zip(arr1, arr2) if b))
| Check the exam | 5a3dd29055519e23ec000074 | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/5a3dd29055519e23ec000074 | 7 kyu |
You must design a function `mangle` that β given an array of 6 distinct numbers in [-59, 60] β returns an array consisting of 5 of those 6 numbers.
Then you must design a function `guess` that β given the result of `mangle` β returns the 6th value.
```if:javascript
`console` is the only global object you will have ac... | games | guesses = {}
def guess(mangled):
return guesses[* mangled]
def mangle(integers):
global guesses
for i, guess in enumerate(integers):
mangled = integers[: i] + integers[i + 1:]
if tuple(mangled) not in guesses:
guesses[* mangled] = guess
return mangled
| Compression : impossible | 5a2950621f7f70c12d000073 | [
"Mathematics",
"Puzzles"
] | https://www.codewars.com/kata/5a2950621f7f70c12d000073 | 5 kyu |
The written representation of a number (with 4 or more digits) can be split into three parts in various different ways. For example, the written number 1234 can be split as [1 | 2 | 34] or [1 | 23 | 4] or [12 | 3 | 4].
Given a written number, find the highest... | reference | from functools import reduce
from operator import mul
def maximum_product_of_parts(n):
s = str(n)
return max(reduce(mul, map(int, (s[: i], s[i: j], s[j:])))
for i in range(1, len(s) - 1) for j in range(i + 1, len(s)))
| Maximum Product of Parts | 5a3a95c2e1ce0efe2c0001b0 | [
"Algorithms"
] | https://www.codewars.com/kata/5a3a95c2e1ce0efe2c0001b0 | 6 kyu |
## Task
Write a function called `hungarian_numeral()` which takes a non-negative integer `n` and returns the corresponding Hungarian numeral to it.
## Precondition
1. `n` is always an __int__
2. `0 <= n < 1000000`
## Rules for Hungarian cardinal numerals (simplified)
General rules for constructing numerals i... | reference | import copy
first = {0: 'nulla', 1: 'egy', 2: 'kettΕ', 3: 'hΓ‘rom',
4: 'nΓ©gy', 5: 'ΓΆt', 6: 'hat', 7: 'hΓ©t', 8: 'nyolc', 9: 'kilenc'}
second = {0: '', 1: 'tizen', 2: 'huszon', 3: 'harminc', 4: 'negyven',
5: 'ΓΆtven', 6: 'hatvan', 7: 'hetven', 8: 'nyolcvan', 9: 'kilencven'}
third = {0: '', 1: 'szΓ‘z'... | Hungarian Cardinal Numerals | 58008f9897917feeec000a3e | [
"Fundamentals"
] | https://www.codewars.com/kata/58008f9897917feeec000a3e | 6 kyu |
We like parsed SQL or PL/SQL blocks...
You need to write function that return list of literals indices from source block, excluding "in" comments, OR return empty list if no literals found.
input:
some fragment of sql or pl/sql code
output:
list of literals indices [(start, end), ...] OR empty list
Sample:
```
get_... | algorithms | import re
SKIPERS = re . compile(r'|' . join(["\\\*.*?\*/", "--.*?(\n|$)", "''"]))
def get_textliterals(code):
code = SKIPERS . sub(lambda m: "x" * len(m . group()), code . rstrip())
if code . count("'") % 2:
code += "'"
return [(m . start(), m . end()) for m in re . finditer(r"'.+?'", cod... | Little PL/SQL parser - get text literals | 5536552b372553087d000086 | [
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/5536552b372553087d000086 | 5 kyu |
In this Kata, you will be given a string of numbers in sequence and your task will be to return the missing number. If there is no number
missing or there is an error in the sequence, return `-1`.
For example:
```Haskell
missing("123567") = 4
missing("899091939495") = 92
missing("9899101102") = 100
missing("599600601... | algorithms | def missing(seq):
for digits in range(1, len(seq) / / 2 + 1):
my_seq = last = seq[: digits]
n = int(my_seq)
missing = None
while len(my_seq) < len(seq):
n += 1
my_seq += str(n)
if not seq . startswith(my_seq):
if missing == None:
missing = n
my_seq = last
el... | Simple number sequence | 5a28cf591f7f7019a80000de | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5a28cf591f7f7019a80000de | 5 kyu |
Write a code that orders collection of Uris based on it's domain next way that it will returns fisrt Uris with domain "com", "gov", "org" (in alphabetical order of their domains) and then all other Uris ordered in alphabetical order of their domains
In addition to that
1. content of Uri should not be changed,
2. othe... | reference | def order_by_domain(addresses):
def weights(a):
_, d = a . rsplit('.', 1)
return {'com': 0, 'gov': 1, 'org': 2}. get(d[: 3], 3), d
return sorted(addresses, key=weights)
| "com", "gov", "org" first | 57f21fcd69e09cb0d2000088 | [
"Fundamentals",
"Algorithms",
"Sorting"
] | https://www.codewars.com/kata/57f21fcd69e09cb0d2000088 | 6 kyu |
Your task is to return the number of visible dots on a die after it has been rolled(that means the total count of dots that would not be touching the table when rolled)
6, 8, 10, 12, 20 sided dice are the possible inputs for "numOfSides"
topNum is equal to the number that is on top, or the number that was rolled.
f... | algorithms | def totalAmountVisible(topNum, numOfSides):
return numOfSides * (numOfSides + 1) / 2 - (numOfSides - topNum + 1)
| Visible Dots On a Die | 5a39724945ddce2223000800 | [
"Algorithms"
] | https://www.codewars.com/kata/5a39724945ddce2223000800 | 7 kyu |
LΠ΅t's create function to play cards. You receive 3 arguments: `card1` and `card2` are cards from a single deck; `trump` is the main suit, which beats all others.
You have a preloaded `deck` (in case you need it):
```
deck = ["joker","2β£","3β£","4β£","5β£","6β£","7β£","8β£","9β£","10β£","Jβ£","Qβ£","Kβ£","Aβ£",
"2β¦... | algorithms | def card_game(card_1, card_2, trump):
deck = ['joker', '2β£', '3β£', '4β£', '5β£', '6β£', '7β£', '8β£', '9β£', '10β£', 'Jβ£', 'Qβ£', 'Kβ£', 'Aβ£',
'2β¦', '3β¦', '4β¦', '5β¦', '6β¦', '7β¦', '8β¦', '9β¦', '10β¦', 'Jβ¦', 'Qβ¦', 'Kβ¦', 'Aβ¦',
'2β₯', '3β₯', '4β₯', '5β₯', '6β₯', '7β₯', '8β₯', '9β₯', '10β₯', 'Jβ₯', 'Qβ₯', 'Kβ₯', 'Aβ₯... | Card game | 5a3141fe55519e04d90009d8 | [
"Algorithms",
"Games",
"Strings"
] | https://www.codewars.com/kata/5a3141fe55519e04d90009d8 | 6 kyu |
You will be given a string and you task is to check if it is possible to convert that string into a palindrome by removing a single character. If the string is already a palindrome, return `"OK"`. If it is not, and we can convert it to a palindrome by removing one character, then return `"remove one"`, otherwise return... | algorithms | def solve(s):
def isOK(x): return x == x[:: - 1]
return ("OK" if isOK(s) else
"remove one" if any(isOK(s[: i] + s[i + 1:]) for i in range(len(s))) else
"not possible")
| Single character palindromes | 5a2c22271f7f709eaa0005d3 | [
"Algorithms"
] | https://www.codewars.com/kata/5a2c22271f7f709eaa0005d3 | 6 kyu |
You have two arguments: ```string``` - a string of random letters(only lowercase) and ```array``` - an array of strings(feelings). Your task is to return how many specific feelings are in the ```array```.
For example:
```
string -> 'yliausoenvjw'
array -> ['anger', 'awe', 'joy', 'love', 'grief']
output -> '3 feelin... | reference | from collections import Counter
def countFeelings(letters, feelings):
counter = Counter(letters)
result = sum(not (Counter(feeling) - counter) for feeling in feelings)
return "{} feeling{}." . format(result, "s" if result != 1 else "")
| How many feelings? | 5a33ec23ee1aaebecf000130 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/5a33ec23ee1aaebecf000130 | 6 kyu |
# Background
A spider web is defined by
* "rings" numbered out from the centre as `0`, `1`, `2`, `3`, `4`
* "radials" labelled clock-wise from the top as `A`, `B`, `C`, `D`, `E`, `F`, `G`, `H`
Here is a picture to help explain:
<img src="https://i.imgur.com/tGeWQVq.png" title="source: imgur.com" />
# Web Coord... | algorithms | import math
def spider_to_fly(spider, fly):
web = {'A': 0, 'B': 45, 'C': 90, 'D': 135,
'E': 180, 'F': 225, 'G': 270, 'H': 315}
angle = min(abs(web[spider[0]] - web[fly[0]]),
360 - abs(web[spider[0]] - web[fly[0]]))
sideA, sideB = int(spider[1]), int(fly[1])
return m... | The Spider and the Fly (Jumping Spider) | 5a30e7e9c5e28454790000c1 | [
"Algorithms"
] | https://www.codewars.com/kata/5a30e7e9c5e28454790000c1 | 6 kyu |
Given a string that contains only letters, you have to find out the number of **unique** strings (including the string itself) that can be produced by re-arranging the letters of the string. Strings are case **insensitive**.
HINT: Generating all the unique strings and calling `length` on that isn't a great solution fo... | algorithms | from operator import mul
from functools import reduce
from collections import Counter
from math import factorial as fact
def uniq_count(s):
return fact(len(s)) / / reduce(mul, map(fact, Counter(s . lower()). values()), 1)
| Unique Strings | 586c7cd3b98de02ef60001ab | [
"Algorithms"
] | https://www.codewars.com/kata/586c7cd3b98de02ef60001ab | 6 kyu |
Your task is to get Zodiac Sign using input ```day``` and ```month```.
For example:
```javascript
getZodiacSign(1,5) => 'Taurus'
getZodiacSign(10,10) => 'Libra'
```
```ruby
get_zodiac_sign(1,5) => 'Taurus'
get_zodiac_sign(10,10) => 'Libra'
```
```python
get_zodiac_sign(1,5) => 'Taurus'
get_zodiac_sign(10,10) => 'Lib... | reference | SIGNS . append('Capricorn')
CUTOFFS = [19, 18, 20, 19, 20, 20, 22, 22, 22, 22, 21, 21]
def get_zodiac_sign(day, month):
return SIGNS[month] if day > CUTOFFS[month - 1] else SIGNS[month - 1]
| Get Zodiac Sign | 5a376259b6cfd77ca000006b | [
"Fundamentals"
] | https://www.codewars.com/kata/5a376259b6cfd77ca000006b | 7 kyu |
Given an integer, take the (mean) average of each pair of consecutive digits. Repeat this process until you have a single integer, then return that integer. e.g.
Note: if the average of two digits is not an integer, round the result **up** (e.g. the average of 8 and 9 will be 9)
## Examples
```
digitsAverage(246) =... | algorithms | def digits_average(input):
digits = [int(c) for c in str(input)]
while len(digits) > 1:
digits = [(a + b + 1) / / 2 for a, b in zip(digits, digits[1:])]
return digits[0]
| Digits Average | 5a32526ae1ce0ec0f10000b2 | [
"Algorithms"
] | https://www.codewars.com/kata/5a32526ae1ce0ec0f10000b2 | 7 kyu |
Create a function that returns the CSV representation of a two-dimensional numeric array.
Example:
```
input:
[[ 0, 1, 2, 3, 4 ],
[ 10,11,12,13,14 ],
[ 20,21,22,23,24 ],
[ 30,31,32,33,34 ]]
output:
'0,1,2,3,4\n'
+'10,11,12,13,14\n'
+'20,21,22,23,24\n'
+'30,31,32,33,34'
```
Array'... | reference | def toCsvText(array):
return '\n' . join(',' . join(map(str, line)) for line in array)
| CSV representation of array | 5a34af40e1ce0eb1f5000036 | [
"Fundamentals",
"Arrays",
"Strings"
] | https://www.codewars.com/kata/5a34af40e1ce0eb1f5000036 | 8 kyu |
Create an identity matrix of the specified size( >= 0).
Some examples:
```
(1) => [[1]]
(2) => [ [1,0],
[0,1] ]
[ [1,0,0,0,0],
[0,1,0,0,0],
(5) => [0,0,1,0,0],
[0,0,0,1,0],
[0,0,0,0,1] ]
```
| reference | def get_matrix(n):
return [[1 if i == j else 0 for i in range(n)] for j in range(n)]
| Matrix creation | 5a34da5dee1aae516d00004a | [
"Fundamentals",
"Arrays",
"Matrix",
"Linear Algebra",
"Mathematics",
"Language Features"
] | https://www.codewars.com/kata/5a34da5dee1aae516d00004a | 7 kyu |
You need to swap the head and the tail of the specified array:
the head (the first half) of array moves to the end, the tail (the second half) moves to the start.
The middle element (if it exists) leaves on the same position.
Return new array.
For example:
```
[ 1, 2, 3, 4, 5 ] => [ 4, 5, 3, 1, 2 ]
\... | algorithms | def swap_head_tail(a):
r, l = (len(a) + 1) / / 2, len(a) / / 2
return a[r:] + a[l: r] + a[: l]
| Swap the head and the tail | 5a34f087c5e28462d9000082 | [
"Algorithms",
"Arrays"
] | https://www.codewars.com/kata/5a34f087c5e28462d9000082 | 7 kyu |
Hello!
Let us have a list `L`
```
l = [1,2,3]
```
Now, if we cycle it and will take consequent pairs, we'll get
```
(1,2), (2, 3), (3, 1), (1, 2) ...
```
and so on.
Your task is to create a generator `gen(n, iterable)` which will iterate over n-tuples of cycled iterable.
| reference | from itertools import cycle
def gen(n, iterable):
iter, r = cycle(iterable), ()
while True:
while len(r) < n:
r += (next(iter),)
yield r
r = r[1:]
| Shifted cycles | 5a31a71c1f7f705a93000005 | [
"Iterators",
"Fundamentals"
] | https://www.codewars.com/kata/5a31a71c1f7f705a93000005 | 6 kyu |
In this kata you will have to modify a sentence so it meets the following rules:
convert every word backwards that is:
longer than 6 characters
OR
has 2 or more 'T' or 't' in it
convert every word uppercase that is:
exactly 2 characters long
OR
before a comma
convert every word to a "0" tha... | reference | import re
def spiner(s, p):
return (s[:: - 1] if len(s) > 6 or s . lower(). count('t') > 1
else s . upper() if len(s) == 2 or p == ','
else '0' if len(s) == 1
else s) + p
def spin_solve(sentence):
return re . sub(r"((?:\w|['-])+)(\W)?", lambda m: spiner(m . group(1), m... | Spin the sentence | 5a3277005b2f00a11b0011c4 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5a3277005b2f00a11b0011c4 | 6 kyu |
## Preface
This is the performance version of the [Prime Ant]( https://www.codewars.com/kata/prime-ant) kata. If you did not complete it yet, you should begin there.
## Description
The "prime ant" is an obstinate animal that navigates the integers and divides them until there are only primes left!
Initially, we ha... | algorithms | n = 10 * * 6
s = list(range(n + 1))
s[4:: 2] = ((n - 4) / / 2 + 1) * [2]
for i in range(3, int((n + 1) * * .5) + 1, 2):
if s[i] == i:
for j in range(i * i, n + 1, i):
if s[j] == j:
s[j] = i
def prime_ant(n):
d, a = 2, list(range(n + 1))
for _ in range(n):
if s[a[d]] == a... | Prime Ant - Performance Version | 5a2e96f1c5e2849eef00014a | [
"Performance",
"Algorithms"
] | https://www.codewars.com/kata/5a2e96f1c5e2849eef00014a | 5 kyu |
It's 3AM and you get the dreaded call from a customer: the program your company sold them is hanging. You eventually trace the problem down to a call to a function named `mystery`. Usually, `mystery` works fine and produces an integer result for an integer input. However, on certain inputs, the `mystery` function just ... | reference | from signal import *
def signal_handler(signum, frame):
raise Exception
def wrap_mystery(n):
signal(SIGALRM, signal_handler)
setitimer(ITIMER_REAL, .01)
try:
return mystery(n)
except:
return - 1
| Program hangs! | 55f9439929875c58a500007a | [
"Fundamentals"
] | https://www.codewars.com/kata/55f9439929875c58a500007a | 5 kyu |
## Objective
As the number of published katas on Codewars grows, so does the likelihood of a newly published kata being a duplicate of an existing one. This is most prevalent among the simpler white katas (those ranked 7 or 8 kyu). Concerned with the ever-increasing number of duplicates, you've decided to start work on... | reference | from collections import Counter
def dupe_detect(functions):
results = [tuple(map(f, range(256))) for f in functions]
repeated = [tup for tup, v in Counter(results). items() if v > 1]
return [[i for i, t in enumerate(results) if t == f] for f in repeated]
| Meta-Kata: Duplicate Detector v0.1 | 5a2f92621f7f701e02000097 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a2f92621f7f701e02000097 | 6 kyu |
Your task it to return ```true``` if the fractional part (rounded to 1 digit) of the result (```a``` / ```b```) exists, more than ```0``` and is multiple of ```n```.
Otherwise return ```false```. (For Python return True or False)
All arguments are positive digital numbers.
Rounding works like toFixed() method. (if mo... | reference | def isMultiple(a, b, n):
remainder = int((a / b + 0.05) * 10) % 10
return remainder > 0 and remainder % n == 0
| Multiple remainder of the division | 5a2f83daee1aae4f1c00007e | [
"Fundamentals"
] | https://www.codewars.com/kata/5a2f83daee1aae4f1c00007e | 7 kyu |
## Task
Write a function that returns `true` if the number is a "Very Even" number.
If a number is a single digit, then it is simply "Very Even" if it itself is even.
If it has 2 or more digits, it is "Very Even" if the sum of its digits is "Very Even".
## Examples
```
number = 88 => returns false -> 8 + 8 = 16 ->... | reference | def is_very_even_number(n):
while len(str(n)) > 1:
n = sum(int(x) for x in str(n))
return True if n % 2 == 0 else False
| "Very Even" Numbers. | 58c9322bedb4235468000019 | [
"Fundamentals",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/58c9322bedb4235468000019 | 7 kyu |
You are presented with a single knight on a chess board.
Your task is to count the number of unique positions that knight could reach using exactly two moves.
In chess a knight can move either 2 squares horizonally and 1 square vertically OR 2 squares vertically and one square horizontally. It must stay on the board a... | algorithms | # (1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)
def moves(pos: tuple):
from itertools import product
x, y = pos
pos = list()
for move in list(product((1, - 1), (2, - 2))) + list(product((2, - 2), (1, - 1))):
if 0 <= x + move[0] <= 7 and 0 <= y + move[1] <= 7:
pos ... | Valid Chess Moves | 5707bf345699a1e98800004b | [
"Algorithms",
"Arrays"
] | https://www.codewars.com/kata/5707bf345699a1e98800004b | 5 kyu |
In this Kata, you will be given a ```number```, two indexes (```index1``` and ```index2```) and a ```digit``` to look for. Your task will be to check if the ```digit``` exists in the ```number```, within the ```indexes``` given.
Be careful, the ```index2``` is not necessarily more than the ```index1```.
```
index1 ... | reference | def check_digit(n, i1, i2, d):
return str(d) in str(n)[min(i1, i2): max(i1, i2) + 1]
| Check digit | 5a2e8c0955519e54bf0000bd | [
"Fundamentals",
"Strings",
"Puzzles"
] | https://www.codewars.com/kata/5a2e8c0955519e54bf0000bd | 7 kyu |
In this kata, you will be given a grid and a point, and you will want to return the numbers in the row, column and both the diagonals that point is on, like a queen's move in chess.
For example, given the grid:
```
[[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 0],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23... | algorithms | def check_grid(grid, pos, size):
c, r = pos
return [
grid[r],
[row[c] for row in grid],
[grid[r2][c - r + r2]
for r2 in range(len(grid)) if 0 <= c - r + r2 < len(grid)],
[grid[r2][c + r - r2]
for r2 in range(len(grid)) if 0 <= c + r - r2 < len(grid... | Find the lines! | 5a2d376ec5e2845ec20000bd | [
"Algorithms",
"Arrays",
"Lists",
"Logic"
] | https://www.codewars.com/kata/5a2d376ec5e2845ec20000bd | 6 kyu |
### Isograms
> An isogram (also known as a "nonpattern word") is a logological term for a word or phrase without a repeating letter.
>
> Isograms can be useful as keys in ciphers, since isogram sequences of the same length make for simple one-to-one mapping between the symbols. Ten-letter isograms like PATHFINDER, DUM... | algorithms | def isogram_encode(input=None, key=None):
try:
assert input and len(key) == len(set(key)) == 10
trans = dict(zip('1234567890', key . upper()))
return '' . join([trans[d] for d in str(input)])
except:
return 'Incorrect key or input!'
def isogram_decode(input=None, key=None):
try:
... | Isogram Cipher | 58fbc832e86f5e905300007f | [
"Ciphers",
"Algorithms"
] | https://www.codewars.com/kata/58fbc832e86f5e905300007f | 6 kyu |
In this Kata, two players, Alice and Bob, are playing a palindrome game. Alice starts with `string1`, Bob starts with `string2`, and the board starts out as an empty string. Alice and Bob take turns; during a turn, a player selects a letter from his or her string, removes it from the string, and appends it to the board... | algorithms | from collections import Counter
def solve(* args):
c1, c2 = map(Counter, args)
return 2 - any(c1[k] - c2[k] >= 2 and k not in c2 for k in c1)
| Simple palindrome game | 5a26af968882f3523100003d | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5a26af968882f3523100003d | 6 kyu |
In this kata, you will be given a string containing numbers from **a** to **b**, one number can be missing from these numbers, then the string will be shuffled, you're expected to return an array of all possible missing numbers.
## Examples (input => output)
Here's a string with numbers from 1 - 21, its missing one n... | games | from collections import Counter
from itertools import permutations
def find_number(start, stop, s):
miss = Counter('' . join(map(str, range(start, stop + 1)))) - Counter(s)
intValues = {int(v) for v in map('' . join, permutations(
'' . join(c * n for c, n in miss . items()))) if v and v[0] != '... | Find the missed number | 5a1d86dbba2a142e040000ee | [
"Mathematics",
"Puzzles",
"Algorithms",
"Logic"
] | https://www.codewars.com/kata/5a1d86dbba2a142e040000ee | 6 kyu |
In this kata, your task is to write a function `to_bytes(n)` (or `toBytes(n)` depending on language) that produces a list of bytes that represent a given non-negative integer `n`. Each byte in the list is represented by a string of `'0'` and `'1'` of length 8. The most significant byte is first in the list. The example... | reference | def to_bytes(n):
if not n:
return ['00000000']
res = []
while n:
res . append('{:08b}' . format(n % 256))
n / /= 256
return res[:: - 1]
| Number to Bytes | 5705601c5eef1fad69000674 | [
"Fundamentals"
] | https://www.codewars.com/kata/5705601c5eef1fad69000674 | 7 kyu |
This kata is part of the collection [Mary's Puzzle Books](https://www.codewars.com/collections/marys-puzzle-books).
# Zero Terminated Sum
Mary has another puzzle book, and it's up to you to help her out! This book is filled with zero-terminated substrings, and you have to find the substring with the largest sum of it... | reference | def largest_sum(s):
return max(sum(map(int, x)) for x in s . split('0'))
| Zero Terminated Sum | 5a2d70a6f28b821ab4000004 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a2d70a6f28b821ab4000004 | 7 kyu |
A **prime number** (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
You will be given the `lower` and `upper` limits: the program will look for any prime number that exists between the lower limit to the upper limit (included).
Your objective is to sum all the pri... | algorithms | # generate primes up to limit
limit = 10 * * 6
sieve = [0] + list(range(3, limit + 1, 2))
for n in sieve:
if n:
for i in range(n * n, limit + 1, n * 2):
sieve[i / / 2] = 0
primes = [2] + list(n for n in sieve if n)
def sumPrimes(lower, upper):
return sum(p for p in primes if lower <= ... | Sum of Primes | 5902ea9b378a92a990000016 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5902ea9b378a92a990000016 | 7 kyu |
Check if it is a vowel(a, e, i, o, u,) on the ```n``` position in a string (the first argument). Don't forget about uppercase.
A few cases:
```
{
checkVowel('cat', 1) -> true // 'a' is a vowel
checkVowel('cat', 0) -> false // 'c' is not a vowel
checkVowel('cat', 4) -> false // this position doesn't exist
}
`... | reference | def check_vowel(s, i):
return 0 <= i < len(s) and s[i] in "aieouAEIOU"
| Is it a vowel on this position? | 5a2b7edcb6486a856e00005b | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/5a2b7edcb6486a856e00005b | 7 kyu |
In this Kata, you will be given a string and your task will be to return a list of ints detailing the count of uppercase letters, lowercase, numbers and special characters, as follows.
```Haskell
Solve("*'&ABCDabcde12345") = [4,5,5,3].
--the order is: uppercase letters, lowercase, numbers and special characters.
```
... | reference | def solve(s):
uc, lc, num, sp = 0, 0, 0, 0
for ch in s:
if ch . isupper():
uc += 1
elif ch . islower():
lc += 1
elif ch . isdigit():
num += 1
else:
sp += 1
return [uc, lc, num, sp]
| Simple string characters | 5a29a0898f27f2d9c9000058 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a29a0898f27f2d9c9000058 | 7 kyu |
Final kata of the series (highly recommended to compute [layers](https://www.codewars.com/kata/progressive-spiral-number-position/) and [branch](https://www.codewars.com/kata/progressive-spiral-number-branch/) first to get a good idea), this is a blatant ripoff of [the one offered on AoC](http://adventofcode.com/2017/d... | reference | def distance(n):
if n == 1:
return 0
r = 0 - (1 - n * * .5) / / 2
d, m = divmod(n - (2 * r - 1) * * 2 - 1, 2 * r)
z = (r * (1 + 1j) - m - 1) * 1j * * d
return abs(z . real) + abs(z . imag)
| Progressive Spiral Number Distance | 5a27e3438882f334a10000e3 | [
"Mathematics",
"Number Theory",
"Fundamentals"
] | https://www.codewars.com/kata/5a27e3438882f334a10000e3 | 6 kyu |
In this Kata, you will be given a list of strings and your task will be to find the strings that have the same characters and return the sum of their positions as follows:
```Haskell
solve(["abc","abbc", "ab", "xyz", "xy", "zzyx"]) = [1,8]
-- we see that the elements at indices 0 and 1 have the same characters, as do... | algorithms | from collections import defaultdict
def solve(arr):
dct = defaultdict(list)
for i, fs in enumerate(map(frozenset, arr)):
dct[fs]. append(i)
return sorted(sum(lst) for lst in dct . values() if len(lst) > 1)
| Arrays of Lists of Sets | 5a296b571f7f70b0b3000100 | [
"Strings",
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/5a296b571f7f70b0b3000100 | 6 kyu |
# Base reduction
## Input
A positive integer:
```
0 < n < 1000000000
```
## Output
The end result of the base reduction.
If it cannot be fully reduced (reduced down to a single-digit number), return -1.
Assume that if 150 conversions from base 11 take place in a row, the number cannot be fully reduced.
## Descri... | algorithms | def basereduct(x):
for _ in range(150):
x = int(str(x), int(max(str(x))) + 1 + ('9' in str(x)))
if x < 10:
return x
return - 1
| Base Reduction | 5840e31f770be1636e0000d3 | [
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/5840e31f770be1636e0000d3 | 6 kyu |
Your task is determine the lowest number base system in which the input `n` ( base 10 ), expressed in this number base system, is all `1`s in its digits.
See some examples:
`7` in base 2 is `111` - fits! answer is `2`
`21` in base 2 is `10101` - contains `0`, does not fit
`21` in base 3 is `210` - contains `0` and... | reference | def get_min_base(number):
for ln in range(number . bit_length(), 2, - 1):
b = int(number * * (1 / (ln - 1)))
if b * * ln - 1 == number * (b - 1):
return b
else:
return number - 1
| Lowest base system | 58bc16e271b1e4c5d3000151 | [
"Performance"
] | https://www.codewars.com/kata/58bc16e271b1e4c5d3000151 | 4 kyu |
Each time the function is called it should invert the passed triangle.
Make upside down the given triangle and invert the chars in the triangle.
```
if a char = " ", make it = "#"
if a char = "#", make it = " "
```
```
#
###
#####
#######
######### // normal
// inverted
# #
## ... | reference | # invert the triangle
# maketri(size_of_triangle) can be called for convenience
def invert_triangle(t):
return t[:: - 1]. translate(str . maketrans('# ', ' #'))
| Invert The Triangle | 5a224a15ee1aaef6e100005a | [
"Puzzles",
"Fundamentals"
] | https://www.codewars.com/kata/5a224a15ee1aaef6e100005a | 7 kyu |
In number theory, Euler's totient is an arithmetic function, introduced in 1763 by Euler, that counts the positive integers less than or equal to `n` that are relatively prime to `n`. Thus, if `n` is a positive integer, then `Ο(n)`, notation introduced by Gauss in 1801, is the number of positive integers `k β€ n` for wh... | algorithms | def totient(n):
if not isinstance(n, int) or n < 1:
return 0
phi = n >= 1 and n
for p in range(2, int(n * * .5) + 1):
if not n % p:
phi -= phi / / p
while not n % p:
n / /= p
if n > 1:
phi -= phi / / n
return phi
| Euler Totient Function | 53c9157c689f841d16000c03 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/53c9157c689f841d16000c03 | 5 kyu |
## Task
Write a function which accepts a sequence of unique integers ( `0 <= x < 32` ) as an argument and returns a 32-bit integer such that the integer, in its binary representation, has `1` at only those indices, numbered from right to left, which are in the sequence.
## Examples
`[0, 1] -> 3`
`[1, 2, 0, 4] -... | algorithms | def sort_by_bit(seq):
return sum(2 * * i for i in seq)
| Construct a bit vector set | 52f5424d0531259cfc000d04 | [
"Algorithms"
] | https://www.codewars.com/kata/52f5424d0531259cfc000d04 | 7 kyu |
Find the area of a generic n-sided polygon. The area_polygon will receive in input a list of n (x, y) tuples which are the coordinates of the n vertices and shall output the area of the polygon rounded to 1 decimal place.
The input will always be at least 3 points, and the polygon will not be self-intersecting. | reference | def area_polygon(vertex):
vertex . append(vertex[0])
return round(abs(sum([((vertex[i][0] * vertex[i + 1][1]) - (vertex[i][1] * vertex[i + 1][0])) for i in range(0, len(vertex) - 1)]) / 2), 1)
| Area of an n-sided polygon | 5727500a20c7f837fc001869 | [
"Geometry",
"Algebra",
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/5727500a20c7f837fc001869 | 6 kyu |
Take a number and check each digit if it is divisible by the digit on its left checked and return an array of booleans.
The booleans should always start with false becase there is no digit before the first one.
## Examples
```
73312 => [false, false, true, false, true]
2026 => [false, true, false, true... | algorithms | def divisible_by_last(n):
l = list(map(int, f"0 { n } "))
return [x and not y % x for x, y in zip(l, l[1:])]
| Divisible by previous digit? | 5a2809dbe1ce0e07f800004d | [
"Algorithms"
] | https://www.codewars.com/kata/5a2809dbe1ce0e07f800004d | 7 kyu |
Similar setting of the [previous](https://www.codewars.com/kata/progressive-spiral-number-position/), this time you are called to identify in which "branch" of the spiral a given number will end up.
Considering a square of numbers disposed as the 25 items in [the previous kata](https://www.codewars.com/kata/progressiv... | games | def branch(n):
k = int((- 1 + (n) * * .5) / 2 - 10 * * - 5)
return (n - 4 * k * (k + 1) - 2) / / (2 * (k + 1)) if n > 1 else 0
| Progressive Spiral Number Branch | 5a26ca51e1ce0e987b0000ee | [
"Mathematics",
"Number Theory",
"Puzzles"
] | https://www.codewars.com/kata/5a26ca51e1ce0e987b0000ee | 6 kyu |
# Task
You are a lonely frog.
You live on an integer array.
The meaning of your life is to jump and jump..
Now, here comes your new task.
You are given an integer array `arr` and a positive integer `n`.
You will jump following the rules below:
- Your initial position at `arr[0]`. arr[0] will always be `0`.
- ... | reference | def jumping(arr, n):
i = 0
while i < len(arr):
x = arr[i]
arr[i] += 1 if x < n else - 1
i += x
return arr . count(n)
| Simple Fun #387: Lonely Frog IV | 5a274c9fc5e284a9f7000072 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a274c9fc5e284a9f7000072 | 6 kyu |
In this Kata, you will be given two strings `a` and `b` and your task will be to return the characters that are not common in the two strings.
For example:
```Haskell
solve("xyab","xzca") = "ybzc"
--The first string has 'yb' which is not in the second string.
--The second string has 'zc' which is not in the first s... | reference | def solve(a, b):
s = set(a) & set(b)
return '' . join(c for c in a + b if c not in s)
| Unique string characters | 5a262cfb8f27f217f700000b | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5a262cfb8f27f217f700000b | 7 kyu |
Assume that you started to store items in progressively expanding square location, like this for the first 9 numbers:
```
05 04 03
06 01 02
07 08 09
```
And like this for the expanding to include up to the first 25 numbers:
```
17 16 15 14 13
18 05 04 03 12
19 06 01 02 11
20 07 08 09 10
21 22 23 24 25
```
You might... | reference | from math import ceil, sqrt
def layers(n):
return ceil(sqrt(n)) / / 2 + 1
| Progressive Spiral Number Position | 5a254114e1ce0ecf6a000168 | [
"Mathematics",
"Number Theory",
"Fundamentals"
] | https://www.codewars.com/kata/5a254114e1ce0ecf6a000168 | 7 kyu |
In this Kata, you will be given a string with brackets and an index of an opening bracket and your task will be to return the index of the matching closing bracket. Both the input and returned index are 0-based **except in Fortran where it is 1-based**. An opening brace will always have a closing brace. Return `-1` if... | algorithms | def solve(s, idx):
stack = []
for i, c in enumerate(s):
if c == '(':
stack += [i]
if c == ')':
if not stack:
break
if stack . pop() == idx:
return i
return - 1
| Simple string indices | 5a24254fe1ce0ec2eb000078 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5a24254fe1ce0ec2eb000078 | 6 kyu |
# Largest Rectangle in Background
Imagine a photo taken to be used in an advertisement. The background on the left of the motive is whitish and you want to write some text on that background. So you scan the photo with a high resolution scanner and, for each line, count the number of pixels from the left that are suff... | reference | # nice kata!
def largest_rect(n):
x, res, i = [], 0, 0
while i < len(n):
if not x or n[i] >= n[x[- 1]]:
x . append(i)
i += 1
else:
res = max(res, n[x . pop()] * (check(i, x)))
while x:
res = max(res, n[x . pop()] * (check(i, x)))
return res
def check(i, x):
... | Largest rectangle in background | 595db7e4c1b631ede30004c4 | [
"Algorithms",
"Fundamentals"
] | https://www.codewars.com/kata/595db7e4c1b631ede30004c4 | 5 kyu |
Hi there! Welcome to "Building an Adaboost model with Sklearn (Introductory Machine Learning)".
If you get stuck at any point I **strongly recommend** you read the relevant documentation:
http://scikit-learn.org/stable/index.html
This kata can be broken up into the following steps:
1. Import the relevant sklearn ... | algorithms | from sklearn . ensemble import AdaBoostClassifier
from sklearn . model_selection import train_test_split
def train_ada_boost(X, target, estimators=3, random_seed=0):
x_train, x_test, target_train, target_test = train_test_split(
X, target, random_state=random_seed)
model = AdaBoostClassifie... | Building an Adaboost model with Sklearn (Introductory Machine Learning) | 5a21bd361f7f7098e800000c | [
"Machine Learning",
"Algorithms",
"Tutorials",
"Data Science"
] | https://www.codewars.com/kata/5a21bd361f7f7098e800000c | 7 kyu |
## Acknowledgments:
I thank [yvonne-liu](https://www.codewars.com/users/yvonne-liu) for the idea and for the example tests :)
## Description:
Encrypt this!
You want to create secret messages which can be deciphered by the [Decipher this!](https://www.codewars.com/kata/decipher-this) kata. Here are the conditions:
... | reference | def encrypt_this(text):
result = []
for word in text . split():
# turn word into a list
word = list(word)
# replace first letter with ascii code
word[0] = str(ord(word[0]))
# switch 2nd and last letters
if len(word) > 2:
word[1], word[- 1] = word[- 1], word[1]
... | Encrypt this! | 5848565e273af816fb000449 | [
"Fundamentals",
"Strings",
"Regular Expressions",
"Arrays",
"Ciphers",
"Algorithms",
"Cryptography",
"Security"
] | https://www.codewars.com/kata/5848565e273af816fb000449 | 6 kyu |
In this Kata, we are going to determine if the count of each of the characters in a string can be equal if we remove a single character from that string.
For example:
```
solve('abba') = false -- if we remove any character, the count of each character will not be equal.
solve('abbba') = true -- if we remove one b, the... | algorithms | from collections import Counter
def solve(s):
return any(len(set(Counter(s . replace(c, '', 1)). values())) == 1 for c in s)
| String character frequency | 5a1a514effe75fd63b0000f2 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5a1a514effe75fd63b0000f2 | 6 kyu |
Write a function ```find_replaced``` that
-takes as an argument a shuffled list of integers from ```1``` to ```n``` (inclusive) where one element was deleted and another number between 1 and n (inclusive) was inserted in its place
-returns a tuple ```(deleted_element, inserted_element)```
See examples for more deta... | algorithms | def find_replaced(arr):
"""
s = len(arr)
sum a_i - duplicate + missing = s * (s + 1) // 2
sum a_i^2 - dumplicate^2 + missing^2 = s * (s + 1) * (2 * s + 1) // 6
"""
s = len(arr)
a = s * (s + 1) / / 2 - sum(arr)
b = s * (s + 1) * (2 * s + 1) / / 6 - sum(n * n for n in arr)
d = (b -... | Untangle list deletion/insertion | 5a179d4346d843ff1200000c | [
"Mathematics",
"Performance",
"Algorithms"
] | https://www.codewars.com/kata/5a179d4346d843ff1200000c | 6 kyu |
# Task
Determine the client's membership level based on the invested `amount` of money and the given thresholds for membership levels.
There are four membership levels (from highest to lowest): `Platinum, Gold, Silver, Bronze`
The minimum investment is the threshold limit for `Bronze` membership. If the given amount... | reference | def membership(amount, platinum, gold, silver, bronze):
ordered = reversed(sorted((v, k)
for k, v in locals(). items() if k != 'amount'))
return next((level . capitalize() for threshold, level in ordered if amount >= threshold), 'Not a member')
| Membership (with restrictions) | 5a21dcc48f27f2afa1000065 | [
"Puzzles",
"Restricted"
] | https://www.codewars.com/kata/5a21dcc48f27f2afa1000065 | 6 kyu |
```if:python
In this kata, you will take the keys and values of a `dict` and swap them around.
```
```if:javascript
In this kata, you will take the keys and values of an `object` and swap them around.
```
```if:haskell
In this kata, you will take the keys and values of a `Map` and swap them around.
```
You will be giv... | reference | def switch_dict(dic):
result = {}
for key, value in dic . items():
result . setdefault(value, []). append(key)
return result
| Swap items in a dictionary | 5a21e090f28b824def00013c | [
"Fundamentals",
"Arrays",
"Logic"
] | https://www.codewars.com/kata/5a21e090f28b824def00013c | 7 kyu |
Take debugging to a whole new level:
Given a string, remove every *single* bug.
This means you must remove all instances of the word 'bug' from within a given string, *unless* the word is plural ('bugs').
For example, given 'obugobugobuoobugsoo', you should return 'ooobuoobugsoo'.
Another example: given 'obbugugo',... | reference | import re
def debug(s):
return re . sub(r'bug(?!s)', '', s)
| Bug Squish! | 5a21f943c5e284d4340000cb | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5a21f943c5e284d4340000cb | 7 kyu |
Following from the previous kata and taking into account how cool psionic powers are compare to the Vance spell system (really, the idea of slots to dumb down the game sucks, not to mention that D&D became a smash hit among geeks, so...), your task in this kata is to create a function that returns how many power points... | reference | def psion_power_points(l, s): return [0, 2, 6, 11, 17, 25, 35, 46, 58, 72, 88, 106, 126, 147, 170, 195, 221, 250, 280, 311, 343][min(l, 20)] + (s - 10) / / 2 * l / / 2 if l and s > 10 else 0
| D&D Character generator #2: psion power points | 596b1d44224071b9f5000010 | [
"Fundamentals"
] | https://www.codewars.com/kata/596b1d44224071b9f5000010 | 6 kyu |
**Background**
You most probably know, that the *kilo* used by IT-People differs from the
*kilo* used by the rest of the world. Whereas *kilo* in kB is (mostly) intrepreted as 1024 Bytes (especially by operating systems) the non-IT *kilo* denotes the factor 1000 (as in "1 kg is 1000g"). The same goes for the prefixe... | reference | def memorysize_conversion(memorysize):
[value, unit] = memorysize . split(" ")
kibis = ["KiB", "MiB", "GiB", "TiB"]
kilos = ["kB", "MB", "GB", "TB"]
if unit in kibis:
return (str(round(float(value) * pow(1.024, kibis . index(unit) + 1), 3)) + " " + kilos[kibis . index(unit)])
else:
re... | Conversion between Kilobyte and KibiByte | 5a115ff080171f9651000046 | [
"Mathematics",
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5a115ff080171f9651000046 | 6 kyu |
You have been hired by a major MP3 player manufacturer to implement a new music compression standard.
In this kata you will implement the ENCODER, and its companion kata deals with the <a href="https://www.codewars.com/kata/a-simple-music-decoder">DECODER</a>. It can be considered a harder version of <a href="https://w... | algorithms | def compress(raw):
# initialize stack
stack = [raw[0], raw[1]]
# calculate inital difference between the first two elements!
difference = stack[1] - stack[0]
out = []
for value in raw[2:] + [float("inf")]:
if (value - stack[- 1]) == difference:
stack . append(value)
elif... | A Simple Music Encoder | 58db9545facc51e3db00000a | [
"Algorithms"
] | https://www.codewars.com/kata/58db9545facc51e3db00000a | 5 kyu |
### Making palindromes
Many numbers can be formed into [palindromic numbers](https://en.wikipedia.org/wiki/Palindromic_number) (a number that remains the same when its digits are reversed) by applying the [**196-algorithm**](http://mathworld.wolfram.com/196-Algorithm.html):
>Take any positive integer, reverse the dig... | algorithms | def alg196(n):
for _ in range(261): # Set a reasonable upper limit for iterations
n += int(str(n)[:: - 1])
if str(n) == str(n)[:: - 1]:
return n
return - 1
| The 196-algorithm and Lychrel numbers | 55e079b1e00f75e1cd00013b | [
"Algorithms"
] | https://www.codewars.com/kata/55e079b1e00f75e1cd00013b | 6 kyu |
**Dear Mr overseer,**
we are delighted that they have still managed to us in time.
We have a big problem.
Mankind will be extinct in the near future. The cause!? - wars, diseases, natural disasters, aliens ... figure it out. But thatβs not the point!
Vault-Tec has started to build vaults around the world. These ar... | reference | def populate_my_vault(n):
if n < 2:
return (n, 0, 0)
half, odd = divmod(n, 2)
crowded = n > 50
return 1 + crowded, half + odd - crowded, half - 1
| Vault experience (3): Populate the vaults | 57adadd36b34faea6b00031b | [
"Fundamentals"
] | https://www.codewars.com/kata/57adadd36b34faea6b00031b | 6 kyu |
Your task is to determine the top 3 place finishes in a pole vault competition involving several different competitors. This is isn't always so simple, and it is often a source of confusion for people who don't know the actual rules.
Here's what you need to know:
As input, you will receive an array of objects. Each o... | reference | def score_pole_vault(vaulter_list):
popytki = len(vaulter_list[0]["results"])
temp = {}
res = {}
for mas in vaulter_list:
i = popytki - 1
while i >= 0 and mas [ "results" ][ i ]. find ( 'O' ) == - 1 :
i -= 1
if i < 0 :
n = 0
m = '' . join ( mas [ "results" ]). count ( 'X' )
else :
... | Determine Results of Pole Vault Competition | 579294724be9121e4d00018f | [
"Arrays",
"Sorting",
"Fundamentals"
] | https://www.codewars.com/kata/579294724be9121e4d00018f | 5 kyu |
We all know about Roman Numerals, and if not, here's a nice [introduction kata](http://www.codewars.com/kata/5580d8dc8e4ee9ffcb000050). And if you were anything like me, you 'knew' that the numerals were not used for zeroes or fractions; but not so!
I learned something new today: the [Romans did use fractions](https:/... | algorithms | FRACTIONS = " . : :. :: :.: S S. S: S:. S:: S:.:" . split(" ")
UNITS = " I II III IV V VI VII VIII IX" . split(" ")
TENS = " X XX XXX XL L LX LXX LXXX XC" . split(" ")
HUNDREDS = " C CC CCC CD D DC DCC DCCC CM" . split(" ")
THOUSANDS = " M MM MMM MMMM MMMMM" . split(" ")
def roman_fractions(n, f=0):
retur... | Roman numerals, Zeroes and Fractions | 55832eda1430b01275000059 | [
"Algorithms"
] | https://www.codewars.com/kata/55832eda1430b01275000059 | 5 kyu |
# Word Search
Create a program to solve a word search puzzle.
In word search puzzles you get a square of letters and have to find specific
words in them.
For example:
```
jefblpepre
camdcimgtc
oivokprjsm
pbwasqroua
rixilelhrs
wolcqlirpc
screeaumgr
alxhpburyi
jalaycalmp
clojurermt
```
There are several programming ... | reference | from collections import defaultdict
class Point (object):
def __init__(self, x, y):
self . x = x
self . y = y
def __eq__(self, other):
return self . x == other . x and self . y == other . y
class WordSearch (object):
def __init__(self, puzzle):
self . grid = defaultdict(list... | Word Search Grid | 58bcdf9a7288983803000042 | [
"Algorithms",
"Puzzles",
"Fundamentals"
] | https://www.codewars.com/kata/58bcdf9a7288983803000042 | 5 kyu |
Wikipedia: [Combination lock](https://en.wikipedia.org/wiki/Combination_lock#Single-dial_locks)
> ***Customarily, a lock of this type is opened by rotating the dial clockwise to the first numeral, counterclockwise to the second, and so on in an alternating fashion until the last numeral is reached.***
---
In this kat... | reference | def rotate_square_clockwise_90(lst): return list(map(list, zip(* lst[:: - 1])))
def square_to_diamond_clockwise_45(lst): return [[lst[x - y][y] for y in range(
len(lst)) if 0 <= x - y < len(lst)] for x in range(len(lst) * 2 - 1)]
def diamond_to_square_cc_45(lst, sqLen): return [
[lst[x + y][sqLen - ... | Combination Lock | 585b7bd53d357b12280003a3 | [
"Fundamentals"
] | https://www.codewars.com/kata/585b7bd53d357b12280003a3 | 5 kyu |
For this game of `BINGO`, you will receive a single array of 10 numbers from 1 to 26 as an input. Duplicate numbers within the array are possible.
Each number corresponds to their alphabetical order letter (e.g. 1 = A. 2 = B, etc). Write a function where you will win the game if your numbers can spell `"BINGO"`. They ... | reference | def bingo(array):
return "WIN" if {2, 7, 9, 14, 15}. issubset(set(array)) else "LOSE"
| Bingo ( Or Not ) | 5a1ee4dfffe75f0fcb000145 | [
"Games",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/5a1ee4dfffe75f0fcb000145 | 7 kyu |
Work out what number day of the year it is.
```
toDayOfYear([1, 1, 2000]) => 1
```
The argument passed into the function is an array with the format `[D, M, YYYY]`, e.g. `[1, 2, 2000]` for February 1st, 2000 or `[22, 12, 1999]` for December 22nd, 1999.
Don't forget to check for whether it's a [leap year](https://en.w... | reference | def to_day_of_year(date):
# Define the number of days in each month, accounting for leap years
days_in_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
day, month, year = date
# Check if it's a leap year and update February's days
if ((year % 4 == 0 and year % 100 != 0) or (year % 400 ==... | Day of the Year | 5a1ebe0d46d843454100004c | [
"Fundamentals"
] | https://www.codewars.com/kata/5a1ebe0d46d843454100004c | 7 kyu |
In this kata you will be given a sequence of the dimensions of rectangles ( sequence with width and length ) and circles ( radius - just a number ).
Your task is to return a new sequence of dimensions, sorted ascending by area.
For example,
```javascript
const array = [ [4.23, 6.43], 1.23, 3.444, [1.342, 3.212] ]; ... | reference | def sort_by_area(seq):
def func(x):
if isinstance(x, tuple):
return x[0] * x[1]
else:
return 3.14 * x * x
return sorted(seq, key=func)
| Sort rectangles and circles by area II | 5a1ebc2480171f29cf0000e5 | [
"Fundamentals",
"Algorithms",
"Sorting",
"Mathematics",
"Geometry"
] | https://www.codewars.com/kata/5a1ebc2480171f29cf0000e5 | 7 kyu |
# Story
It was nearly midnight when I staggered sleepily into the kitchen to get a glass of milk...
I turned on the light and... <span style='font-size:2em;color:orange'>**AARRRGGHHHHH!!!!**</span>
Damn bugs scatter in all directions!
<img src="http://www.animatedimages.org/data/media/... | algorithms | def cockroaches(room):
WALLS = {'L': '' . join(r[0] for r in room), 'D': room[- 1],
'R': '' . join(r[- 1] for r in room), 'U': room[0]}
def hole(d, i=0):
wall = WALLS[d][i:] if d in 'LD' else WALLS[d][: i +
1][:: - 1] if i else WALLS[d][... | Cockroach Bug Scatter | 59aac7a9485a4dd82e00003e | [
"Algorithms"
] | https://www.codewars.com/kata/59aac7a9485a4dd82e00003e | 5 kyu |
# Story
`Joe Stoy`, in his book "Denotational Semantics", tells following story:
```
The decision which way round the digits run is, of course, mathematically trivial.
Indeed, one early British computer had numbers running from right to left (because
the spot on an oscilloscope tube runs from left to right, but in se... | reference | import re
def is_turing_equation(s):
a, b, c = (int(n[:: - 1]) for n in re . split('[+=]', s))
return a + b == c
| Simple Fun #384: Is Turing's Equation? | 5a1e6323ffe75f71ae000026 | [
"Fundamentals",
"Strings",
"Mathematics"
] | https://www.codewars.com/kata/5a1e6323ffe75f71ae000026 | 7 kyu |
<div style='float: right; width: 180px; padding-left: 20px'>
</div>
## Story
Bob is sailing on his boat. The weather is very stormy and gloomy. Bob calls Alice. After some talk, Alice and Bob play a game on the phone.
Alice has a piece of paper with coordinate... | algorithms | def triangle_area(a, b, c):
(xa, ya), (xb, yb), (xc, yc) = a, b, c
return abs(xa * (yb - yc) + xb * (yc - ya) + xc * (ya - yb))
def point_vs_triangle(point, triangle):
area = triangle_area(* triangle)
assert area > 1e-9
a, b, c = triangle
pab, pbc, pca = triangle_area(point, a, b), ... | [Geometry B -1] Point in a triangle? | 55675eb82a2ca0bcd300006d | [
"Geometry",
"Algorithms"
] | https://www.codewars.com/kata/55675eb82a2ca0bcd300006d | 5 kyu |
Removed due to copyright infringement.
<!---
# Task
Consider a `bishop`, a `knight` and a `rook` on an `n Γ m` chessboard. They are said to form a `triangle` if each piece attacks exactly one other piece and is attacked by exactly one piece.
Calculate the number of ways to choose positions of the pieces to form ... | games | def chess_triangle(n, m):
return sum(8 * (n - x + 1) * (m - y + 1) for dims in {(3, 4), (3, 3), (2, 4), (2, 3)} for x, y in [dims, dims[:: - 1]] if x <= n and y <= m)
| Chess Fun #7: Chess Triangle | 5897eebff3d21495a70000df | [
"Puzzles",
"Games"
] | https://www.codewars.com/kata/5897eebff3d21495a70000df | 5 kyu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.