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
Hello. Today our job is to find the `N`th Pipi number. Let us define P<sub>n</sub> such that the following expression: `$P_{0}+\sqrt{P_{1}+\sqrt{P{_2}+\sqrt{...\sqrt{P_{n-1}+\sqrt{P_n}}}}}$` is equal to `n`, if P<sub>0</sub> = 0. --- # Examples: ``` pipi(0) == 0 ``` because ```math 0 = 0 ``` --- ``` pipi(1) ...
algorithms
from functools import reduce ps = [] for i in range(22): ps . append(reduce(lambda a, p: (a - p) * * 2, ps, i)) def pipi(n): return ps[n]
pipi Numbers!
5af27e3ed2ee278c2c0000e2
[ "Mathematics", "Algorithms", "Performance" ]
https://www.codewars.com/kata/5af27e3ed2ee278c2c0000e2
6 kyu
# Scenario *Now that the competition gets tough it will* **_Sort out the men from the boys_** . **_Men_** are the **_Even numbers_** and **_Boys_** are the **_odd_** ![!alt](https://i.imgur.com/mdX8dJP.png) ![!alt](https://i.imgur.com/mdX8dJP.png) ___ # Task **_Given_** an *array/list [] of n integers* , **_Se...
reference
def men_from_boys(arr): men = [] boys = [] for i in sorted(set(arr)): if i % 2 == 0: men . append(i) else: boys . append(i) return men + boys[:: - 1]
Sort Out The Men From Boys
5af15a37de4c7f223e00012d
[ "Fundamentals", "Algorithms", "Sorting" ]
https://www.codewars.com/kata/5af15a37de4c7f223e00012d
7 kyu
You've purchased a ready-meal from the supermarket. The packaging says that you should microwave it for 4 minutes and 20 seconds, based on a 600W microwave. Oh no, your microwave is 800W! How long should you cook this for?! ___ # Input You'll be given 4 arguments: ## 1. needed power The power of the needed microw...
reference
import math def cooking_time(needed_power, minutes, seconds, power): t = math . ceil((60 * minutes + seconds) * int(needed_power[: - 1]) / int(power[: - 1])) return '%d minutes %d seconds' % (t / / 60, t - t / / 60 * 60)
How long should you cook this for?
5aefd0a686d075d5f3000091
[ "Fundamentals" ]
https://www.codewars.com/kata/5aefd0a686d075d5f3000091
7 kyu
This challenge is based on [a kata](https://www.codewars.com/kata/n-smallest-elements-in-original-order) by GiacomoSorbi. Before doing this one it is advisable to complete the non-performance version first. ___ ## Task You will be given an array of integers in a `[1; 50]` range, and a number `n`. You have to extract...
algorithms
def performant_smallest(xs, n): ys = sorted(xs) del ys[n:] m = ys[- 1] km = ys . count(m) res = [] for x in xs: if x <= m: if x < m: res . append(x) elif km > 0: res . append(x) km -= 1 return res
N smallest elements in original order (performance edition)
5aeed69804a92621a7000077
[ "Algorithms", "Arrays", "Performance" ]
https://www.codewars.com/kata/5aeed69804a92621a7000077
6 kyu
In this kata you will be given an **integer n**, which is the number of times that is thown a coin. You will have to return an array of string for all the possibilities (heads[H] and tails[T]). Examples:<br><br> ```coin(1) should return {"H", "T"}```<br> ```coin(2) should return {"HH", "HT", "TH", "TT"}```<br> ```co...
reference
from itertools import product def coin(n): return list(map('' . join, product(* (["HT"] * n))))
Possibilities of throwing a coin n times
5ad6266b673f2f067b000004
[ "Mathematics", "Statistics", "Permutations", "Performance" ]
https://www.codewars.com/kata/5ad6266b673f2f067b000004
6 kyu
Quadratic equations come in the form `y(x) = ax^2 + bx + c`. Substituting in different values of `x` gives us different coordinates/points on the graph of the given quadratic function. # Task: Your job is to create a function that does the following: 1. Takes in three required parameters: `a`, `b`, and `c`, and two ...
reference
def quadratic_gen(a, b, c, start=0, step=1): x = start while True: yield [x, a * x * * 2 + b * x + c] x += step
Quadratic Enumerator
5aee96e22c5061ee90000024
[ "Fundamentals" ]
https://www.codewars.com/kata/5aee96e22c5061ee90000024
7 kyu
Adapted from <a href="https://www.hackerrank.com/challenges/kangaroo/problem">here</a>, with less terrible instructions and a couple tweaks. Two kangaroos are jumping on a line. They start out at different points on the line, and jump in the same direction at different speeds. Your task is to determine whether or not ...
reference
def kangaroo(k1, r1, k2, r2): if r1 == r2: return k1 == k2 cross, r = divmod(k1 - k2, r2 - r1) return cross >= 0 and not r
Jumping Kangaroos
5ae7e1522c5061beb7000051
[ "Fundamentals" ]
https://www.codewars.com/kata/5ae7e1522c5061beb7000051
7 kyu
Your task is to write a function that does just what the title suggests (so, fair warning, be aware that you are not getting out of it just throwing a lame bas sorting method there) with an array/list/vector of integers and the expected number `n` of smallest elements to return. Also: * the number of elements to be r...
algorithms
def first_n_smallest(arr, n): lst = sorted(enumerate(arr), key=lambda it: it[1])[: n] lst . sort(key=lambda it: it[0]) return [v for _, v in lst]
N smallest elements in original order
5aec1ed7de4c7f3517000079
[ "Arrays", "Lists", "Data Structures", "Algorithms" ]
https://www.codewars.com/kata/5aec1ed7de4c7f3517000079
6 kyu
My 7th kata, a Python puzzle, define `x` such that `str(x)` raises an exception. Note that `str()` calls rarely raise an exception, for example: print(str(1)) #1 print(str(sum)) #<built-in function sum> print(str(i for i in range(2))) #<generator object <genexpr> at 0x7f5c0b54e798> import ...
games
x = {} for i in range(1000000): x = {1: x}
Cause str(x) to raise an exception
5ae786ad68e644e861000075
[ "Strings", "Puzzles" ]
https://www.codewars.com/kata/5ae786ad68e644e861000075
6 kyu
Your task is to implement a function that takes one or more dictionaries and combines them in one result dictionary. The keys in the given dictionaries can overlap. In that case you should combine all source values in an array. Duplicate values should be preserved. Here is an example: ```cs var source1 = new Dictiona...
reference
from collections import defaultdict def merge(* dicts): d = defaultdict(list) for dd in dicts: for k, v in dd . items(): d[k]. append(v) return d
Dictionary Merge
5ae840b8783bb4ef79000094
[ "Fundamentals" ]
https://www.codewars.com/kata/5ae840b8783bb4ef79000094
6 kyu
# Scenario *You're saying good-bye your best friend* , **_See you next happy year_** . **_Happy Year_** *is the year with only distinct digits* , (e.g) **_2018_** ___ # Task **_Given_** a year, **_Find_** **_The next happy year_** or **_The closest year You'll see your best friend_** ![!alt](https://i.imgur....
reference
def next_happy_year(year): year += 1 while len(set(str(year))) != 4: year += 1 return year
See You Next Happy Year
5ae7e3f068e6445bc8000046
[ "Fundamentals" ]
https://www.codewars.com/kata/5ae7e3f068e6445bc8000046
7 kyu
Part 2 version [Find X Ⅱ](https://www.codewars.com/kata/5d339b01496f8d001054887f) We have a function that takes in an integer `n`, and returns a number `x`. Lets call this function `findX(n)`/`find_x(n)` (depending on your language): ```python def find_x(n): x = 0 for i in range(n): for j in range(2*...
games
def findX(n): return n * * 2 * (3 * n - 2)
Find X
5ae71f8c2c5061059e000044
[ "Puzzles" ]
https://www.codewars.com/kata/5ae71f8c2c5061059e000044
6 kyu
You are given an array that of arbitrary depth that needs to be nearly flattened into a 2 dimensional array. The given array's depth is also non-uniform, so some parts may be deeper than others. All of lowest level arrays (most deeply nested) will contain only integers and none of the higher level arrays will contain ...
reference
def near_flatten(a): r = [] for x in a: if isinstance(x[0], int): r . append(x) else: r . extend(near_flatten(x)) return sorted(r)
Nearly Flatten a Messy Array
5ae64f86783bb4722c0000d7
[ "Fundamentals" ]
https://www.codewars.com/kata/5ae64f86783bb4722c0000d7
6 kyu
This kata is <del> blatantly copied from </del> inspired by <a title="This Kata" href="https://www.codewars.com/kata/reversing-fun">This Kata</a> <h1>Welcome</h1> this is the second in the series of the string iterations kata! Here we go! -----------------------------------------------------------------------------...
algorithms
def string_func(s, n): l, s = [s], list(s) while True: s[:: 2], s[1:: 2] = s[: len(s) / / 2 - 1: - 1], s[: len(s) / / 2] l . append('' . join(s)) if l[0] == l[- 1]: del l[- 1] break return l[n % len(l)]
String -> X-Iterations -> String
5ae64f28d2ee274164000118
[ "Algorithms", "Puzzles", "Mathematics", "Language Features" ]
https://www.codewars.com/kata/5ae64f28d2ee274164000118
4 kyu
<h1>Welcome</h1> This kata is inspired by <a title="This Kata" href="https://www.codewars.com/kata/odd-even-string-sort">This Kata</a> We have a string <strong>s</strong> We have a number <strong>n</strong> Here is a function that takes your string, concatenates the even-indexed chars to the front, odd-in...
algorithms
def jumbled_string(s, n): iterations = [s] while True: s = s[:: 2] + s[1:: 2] if s == iterations[0]: break iterations . append(s) return iterations[n % len(iterations)]
String -> N iterations -> String
5ae43ed6252e666a6b0000a4
[ "Strings", "Algorithms", "Puzzles" ]
https://www.codewars.com/kata/5ae43ed6252e666a6b0000a4
5 kyu
Given a string that includes alphanumeric characters ("3a4B2d") return the expansion of that string: The numeric values represent the occurrence of each letter preceding that numeric value. There should be no numeric characters in the final string. #### Notes * The first occurrence of a numeric value should be the num...
reference
def string_expansion(s): m, n = '', 1 for j in s: if j . isdigit(): n = int(j) else: m += j * n return m
Simple Simple Simple String Expansion
5ae326342f8cbc72220000d2
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/5ae326342f8cbc72220000d2
6 kyu
Define a function that will receive a logarithm function, and returns the base of that logarithm. ``` guessBase(ln) == e ``` Base is a real number (not only integers) guaranteed to be less than `1e6`. Have a fun time coding!
reference
def determine_base(f): return 2 * * f(2) * * - 1
Determine the logarithm base
5ae1dcde9c0e489ae00019fc
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5ae1dcde9c0e489ae00019fc
7 kyu
This kata is based on a [variation](https://www.codewars.com/kata/happy-numbers-5) of *Happy Numbers* by TySlothrop. It is advisable to complete it first to grasp the idea and then move on to this one. ___ Hello, my dear friend, and welcome to another *Happy Numbers* kata! What? You're not interested in them anymore?...
algorithms
sum_dig = lambda n, D = { str(d): d * d for d in range(10)}: sum(map(D . get, str(n))) def is_happy(n): return n > 4 and is_happy(sum_dig(n)) or n == 1 happy_set = set(filter(is_happy, range(100))) for n in range(100, 3 * 10 * * 5): if sum_dig(n) in happy_set: happy_set . add(n) fro...
Happy Numbers (performance edition)
5adf5b6a2f10c6c4bc000200
[ "Performance", "Algorithms" ]
https://www.codewars.com/kata/5adf5b6a2f10c6c4bc000200
5 kyu
With your birthday coming up soon, your eccentric friend sent you a message to say "happy birthday": hhhappyyyy biirrrrrthddaaaayyyyyyy to youuuu hhapppyyyy biirtttthdaaay too youuu happy birrrthdayy to youuu happpyyyy birrtthdaaay tooooo youu At first it looks like a song, but upon closer investigati...
algorithms
def count_subsequences(needle, haystack): count = [1] + [0] * len(needle) for a in haystack: count = [1] + [count[i] + count[i - 1] * (a == b) for i, b in enumerate(needle, 1)] return count[- 1] % 10 * * 8
Counting String Subsequences
52f7892a747862fc9a0009a6
[ "Algorithms", "Dynamic Programming", "Strings" ]
https://www.codewars.com/kata/52f7892a747862fc9a0009a6
4 kyu
# 7 Wonders [7 Wonders](https://en.wikipedia.org/wiki/7_Wonders_(board_game)) is a board game that consists of building your city, gathering resources and fighting your neighbors. One part of the game is also to research science in order to gain points at the end of the game. There are 3 types of science glyphs you ca...
algorithms
def seven_wonders_science(* a): return 7 * min(a) + sum(x * x for x in a)
Count up the points for the 7 Wonders board game! Easy version
5adadcb36edb07df5600092e
[ "Puzzles" ]
https://www.codewars.com/kata/5adadcb36edb07df5600092e
7 kyu
In this kata you must implement the "fizz buzz reloaded function". This function takes the following arguments: * start (integer >= 0). -> this is the point where we start counting (inclusive). * stop (integer >= 1) -> this is the point where we stop counting (inclusive). * step (integer) if step is positive count for...
reference
def fizz_buzz_reloaded(s, e, step, funcs): return ' ' . join('' . join([n for n, f in funcs . items() if f(x)] or [str(x)]) for x in range(s, e + step / / abs(step), step))
Fizz Buzz Reloaded
5adbc57f0774dbaa5600011b
[ "Fundamentals" ]
https://www.codewars.com/kata/5adbc57f0774dbaa5600011b
6 kyu
*Shamelessly stolen from <a href="https://adventofcode.com/2017/day/6">Here</a> :)* Your server has sixteen memory banks; each memory bank can hold any number of blocks. You must write a routine to balance the blocks between the memory banks. The reallocation routine operates in cycles. In each cycle, it finds the me...
reference
def mem_alloc(banks): seen = set() while tuple(banks) not in seen: seen . add(tuple(banks)) number = max(banks) index = banks . index(number) banks[index] = 0 while number: index = (index + 1) % 16 banks[index] += 1 number -= 1 return len(seen)
Memory Reallocation
5ad927c932d79e34fb000091
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5ad927c932d79e34fb000091
6 kyu
# Relations : The following challenge is partially related to two already existing Kata's. But is differnt in the sense that neither approach will work here and this is a more performance version as well. Links : [number1](https://www.codewars.com/kata/complete-the-pattern-number-9-diamond) , [number2](https://www....
games
def D(n): s = [' ' * i + '+' * (2 * (n - i) - 1) for i in range(n)]; return '\n' . join(['+' * n] + s[:: - 1] + s)
One Line Task: Diamond Creator Pro
5ad86a0fcc0f9614e1000091
[ "Strings", "Arrays", "Mathematics", "Puzzles", "Restricted" ]
https://www.codewars.com/kata/5ad86a0fcc0f9614e1000091
5 kyu
Hello. I hope you know something about <a href='https://en.wikipedia.org/wiki/Graph_theory'>Graph Theory</a>. In this simple task lets implement our own class for future use. <b>Don't be scared of long description!</b> The <code>class Graph</code> represents an undirected graph of vertices named 0 through <em>V</em> -...
reference
class IllegalArgumentError (Exception): pass # Won't work if we add the same edge but that's not asked class Graph: def __init__(self, v): if v < 0: raise IllegalArgumentError() self . V = v self . E = 0 self . adj = [[] for _ in range(v)] def add_edge(self, v, w)...
Construct Graph Class (simple)
58867e2e2d2177547500007f
[ "Object-oriented Programming", "Fundamentals", "Graph Theory" ]
https://www.codewars.com/kata/58867e2e2d2177547500007f
6 kyu
# Description : Given a string consisting entirely of binary digits (0 , 1) seperated using spaces. Find the XOR of all digits and return the answer. # Examples : Given ``` "1 0 0 1 0" --> 0 "1 0 1 1 1 0 0 1 0 0 0 0" --> 1 ``` # How : ``` 1 0 0 1 0 ``` Solving : ``` (1 XOR 0) (0 XOR 1) 0 1 1 0 (1 XOR 1) 0 0 0 ...
games
def X(s): return s . count('1') & 1
XOR string reduction
5ad6e5bdb0e8d46b4500201a
[ "Strings", "Mathematics", "Restricted" ]
https://www.codewars.com/kata/5ad6e5bdb0e8d46b4500201a
6 kyu
<h2>Friends</h2> <p>Andrzej was given a task:</p> <p>There are <code>n</code> jars with pills. In every jar there is a different type of pill and the amount of pills in each jar is infinite. One type of pill makes a person glow about 30 minutes after taking and none of the other types has any effect.</p> <p>His job ...
reference
def friends(n): return (n - 1 or 1). bit_length() - 1
Friends
5ad29cd95e8240dd85000b54
[ "Algorithms", "Puzzles", "Fundamentals" ]
https://www.codewars.com/kata/5ad29cd95e8240dd85000b54
7 kyu
In this Kata you have to create a function,named `insertMissingLetters`,that takes in a `string` and outputs the same string processed in a particular way. The function should insert **only after the first occurrence** of each character of the input string, all the **alphabet letters** that: -**are NOT** in the origi...
algorithms
def insert_missing_letters(s): s, lst, found, inside = s . lower(), [], set(), set(s . upper()) for a in s: lst . append(a if a in found else a + '' . join(c for c in map(chr, range(ord(a) - 31, 91)) if c not in inside)) found . add(a) return '' . join(lst)
Missing Alphabet
5ad1e412cc2be1dbfb000016
[ "Strings", "Algorithms", "Games" ]
https://www.codewars.com/kata/5ad1e412cc2be1dbfb000016
6 kyu
Hepellopo! Jeringonza is a Spanish language game, similar to Pig Latin, played by children in Spain and all over Hispanic America. It consists of adding the letter p after each vowel (a, e, i, o or u) of a word, and repeating the vowel. For example, `jeringonza` becomes `jeperipingoponzapa` (or j-**epe**-r-**ipi**-ng-...
reference
def jeringonza(s): for c in 'aeiou': s = s . replace(c, c + 'p' + c) for c in 'AEIOU': s = s . replace(c, c + 'P' + c) return s
Simple Jeringonza
5aba0a08379d20026e0000be
[ "Fundamentals" ]
https://www.codewars.com/kata/5aba0a08379d20026e0000be
7 kyu
Mary wrote a recipe book and is about to publish it, but because of a new European law, she needs to update and include all measures in grams. Given all the measures in tablespoon (`tbsp`) and in teaspoon (`tsp`), considering `1 tbsp = 15g` and `1 tsp = 5g`, append to the end of the measurement the biggest equivalent ...
algorithms
import re import math def convert_recipe(recipe): def repl(m): ratio = 15 if m . group(2) == "tbsp" else 5 return m . group(0) + " (%sg)" % math . ceil(eval(m . group(1)) * ratio) return re . sub("([0-9/]+) (tb?sp)", repl, recipe)
Converting Measures
5acfab8d23c81836c90000eb
[ "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/5acfab8d23c81836c90000eb
6 kyu
1. You are to write a function that takes a string as its first parameter. This string will be a string of words. 2. You are expected to then use the second parameter, which will be an integer, to find the corresponding word in the given string. The first word would be represented by 0. 3. Once you have the locate...
reference
def modify_multiply(st, loc, num): return '-' . join([st . split()[loc]] * num)
Multiply Word in String
5ace2d9f307eb29430000092
[ "Strings", "Algorithms", "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5ace2d9f307eb29430000092
7 kyu
In the Deca Forest, grow the Deca Trees. On each Deca Tree, a trunk has 10 branches. On each branch, there are 10 twigs. On each twig, there are 10 leaves. Unfortunately, the Deca Forest is becoming wildly overgrown and is endangering the local wildlife. You must add methods to the tree object so that the woodcutte...
reference
class Tree (object): def __init__(self, trunks): self . data = [trunks * 10 * * i for i in range(4)] @ property def trunks(self): return self . data[0] @ property def branches(self): return self . data[1] @ property def twigs(self): return self . data[2] @ property de...
The Deca Tree
5acf710f46b4cb00810001e2
[ "Fundamentals" ]
https://www.codewars.com/kata/5acf710f46b4cb00810001e2
7 kyu
This is a problem that involves adding numbers to items in a list. In a list you will have to add the item's remainder when divided by a given divisor to each item. For example if the item is 40 and the divisor is 3 you would have to add 1 since 40 minus the closest multiple of 3 which is 39 is 1. So the 40 in the lis...
reference
def solve(nums, div): return [x + x % div for x in nums]
Adding remainders to a list
5acc3634c6fde760ec0001f7
[ "Fundamentals" ]
https://www.codewars.com/kata/5acc3634c6fde760ec0001f7
7 kyu
Determine if the poker hand is flush, meaning if the five cards are of the **same suit**. Your function will be passed a list/array of 5 strings, each representing a poker card in the format `"5H"` (5 of hearts), meaning the value of the card followed by the initial of its suit (`H`earts, `S`pades, `D`iamonds or `C`lu...
games
def CheckIfFlush(cards): return len({c[- 1] for c in cards}) == 1
Determine if the poker hand is flush
5acbc3b3481ebb23a400007d
[ "Arrays", "Algorithms", "Logic", "Strings", "Games" ]
https://www.codewars.com/kata/5acbc3b3481ebb23a400007d
7 kyu
Given a number and a binary tree ( _not_ a Binary Search Tree! ): * return `True`/`true` if the given number is in the tree * return `False`/`false` if it isn't ~~~if:javascript Each node in the binary tree is either of this `Node` class or `null`: ```javascript class Node { constructor(value, left = null, right =...
reference
from __future__ import annotations from typing import Optional class Node: def __init__(self, value: int, left: Optional[Node] = None, right: Optional[Node] = None): self . value = value self . left = left self . right = right def search(n: int, root: Optional[Node]) - > bool: if not root: ...
Binary Tree Search (not BST)
5acc79efc6fde7838a0000a0
[ "Binary Trees", "Fundamentals" ]
https://www.codewars.com/kata/5acc79efc6fde7838a0000a0
7 kyu
There are [a](https://www.codewars.com/kata/church-numbers-add-multiply-exponents) [few](https://www.codewars.com/kata/church-numbers-1) [Katas](https://www.codewars.com/kata/church-numbers-ii) about Church Numerals so let's talk about booleans. In lambda calculus, the only primitive are lambdas. No numbers, no string...
reference
def Not(X): return X(false)(true) def And(X): return lambda Y: X(Y)(false) def Or(X): return lambda Y: X(true)(Y) def Xor(X): return lambda Y: X(Not(Y))(Y)
Church Booleans
5ac739ed3fdf73d3f0000048
[ "Fundamentals" ]
https://www.codewars.com/kata/5ac739ed3fdf73d3f0000048
5 kyu
Given an array of words and a target compound word, your objective is to find the two words which combine into the target word, returning both words *in the order they appear in the array*, and their respective indices *in the order they combine to form the target word*. Words in the array you are given may repeat, but...
algorithms
def compound_match(words, target): for i in range(1, len(target) - 1): t1 = target[: i] t2 = target[i:] if (t1 in words) and (t2 in words): i1 = words . index(t1) i2 = words . index(t2) return ([t1, t2] if i1 < i2 else [t2, t1]) + [[i1, i2]]
Find the Word Pair!
5aaae0f5fd8c069e8c00016e
[ "Arrays", "Performance", "Algorithms" ]
https://www.codewars.com/kata/5aaae0f5fd8c069e8c00016e
5 kyu
In mathematics, a **pandigital number** is a number that in a given base has among its significant digits each digit used in the base at least once. For example, 1234567890 is a pandigital number in base 10. For simplification, in this kata, we will consider pandigital numbers in *base 10* and with all digits used *ex...
reference
def get_sequence(o, s, st=1023456789): li = [] for i in range([st, o][o > 0 and o > st], 9876543211): i = str(i) if i[0] != '0' and len(set(i)) == 10: li . append(int(i)) if len(li) == s: break return li
Pandigital Sequence
5ac69d572f317bdfc3000124
[ "Fundamentals", "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/5ac69d572f317bdfc3000124
5 kyu
You have to create a function `calcType`, which receives 3 arguments: 2 numbers, and the result of an unknown operation performed on them (also a number). Based on those 3 values you have to return a string, that describes which operation was used to get the given result. The possible return strings are: `"additio...
reference
def calc_type(a, b, res): return {a + b: "addition", a - b: "subtraction", a * b: "multiplication", a / b: "division"}[res]
Find the calculation type
5aca48db188ab3558e0030fa
[ "Fundamentals" ]
https://www.codewars.com/kata/5aca48db188ab3558e0030fa
7 kyu
<i><font color="gray">This is the performance edition of [this kata](https://www.codewars.com/kata/ulam-sequences). If you didn't do it yet, you should begin there.</font></i> --- The Ulam sequence U is defined by `u0=u`, `u1=v`, with the general term `u_n` for `n>2` given by the least integer expressible uniquely as...
refactoring
def ulam_sequence(u, v, n): lst, seq, ex, q = [], 1, 1, 1 << v | 1 << u # Put u and v into queue for _ in range(n): # Repeat n times w = q & - q # Take the smallest candidate l = w . bit_length() - 1 # and its value s = seq << l # Generate its sums with all previous values seq |= w # Appen...
Ulam Sequences (performance edition)
5ac94db76bde60383d000038
[ "Algorithms", "Refactoring" ]
https://www.codewars.com/kata/5ac94db76bde60383d000038
5 kyu
`Description:` Given an input array (`arr`) of positive integers, the objective is to return an output array where each index represents the amount of times an element appeared (frequency) in the input array. More specifically, the element at each index of the output array will be an array (bucket) containing intege...
reference
from collections import Counter def bucketize(* a): D = {} for k, v in Counter(a). items(): D[v] = sorted(D . get(v, []) + [k]) return [D . get(i, None) for i in range(len(a) + 1)]
Frequency Analysis With Buckets
5ac95cb05624bac42e000005
[ "Fundamentals", "Arrays", "Sorting" ]
https://www.codewars.com/kata/5ac95cb05624bac42e000005
6 kyu
In English there are types of words called nouns which are persons, places, or things. There are two main classifications of nouns: common and proper nouns. In the common nouns there is another set of classifications that includes collective, compound, and normal nouns. Today we are focused on classifying compound noun...
reference
compounds = {left + right for right in nouns for left in nouns | adjectives} def part(word): if word in nouns: return "common" if word in adjectives: return "adjective" if word in compounds: return "compound" return "neither"
Compound Nouns, Common Nouns, and Adjectives Test
5ac9662d58b03979d800000d
[ "Fundamentals", "Strings", "Parsing" ]
https://www.codewars.com/kata/5ac9662d58b03979d800000d
6 kyu
Ho ho! So you think you know integers, do you? Well then, young wizard, tell us what the Nth digit of the [Champernowne constant](https://en.wikipedia.org/wiki/Champernowne_constant) is! The constant proceeds like this: `0.12345678910111213141516...` I hope you see the pattern! Conjure a function that will accept an...
algorithms
from math import log, ceil def champernowne_digit(n): if type(n) != int or n < 1: return float('nan') ln, diff = 0, n - 1 while diff > 9 * (ln + 1) * 10 * * ln: diff -= 9 * (ln + 1) * 10 * * ln ln += 1 return int(str(10 * * (ln) - 1 + ceil(diff / (ln + 1)))[(diff - 1) % (ln + 1)])
Champernowne's Championship
5ac53c71376b11df7e0001a9
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5ac53c71376b11df7e0001a9
6 kyu
# Task **_Given_** a **_list of digits_**, *return the **_smallest number_** that could be formed from these digits, using the digits only once (ignore duplicates).* ___ # Notes: * Only **_positive integers_** *will be passed to the function (> 0 ), no negatives or zeros.* ___ # Input >> Output Examples ``` minVa...
reference
def min_value(digits): return int("" . join(map(str, sorted(set(digits)))))
Form The Minimum
5ac6932b2f317b96980000ca
[ "Fundamentals" ]
https://www.codewars.com/kata/5ac6932b2f317b96980000ca
7 kyu
Lexicographic permutations are ordered combinations of a set of items ordered in a specific way. For instance, the first 8 permutations of the digits 0123, in lexicographic order, are: ``` 1st 0123 2nd 0132 3rd 0213 4th 0231 5th 0312 6th 0321 7th 1023 8th 1032 ``` Your task is to write a function ```L( n, d )``` tha...
reference
def nth_perm(n, d): k = n - 1 digits = [str(i) for i in range(d)] for i in [362880, 40320, 5040, 720, 120, 24, 6, 2, 1, 1][- d:]: i, k = divmod(k, i) digits . append(digits . pop(i)) return '' . join(digits)
Lexicographic Permutations
55baa55cf332e67eb000000a
[ "Fundamentals", "Algorithms", "Combinatorics", "Mathematics", "Logic" ]
https://www.codewars.com/kata/55baa55cf332e67eb000000a
6 kyu
Given a string of characters, I want the function `findMiddle()`/`find_middle()` to return the middle number in the product of each digit in the string. Example: 's7d8jd9' -> 7, 8, 9 -> 7\*8\*9=504, thus 0 should be returned as an integer. Not all strings will contain digits. In this case and the case for any non-str...
reference
from operator import mul from functools import reduce def find_middle(s): if not s or not isinstance(s, str): return - 1 lstDig = [int(c) for c in s if c . isnumeric()] if not lstDig: return - 1 prod = str(reduce(mul, lstDig)) i = (len(prod) - 1) / / 2 return int(prod[i: - i or...
Find the Middle of the Product
5ac54bcbb925d9b437000001
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/5ac54bcbb925d9b437000001
7 kyu
It started as a discussion with a friend, who didn't fully grasp some way of setting defaults, but I thought the idea was cool enough for a beginner kata: binary `OR` each matching element of two given arrays (or lists, if you do it in Python; vectors in c++) of integers and give the resulting ORed array [starts to sou...
reference
from itertools import zip_longest def or_arrays(a1, a2, d=0): return [x | y for x, y in zip_longest(a1, a2, fillvalue=d)]
ORing arrays
5ac5e9aa3853da25d9000102
[ "Arrays", "Lists", "Binary", "Fundamentals" ]
https://www.codewars.com/kata/5ac5e9aa3853da25d9000102
7 kyu
Write a function ```python alternate_sort(l) ``` that combines the elements of an array by sorting the elements ascending by their **absolute value** and outputs negative and non-negative integers alternatingly (starting with the negative value, if any). E.g. ```python alternate_sort([5, -42, 2, -3, -4, 8, -9,]) == [-...
algorithms
from itertools import chain, zip_longest def alternate_sort(l): l = sorted(l, key=abs) p, n = [n for n in l if n >= 0], [n for n in l if n < 0] return [n for n in chain(* zip_longest(n, p)) if n is not None]
Alternating sort
5ac49156376b11767f00060c
[ "Algorithms", "Arrays", "Sorting" ]
https://www.codewars.com/kata/5ac49156376b11767f00060c
6 kyu
# Scenario **_Several people_** are standing in *a row divided into two teams*. The **_first person_** goes into **_team 1_**, **_the second_** goes into **_team 2_**, **_the third_** goes into **_team 1_**, and so on. ___ # Task **_Given_** *an array of positive integers (the weights of the people)*, **_return_** ...
reference
def row_weights(array): return sum(array[:: 2]), sum(array[1:: 2])
Row Weights
5abd66a5ccfd1130b30000a9
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5abd66a5ccfd1130b30000a9
7 kyu
You are given a string. Your job is to convert that string to upper case, then find the sum of each character converted to its ASCII value, then divide the sum by the string's length and round it down then convert that to its equivalent character in ASCII. ~~~if:python,ruby **Note:** do it in maximum `57` characters ~...
algorithms
def solution(s): return chr(sum(map(ord, s . upper())) / / len(s))
[Code Golf] String to ASCII Character
5abbb33396194245d5000161
[ "Restricted", "Strings", "Algorithms" ]
https://www.codewars.com/kata/5abbb33396194245d5000161
7 kyu
# Task **_Given_** a **_Divisor and a Bound_** , *Find the largest integer N* , Such That , # Conditions : * **_N_** is *divisible by divisor* * **_N_** is *less than or equal to bound* * **_N_** is *greater than 0*. ___ # Notes * The **_parameters (divisor, bound)_** passed to the function are *only posit...
bug_fixes
def max_multiple(divisor, bound): return bound - (bound % divisor)
Maximum Multiple
5aba780a6a176b029800041c
[ "Fundamentals" ]
https://www.codewars.com/kata/5aba780a6a176b029800041c
7 kyu
Mr Leicester's cheese factory is the pride of the East Midlands, but he's feeling a little blue. It's the time of the year when **the taxman is coming round to take a slice of his cheddar** - and the final thing he has to work out is how much money he's spending on his staff. Poor Mr Leicester can barely sleep he's so ...
reference
from math import ceil def pay_cheese(arr): return f'L { ceil ( sum ( arr ) / 100 ) * 35 } '
Sweet Dreams are Made of Cheese
5ab7ee556a176b1043000047
[ "Fundamentals" ]
https://www.codewars.com/kata/5ab7ee556a176b1043000047
7 kyu
> In computing, a hex dump is a hexadecimal view (on screen or paper) of computer data, from RAM or from a file or storage device. Looking at a hex dump of data is commonly done as a part of debugging, or of reverse engineering. > > In a hex dump, each byte (8-bits) is represented as a two-digit hexadecimal number. He...
algorithms
def hexdump(data): return '\n' . join('{:08x}: {:48} {}' . format(i, ' ' . join( map('{:02x}' . format, data[i: i + 16])), bytes(b if 32 <= b < 127 else or...
Hex Dump
5ab3be5f6a176bef4e00012d
[ "Algorithms" ]
https://www.codewars.com/kata/5ab3be5f6a176bef4e00012d
5 kyu
Complete the function that accepts a valid string and returns an integer. Wait, that would be too easy! Every character of the string should be converted to the hex value of its ascii code, then the result should be the sum of the numbers in the hex strings (ignore letters). ## Examples ``` "Yo" ==> "59 6f" ==> 5 + 9...
reference
def hex_hash(code): return sum(int(d) for c in code for d in hex(ord(c)) if d . isdigit())
Hex Hash Sum
5ab363ff6a176b29880000dd
[ "Mathematics", "Security", "Fundamentals" ]
https://www.codewars.com/kata/5ab363ff6a176b29880000dd
7 kyu
You will be given a 2d char array <strong>data. The task is to rearrange the elements in the SAME order, diagonally, like this: c h a c a c r a c ==> h a e t e r r t r here's another example j a v a j v o t c o d e ==> a c e c ...
algorithms
def diagonal_sort(data): if not data: return data p, lX, lY = 0, len(data), len(data[0]) lst = [[''] * lY for _ in range(lX)] for z in range(lX + lY - 1): x, y = min(lX - 1, z), max(0, z - lX + 1) while 1: lst[x][y] = data[p / / lY][p % lY] x, y, p = x - 1, y + 1, p + ...
Arrange Matrix by Diagonals -- OMG
5ab1f8d38d28f67410000090
[ "Algorithms", "Matrix" ]
https://www.codewars.com/kata/5ab1f8d38d28f67410000090
6 kyu
Your computer has forgotten how to speak ASCII! (or Unicode, whatever) It can only communicate in binary, and it has something important to tell you. Write a function which will receive a long string of binary code and convert it to a string. Remember, in Python binary output starts with '0b'. As an example: `binary_t...
reference
def binary_to_string(binary): return '' . join(chr(int(b, 2)) for b in binary[2:]. split('0b'))
Binary to string
5ab3495595df9ec78f0000b4
[ "Binary", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5ab3495595df9ec78f0000b4
7 kyu
Your task is to write regular expression that validates gregorian date in format "DD.MM.YYYY" Correct date examples: ```python "23.12.2008" "01.08.1994" ``` Incorrect examples: ```python "12.23.2008" "01-Aug-1994" " 01.08.1994" ``` Notes: * maximum length of validator is 400 characters to avoid hardcoding. (shortest...
reference
date_validator = ( '(((' '(0[1-9]|1\d|2[0-8])\.(0[1-9]|1[012])|' # 01-28 of any month '(29|30)\.(0[13-9]|1[012])|' # 29-30 of months, except February '(31\.(0[13578]|1[02])))\.' # 31 of long months '([1-9]\d{3}|\d{3}[1-9]))|' # any year, except 0000 '(29\.02\.(' # leap day '\d\d([2468][...
Regex for Gregorian date validation
5ab23a9c1cec39668c000055
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/5ab23a9c1cec39668c000055
5 kyu
Freddy has a really fat left pinky finger, and every time Freddy tries to type an ```A```, he accidentally hits the CapsLock key! Given a string that Freddy wants to type, emulate the keyboard misses where each ```A``` supposedly pressed is replaced with CapsLock, and return the string that Freddy actually types. It d...
reference
def fat_fingers(s): if not s: return s swap = [False] return '' . join(c . swapcase() if swap[0] else c for c in s if c not in "aA" or swap . __setitem__(0, not swap[0]))
Fat Fingers
5aa99584fd5777ee9a0001f1
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5aa99584fd5777ee9a0001f1
6 kyu
According to [Gary Chapman](https://en.wikipedia.org/wiki/Gary_Chapman_(author)), marriage counselor and the author of ["The Five Love Languages"](https://en.wikipedia.org/wiki/The_Five_Love_Languages) books, there are five major ways to express our love towards someone: *words of affirmation, quality time, gifts, acts...
algorithms
import random def love_language(partner, weeks): rst = [0, 0, 0, 0, 0] for i in range(0, weeks * 7): if (partner . response(LOVE_LANGUAGES[i % 5]) == 'positive'): rst[i % 5] += 1 return LOVE_LANGUAGES[rst . index(max(rst))]
The 5 Love Languages
5aa7a581fd8c06b552000177
[ "Machine Learning", "Algorithms", "Data Science" ]
https://www.codewars.com/kata/5aa7a581fd8c06b552000177
6 kyu
Generate and return **all** possible increasing arithmetic progressions of six primes `[a, b, c, d, e, f]` between the given limits. Note: the upper and lower limits are inclusive. An arithmetic progression is a sequence where the difference between consecutive numbers is the same, such as: 2, 4, 6, 8. A prime number...
reference
def is_prime(n): return all(n % d for d in range(3, int(n * * .5) + 1, 2)) def primes_a_p(lower_limit, upper_limit): a_p = [] for n in range(lower_limit | 1, upper_limit, 2): for gap in range(30, (upper_limit - n) / / 5 + 1, 30): sequence = [n + i * gap for i in range(6)] if all(map(is_pri...
Arithmetic Progression of Primes
5aa7ce59373c2e3ed30000cb
[ "Fundamentals" ]
https://www.codewars.com/kata/5aa7ce59373c2e3ed30000cb
6 kyu
In this kata you're expected to find the longest consecutive sequence of positive squares that sums up to a number. E.g, ** 595 = 6<sup>2</sup> + 7<sup>2</sup> + 8<sup>2</sup> + 9<sup>2</sup> + 10<sup>2</sup> + 11<sup>2</sup> + 12<sup>2</sup> **. ```if:python Your task is to write the function `longest_sequence(n)` ...
algorithms
def longest_sequence(n): l = r = s = 1 while s != 0 and s != n: if s > n: s -= l * l l += 1 else: r += 1 s += r * r return range(l, r + 1) if s == n else []
Longest Consecutive Sequence of Squares
5aa69e68ba1bb5ecdf000557
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5aa69e68ba1bb5ecdf000557
6 kyu
This kata generalizes [Twice Linear](https://www.codewars.com/kata/5672682212c8ecf83e000050). You may want to attempt that kata first. ## Sequence Consider an integer sequence `U(m)` defined as: 1. `m` is a given non-empty set of positive integers. 2. `U(m)[0] = 1`, the first number is always 1. 3. For each `x` in `...
refactoring
from heapq import * def n_linear(ms, n): lst = [1] * (n + 1) q = [(1 + v, v, 1) for v in ms] heapify(q) for i in range(1, n + 1): v, x, j = heappop(q) lst[i] = v heappush(q, (lst[j] * x + 1, x, j + 1)) while q[0][0] == lst[i]: v, x, j = heappop(q) heappush(q, (lst[...
N Linear
5aa417aa4a6b344e2200009d
[ "Algorithms", "Mathematics", "Refactoring" ]
https://www.codewars.com/kata/5aa417aa4a6b344e2200009d
4 kyu
Given a mathematical equation that has `*,+,-,/`, reverse it as follows: ```Haskell solve("100*b/y") = "y/b*100" solve("a+b-c/d*30") = "30*d/c-b+a" ``` More examples in test cases. Good luck! Please also try: [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2) [Simple remove duplicat...
algorithms
import re def solve(eq): return '' . join(reversed(re . split(r'(\W+)', eq)))
Simple equation reversal
5aa3af22ba1bb5209f000037
[ "Algorithms" ]
https://www.codewars.com/kata/5aa3af22ba1bb5209f000037
7 kyu
Given that ``` f0 = '0' f1 = '01' f2 = '010' = f1 + f0 f3 = '01001' = f2 + f1 ``` You will be given a number and your task is to return the `nth` fibonacci string. For example: ``` solve(2) = '010' solve(3) = '01001' ``` More examples in test cases. Good luck! If you like sequence Katas, you will enjoy this Kata: ...
algorithms
def solve(n): a, b = '01' for _ in range(n): a, b = a + b, a return a
Simple fibonacci strings
5aa39ba75084d7cf45000008
[ "Algorithms" ]
https://www.codewars.com/kata/5aa39ba75084d7cf45000008
7 kyu
You're given an ancient book that unfortunately has a few pages in the wrong position, fortunately your computer has a list of every page number in order from ``1`` to ``n``. You're supplied with an array of numbers, and should return an array with each page number that is out of place. Incorrect page numbers may appe...
algorithms
def find_page_number(pages): n, miss = 1, [] for i in pages: if i != n: miss . append(i) else: n += 1 return miss
Disorganised page lists
5aa20a964a6b34417c00008d
[ "Arrays", "Lists", "Algorithms" ]
https://www.codewars.com/kata/5aa20a964a6b34417c00008d
7 kyu
# Story The construction of the new Death Star is almost complete. It only needs a certain amount of 3 materials – iron, steel, and chromium. The emperor wants the construction finished within a week because he senses an impending rebel attack and knows the battle station will be destroyed if it is not completed withi...
reference
def death_star(week, attack): iron = sum(w[0] for w in week[: attack]) steel = sum(w[1] for w in week[: attack]) chromium = sum(w[2] for w in week[: attack]) if (iron >= 100 and steel >= 75 and chromium >= 50): return 'The station is completed!' else: return f'The station is destroy...
Death Star Construction
5a996f3d5084d73a7100040c
[ "Fundamentals" ]
https://www.codewars.com/kata/5a996f3d5084d73a7100040c
7 kyu
# Task **_Given_** an *array/list [] of n integers* , *find maximum triplet sum in the array* **_Without duplications_** . ___ # Notes : * **_Array/list_** size is *at least 3* . * **_Array/list_** numbers could be a *mixture of positives , negatives and zeros* . * **_Repetition_** of numbers in *the array/list ...
reference
def max_tri_sum(numbers): return sum(sorted(set(numbers))[- 3:])
Maximum Triplet Sum (Array Series #7)
5aa1bcda373c2eb596000112
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5aa1bcda373c2eb596000112
7 kyu
The queen can be moved any number of unoccupied squares in a straight line vertically, horizontally, or diagonally, thus combining the moves of the rook and bishop. The queen captures by occupying the square on which an enemy piece sits. (wikipedia: https://en.wikipedia.org/wiki/Queen_(chess)). ## Task: Write a functi...
reference
from itertools import product BOARD = set(map("" . join, product("ABCDEFGH", "12345678"))) def available_moves(position): if isinstance(position, str) and position in BOARD: return sorted(p for p in BOARD - {position} if abs(ord(p[0]) - ord(position[0])) == abs(int(p[1]) - int(posit...
The queen on the chessboard
5aa1031a7c7a532be30000e5
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5aa1031a7c7a532be30000e5
6 kyu
_Based on [Project Euler problem 35](https://projecteuler.net/problem=35)_ A circular prime is a prime in which every circular permutation of that number is also prime. Circular permutations are created by rotating the digits of the number, for example: `197, 971, 719`. One-digit primes are circular primes by definiti...
algorithms
def circular_permutations(n): n = str(n) return [int(n[i:] + n[: i]) for i in range(len(n))] def is_prime(n): return n > 1 and all(n % i != 0 for i in range(2, int(n * * 0.5) + 1)) def circular_prime(n): return all(is_prime(x) for x in circular_permutations(n))
Circular Primes
56b2333e2542c2aadb000079
[ "Algorithms" ]
https://www.codewars.com/kata/56b2333e2542c2aadb000079
7 kyu
Given an array with exactly 5 strings `"a"`, `"b"` or `"c"` (`char`s in Java, `character`s in Fortran), check if the array contains three and two of the same values. ## Examples ``` ["a", "a", "a", "b", "b"] ==> true // 3x "a" and 2x "b" ["a", "b", "c", "b", "c"] ==> false // 1x "a", 2x "b" and 2x "c" ["a", "a", "a"...
reference
def check_three_and_two(array): return {array . count(x) for x in set(array)} == {2, 3}
Check three and two
5a9e86705ee396d6be000091
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5a9e86705ee396d6be000091
7 kyu
[Georg Cantor's](http://en.wikipedia.org/wiki/Georg_Cantor) in one of his proofs used following sequence: <pre> 1/1 1/2 1/3 1/4 1/5 ... 2/1 2/2 2/3 2/4 ... 3/1 3/2 3/3 ... 4/1 4/2 ... 5/1 ... </pre> There are many ways to order those expressions. In this kata we'll use this approach: ![](https://lh3.googleuserco...
algorithms
def cantor(n: int) - > str: if n == 1: return '1/1' else: k = 1 while n > k: n -= k k += 1 if k % 2 == 0: return str(n) + '/' + str(k - n + 1) else: return str(k - n + 1) + '/' + str(n)
Cantor's pairing function
543b9113def6343e43000875
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/543b9113def6343e43000875
6 kyu
"Hello Traveler. I wanna play a game" There is a game called [23 Matches](http://ascii-world.wikidot.com/23-matches). Rules: there are 23 matches on the table. Each turn a player takes 1, 2 or 3 matches away. Player who takes the last match - loses. This is generalized version of the game. Here we have **X** match...
algorithms
from collections import namedtuple Bot = namedtuple('Bot', ('name', 'make_move')) def create_bot(x, y): return Bot( name='🏆', make_move=lambda on_table: (on_table - 1) % (y + 1) or 1)
23 Matches. Or more...
5a9dbc735ee396ef590001de
[ "Puzzles", "Games", "Algorithms", "Game Solvers" ]
https://www.codewars.com/kata/5a9dbc735ee396ef590001de
6 kyu
# Concept Multicast IP addresses, which range from `224.0.0.0` to `239.255.255.255`, are defined by the leading address bits of `1110`. In Classless Inter-Domain Routing (CIDR) prefix, this group is `224.0.0.0/4`.<sup>[1](#mcastIp)</sup> To support IP multicasting, the Internet authorities have reserved the multicast...
reference
def mcast_ip_to_mac(ip_string): ip = ip_string . split(".") return "01:00:5E:%0.2X:%0.2X:%0.2X" % (int(ip[1]) % 128, int(ip[2]), int(ip[3]))
Multicast IP Address to MAC address mapping
5a9d43ceba1bb52492000080
[ "Parsing", "Fundamentals" ]
https://www.codewars.com/kata/5a9d43ceba1bb52492000080
6 kyu
# Disclaimer This Kata is an insane step-up from [my previous Kata](https://www.codewars.com/kata/59951f21d65a27e95d00004f), so I recommend to solve it first before trying this one. # Problem Description Let's imagine a function `F(n)`, which is defined over the integers in the range of `1 <= n <= max_n`, and `0 <= ...
algorithms
''' Let G be an unweighted graph with max_fn + 1 nodes, labeled from 0 to max_fn, and let there be an edge between two nodes A and B if A + B <= max_fn. Let A be the adjacency matrix representation of G, such that A[i][j] = 1 if there is an edge between node i and j, and A[i][j] = 0 otherwise. Then A[i][j] = ...
Insane Circular Limited Sums
59953009d65a278783000062
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/59953009d65a278783000062
3 kyu
# Problem Description Let's imagine a function `F(n)`, which is defined over the integers in the range of `1 <= n <= max_n`, and `0 <= F(n) <= max_fn` for every `n`. There are `(1 + max_fn) ** max_n` possible definitions of `F` in total. Out of those definitions, how many `F`s satisfy the following equations? Since ...
algorithms
def circular_limited_sums(max_n, max_fn): if max_n == 1: return sum([1 for i in range(max_fn + 1) if i + i <= max_fn]) % 12345787 nexts = [list(filter(lambda x: i + x <= max_fn, range(max_fn + 1))) for i in range(max_fn + 1)] result = 0 for ii in range(max_fn + 1): v = [[1 if...
Circular Limited Sums
59951f21d65a27e95d00004f
[ "Algorithms", "Mathematics", "Dynamic Programming" ]
https://www.codewars.com/kata/59951f21d65a27e95d00004f
4 kyu
# Problem Description You build a string of length `l` which entirely consists of `n` types of characters `1`, `2`, ..., `n`. Let's define such a string "permutation-free" if it has no substring which is a permutation of `12...n` (in other words, substring of length `n` which contains all types of characters exactly ...
algorithms
import numpy as np def permutation_free(n, l): m = np . tril(np . ones((n, n), object), - 1) + \ np . diagflat(range(n, 0, - 1)) return (np . matrix(np . vstack((m[1:], m[0, :: - 1]))) * * l)[0, 0] * n % 12345787
Permutation-free Strings
59b53be0bf10a4b39300001f
[ "Algorithms", "Dynamic Programming", "Mathematics" ]
https://www.codewars.com/kata/59b53be0bf10a4b39300001f
3 kyu
# Disclaimer This Kata is an insane step-up from [my previous Kata](https://www.codewars.com/kata/599266b417bc9785f2000001), so I recommend to solve it first before trying this one. # Problem Description You have a row of `n` square tiles, which are colored black and the side length is 1. You also have infinite supp...
algorithms
import numpy as np from itertools import combinations modulus = 12345787 def f(n, colors): a = np . matrix([ [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0] ]) for color in colors: a[0, color - 1] += 1 b = n...
Insane Tri-Bicolor Tiling
59928e2889d6a01970000051
[ "Algorithms", "Fundamentals", "Mathematics", "Performance" ]
https://www.codewars.com/kata/59928e2889d6a01970000051
3 kyu
### Please also check out other katas in [Domino Tiling series](https://www.codewars.com/collections/5d19554d13dba80026a74ff5)! --- # Task A domino is a rectangular block with `2` units wide and `1` unit high. A domino can be placed on a grid in two ways: horizontal or vertical. ``` ## or # # ``` You have in...
games
""" def three_by_n_without_hole_missing_top(n): # the first column can be _11, _12 assert n%2 == 1 if n == 1: return 1 return three_by_n_without_hole_missing_top(n-2) \ + three_by_n_without_hole(n-1) def three_by_n_without_hole(n): # the first column can be 112, 122, 123 # the first two cases are th...
Domino Tiling - 3 x N Board
5993dcfca6a7632807000017
[ "Algorithms", "Mathematics", "Dynamic Programming", "Puzzles" ]
https://www.codewars.com/kata/5993dcfca6a7632807000017
4 kyu
Let's create some scrolling text! Your task is to complete the function which takes a string, and returns an array with all possible rotations of the given string, **in uppercase**. ## Example `scrollingText("codewars")` should return: ```javascript [ "CODEWARS", "ODEWARSC", "DEWARSCO", "EWARSCOD", "WARSCOD...
reference
def scrolling_text(text): text = text . upper() return [text[i:] + text[: i] for i in range(len(text))]
Scrolling Text
5a995c2aba1bb57f660001fd
[ "Strings", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5a995c2aba1bb57f660001fd
7 kyu
You are given two positive integers `a` and `b` (`a < b <= 20000`). Complete the function which returns a list of all those numbers in the interval `[a, b)` whose digits are made up of prime numbers (`2, 3, 5, 7`) but which are not primes themselves. Be careful about your timing! Good luck :) Check my other katas:...
reference
from math import sqrt def is_prime(n): if n < 2: return False for x in range(2, int(sqrt(n)) + 1): if n % x == 0: return False return True def all_dig_prime(n): for d in str(n): if d not in "2357": return False return True def not_primes(a, b)...
Not prime numbers
5a9a70cf5084d74ff90000f7
[ "Fundamentals", "Performance", "Algorithms" ]
https://www.codewars.com/kata/5a9a70cf5084d74ff90000f7
6 kyu
# Definition (Primorial Of a Number) *Is similar to factorial of a number*, **_In primorial_**, not all the natural numbers get multiplied, **_only prime numbers are multiplied to calculate the primorial of a number_**. It's denoted with **_P_**<sub>**_#_**</sub> and it is the product of the first n prime numbers. ___...
reference
def num_primorial(n): primorial, x, n = 2, 3, n-1 while n: if all(x % d for d in range(3, int(x ** .5) + 1, 2)): primorial *= x n -= 1 x += 2 return primorial
Primorial Of a Number
5a99a03e4a6b34bb3c000124
[ "Fundamentals", "Arrays", "Number Theory" ]
https://www.codewars.com/kata/5a99a03e4a6b34bb3c000124
6 kyu
For "x", determine how many positive integers less than or equal to "x" are odd but not prime. Assume "x" is an integer between 1 and 10000. Example: 5 has three odd numbers (1,3,5) and only the number 1 is not prime, so the answer is 1 Example: 10 has five odd numbers (1,3,5,7,9) and only 1 and 9 are not prime, so t...
algorithms
def odd_not_prime(n): return 1 + sum(any(not x % y for y in range(3, int(x * * .5) + 1, 2)) for x in range(1, n + 1, 2))
Odd Not Prime
5a9996fa8e503f2b4a002e7a
[ "Algorithms" ]
https://www.codewars.com/kata/5a9996fa8e503f2b4a002e7a
7 kyu
You get a list of integers. Return a new list by adding each consecutive pair of the list. ## Examples ```python [1, 1, 1, 1] --> [2, 2, 2] # [1+1, 1+1, 1+1] [1, 2, 3, 4] --> [3, 5, 7] # [1+2, 2+3, 3+4] [1, 10, 100] --> [11, 110] # [1+10, 10+100] ``` ## Restriction ~~~if:python,ruby Your code size can be ...
reference
def make_new_list(l): return list(map(sum, zip(l, l[1:])))
[ Code Golf ] Add 2 values for each
5a99a1418e503ffb8300384c
[ "Restricted", "Fundamentals" ]
https://www.codewars.com/kata/5a99a1418e503ffb8300384c
7 kyu
Your program will receive an array of complex numbers represented as strings. Your task is to write the `complexSum` function which have to return the sum as a string. Complex numbers can be written in the form of `a+bi`, such as `2-3i` where `2` is the real part, `3` is the imaginary part, and `i` is the "imaginary ...
reference
def complexSum(l): z = sum(complex(s . replace('i', 'j')) for s in l) x, y = round(z . real), round(z . imag) if y == 0: return str(x) sign = '-' if y < 0 else ('' if x == 0 else '+') y = abs(y) x = '' if x == 0 else str(x) y = '' if y == 1 else str(y) return '{}{}{}i' ....
Really Complex Sum
5a981424373c2e479c00017f
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/5a981424373c2e479c00017f
6 kyu
`$i$` is the imaginary unit, it is defined by `$i² = -1$`, therefore it is a solution to `$x² + 1 = 0$`. ## Your Task Complete the function `pofi` that returns `$i$` to the power of a given non-negative integer in its simplest form, as a string (answer may contain `$i$`). ~~~if:fortran *NOTE: Your returned character...
reference
def pofi(n): return ['1', 'i', '-1', '-i'][n % 4]
Powers of i
5a97387e5ee396e70a00016d
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5a97387e5ee396e70a00016d
7 kyu
While using public transport we could see simple displays with a ticker. It often provides information about next stations and expected arrival time. Let's implement a function which will return a chunk of text to be displayed on a display of fixed width. The function should take `text` to display, `width` of the disp...
reference
def ticker(text, width, tick): tick %= len(text) + width text = ' ' * width + text + ' ' * width return text[tick: tick + width]
Ticker
5a959662373c2e761d000183
[ "Fundamentals" ]
https://www.codewars.com/kata/5a959662373c2e761d000183
6 kyu
Create a bot that can play the darts game <a href="https://en.wikipedia.org/wiki/Darts#Scoring">501</a>: <li>Two players throw in turn three darts at a <a href="https://en.wikipedia.org/wiki/Darts#Scoring">dartboard</a></li> <li>Both players start a <i>leg</i> with a score of 501</li> <li>After each throw th...
algorithms
import math angleGoal = [0, 72, 306, 270, 36, 108, 0, 234, 198, 144, 342, 180, 126, 18, 162, 324, 216, 288, 54, 252, 90] distGoal = [0, 138, 166, 103] # bullseye, single, double, triple def get_coordinates(score): if score >= 66: theta = angleGoal[20] depth = distGoal[3] elif s...
Let's Play Darts: Beat The Power!
58756f1054486312c5000a64
[ "Games", "Algorithms" ]
https://www.codewars.com/kata/58756f1054486312c5000a64
5 kyu
In this Kata, you will count the number of times the first string occurs in the second. ```Haskell solve("zaz","zazapulz") = 4 because they are ZAZapulz, ZAzapulZ, ZazApulZ, zaZApulZ ``` More examples in test cases. Good luck! Please also try [Simple time difference](https://www.codewars.com/kata/5b76a34ff71e5de9...
algorithms
def solve(a, b): if len(a) is 1: return b . count(a) index = [x for x in range(len(b) - 1) if b[x] is a[0]] return sum(solve(a[1:], b[x + 1:]) for x in index)
Simple repeated words
5a942c461a60f677730032df
[ "Algorithms" ]
https://www.codewars.com/kata/5a942c461a60f677730032df
6 kyu
# Task : **_Given_** *a List [] of n integers* , **_find minimum number_** to be **inserted** in a *list*, so that **_sum of all elements of list_** should *equal the closest prime number* . ___ # Notes * **_List size_** is *at least 2* . * **_List's numbers_** will only **_positives_** (n > 0) . * **_Repetition_*...
reference
def check_prime(number): for i in range(2, number): if number % i == 0: return False return True def minimum_number(numbers): suma = sum(numbers) while check_prime(suma) != True: suma = suma + 1 print(suma) return suma - sum(numbers)
Transform To Prime
5a946d9fba1bb5135100007c
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5a946d9fba1bb5135100007c
6 kyu
In this Kata, we will calculate the **minimum positive number that is not a possible sum** from a list of positive integers. ``` solve([1,2,8,7]) = 4 => we can get 1, 2, 3 (from 1+2), but we cannot get 4. 4 is the minimum number not possible from the list. solve([4,1,2,3,12]) = 11. We can get 1, 2, 3, 4, 4+1=5, 4+2=...
algorithms
def solve(xs): m = 0 for x in sorted(xs): if x > m + 1: break m += x return m + 1
Simple missing sum
5a941f3a4a6b34edf900006f
[ "Algorithms" ]
https://www.codewars.com/kata/5a941f3a4a6b34edf900006f
6 kyu
You are given an array with several `"even"` words, one `"odd"` word, and some numbers mixed in. Determine if any of the numbers in the array is the index of the `"odd"` word. If so, return `true`, otherwise `false`.
algorithms
def odd_ball(arr): return arr . index("odd") in arr
Odds-Index
5a941f4e1a60f6e8a70025fe
[ "Algorithms" ]
https://www.codewars.com/kata/5a941f4e1a60f6e8a70025fe
7 kyu
In this Kata, you will be given a number and your task will be to return the nearest prime number. ```Haskell solve(4) = 3. The nearest primes are 3 and 5. If difference is equal, pick the lower one. solve(125) = 127 ``` We'll be testing for numbers up to `1E10`. `500` tests. More examples in test cases. Good lu...
algorithms
from itertools import count from gmpy2 import is_prime def solve(n): return next(b for a in count(0) for b in [n - a, n + a] if is_prime(b))
Simple nearest prime
5a9078e24a6b340b340000b8
[ "Algorithms" ]
https://www.codewars.com/kata/5a9078e24a6b340b340000b8
6 kyu
The number ```89``` is the first positive integer that has a particular, curious property: The square of ```89``` is ```7921```; ```89² = 7921``` The reverse of ```7921``` is ```1297```, and ```1297``` is a prime number. The cube of ```89``` is ```704969```; ```89³ = 704969``` The reverse of ```704969``` is ```9694...
algorithms
sq_cub_rev_prime = (None, 89, 271, 325, 328, 890, 1025, 1055, 1081, 1129, 1169, 1241, 2657, 2710, 3112, 3121, 3149, 3244, 3250, 3263, 3280, 3335, 3346, 3403, 4193, 4222, 4231, 4289, 4291, 5531, 5584, 5653, 5678, 5716, 5791, 5795, 5836, 5837, 8882, 8900, 8926, 8942, 9664, 9794, 9875, 9962, 10178, 10250, 10393, 10429, 10...
Square and Cube of a Number Become Prime When Reversed
5644a69f7849c9c097000073
[ "Fundamentals", "Mathematics", "Memoization", "Algorithms" ]
https://www.codewars.com/kata/5644a69f7849c9c097000073
4 kyu
Given a name, turn that name into a perfect square matrix (nested array with the amount of arrays equivalent to the length of each array). You will need to add periods (`.`) to the end of the name if necessary, to turn it into a matrix. If the name has a length of 0, return `"name must be at least one letter"` ## ...
algorithms
from math import ceil def matrixfy(s): if not s: return "name must be at least one letter" x = ceil(len(s) * * .5) it = iter(s . ljust(x * x, '.')) return [[next(it) for _ in range(x)] for _ in range(x)]
Name to Matrix
5a91e0793e9156ccb0003f6e
[ "Strings", "Arrays", "Algorithms", "Matrix" ]
https://www.codewars.com/kata/5a91e0793e9156ccb0003f6e
6 kyu
Consider a sequence made up of the consecutive prime numbers. This infinite sequence would start with: ```python "2357111317192329313741434753596167717379..." ``` You will be given two numbers: `a` and `b`, and your task will be to return `b` elements starting from index `a` in this sequence. ``` For example: solve(1...
algorithms
def solve(a, b): primes = "235711131719232931374143475359616771737983899710110310710911312713113713914915115716316717317918119119319719921122322722923323924125125726326927127728128329330731131331733133734734935335936737337938338939740140941942143143343944344945746146346747948749149950350952152354154755756356957157...
Simple prime streaming
5a908da30025e995880000e3
[ "Algorithms" ]
https://www.codewars.com/kata/5a908da30025e995880000e3
6 kyu
# Task **_Given_** *an array of N integers, you have to find* **_how many times_** *you have to* **_add up the smallest numbers_** *in the array until* **_their Sum_** *becomes greater or equal to* **_K_**. ___ # Notes: * **_List size_** is *at least 3*. * **_All numbers_** *will be* **_positive_**. * **_Num...
reference
def minimum_steps(arr, n): arr = sorted(arr) s = 0 for i, v in enumerate(arr): s += v if s >= n: return i
Minimum Steps (Array Series #6)
5a91a7c5fd8c061367000002
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5a91a7c5fd8c061367000002
7 kyu
Consider the number triangle below, in which each number is equal to the number above plus the number to the left. If there is no number above, assume it's a `0`. ```haskell 1 1 1 1 2 2 1 3 5 5 1 4 9 14 14 ``` The triangle has `5` rows and the sum of the last row is `sum([1,4,9,14,14]) = 42`. You will be given an int...
algorithms
from math import comb def solve(n): """ See: https://en.wikipedia.org/wiki/Catalan's_triangle """ return comb(n << 1, n) / / (n + 1)
Simple number triangle
5a906c895084d7ed740000c2
[ "Algorithms", "Discrete Mathematics" ]
https://www.codewars.com/kata/5a906c895084d7ed740000c2
6 kyu
In this Kata, you will be given an array of integers and your task is to return the number of arithmetic progressions of size `3` that are possible from that list. In each progression, the differences between the elements must be the same. ``` [1, 2, 3, 5, 7, 9] ==> 5 // [1, 2, 3], [1, 3, 5], [1, 5, 9], [3, 5, 7], and...
algorithms
from itertools import combinations def solve(xs): return sum(1 for a, b, c in combinations(xs, 3) if a - b == b - c)
Simple arithmetic progression
5a903c0557c562cd7500026f
[ "Algorithms" ]
https://www.codewars.com/kata/5a903c0557c562cd7500026f
6 kyu
No Story No Description Only by Thinking and Testing Look at the result of testcase, guess the code! # #Series:<br> <a href="http://www.codewars.com/kata/56d904db9963e9cf5000037d">01:A and B?</a><br> <a href="http://www.codewars.com/kata/56d9292cc11bcc3629000533">02:Incomplete string</a><br> <a href="http://w...
games
def digitsum(n): return sum(map(int, str(n))) def test_it(a, b): return digitsum(a) * digitsum(b)
Thinking & Testing: A * B?
5a90c9ecb171012b47000077
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/5a90c9ecb171012b47000077
6 kyu
In *continuation passing style* programming, the functions, instead of returning a value, take an extra argument which is a *continuation function*, taking the value that would have been returned as its argument. Even the basic operations must take an extra argument. For that end, we defined `add(x,y,k)` and `mult(x,y...
reference
def f(x, k): mult(x, 2, k) def g(x, k): mult(10, x, lambda x: add(x, 1, k)) def main(k): g(2, lambda y: f(y, lambda x: show(x, k)))
Continuation in arguments, part 1
5a90bc1fba1bb5aae800007e
[ "Fundamentals" ]
https://www.codewars.com/kata/5a90bc1fba1bb5aae800007e
6 kyu
# Introduction and Warm-up (Highly recommended) # [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays) ___ # Task **_Given_** an *array/list [] of integers* , **_Construct_** a *product array **_Of same size_** Such That prod[i] is equal to The Product of all the e...
reference
from operator import mul from functools import reduce def product_array(numbers): tot = reduce(mul, numbers) return [tot / / n for n in numbers]
Product Array (Array Series #5)
5a905c2157c562994900009d
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5a905c2157c562994900009d
7 kyu