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
To complete this kata you will have to finish a function that returns a string of characters which when printed resemble a Rubik's cube. The function is named `cube`, and it has one integer parameter (formal argument) `n`, for the dimensions of the cube. For example, when I call the function `cube(3)` it will return ...
algorithms
def cube(n): top = "\n" . join(' ' * (n - i - 1) + '/\\' * (i + 1) + '_\\' * n for i in range(n)) bottom = "\n" . join(' ' * i + '\\/' * (n - i) + '_/' * n for i in range(n)) return top + '\n' + bottom
Rubik's Cube Art
6387ea2cf418c41d277f3ffa
[ "ASCII Art" ]
https://www.codewars.com/kata/6387ea2cf418c41d277f3ffa
7 kyu
<h2>Puzzle</h2> <p>If you don't know who <a href="https://en.wikipedia.org/wiki/Where%27s_Wally%3F">Waldo</a> is, he's a nice guy who likes to be in crowded places. But he's also a bit odd as he always likes to hide in plain sight. Can you spot Waldo in the crowd?</p> <h2>Task</h2> <p>Given <code>crowd</code>, an arra...
games
from collections import defaultdict def find_waldo(crowd): d = defaultdict(list) for y, row in enumerate(crowd): for x, c in enumerate(row): if c . isalpha(): d[c]. append([y, x]) return next(v[0] for k, v in d . items() if len(v) == 1)
Where's Waldo?
638244fb08da6c61361d2c40
[ "Puzzles", "Strings", "Arrays", "Logic" ]
https://www.codewars.com/kata/638244fb08da6c61361d2c40
7 kyu
You are given a string with three lowercase letters ( `pattern` ). **Your Task** Implement a function `find_matched_by_pattern(pattern)` that returns a predicate function, testing a string input and returning `true` if the string is matching the pattern, `false` otherwise. A word is considered a match for a given pa...
algorithms
def find_matched_by_pattern(pattern): def f(s, p=pattern): for c in s: if c == p[0]: p = p[1:] elif c in p: break if not p: return True return False return f
Get match by pattern
637d1d6303109e000e0a3116
[ "Regular Expressions", "Strings" ]
https://www.codewars.com/kata/637d1d6303109e000e0a3116
6 kyu
# Context The Explosive Ordinance Disposal Unit of your country has found a small mine field near your town, and is planning to perform a **controlled detonation** of all of the mines. They have tasked you to write an algorithm that helps them find **all safe spots in the area**, as they want to build a temporal base ...
algorithms
def safe_mine_field(mine_field): if mine_field: h, w = len(mine_field), len(mine_field[0]) for i, row in enumerate(mine_field): for j, x in enumerate(row): if x == 'M': for a, b in ((- 1, 0), (1, 0), (0, - 1), (0, 1)): k, l = i + a, j + b while 0 <= k < h and 0 <= l < w and 'M' !...
Controlled Detonation Safety
63838c67bffec2000e951130
[ "Arrays", "Algorithms", "Puzzles" ]
https://www.codewars.com/kata/63838c67bffec2000e951130
6 kyu
Oh no!! You dropped your interpreter!? That didn't sound so good... Write a function that returns the Nth fibonacci number. The use of the character "(" and the words "while", "for" and "gmpy2" has been disabled (broken). You may only use up to 1000 letters in your solution. The use of one "(" is permite...
games
import numpy funny = numpy . matrix # Sorry funny . __class_getitem__ = numpy . matrix arr = funny[[[1, 1], [1, 0]]] funny . __class_getitem__ = arr . astype arr = funny[object] funny . __class_getitem__ = lambda v: v[0, 1] def fibo(n): return funny[arr * * n]
Fibonacci With a Broken Interpreter
637d054dca318e60ef4a3830
[ "Puzzles", "Restricted" ]
https://www.codewars.com/kata/637d054dca318e60ef4a3830
5 kyu
Write a function that accepts a string consisting only of ASCII letters and space(s) and returns that string in block letters of 5 characters width and 7 characters height, with one space between characters. ```if:cpp The string should be formatted in a way that shows the desired output via cpps' <code>std::cout</code>...
algorithms
LETTERS = '''\ AAA BBBB CCC DDDD EEEEE FFFFF GGG H H IIIII JJJJJ K K L M M N N OOO PPPP QQQ RRRR SSS TTTTT U U V V W W X X Y Y ZZZZZ A A B B C C D D E F G G H H I J K K L MM MM NN N O O P P Q Q R R S S T U U V V W W X X Y Y Z A A B B C D D E F G H H I J K K L M M M N N O O P P Q Q R R S T U U V V W W X X Y Y Z ...
Block Letter Printer
6375587af84854823ccd0e90
[ "Strings", "ASCII Art", "Algorithms" ]
https://www.codewars.com/kata/6375587af84854823ccd0e90
6 kyu
Introduction ============ Not having to go to school or work on your birthday is always a treat, so when your birthday would have fallen on a weekend, it's really annoying if a leap year means you miss out. Some friends are discussing this and think they have missed out more than others, so they need your help. The C...
algorithms
from dateutil . parser import parse from dateutil . relativedelta import relativedelta def most_weekend_birthdays(friends, conversation_date): def func(args): count, year, birthday = 0, 1, parse(args[1]) while (current := birthday + relativedelta(years=year)) <= today: count += (current . week...
Weekend Birthdays
6375e9030ac764004a036840
[ "Date Time" ]
https://www.codewars.com/kata/6375e9030ac764004a036840
6 kyu
You just started working at a local cinema, and your first task is to write a function that returns the **showtimes of a specific movie**, given its **length**. In order to make your job easier, you will work with **24-hour format** throughout this kata. Your function receives three parameters, all of them being **int...
algorithms
def movie_times(open, close, length): if close <= 6 or close < open: close += 24 r, t, u = [], open * 60, close * 60 while t + length <= u: r . append((t / / 60 % 24, t % 60)) t += length + 15 return r
Movie Showtimes
6376bbc66f2ae900343b7010
[ "Logic", "Date Time" ]
https://www.codewars.com/kata/6376bbc66f2ae900343b7010
7 kyu
## Puzzle 12 bits, some are sleeping, some are awake. They are all tired and yearn for some sleep. One of them has to stay awake while all others can go to sleep. Can you figure out which one stays awake? ### Hints * _why exactly 12 bits? (perhaps there are realtime applications for this)_ * _fixed test cases will s...
games
def sleep(bits: str) - > str: i = min(range(12), key=lambda i: (bits[i:] + bits[: i])[:: - 1]) return '0' * i + '1' + '0' * (11 - i)
12 Sleepy Bits
63753f7f64c31060a564e790
[ "Puzzles", "Algorithms", "Set Theory" ]
https://www.codewars.com/kata/63753f7f64c31060a564e790
6 kyu
Given a `string`, your task is to count the number and length of arrow symbols in that string and return an `int` using the following rules: - The string will only contain the characters `.`, `-`, `=`, `<`, `>`. - An arrow must start with either `<` or `>`. - Arrows are scored based on their length and direction, for e...
games
import re # regex is good, let's use it def arrow_search(string: str) - > int: return sum( # calculate sum of scores for each arrow # using the below method: len(arrow) # size of the arrow # multiplied by +1/-1 based on direction * ((">" in arrow) - ("<" in arrow)) * (2 ...
Finding Arrows in a String
63744cbed39ec3376c84ff4a
[ "Strings" ]
https://www.codewars.com/kata/63744cbed39ec3376c84ff4a
6 kyu
In his book, _Gödel, Escher, Bach_, Douglas Hofstadter describes a sequence of numbers which begins: ``` 1, 3, 7, 12, 18, 26, 35, 45, 56, 69, 83, 98 .. (sequence A) ``` It has the following property: _**The sequence, together with its sequence of first differences (the differences between successive terms), lists al...
reference
from itertools import count def hofs(): yield 1 xs, ys, n, y = count(1), hofs(), 1, None while True: x, y = next(xs), y or next(ys) if x == y: yield (n := n + next(xs)) y = None else: yield (n := n + x) hofs_gen, hofs_cache = hofs(), [] def hof(n): wh...
Hofstadter's Figure-Figure sequence
636bebc1d446bf71b3f65fa4
[ "Lists", "Algorithms", "Recursion", "Performance" ]
https://www.codewars.com/kata/636bebc1d446bf71b3f65fa4
5 kyu
This is a very common case of operations counting. However, time is money. Given a function called `operations` that receives an Integer argument `number > 0` and does mathematical operations with it. Division and subtraction, division by 2 while the number is even, subtraction by 1 while the number is odd; how many of...
algorithms
def operations(x): return x . bit_count() + x . bit_length() - 1
Time Is Money (number of operations)
636b03830ae6cd00388cd228
[ "Algorithms" ]
https://www.codewars.com/kata/636b03830ae6cd00388cd228
6 kyu
You are a security guard at a large company, your job is to look over the cameras. Finding yourself bored you decide to make a game from the people walking in a hallway on one of the cameras. As many people walk past the hallway you decide to figure out the minimum steps it will take before 2 people cross or come into ...
games
import re def contact(hallway): pairs = re . findall('>-*<', hallway) return min(map(len, pairs)) / / 2 if pairs else - 1
Walking in the hallway
6368426ec94f16a1e7e137fc
[ "Fundamentals", "Strings", "Puzzles", "Algorithms" ]
https://www.codewars.com/kata/6368426ec94f16a1e7e137fc
7 kyu
In the [On-line Encyclopedia of Integer Sequences](https://oeis.org/) a sequence [A112382](https://oeis.org/A112382) which begins ``` 1, 1, 2, 1, 3, 4, 2, 5, 1, 6, 7, 8, 3, 9, 10, 11, 12, 4, 13, 14, 2, 15, 16, 17, 18, 19, 5, 20, .. ``` is described. It is a fractal sequence because it contains every positive integer...
reference
from itertools import count, islice def sequence(): cnt, seq = count(1), sequence() while 1: yield next(cnt) n = next(seq) yield from islice(cnt, n - 1) yield n a112382 = list(islice(sequence(), 1_000_000)). __getitem__
A self-descriptive fractal sequence
6363b0c4a93345115c7219cc
[ "Algorithms", "Lists", "Number Theory", "Recursion" ]
https://www.codewars.com/kata/6363b0c4a93345115c7219cc
5 kyu
# Back and Forth: You are carrying boxes between 2 locations, to be easy, we call them `first` and `second`. You will receive a list of numbers as input, called `lst`. You are moving back and forth between `first` and `second`, carrying that amount of boxes to the other side. You always start from `first`. See th...
games
def minimum_amount(lst): f = s = r1 = r2 = 0 for i, x in enumerate(lst): if i % 2: f, s = f + x, s - x r2 = max(r2, - s) else: f, s = f - x, s + x r1 = max(r1, - f) return r1, r2
Back and Forth: How Many for Each Side?
63624a696137b6000ed726a6
[ "Puzzles", "Logic", "Algorithms", "Performance" ]
https://www.codewars.com/kata/63624a696137b6000ed726a6
6 kyu
## Overview This is a simple "chess themed" algorithmic puzzle - but you don't need to know anything about chess to solve it, other than 3 basic moves. The game is played between two players who take turns moving a piece on the board: Player 1, **who always plays the first move,** and Player 2. The game takes place...
games
tbl = { 'r': [ [1, 1, 1, 1, 1], [1, 0, 1, 0, 1], [1, 1, 1, 1, 1], [1, 0, 1, 0, 1], [1, 1, 1, 1, 1], ], 'b': [ [1, 0, - 1, 0, 1], [0, 1, 0, 1, 0], [- 1, 0, 1, 0, - 1], [0, 1, 0, 1, 0], [1, 0, - 1, 0, 1], ], ...
Transforming Chess Piece Puzzle
635d9b5c8f20017aa1cf2cf6
[ "Puzzles", "Games", "Logic" ]
https://www.codewars.com/kata/635d9b5c8f20017aa1cf2cf6
7 kyu
For this kata, you need to build two regex strings to paint dogs and cats blue. Each of the given inputs will be a word of mixed case characters followed by either `cat` or `dog`. The string will be matched and replaced by the respective expressions. `search` will be used to capture the given strings. For example: ``...
games
search = ".+(?= (dog|cat))" substitute = "blue"
Painting Pets Blue (with regex)
6361bdb5d41160000ee6db86
[ "Strings", "Regular Expressions" ]
https://www.codewars.com/kata/6361bdb5d41160000ee6db86
7 kyu
You are a robot. As a robot, you are programmed to take walks following a path. The path is input to you as a string of the following characters where: * `"^"` -> step up * `"v"` -> step down * `">"` -> step right * `"<"` -> step left For example, a valid path would look like: ``` "^^vv>><<^v>" ``` However, you ...
games
from itertools import groupby DIRS = {'^': 'up', 'v': 'down', '<': 'left', '>': 'right'} def walk(path): if not path: return 'Paused' steps = [] for k, g in groupby(path): l = len(list(g)) steps . append(f"Take { l } step { 's' * ( l > 1 )} { DIRS [ k ]} ") return '\n' . join(st...
You are a Robot: Translating a Path
636173d79cf0de003d6834e4
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/636173d79cf0de003d6834e4
6 kyu
<h1>The Task</h1> <p><i>Please read the introduction below if you are not familiar with the concepts you are being presented in this task.</i></p> <p>Given a root note and a color, return a list of notes that represent the chord.</p> <p>Input arguments: <li> <ul>root: the root note of the chord; concatenation of the d...
reference
from typing import Tuple """Gets the chord, given the root and color. returns ---------- chord : tuple the chord consisting of its notes -> (C, Eb, G), (F#, A, C#), .. arguments ---------- root : str the root note of the chord -> C, D, F#, Ab, .. color : str ...
Learning Chords Triads
579f54c672292dc1a20001bd
[ "Logic", "Fundamentals" ]
https://www.codewars.com/kata/579f54c672292dc1a20001bd
6 kyu
Frank, Sam and Tom build the ship. Then they went on a voyage. This was not a good idea, because the ship crashed on an iceberg and started sinking. Your job is to save the survivors. ## Details The crash scheme looks like an ASCII picture ``` |-| |-| |-| | | | | | | ~\-------|-|-|-|...
reference
CREW = {"F": "Frank", "S": "Sam", "T": "Tom"} NON_WATER_PROOF = [* CREW, ' ', 'x'] class Flotsam: def __init__(self, pic): self . pic = pic self . sea_level = next(i for i, x in enumerate(pic) if '~' in x) self . bottom = len(self . pic) self . width = len(self . pic[0]) self . survi...
Flotsam
635f67667dadea064acb2c4a
[ "Algorithms", "ASCII Art" ]
https://www.codewars.com/kata/635f67667dadea064acb2c4a
5 kyu
Letter triangles Similar to [Coloured triangles](https://www.codewars.com/kata/5a25ac6ac5e284cfbe000111). But this one sums indexes of letters in alphabet. <font size=5>Examples</font> ``` c o d e w a r s c is 3 o is 15 15+3=18 18. letter in the alphabet is r then append r next is o d sum is 19 append s do this unti...
reference
from itertools import pairwise def triangle(row): return len(row) == 1 and row or triangle('' . join(chr((x + y + 15) % 26 + 97) for x, y in pairwise(map(ord, row))))
Letter triangles
635e70f47dadea004acb5663
[ "Algorithms" ]
https://www.codewars.com/kata/635e70f47dadea004acb5663
6 kyu
# Definition A laser positioned `h` units from the ground on the left wall of a unit square (side = 1) will shoot a ray at an angle `a` with the x-axis and it will bounce around the walls until the ray has length `l`. Calculate the end coordinate of the laser ray to 3 decimal places and return it as a tuple `(x, y)`. A...
games
from math import sin, cos, pi, radians def laser_coord(h, a, l): x, y = (l * cos(radians(a))) % 2, (h + l * sin(radians(a))) % 2 return (2 - x if x > 1 else x), (2 - y if y > 1 else y)
Laser in a square room
635d6302fdfe69004a3eba84
[ "Mathematics", "Geometry", "Performance" ]
https://www.codewars.com/kata/635d6302fdfe69004a3eba84
6 kyu
# Definition The Fibonacci number can be extended non-linearly to a new number called `$P(n)$` with the recurrence relation `$\frac{1+P(n+2)}{1+P(n)}=1+P(n+1)$`, for `$n \geq 0$`. Find `$G(n)=P(n)\mod 9$` if `$P(0)=7$` and `$P(1)=31$`. Brute force will not work! # Constraints ``` 0 <= n <= 10^9 ``` ### Good luck!
algorithms
""" (1 + P(n+2)) = (1 + P(n+1)) * (1 + P(n)) (1 + P(n+3)) = (1 + P(n+2)) * (1 + P(n+1)) = (1 + P(n+1))**2 + (1 + P(n)) (1 + P(n+4)) = (1 + P(n+3)) * (1 + P(n+2)) = (1 + P(n+1))**3 + (1 + P(n))**2 (1 + P(n+5)) = (1 + P(n+1))**5 + (1 + P(n))**3 the exponents follow a fibonacci pattern, so we can calculate the...
Fibofamily #1
635d422dfdfe6900283eb892
[ "Mathematics", "Performance" ]
https://www.codewars.com/kata/635d422dfdfe6900283eb892
6 kyu
## Overview Imagine you have an `alphabet` of `n` distinct letters. There are of course `n!` permutations of this `alphabet`. For simplicity in this kata we will always use the first `n` letters from the uppercase alphabet `'ABCDEF...XYZ'`. Now imagine that you are also given a list of "bad subpermutations", each of ...
algorithms
from math import comb as nCk, factorial as fac from itertools import combinations, chain, product def totally_good(alphabet, bads): # starting conditions bads = [b for b in bads if not any(o != b and o in b for o in bads)] n, t = len(alphabet), fac(len(alphabet)) # simple edge cases i...
Totally Good Permutations
6355b3975abf4f0e5fb61670
[ "Algorithms", "Mathematics", "Combinatorics", "Discrete Mathematics", "Strings", "Set Theory", "Number Theory" ]
https://www.codewars.com/kata/6355b3975abf4f0e5fb61670
3 kyu
``` X X X X X 𝙫𝙧𝙤𝙤𝙤𝙤𝙢! ===== O='`o X X X X ``` A car is zooming throug...
reference
# The speeding car: "O='`o" # The other cars: "X" def car_crash(road): return "O='`oX" in road . replace(' ', '')
Car Crash! ==== O='`o
6359f0158f20011969cf0ebe
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/6359f0158f20011969cf0ebe
7 kyu
Given a string of numbers, you must perform a method in which you will translate this string into text, based on the below image: <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Telephone-keypad2.svg/1024px-Telephone-keypad2.svg.png"> For example if you get `"22"` return `"b"`, if you get `"222"` ...
algorithms
import re def phone_words(str): ansd = {'0': ' ', '2': 'a', '22': 'b', '222': 'c', '3': 'd', '33': 'e', '333': 'f', '4': 'g', '44': 'h', '444': 'i', '5': 'j', '55': 'k', '555': 'l', '6': 'm', '66': 'n', '666': 'o', '7': 'p', '77': 'q', '777': 'r', '7777': 's', '8': 't', '88': 'u', ...
PhoneWords
635b8fa500fba2bef9189473
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/635b8fa500fba2bef9189473
6 kyu
The police have placed radars that will detect those vehicles that exceed the speed limit on that road. If the driver's speed is ```10km/h to 19km/h``` above the speed limit, the fine will be ```100``` dollars, if it is exceeded by ```20km/h to 29km/h``` the fine will be ```250``` dollars and if it is exceeded by more ...
algorithms
def speed_limit(скорость, сигналы): штраф = 0 for и in сигналы: if 10 <= скорость - и <= 19: штраф += 100 if 20 <= скорость - и <= 29: штраф += 250 if 30 <= скорость - и: штраф += 500 return штраф
Speed Limit
635a7827bafe03708e3e1db6
[ "Arrays" ]
https://www.codewars.com/kata/635a7827bafe03708e3e1db6
7 kyu
This kata will return a string that represents the difference of two perfect squares as the sum of consecutive odd numbers. Specifications: • The first input minus the second input reveals the exact number of consecutive odd numbers required for the solution - you can check this in the examples below. • The first in...
games
def squares_to_odd(a, b): return f' { a } ^2 - { b } ^2 = { " + " . join ( map ( str , range ( 2 * b + 1 , 2 * a , 2 )))} = { a * a - b * b } '
Difference of perfect squares displayed as sum of consecutive odd numbers
6359b10f8f2001f29ccf0db4
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/6359b10f8f2001f29ccf0db4
6 kyu
# The task You have to make a program capable of returning the sum of all the elements of all the triangles with side of smaller or equal than `$n+1$`. If you have not seen the previous Kata, [take a look](https://www.codewars.com/kata/63579823d25aad000ecfad9f). # The problem Your solution has to support `$0\leq n \le...
games
def get_sum(n): n, m = divmod(n, 2) return - (n + 2 * m - 1) * (n + m + 1) * * 2
Summation Triangle #3
63586460bafe0300643e2caa
[ "Mathematics", "Performance" ]
https://www.codewars.com/kata/63586460bafe0300643e2caa
6 kyu
# The task You have to make a program capable of returning the sum of all the elements of a triangle with side of size `$n+1$`. If you have not seen the previous Kata, [take a look](https://www.codewars.com/kata/6357825a00fba284e0189798). # The problem Your solution has to support `$0\leq n \leq 10^6$`. Brute-forcing ...
games
# see: https://oeis.org/A035608 def get_sum(n): return (- 1) * * n * ((n := n + 1) * n + n - 1 - (n - 1) / / 2)
Summation Triangle #2
63579823d25aad000ecfad9f
[ "Mathematics", "Performance" ]
https://www.codewars.com/kata/63579823d25aad000ecfad9f
6 kyu
It's been a year since a mystery team famously drove a large broadcasting network to bankruptcy by managing to crack its incredibly popular game show [Hat Game](https://www.codewars.com/kata/618647c4d01859002768bc15), allowing them to win consistently. A new network has decided to try and capitalize on the story, by c...
games
def make_strategies(hats): ''' We can ensure that one team member always wins, by making sure that there is no overlap between the guesses of each of our contestants. We do this by giving each team member a unique number (from 0 to n-1). They are then to assume that the total "sum" of hats ...
Hat Game 2
634f18946a80b8003d80e728
[ "Riddles" ]
https://www.codewars.com/kata/634f18946a80b8003d80e728
5 kyu
# The task You have to make a program capable of returning the sum of all the elements of a triangle with side of size `$n+1$`. # The problem Your solution has to support `$0\leq n \leq 10^6$`. Brute-forcing will not work! # The definition A triangle element `$a_{ij}$` where `$i$` is the column and `$j$` is the row c...
games
def get_sum(n): return (n + 1) * (n + 2) * (4 * n + 3) / / 6
Summation Triangle #1
6357825a00fba284e0189798
[ "Mathematics", "Performance" ]
https://www.codewars.com/kata/6357825a00fba284e0189798
7 kyu
## The simple task You have to calculate k-th digit of π, knowing that: ``` π = 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342... ``` Make sure to check the anti-cheat rules at the bottom. ## Examples ``` For k = 0: 3.14159265358979323... ^ ``` ``` For k = 6: 3.14159...
algorithms
# for a proper solution: ...://bellard.org/pi/pi1.c def pi_gen(limit): q, r, t, k, n, l, cn, d = 1, 0, 1, 1, 3, 3, 0, limit while cn != d + 1: if 4 * q + r - t < n * t: yield n if d == cn: break cn, nr, n, q = cn + 1, 10 * (r - n * t), ((10 * (3 * q + r)) / / t) - 10 * n, q * 10 r = ...
Calculate k-th digit of π (Pi)
6357205000fba205ed189a52
[ "Number Theory" ]
https://www.codewars.com/kata/6357205000fba205ed189a52
4 kyu
You will be given a string that contains space-separated words. Your task is to group the words in this way: - Group them by their beginning. - Count how many letters they share in said group. - Return the grouped words, ordered in ascending order, ONLY if their group size (or array length) is equal to the number...
reference
from collections import defaultdict from itertools import chain def letter(msg): D = defaultdict(list) for w in map(str . lower, msg . split()): for i in range(len(w)): D[w[: i + 1]]. append(w) return sorted(chain . from_iterable(v for k, v in D . items() if len(k) == len(v)))
[St]arting [St]ring
635640ee633fad004afb0465
[ "Strings" ]
https://www.codewars.com/kata/635640ee633fad004afb0465
5 kyu
# Pedro's Urns Pedro has `n` urns, numbered from `0` to `n-1`. Each urn `i` contains `r_i` red balls and `b_i` black balls. Pedro removes a random ball from urn `i = 0` and places it in urn `i = 1`. For the next step, he removes a random ball from urn `i = 1` and places it inside urn `i = 2`. He repeats this process...
reference
from fractions import Fraction def get_probability(n, nbs, nrs): pr = Fraction(0) for i, (nb, nr) in enumerate(zip(nbs, nrs)): pr = (nr + pr) / (nb + nr + (i != 0)) return float(pr)
Pedro's Urns
6352feb15abf4f44f9b5cbda
[ "Probability" ]
https://www.codewars.com/kata/6352feb15abf4f44f9b5cbda
6 kyu
Given two Arrays in which values are the power of each soldier, return true if you survive the attack or false if you perish. **CONDITIONS** * Each soldier attacks the opposing soldier in the **same index** of the array. The survivor is the number with the **highest** value. * If the value is the same they both per...
algorithms
def is_defended(attackers, defenders): survivors = [0, 0] for k in range(max(len(attackers), len(defenders))): if len(attackers) <= k: # Empty attacker survivors[1] += 1 elif len(defenders) <= k: # Empty defender survivors[0] += 1 elif attackers[k] < defenders[k]: survivors[1] += 1 ...
Survive the attack
634d0f7c562caa0016debac5
[ "Arrays" ]
https://www.codewars.com/kata/634d0f7c562caa0016debac5
7 kyu
Imagine a circle. To encode the word `codewars`, we could split the circle into 8 parts (as `codewars` has 8 letters): <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKcAAACnCAYAAAB0FkzsAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsIAAA7CARUoSoAAADcVSURBVHhe7Z0LvFVj+sdXVKerLud0OtGFLqd7KpWUcldRRDWj0TSY...
reference
def encode(s): return "" . join(s[((i + 1) / / 2) * (- 1) * * i] for i in range(len(s))) def decode(s): return s[:: 2] + s[1:: 2][:: - 1]
Circle cipher
634d0723075de3f97a9eb604
[ "Ciphers", "Algorithms" ]
https://www.codewars.com/kata/634d0723075de3f97a9eb604
7 kyu
A matrix is "fat" when the sum of the roots of its "Widths" is greater than the sum of the roots of its "Heights". Otherwise, we call it as a "thin" matrix. But what is the meaning of that? A Width of a matrix is the sum of all the elements in a row. Similarly, a Height of a matrix is the sum of all the elements...
algorithms
def root(M): return sum(sum(r) * * .5 for r in M) def thin_or_fat(M): w, h = root(M), root(zip(* M)) if not any(isinstance(v, complex) for v in (w, h)): return "perfect" if abs(w - h) < 1e-10 else "fat" if w > h else "thin"
Matrix Weight
6347f9715467f0001b434936
[ "Matrix" ]
https://www.codewars.com/kata/6347f9715467f0001b434936
7 kyu
## Overview One of the most remarkable theorems in basic graph theory is [Cayley's formula](https://en.wikipedia.org/wiki/Cayley%27s_formula) which states that there are `$n^{n-2}$` trees on `$n$` labeled vertices. One of the most ingenious ways of proving this was discovered by Heinz Prüfer who showed that each such...
reference
def tree_to_prufer(tree): res = [] for _ in range(len(tree) - 2): mn = min(k for k, v in tree . items() if len(v) == 1) res . append([* tree[mn]][0]) tree . pop(mn) for k, v in tree . items(): if mn in v: v . remove(mn) return res def prufer_to_tree(prufer_sequenc...
Prüfer sequences and labeled trees
6324c4282341c9001ca9fe03
[ "Algorithms", "Mathematics", "Graphs", "Graph Theory", "Trees", "Combinatorics" ]
https://www.codewars.com/kata/6324c4282341c9001ca9fe03
6 kyu
~~~if-not:bf Yup, fill the provided set with the keywords of your language. ~~~ ~~~if:bf Write a program that will output all 8 instuctions. ~~~ The test provides the number of needed keywords, and the error messages contain hints if you need help. <!--Translators: Add 3 keywords, one of which should be difficult/obsc...
games
from keyword import kwlist keywords = set(kwlist)
Oh, so you like programming? Name all of the keywords!
634ac4e77611b9f57dff456d
[ "Puzzles" ]
https://www.codewars.com/kata/634ac4e77611b9f57dff456d
7 kyu
Prince Arthas needs your help! Mal'ganis has spread an infection amongst the Stratholme citizens, and we must help Arthas prevent this infection from spreading to other parts of the Kingdom. You will receive a string `s` as input: Each "word" represents a house, and each letter represents a citizen. All infected citiz...
reference
import re def purify(s: str) - > str: return ' ' . join(re . sub(r"[\S]?[iI][^\siI]?", "", s). split())
The Culling of Stratholme
634913db7611b9003dff49ad
[ "Strings", "Games", "Regular Expressions" ]
https://www.codewars.com/kata/634913db7611b9003dff49ad
7 kyu
The set of words is given. Words are joined if the last letter of one word and the first letter of another word are the same. Return `true` if all words of the set can be combined into one word. Each word can and must be used only once. Otherwise return `false`. ## Input ```if:csharp,cpp,javascript,java,groovy,ruby,v...
algorithms
from itertools import pairwise, permutations def solution(arr): for perm in permutations(arr, len(arr)): if all(a[- 1] == b[0] for a, b in pairwise(perm)): return True return False
Millipede of words
6344701cd748a12b99c0dbc4
[ "Algorithms", "Arrays", "Strings" ]
https://www.codewars.com/kata/6344701cd748a12b99c0dbc4
6 kyu
**Task:** Given an array of tuples (int, int) indicating one or more buildings height and width, draw them consecutively one after another as in a street. For example, given the input of [(5,9), (7,13)], the output should be: ``` ■■■■■■■■■■■■■ ■ ■ ■■■■■■■■■ ■ ■ ■ ■ ...
reference
def draw_street(dimensions): maxHeight = max(map(lambda x: x[0], dimensions)) def building(dimensions): h, w = dimensions return [' ' * w] * (maxHeight - h) + [ '■' * w] + [ '■' + ' ' * (w - 2) + '■'] * (h - 4) + [ '■' + '___' . center(w - 2, ' ') + '■', '■' + '| ...
Draw a street
63454405099dba0057ef4aa0
[ "ASCII Art" ]
https://www.codewars.com/kata/63454405099dba0057ef4aa0
6 kyu
<h1>Task</h1> Given a circuit with fixed resistors connected in series and/or in parallel, calculate the total effective resistance of the circuit. All resistors are given in Ω, and the result should be in Ω too (as a float; tested to ± 1e-6). Assume wires have negligible resistance. The voltage of the battery is ir...
algorithms
def series(x): return x def parall(x): return 1 / x if x else float('inf') def rec(circuit): if not isinstance(circuit, list): return circuit test, * circuit = circuit if not circuit: return not test and float('inf') func = test and series or parall return func(sum(func(rec(...
Effective Resistance of a Simple Circuit
63431f9b9943dd4cee787da5
[ "Recursion", "Arrays", "Algorithms", "Fundamentals", "Physics" ]
https://www.codewars.com/kata/63431f9b9943dd4cee787da5
6 kyu
'Evil' numbers are non-negative numbers with even parity, that is, numbers with an even number of `1`s in their binary representation. The first few evil numbers are: ``` 0,3,5,6,9,10,12,15,17,18,20 ``` Write a function to return the n<sup>th</sup> evil number. ```haskell input 1 returns 0 input 2 returns 3 input 3 ...
algorithms
def is_evil(number): count = 0 while number: number &= number - 1 count += 1 return count % 2 == 0 def get_evil(n): t = 2 * (n - 1) return t if is_evil(t) else t + 1
Find the nth evil number
634420abae4b81004afefca7
[ "Mathematics", "Algorithms", "Performance" ]
https://www.codewars.com/kata/634420abae4b81004afefca7
6 kyu
## Story (skippable): Once upon a time, a farmer came across a magic seed shop. Once inside, the salesman sold him a pack of magical trees. Before leaving, the salesman gave him a warning: "These are no ordinary trees, farmer. These trees split up into smaller, further dividing duplicate trees with each passing day," ...
algorithms
def magic_plant(p_feild, split, n): t = p_feild . split('\n') return '\n' . join(c * (split * * n) for c in t[: len(t) - n])
Magical Duplication Tree
6339de328a3b8f0016cc5b8d
[ "Mathematics", "Performance", "Algorithms" ]
https://www.codewars.com/kata/6339de328a3b8f0016cc5b8d
7 kyu
This kata is a direct continuation of [Infinite continued fractions](https://www.codewars.com/kata/63178f6f358563cdbe128886/python) kata, and we'll use our ability to compute coefficients of continued fractions for integer factorization. ## The task Perform a first step of [CFRAC method](https://en.wikipedia.org/wiki...
reference
from typing import Generator from fractions import Fraction import math import itertools def generate_continued_fraction(b) - > Generator[int, None, None]: a, c = 0, 1 while True: if not c: yield from itertools . repeat(0) i = (math . isqrt(b) + a) / / c yield i a, c = c * i - a, (b - ...
Integer factorization: CFRAC basics
63348506df3ef80052edf587
[ "Mathematics", "Algorithms", "Fundamentals", "Performance" ]
https://www.codewars.com/kata/63348506df3ef80052edf587
4 kyu
**Introduction** As a programmer, one must be familiar with the usage of iterative statements in coding implementations! Depending on the chosen programming language, iterative statements can come in the form of `for`, `while`, `do-while` etc. Below is an example of a `nested C-style for-loop`: ```c for(int i = 0; i...
algorithms
def count_loop_iterations(arr): res = [] acc = 1 for n, b in arr: n = n + 2 if b else n + 1 res . append(acc * n) acc *= n - 1 return res
Can you count loop's execution?
633bbba75882f6004f9dae4c
[ "Algorithms" ]
https://www.codewars.com/kata/633bbba75882f6004f9dae4c
7 kyu
<h2 style='color:#f88'>EXPLANATIONS </h2> We will work with the numbers of the form: ```math p_1 × p^2_2 × p^3_3 ×.......× p^n_n ``` and ```math p_1, p_2, p_3, .....,p_n ``` It's a chain of ```n``` consecutive primes. As you can see, each prime is raised to an exponent. All the exponents are in an increasing seque...
reference
def primes(n): sieve = n / / 2 * [True] for i in range(3, int(n * * 0.5) + 1, 2): if sieve[i / / 2]: sieve[i * i / / 2:: i] = [False] * ((n - i * i - 1) / / (2 * i) + 1) return [2] + [2 * i + 1 for i in range(1, n / / 2) if sieve[i]] from string import ascii_uppercase as u, ascii_lowerca...
Involution in Numbers of Different Bases Using the Alphabetical System.
632abe6080604200319b7818
[ "Mathematics", "Number Theory" ]
https://www.codewars.com/kata/632abe6080604200319b7818
6 kyu
Twelve cards with grades from `0` to `11` randomly divided among `3` players: Frank, Sam, and Tom, `4` cards each. The game consists of `4` rounds. The goal of the round is to move by the card with the most points.<br> In round `1`, the first player who has a card with `0` points, takes the first turn, and he starts wi...
games
def solution(frank, sam, tom): count = 0 for i in range(4): for j in range(4): if frank[j] > sam[i] and frank[j] > tom[i]: count += 1 frank[j] = 0 break return count >= 2
Another card game
633874ed198a4c00286aa39d
[ "Algorithms", "Games" ]
https://www.codewars.com/kata/633874ed198a4c00286aa39d
7 kyu
There are `N` lights in the room indexed from `0` to `N-1`. All the lights are currently off, and you want to turn them on. At this point, you find that there are `M` switches in the room, indexed from `0` to `M-1`. Each switch corresponds to several lights. Once the switch is toggled, all the lights related to the swi...
algorithms
def light_switch(n, lights): result = {0} for s in lights: result |= {x ^ sum(1 << x for x in s) for x in result} return (1 << n) - 1 in result
Light Switch
63306fdffa185d004a987b8e
[ "Algorithms", "Puzzles", "Searching", "Performance" ]
https://www.codewars.com/kata/63306fdffa185d004a987b8e
5 kyu
The greatest common divisor (gcd) of two non-negative integers `$a$` and `$b$` is, well, their greatest common divisor. For instance, `$ \mathrm{gcd}(6, 4) = 2$` and `$ \mathrm{gcd}(100, 17) = 1$`. Note that in these cases the gcd can be expressed as a linear combination with integer coefficients of the given two numbe...
algorithms
from gmpy2 import gcdext def gcd_coeff(a, b): _, x, y = gcdext(a, b) return int(x), int(y)
Greatest common divisor as linear combination
63304cd2c68f640016b5d162
[ "Algorithms", "Mathematics", "Number Theory", "Cryptography" ]
https://www.codewars.com/kata/63304cd2c68f640016b5d162
6 kyu
In a computer operating system that uses paging for virtual memory management, page replacement algorithms decide which memory pages to page out when a page of memory needs to be allocated. Page replacement happens when a requested page is not in memory (page fault) and a free page cannot be used to satisfy the allocat...
algorithms
def lru(n, reference_list): cache, time = [- 1] * n, [- 1] * n for i, x in enumerate(reference_list): idx = cache . index(x) if x in cache else time . index(min(time)) cache[idx] = x time[idx] = i return cache
Page replacement algorithms: LRU
6329d94bf18e5d0e56bfca77
[ "Algorithms", "Lists" ]
https://www.codewars.com/kata/6329d94bf18e5d0e56bfca77
6 kyu
## Overview Suppose you build a pyramid out of unit-cubes, starting from a square base, and such that cubes stack exactly onto cubes below them (they do not overlap or sit on "lines" in the level below theirs). For example: if you start with a square base of side = 7 cubes, your first level has a total of `7**2 = 49`...
games
def pyramid(h): return (8 * h * h - 4 * h + 1, 8 * h * * 3 - 2 * h)
[Code Golf] Painted Pyramid Probability Puzzle
62f7ca8a3afaff005669625a
[ "Puzzles", "Mathematics", "Restricted", "Probability" ]
https://www.codewars.com/kata/62f7ca8a3afaff005669625a
6 kyu
### Task Given Points `A`, `B`, `C` ∈ ℤ<sup>2</sup> and `dA`, `dB`, `dC` ∈ ℤ their respective squared euclidian distances to a certain point `P` ∈ ℤ<sup>2</sup>, return the value of `P`. ### Note A, B, and C will always be distinct and non-collinear
games
def triangulate(A, dA, B, dB, C, dC): a11, a21 = 2 * (B[0] - A[0]), 2 * (C[0] - A[0]) a12, a22 = 2 * (B[1] - A[1]), 2 * (C[1] - A[1]) b1, b2 = dA - dB - A[0] * * 2 - A[1] * * 2 + B[0] * * 2 + B[1] * * 2, dA - dC - A[0] * * 2 - A[1] * * 2 + C[0] * * 2 + C[1] * * 2 dt = a11 * a22 - a12 * a21 x, y...
Locate P using 3 Points and their distances to P
6326533f8b7445002e856ca3
[ "Mathematics", "Geometry" ]
https://www.codewars.com/kata/6326533f8b7445002e856ca3
6 kyu
## Overview Given an `integer`, `n`, consider its binary representation - I shall call a **binary bunching of `n`** any rearrangement of the bits of `n` such that all **set bits are contiguous** (i.e. all its `1`s are side-by-side when viewed as a string). There are many possible ways of binary bunching the bits of `...
reference
def bunch(n): s, w = n . bit_length(), n . bit_count() base = (1 << w) - 1 chunks = (base << i for i in range(s - w + 1)) return min(chunks, key=lambda v: ((n ^ v). bit_count(), v))
Binary Bunch Transform of an Integer
62cc5882ea688d00428ad2b0
[ "Fundamentals", "Binary" ]
https://www.codewars.com/kata/62cc5882ea688d00428ad2b0
6 kyu
<h2 style="color:#4bd4de">Description</h2> In mathematics, and more specifically number theory, the hyperfactorial of a positive integer `$n$` is the product of the numbers `$1^1 , 2^2, ..., n^n $`: `$H(n) = 1^1 \times 2^2 \times 3^3 \times ... \times (n-1)^{n-1} \times n^n$` `$H(n) = \prod_{i=1}^{n} i^i $` <a href...
reference
from itertools import accumulate H = [0, * accumulate(range(1, 301), lambda a, n: a * n * * n % 1000000007)] hyperfact = H . __getitem__
The Hyperfactorial
6324786fcc1a9700260a2147
[ "Mathematics" ]
https://www.codewars.com/kata/6324786fcc1a9700260a2147
7 kyu
```if-not:c This kata is about static method that should return different values. ``` ```if:c This kata is about a function that should return different values. ``` On the first call it must be 1, on the second and others - it must be a double from previous value. Look tests for more examples, good luck :)
reference
class Class: value = 1 def get_number(): result = Class . value Class . value *= 2 return result
Double value every next call
632408defa1507004aa4f2b5
[ "Object-oriented Programming" ]
https://www.codewars.com/kata/632408defa1507004aa4f2b5
7 kyu
I invented a new operator, ```@```, which is left associative. ```a @ b = (a + b) + (a - b) + (a * b) + (a // b)``` Side note: ```~~``` is shorthand for ```Math.floor```. Given a string containing only integers and the operators, find out the value of that string. The strings will always be "well formed", meaning w...
algorithms
from functools import reduce def evaluate(equation): try: return reduce(lambda a, b: a * (b + 2) + a / / b, map(int, equation . split(' @ '))) except ZeroDivisionError: pass
The @ operator
631f0c3a0b9cb0de6ded0529
[ "Algorithms" ]
https://www.codewars.com/kata/631f0c3a0b9cb0de6ded0529
7 kyu
I suggest you write a program that, having a string containing the solution of the level for the game Sokoban, will restore the original level. <i>The rules of the Sokoban:</i><br> The objective of the Sokoban game is to move objects (usually boxes) to designated locations by pushing them. These objects are located i...
algorithms
# Just having some fun with the new match/case :D def level_recovery(solution): D, boxes, i, j = {}, set(), 0, 0 for c in solution: D[(i, j)] = ' ' match c: case 'l' | 'L': k, l = 0, - 1 case 'r' | 'R': k, l = 0, 1 case 'u' | 'U': k, l = - 1, 0 case 'd' | 'D': k, l = 1, 0 if c . isup...
Sokoban re-solver : level recovery from solution
6319f8370b9cb0ffc2ecd58d
[ "Game Solvers", "Games", "Puzzles", "Algorithms" ]
https://www.codewars.com/kata/6319f8370b9cb0ffc2ecd58d
5 kyu
_The world of reality has its limits; the world of imagination is boundless._ Jean-Jacques Rousseau Each positive integer may have a specific set of pairs of factors which each value equals the number. But, how can it possible to get an _area value_ for each positive integer? In order to get that value for an int...
reference
def area_value(n): res, i, j = 0, 1, 2 while j * j <= n: if n % j == 0: res += n / / i * j - n / / j * i i = j j += 1 return 0 if n < 2 else res + ((n / / i) * * 2 - i * i) / / 2
Positive Integers Having Specific Area? # 1
631373e489d71c005d880f18
[ "Mathematics", "Geometry" ]
https://www.codewars.com/kata/631373e489d71c005d880f18
6 kyu
In a string we describe a road. There are cars that move to the right and we denote them with ">" and cars that move to the left and we denote them with "<". There are also cameras that are indicated by: " . ". <br> A camera takes a photo of a car if it moves to the direction of the camera. <b style="font-size: 20px;...
algorithms
def count_photos(road): photos = 0 left = 0 dot_founds = 0 for item in road: if item == ">": left += 1 elif item == ".": photos += left dot_founds += 1 elif item == "<": photos += dot_founds return photos
Count the photos!
6319dba6d6e2160015a842ed
[ "Algorithms", "Performance", "Arrays" ]
https://www.codewars.com/kata/6319dba6d6e2160015a842ed
6 kyu
You are given a list/array of example equalities such as: [ "a + a = b", "b - d = c ", "a + b = d" ] Use this information to solve a given `formula` in terms of the remaining symbol such as: formula = "c + a + b" In this example: "c + a + b" = "2a" so the output is `"2a"`. Notes: * Variables names a...
games
import re token = re . compile(r'([+-]?)\s*(\d*)\s*([a-zA-Z\(\)])') def substitute(formula, substitutes): res = formula for var, sub in substitutes: res = res . replace(var, '({})' . format(sub)) return res if res == formula else substitute(res, substitutes) def reduce(tokens): res...
Simplifying
57f2b753e3b78621da0020e8
[ "Games", "Puzzles" ]
https://www.codewars.com/kata/57f2b753e3b78621da0020e8
3 kyu
A continuation kata published: [Integer factorization: CFRAC basics](https://www.codewars.com/kata/63348506df3ef80052edf587) ## General info A [continued fraction](https://en.wikipedia.org/wiki/Continued_fraction) is a mathematical expression of the following form: ```math [a_0; a_1, a_2, a_3, ..., a_n, ...] = a_0 +...
algorithms
from typing import Generator from math import isqrt def generate_continued_fraction(n) - > Generator[int, None, None]: a0 = isqrt(n) a, b, c = a0, 0, 1 yield a0 while True: b = c * a - b c = (n - b * b) / / c if not c: break a = (a0 + b) / / c yield a while True: yi...
Infinite continued fractions
63178f6f358563cdbe128886
[ "Mathematics", "Fundamentals", "Performance" ]
https://www.codewars.com/kata/63178f6f358563cdbe128886
5 kyu
<div style="width: 100%; margin: 16px 0; border-top: 1px solid grey;" /> - This is Part 2 of this series of two katas — Part 1 is [here](https://www.codewars.com/kata/630647be37f67000363dff04). - If you like playing cards, have also a look at [Hide a message in a deck of playing cards](https://www.codewars.com/kata/59...
algorithms
from collections import deque def prepare_deck(drawn_cards): deck = deque() for c in reversed(drawn_cards): deck . rotate(1) deck . appendleft(c) return list(deck)
Playing Cards Draw Order – Part 2
6311b2ce73f648002577f04a
[ "Games", "Permutations", "Algorithms" ]
https://www.codewars.com/kata/6311b2ce73f648002577f04a
6 kyu
<div style="width: 100%; margin: 16px 0; border-top: 1px solid grey;" /> - This is Part 1 of this series of two katas — Part 2 is [here](https://www.codewars.com/kata/6311b2ce73f648002577f04a). - If you like playing cards, have also a look at [Hide a message in a deck of playing cards](https://www.codewars.com/kata/59...
algorithms
def draw(deck): order = [] while deck: order . append(deck . pop(0)) if deck: deck . append(deck . pop(0)) return order
Playing Cards Draw Order – Part 1
630647be37f67000363dff04
[ "Mathematics", "Games", "Permutations" ]
https://www.codewars.com/kata/630647be37f67000363dff04
7 kyu
> The Twenty-One Card Trick, also known as the 11th card trick or three column trick, is a simple self-working card trick that uses basic mathematics to reveal the user's selected card. > The game uses a selection of 21 cards out of a standard deck. These are shuffled and the player selects one at random. The cards a...
games
DECK = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21] def guess_the_card(audience): deck = DECK for _ in range(3): deal = [deck[:: 3], deck[1:: 3], deck[2:: 3]] deal . insert(1, deal . pop(audience . get_input(deal))) deck = sum(deal, []) return d...
Mathemagics: the 21 Cards Trick
62b76a4f211432636c05d0a9
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/62b76a4f211432636c05d0a9
7 kyu
We have a positive integer ```N, N > 0```. We have a special integer ```N1, N1 > N```, such that ```N1 = c ‧ d``` and ```N = c + d``` with the constraint that ```c ≠ d``` Let´s see an example: ``` N = 26 (starting integer) ``` The next integer ```N1```, chained with this property with ```N```, will be ```48```. Be...
reference
def max_int_chain(n): return - 1 if n < 5 else (n / / 2) * (n - n / / 2) if n % 2 else (n / / 2 - 1) * (n / / 2 + 1)
I Will Take the Biggest One and Nothing Else.
631082840289bf000e95a334
[ "Mathematics" ]
https://www.codewars.com/kata/631082840289bf000e95a334
7 kyu
Now that you’re back to school for another term, you need to remember how to work the combination lock on your locker. The lock has a dial with 40 calibration marks numbered 0 to 39 in clockwise order. A combination of this lock consists of 3 of these numbers; for example: 15-25-8. ![Example Lock](https://b3h2.scene7...
algorithms
def degrees_of_lock(initial, first, second, third): return 1080 + ((initial - first) % 40 + (second - first) % 40 + (second - third) % 40) * 9
Combination Lock
630e55d6c8e178000e1badfc
[ "Mathematics" ]
https://www.codewars.com/kata/630e55d6c8e178000e1badfc
6 kyu
## Task Given a list of points, construct a graph that includes all of those points and the position **(0, 0)**. ```if:javascript Points will be objects like so: `{x: 1, y: -1}`. ``` ```if:coffeescript Points will be objects like so: `{x: 1, y: -1}`. ``` ```if:python Points will be dictionaries like so: `{"x": 1, "y":...
reference
def construct_graph(points): if not points: return [['+']] min_x = min(0, min(point['x'] for point in points)) min_y = min(0, min(point['y'] for point in points)) max_x = max(0, max(point['x'] for point in points)) max_y = max(0, max(point['y'] for point in points)) graph = [[' '] * (...
Construct a Graph
630649f46a30e8004b01b3a3
[ "Graphs", "ASCII Art" ]
https://www.codewars.com/kata/630649f46a30e8004b01b3a3
6 kyu
# Story & Task You're a pretty busy billionaire, and you often fly your personal Private Jet to remote places. Usually travel doesn't bother you, but this time you are unlucky: it's New Year's Eve, and since you have to fly halfway around the world, you'll probably have to celebrate New Year's Day in mid-air! Your cou...
games
def new_year_celebrations(take_off_time, minutes): h, m = map(int, take_off_time . split(':')) res, m = 0, 60 * h + m or 1440 for x in map(int . __sub__, minutes, [0] + minutes): res += m <= 1440 and m + x >= 1440 m += x - 60 return res + (m <= 1440)
Simple Fun #100: New Year Celebrations
589816a7d07028ac5c000016
[ "Puzzles" ]
https://www.codewars.com/kata/589816a7d07028ac5c000016
6 kyu
Recently you had a quarrel with your math teacher. Not only that nerd demands knowledge of all the theorems, but he turned to be an constructivist devotee! After you recited by heart [Lagranges theorem of sum of four squares](https://en.wikipedia.org/wiki/Lagrange%27s_four-square_theorem), he now demands a computer pro...
algorithms
from typing import Tuple from math import gcd from gmpy2 import is_prime def four_squares(n: int) - > Tuple[int, int, int, int]: print(n) if n == 0: return 0, 0, 0, 0 twos = 1 while n % 4 == 0: n / /= 4 twos *= 2 nums = [] if n % 8 == 7: sqrtn = isqrt...
Express number as sum of four squares
63022799acfb8d00285b4ea0
[ "Performance", "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/63022799acfb8d00285b4ea0
1 kyu
### Task Use the characters `" "` and `"█"` to draw the nth iteration of the [Sierpiński carpet](https://en.wikipedia.org/wiki/Sierpi%C5%84ski_carpet). In the following you are given the first three iterations. Implement `sierpinski_carpet_string(n)` which returns the Sierpiński carpet as string for `n` iterations. ...
algorithms
def sierpinski_carpet_string(n): m = ["██"] for i in range(n): m = [x + x + x for x in m] + \ [x + x . replace("█", " ") + x for x in m] + [x + x + x for x in m] return "\n" . join(m)
ASCII Sierpiński Carpet
630006e1b4e54c7a7e943679
[ "ASCII Art", "Mathematics" ]
https://www.codewars.com/kata/630006e1b4e54c7a7e943679
6 kyu
# Structural Pattern Matching: ___NOTE: Make Sure You Select Python 3.10 for Structural Pattern Matching.___ Read [PEP 636](https://peps.python.org/pep-0636/) may help you understand it. This Kata is made to practice the Structural Pattern Matching. ___ # Examples of Structural Pattern Matching: There is some speci...
reference
def matching(arg): match arg: case[]: return 0 case[x]: return int(x) case[a, * _, 0 | '0']: return None case[a, * _, b]: return int(a) / int(b)
Practicing - Structural Pattern Matching
62fd5b557d267aa2d746bc19
[ "Fundamentals" ]
https://www.codewars.com/kata/62fd5b557d267aa2d746bc19
7 kyu
In a computer operating system that uses paging for virtual memory management, page replacement algorithms decide which memory pages to page out when a page of memory needs to be allocated. Page replacement happens when a requested page is not in memory (page fault) and a free page cannot be used to satisfy the allocat...
algorithms
def clock(n, xs): ks, vs, ptr = [- 1] * n, [0] * n, 0 def inc(): nonlocal ptr ptr = (ptr + 1) % n for x in xs: if x in ks: vs[ks . index(x)] = 1 else: while vs[ptr]: vs[ptr] -= 1 inc() ks[ptr] = x inc() return ks
Page replacement algorithms: clock
62f23d84eb2533004be50c0d
[ "Algorithms", "Lists" ]
https://www.codewars.com/kata/62f23d84eb2533004be50c0d
6 kyu
### The Mandelbrot set The [Mandelbrot set](https://en.wikipedia.org/wiki/Mandelbrot_set) is the set of complex numbers `$c$` for which the recursive function `$z = z^2 + c$` does not diverge to infinity when starting at `$z = 0$` We will estimate for a set of values if they belong to the Mandelbrot set. For this est...
algorithms
def mandelbrot_string(x, y, width, height, stepsize, max_iter): def mandelbrot_pixel(c): z = 0 for n in range(max_iter + 1): z = z * z + c if not abs(z) < 2: break return n return '\n' . join( '' . join( ' ░▒▓█' [4 * mandelbrot_pixel( co...
ASCII Mandelbrot Set
62fa7b95eb6d08fa9468b384
[ "ASCII Art", "Mathematics" ]
https://www.codewars.com/kata/62fa7b95eb6d08fa9468b384
5 kyu
# Task: In this Golfing Kata, you are going to do simple things: * Reverse a string; then * Return the index of first uppercase letter. ___ # Input: You are going to get a `string` which consists only __uppercase__ and __lowercase__ English letters. It will have at least one uppercase letter. ___ # Output: Retur...
games
def f(s): return s[- 1] > "Z" and - ~ f(s[: - 1])
[Code Golf] Reversed Upper Index
62f8d0ac2b7cd50029dd834c
[ "Strings", "Restricted" ]
https://www.codewars.com/kata/62f8d0ac2b7cd50029dd834c
6 kyu
**SITUATION** Imagine you are trying to roll a ball a certain distance down a road. The ball will have a starting speed that slowly degrades due to friction and cracks in the road. Every time the ball rolls a distance equal to its speed or rolls over a crack, its speed decreases by 1. Given a speed of s which the ball...
reference
def ball_test(s, r): if len(r) <= s: return True elif s <= 0 and r: return False cracks = r[: s]. count('x') return ball_test(s - 1 - cracks, r[s:])
Street Bowling
62f96f01d67d0a0014f365cf
[ "Algorithms", "Strings" ]
https://www.codewars.com/kata/62f96f01d67d0a0014f365cf
7 kyu
Copy of [Is the King in check ?](https://www.codewars.com/kata/5e28ae347036fa001a504bbe/javascript). But this time your solution has to be ` < 280` characters, no semicolons or new lines. You have to write a function ``` is_check ``` that takes for input a 8x8 chessboard in the form of a bi-dimensional array of str...
games
is_check = lambda g, n = '(.{7}|.{11}|.{18}(|..))', r = '((.{9} )*.{9}| *)', b = '((.{8} )*.{8}|(.{10} )*.{10})': bool(__import__( 're'). search(f"♔ { n } ♞|♞ { n } ♔|♔ { r } [♛♜]|[♛♜] { r } ♔|[♛♝] { b } ♔|♔ { b } [♛♝]|♟.{{ 8}} (|..)♔", '||' . join(map('' . join, g))))
One line task: Is the King in check ?
5e320fe3358578001e04ad55
[ "Restricted", "Puzzles" ]
https://www.codewars.com/kata/5e320fe3358578001e04ad55
3 kyu
Everybody likes sliding puzzles! For this kata, we're going to be looking at a special type of sliding puzzle called Loopover. With Loopover, it is more like a flat rubik's cube than a sliding puzzle. Instead of having one open spot for pieces to slide into, the entire grid is filled with pieces that wrap back around w...
games
def loopover(mixed, solved): t = {c: (i, j) for (i, row) in enumerate(solved) for (j, c) in enumerate(row)} b = {(i, j): t[c] for (i, row) in enumerate(mixed) for j, c in enumerate(row)} unsolved = {k for k, v in b . items() if k not in ( (0, 0), (0, 1)) and k != v} sol ...
Loopover
5c1d796370fee68b1e000611
[ "Puzzles", "Algorithms", "Game Solvers" ]
https://www.codewars.com/kata/5c1d796370fee68b1e000611
1 kyu
<img src='https://i.imgur.com/3W4hpEW.png' align="right">Have you ever played <a href='https://en.wikipedia.org/wiki/Microsoft_Minesweeper'>Minesweeper</a>? It's a WINDOWS own game that mainly tests the player's ability to think logically. Here are the rules of the game, maybe helpful to someone who hasn't played Mine...
games
from itertools import combinations def solve_mine(mapStr, n): return MineSweeper(mapStr, n). solve() class MineSweeper (object): IS_DEBUG = False around = [(dx, dy) for dx in range(- 1, 2) for dy in range(- 1, 2) if (dx, dy) != (0, 0)] def __init__(self, mapStr, nMines): ...
Mine Sweeper
57ff9d3b8f7dda23130015fa
[ "Puzzles", "Game Solvers" ]
https://www.codewars.com/kata/57ff9d3b8f7dda23130015fa
1 kyu
# Whitespace [Whitespace](http://compsoc.dur.ac.uk/whitespace/tutorial.php) is an esoteric programming language that uses only three characters: * `[space]` or `" "` (ASCII 32) * `[tab]` or `"\t"` (ASCII 9) * `[line-feed]` or `"\n"` (ASCII 10) All other characters may be used for comments. The interpreter ignores t...
algorithms
def whitespace(code, inp=''): code = '' . join(['STN' [' \t\n' . index(c)] for c in code if c in ' \t\n']) output, stack, heap, calls, pos, run, search, inp = [ ], [], {}, [], [0], [True], [None], list(inp) def set_(t, i, val): t[i] = val # Stack operations def...
Whitespace Interpreter
52dc4688eca89d0f820004c6
[ "Esoteric Languages", "Interpreters", "Algorithms" ]
https://www.codewars.com/kata/52dc4688eca89d0f820004c6
2 kyu
_(Revised version from previous series 6)_ # Number Pyramid: Image a number pyramid starts with `1`, and the numbers increasing by `1`. Today, it has total `5000` levels. For example, the top 4 levels of the pyramid looks like: ``` 1 2 3 4 5 6 7 8 9 10 ``` ___ # Left and Right: Now from the center line,...
games
def left_right(n): return 'CLR' [int((8 * n - 4) * * .5 % 2 / / - 1)]
[Code Golf] Number Pyramid Series 6(Revised) - Left or Right
62eedcfc729041000ea082c1
[ "Mathematics", "Restricted" ]
https://www.codewars.com/kata/62eedcfc729041000ea082c1
6 kyu
In a computer operating system that uses paging for virtual memory management, page replacement algorithms decide which memory pages to page out when a page of memory needs to be allocated. Page replacement happens when a requested page is not in memory (page fault) and a free page cannot be used to satisfy the allocat...
algorithms
def fifo(n, reference_list): memory = [- 1] * n c = 0 for ref in reference_list: if ref in memory: continue memory[c] = ref c = (c + 1) % n return memory
Page replacement algorithms: FIFO
62d34faad32b8c002a17d6d9
[ "Algorithms", "Lists" ]
https://www.codewars.com/kata/62d34faad32b8c002a17d6d9
7 kyu
## Overview The genius supervillain Professor Lan X, head of the mysterious organization Just4EvilCoders, is bored in his secret volcano research laboratory and challenges you to the following game: First, **you will be blindfolded**. Then on a very, very large 2d chessboard, he will place a chess piece on a start...
algorithms
from functools import reduce from itertools import combinations def _add(v0, v1): return v0[0] + v1[0], v0[1] + v1[1] def _mul(v, k): return v[0] * k, v[1] * k def _blindfold_chess(moves): mcs = {k: [reduce(_add, c) for c in combinations(moves, k)] for k in range(1, len(move...
Evil genius game - Find the moving chess piece while blindfolded
62e068c14129156a2e0df46a
[ "Algorithms", "Mathematics", "Combinatorics", "Performance" ]
https://www.codewars.com/kata/62e068c14129156a2e0df46a
4 kyu
One of the common ways of representing color is the RGB color model, in which the Red, Green, and Blue primary colors of light are added together in various ways to reproduce a broad array of colors. One of the ways to determine brightness of a color is to find the value V of the alternative HSV (Hue, Saturation, Valu...
reference
# String comparison is enough, no need to convert def brightest(colors): return max(colors, key=lambda c: max(c[1: 3], c[3: 5], c[5:]))
Which color is the brightest?
62eb800ba29959001c07dfee
[ "Algorithms", "Strings" ]
https://www.codewars.com/kata/62eb800ba29959001c07dfee
7 kyu
In this kata you will compute the last digit of the sum of squares of Fibonacci numbers. Consider the sum `$S_n = F_0^2 + F_1^2 + ... + F_n^2$`, where `$F_0=0$`, `$F_1=1$` and `$F_i=F_{i-1}+F_{i-2}$` for `$i\geq2$` , you must compute the last digit of `$S_n$`. Example: Given input `$n=7$`, `$S_n=273$`. Therefore the ...
algorithms
def fibonacci_squared_sum(n): return int( "012650434056210098450676054890" [n % 30])
Last digit of the squared sum of Fibonacci numbers
62ea53ae888e170058f00ddc
[ "Mathematics" ]
https://www.codewars.com/kata/62ea53ae888e170058f00ddc
6 kyu
# Summary If you've ever been at rock/metal concerts, you know that they're great, but can be quite uncomfortable sometimes. In this kata, we're going to find the best place at the dance floor to be standing at! `dance_floor` will be given as an array of strings, each containing: * ASCII letters (uppercase and lowerc...
algorithms
def places_around(dance_floor, row, col, empty=False): places = [] for i in ((- 1, 0), (0, - 1), (0, 1), (1, 0)): rel_row, rel_col = row + i[0], col + i[1] if 0 <= rel_row < rows and 0 <= rel_col < cols and (not empty or dance_floor[rel_row][rel_col] == ' '): places . append((rel_row, rel_c...
Best place at concert
6112917ef983f2000ecbd506
[ "Strings", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/6112917ef983f2000ecbd506
5 kyu
# Peg Solitaire <svg width="92.004997mm" height="92.004997mm" viewBox="0 0 92.004997 92.004997" version="1.1" id="svg5" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg"> <defs id="defs2"> <linearGradient id="l...
algorithms
from functools import cache def solve(board): moves, board = [], board . splitlines() poss = {p: i for i, p in enumerate( ((x, y) for x, r in enumerate(board) for y, v in enumerate(r) if v != '_'), 1)} @ cache def dfs(pegs): if len(pegs) == 1: return True for (x, y...
Peg Solitaire
62e41d4816d2d600367aee79
[ "Game Solvers", "Games" ]
https://www.codewars.com/kata/62e41d4816d2d600367aee79
4 kyu
## Backstory The problem is based on these katas, although completing it does not require completing these ones first: https://www.codewars.com/kata/514b92a657cdc65150000006 https://www.codewars.com/kata/62e5ab2316d2d6d2a87af831 Since my previous enhancement was not big of a deal, I decided to give my friend a real...
games
from itertools import combinations from functools import reduce from operator import mul def find_them(number_limit, primes): res = 0 for ln in range(1, len(primes) + 1): for cmb in combinations(primes, ln): mlt, sgn = reduce(mul, cmb), (- 1) * * (ln + 1) pw = (number_limit - 1) / / mlt res +=...
Multiples of some primes
62e66bea9db63bab88f4098c
[ "Mathematics", "Algorithms", "Performance" ]
https://www.codewars.com/kata/62e66bea9db63bab88f4098c
5 kyu
```0, 0, 1, 0, 2, 0, 2, 2, 1, 6, 0, 5, 0, 2, 6, 5, 4, 0, 5, 3, 0, 3, …``` This is the ```Van Eck's Sequence```. Let's go through it step by step. ``` Term 1: The first term is 0. Term 2: Since we haven’t seen 0 before, the second term is 0. Term 3: Since we had seen a 0 before, one step back, the third term is 1 Ter...
reference
def dist(arr): for i in range(1, len(arr)): if arr[- 1 - i] == arr[- 1]: return i return 0 def seq(n): s = [0, 0] for _ in range(n): s . append(dist(s)) return s[n - 1]
Van Eck's Sequence
62e4df54323f44005c54424c
[ "Algorithms" ]
https://www.codewars.com/kata/62e4df54323f44005c54424c
6 kyu
*Note: this kata assumes that you are familiar with basic functional programming.* In this kata, you are going to infer the type of an expression based on a given context. Your goal is to implement the `infer_type` function so that it can take in a context like: ```python """ myValue : A concat : List -> List -> List...
reference
import re def parse_type(s): tokens = re . findall(r'->|[()]|[A-Z][a-zA-Z0-9]*', s) def next_token(): return tokens and tokens . pop(0) or None def peek_token(): return tokens and tokens[0] or None def parse_func(): ty = parse_atom() if peek_token() == "->": next_token() ty ...
The Little Typer: Values, Functions and Currying
62975e268073fd002780cb0d
[ "Functional Programming" ]
https://www.codewars.com/kata/62975e268073fd002780cb0d
3 kyu
Define a variable `ALPHABET` that contains the *(english)* alphabet in lowercase. <br> **Too simple?** Well, you can only use the following characters set: - ` abcdefghijklmnopqrstuvwxyz().` (space included) <br> You code must starts with `ALPHABET = ` then respects the charset limitation. *Ofc you wouldn't che...
games
ALPHABET = str(). join(chr(i) for i in range(sum(range(len(str(complex))))) if chr(i). islower())
Hellphabet - Can you give the alphabet
62dcbe87f4ac96005f052962
[ "Puzzles", "Restricted", "Strings" ]
https://www.codewars.com/kata/62dcbe87f4ac96005f052962
6 kyu
## Description Given a list of strings of equal length, return any string which **minimizes** the **maximum** hamming distance between it and every string in the list. The string returned does not necessarily have to come from the list of strings. #### Hamming Distance The hamming distance is simply the amount of po...
algorithms
from collections import Counter def closest_string(list_str): counters = [Counter(s[i] for s in list_str) for i in range(len(list_str[0]))] minweight = len(list_str[0]) + 1 mins = None # backtracking with prunning: def rec(s, weights): nonlocal minweight, mins if...
Closest String
6051151d86bab8001c83cc52
[ "Algorithms" ]
https://www.codewars.com/kata/6051151d86bab8001c83cc52
6 kyu
Even more meticulously, Alex keeps records of [_snooker_](https://en.wikipedia.org/wiki/Snooker) matches. Alex can see into the past or the future (magic vision or balls stuffed with all sorts of electronics?). Your task is to find out how many points the player scored in the match, having only one single record of a p...
games
def score(ball: Ball) - > int: res, left, right = ball . point, ball . previous, ball . next while left: res += left . point left = left . previous while right: res += right . point right = right . next return res
Alex & snooker: Find Them All
62dc0c5df4ac96003d05152c
[ "Puzzles", "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/62dc0c5df4ac96003d05152c
6 kyu
You've sent your students home for the weekend with an assignemnt. The assignment is to write a 4 part ```harmony``` consisting of 4 chords. ---- Scale: ---- The major scale has 7 notes: ```"do re mi fa sol la ti"``` ---- Chord: ---- For this assignment a chord may consist of any 4 notes from the major scale. Exam...
reference
from itertools import combinations def pass_or_fail(harmony): for c1, c2 in zip(harmony, harmony[1:]): for (n1, n2), (n3, n4) in combinations(zip(c1 . split(), c2 . split()), 2): if n1 == n3 != n2 == n4: return "Fail" return "Pass"
Find Parallel Octaves
62dabb2225ea8e00293da513
[ "Algorithms" ]
https://www.codewars.com/kata/62dabb2225ea8e00293da513
7 kyu
# Number Pyramid: Image a number pyramid starts with `1`, and the numbers increasing by `1`. For example, when the pyramid has `4` levels: ``` 1 2 3 4 5 6 7 8 9 10 ``` ___ # Spiral: Now let's make a `spiral`, starts with `1`, `clockwise` direction, move `inward`. In the above example, we will get the num...
games
def last(n): return (2 * - ~ n / / 3) * * 2 + 1 >> 1
[Code Golf] Number Pyramid Series 5 - Spiral End with
62d6b4990ba2a64cf62ef0c0
[ "Mathematics", "Restricted" ]
https://www.codewars.com/kata/62d6b4990ba2a64cf62ef0c0
5 kyu
# Description Steve, from minecraft, is jumping down from blocks to blocks and can get damages at each jump. Damage depends on `distance` between blocks and `block type` he jumped on. The goal is to know if he survives his descent or not. You are given a list of `N` blocks as strings, in the format `'BLOCK_HEIGH...
reference
dmg = dict(zip("DBHW", (0, 0.5, 0.8, 1))) def jumping(arr): hp = 20 for i, (p1, p2) in enumerate(zip(arr, arr[1:]), 1): (h1, _), (h2, b) = p1 . split(), p2 . split() hp -= max(0, int((int(h1) - int(h2) - 3.5) * (1 - dmg[b]))) if hp <= 0: return f"died on { i } " return f"jumped t...
Steve jumping
62d81c6361677d57d8ff86c9
[ "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/62d81c6361677d57d8ff86c9
7 kyu
<h2 style="color:#4bd4de">Foreword</h2> Most kata on Codewars require to define a function of specific name that either returns a value from given inputs or alters the input itself. The whole thing looks like this. ``` def some_func(arg1, arg2): # code... # code... # code... return # something ``` <b>Kata sen...
games
# d e f c h a n g e _ l i s t ( x ) : # f o r i , v i n e n u m e r a t e ( x [ : : - 1 ] ) : # i f i s i n s t a n c e ( v , b o o l ) : # x [ i ] = n o t v # e l i f i s i n s t a n c e ( v , s t r ) : # x [ i ] = v + v [ : : - 1 ] # e l s e : # x [ i ] = v * * 2 # ' ' ' def change_list(x): for i, v in enumerate(...
Leapfrog Code
62d6d9e90ba2a6b6942ee6e5
[ "Restricted" ]
https://www.codewars.com/kata/62d6d9e90ba2a6b6942ee6e5
6 kyu
# Number Pyramid: Image a number pyramid starts with `1`, and the numbers increasing by `1`. And now, the pyramid has `5000` levels. For example, the top `5` levels of the pyramid are: ``` 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 ... ``` ___ # Location: Define the `location` of a n...
games
def location(c, r=1): while c > r: c -= r r += 1 return r, c
[Code Golf] Number Pyramid Series 4 - Location
62d1d6389e2b3904b3825309
[ "Mathematics", "Restricted" ]
https://www.codewars.com/kata/62d1d6389e2b3904b3825309
6 kyu