description
stringlengths
38
154k
category
stringclasses
5 values
solutions
stringlengths
13
289k
name
stringlengths
3
179
id
stringlengths
24
24
tags
listlengths
0
13
url
stringlengths
54
54
rank_name
stringclasses
8 values
In this task you are required to determine an expression consisting of variables and operators. * The variables are all single lower-case alphabetic characters * Each variable occurs only once in the expression * The operators are either `+` or `-` * There are no parentheses. For example: `"x-y+z"` or `"-d-b-c+w"` Yo...
algorithms
def plus_or_minus(vs, test): d = (test([2 * * i for i, _ in enumerate(vs)]) + (2 * * len(vs) - 1)) / / 2 return '' . join('-+' [d >> i & 1] + c for i, c in enumerate(vs)). lstrip('+')
Plus or Minus
65f8279c265f42003ffbd931
[ "Mathematics" ]
https://www.codewars.com/kata/65f8279c265f42003ffbd931
6 kyu
# Task Write a function that takes an array containing numbers and functions. The output of the function should be an array of only numbers. So how are we to remove the functions from the array? All functions must be applied to the number before it prior to the function being discarded from the array. It is as if the...
games
def operation_arguments(arr): result = [] for val in arr: if callable(val): result . append(val(result . pop() if result else 0)) else: result . append(val) return result
Collapse Left
65f1c009e44a0f0777c9fa06
[ "Arrays" ]
https://www.codewars.com/kata/65f1c009e44a0f0777c9fa06
6 kyu
There is a row of ants. An ant can be represented by letter "R" - facing right, and "L" - facing left. Every ant is moving with constant speed. When ants collide, they are changing their direction to opposite. Our task is to count collisions for each ant. There is a starting gap between ants, lets say that it is 2 mete...
algorithms
def bump_counter(ants): res = [] n, c = ants . count("L"), 0 for i, d in enumerate(ants): t = (i < n) - (d == "L") res . append(2 * c + t) c += t return " " . join(map(str, res))
Disorganized ants
65ee024f99785f0906e65bee
[ "Performance" ]
https://www.codewars.com/kata/65ee024f99785f0906e65bee
5 kyu
You stumble upon a genie who offers you a single wish. Being a food enthusiast, you wish for the opportunity to experience all the food at your favorite tapas restaurant. However, the genie has a twist in store and traps you in a time loop, destined to repeat the same evening until you've experienced every possible com...
algorithms
def count_time_loops(menu, a, b): # Initialize a dynamic programming table dp = [0] * (b + 1) dp[0] = 1 # Base case: 1 way to achieve cost 0 (empty meal) # Iterate over each dish cost in the menu for cost in menu: # Update the dynamic programming table from right to left for i in...
Too many meals
65ee35959c3c7a2b4f8d79c1
[ "Combinatorics", "Performance", "Mathematics", "Dynamic Programming" ]
https://www.codewars.com/kata/65ee35959c3c7a2b4f8d79c1
5 kyu
# Will The DVD Logo Hit The Corner You've probably seen the meme where people want the DVD logo to hit the corner. But it won't always hit it. When will it? ![DVD Logo Gif](https://user-images.githubusercontent.com/19642322/66207589-d054c500-e6bb-11e9-9d84-a0fbb5d2ef93.gif) To simplify the problem, instead of a recta...
algorithms
# Just imagine a straight line on a lattice of infinite copies of the TV. from math import gcd def will_hit_corner(w, h, x, y, dir): if dir == "NE" or dir == "SW": slope = 1 else: slope = - 1 return (y - slope * x) % gcd(w, h) == 0
Will The DVD Logo Hit The Corner? - Efficiency Version
65e8b02a9e79a010e5210b6c
[ "Algorithms", "Performance" ]
https://www.codewars.com/kata/65e8b02a9e79a010e5210b6c
6 kyu
## Task You are given a big cube, made up of several little cubes. You paint the outside of the big cube and are now supposed to find out how many of the little cubes have zero faces painted, one face painted, two faces painted, etc. Write a function which accepts two parameters: 1) `length`: the side length of the ...
games
def painted_faces(sides, n): if sides == 0: return 0 elif sides == 1: if n == 6: return 1 else: return 0 else: if n == 0: return (sides - 2) * * 3 # inside cubes elif n == 1: return 6 * (sides - 2) * * 2 # face cubes elif n == 2: return 12 * (sides...
Painted Sides
65e594c5a93ef700294ced80
[ "Mathematics", "Logic", "Puzzles" ]
https://www.codewars.com/kata/65e594c5a93ef700294ced80
7 kyu
You're in a competition with another guy. You take turns hammering the nail. Whoever hits the last blow wins. The last blow means that the nail will be completely hammered. Your input is the length of the nail (`0 < l < 100`). You can hit with different strengths: `1, 2 or 3` units of nail length at a time. Your oppon...
games
def hit(l): return l % 5
The Nail
65e2df8302b29a005831eace
[ "Puzzles" ]
https://www.codewars.com/kata/65e2df8302b29a005831eace
7 kyu
##### Disclaimer If you're not into math, you might want to skip this kata. ### Property Some rectangles have a recurring ratio of side lengths (the most famous example is A-series paper). For some of them, when removing a number of inner squares (each such square must have the side length of the smallest side of th...
games
import math def get_rectangle_ratio(n): return (n + math . sqrt(n * n + 4)) / 2
Recurring Rectangle Ratio
65e0fa45446dba00143d3744
[ "Puzzles", "Mathematics", "Geometry" ]
https://www.codewars.com/kata/65e0fa45446dba00143d3744
7 kyu
Well known Fibonacci sequence have interesting property - if you take every Fibonacci number modulo n, eventually they will form cycle. For example, if n = 5, {F_k mod 5} is ```C# 0, 1, 1, 2, 3, 0, 3, 3, 1, 4, 0, 4, 4, 3, 2, 0, 2, 2, 4, 1, 0, 1, ... ``` Length of this cycle called Pisano period. You can read more a...
algorithms
from collections import Counter from random import randrange from math import gcd, lcm, log, log2 def miller_rabin_test(n): if n < 2 or not n % 2 or not n % 3: return n in (2, 3) k, r, d = 5, 0, n - 1 while d % 2 == 0: d / /= 2 r += 1 while k >= 1: k -= 1 a = randrang...
Pisano Period - Performance Edition
65de16794ccda6356de32bfa
[ "Performance", "Mathematics", "Number Theory", "Algorithms" ]
https://www.codewars.com/kata/65de16794ccda6356de32bfa
2 kyu
You order a shirt for your friend that has a word written in sign language on it, you would like to fool your friend into thinking it says something other than what it actually says. Your friend is smart, but he can't know what he doesn't already know, he only knows a certain amount of letters in sign language. Given ...
reference
def gaslighting(s, y, f): return any(a != b and (a in f or b in f) for a, b in zip(s, y))
Misleading Signs
65dd5b414ccda60a4be32c2a
[ "Fundamentals", "Algorithms", "Strings" ]
https://www.codewars.com/kata/65dd5b414ccda60a4be32c2a
7 kyu
## Task Write a function create_compound which gives the **chemical formula** of a compound when given its **name**. For example, ``` create_compound('Lead Nitrate') -> 'Pb(NO₃)₂' create_compound('Aluminium Sulphate') -> 'Al₂(SO₄)₃' create_compound('Sodium Carbonate') -> 'Na₂CO₃' create_compound('Magnesium Oxide') -...
reference
from preloaded import symbols, valency from math import gcd def create_compound(name): ind = {1: '', 2: '₂', 3: '₃', 4: '₄'} cmps = name . split() s1, s2 = map(symbols . get, cmps) v1, v2 = map(valency . get, cmps) g = gcd(v1, v2) v1, v2 = v1 / / g, v2 / / g def comp(s, v): ...
Deriving Compounds
65dc66fc48727d28ac00db5c
[ "Logic" ]
https://www.codewars.com/kata/65dc66fc48727d28ac00db5c
6 kyu
## Trilingual democracy Switzerland has [four official languages](https://www.fedlex.admin.ch/eli/cc/2009/821/en#art_5): German, French, Italian, and Romansh.<sup>1</sup> When native speakers of one or more of these languages meet, they follow certain [regulations](https://www.fedlex.admin.ch/eli/cc/2010/355/en) to c...
games
def trilingual_democracy(group: str) - > str: _set = set(group) if len(_set) == 1: return group[0] if len(_set) == 3: return next(iter(set('DFIK') - _set)) return min(group, key=group . count)
Trilingual democracy
62f17be8356b63006a9899dc
[ "Fundamentals", "Puzzles", "Strings" ]
https://www.codewars.com/kata/62f17be8356b63006a9899dc
7 kyu
## Introduction In a parallel universe not too distant from our own, *Julius Caesar* finds himself locked in a fierce conflict with *Genghis Khan*. Legend has it that Khan's armies were renowned for their mastery of horseback archery, a formidable advantage in battle. To level the playing field, divine intervention ...
algorithms
def or_sum(n: int) - > int: return n * * 2 + sum(n >> i + 1 << 2 * i for i in range(n . bit_length()) if not 1 << i & n)
The OR sum
65d81be5ac0d2ade3a6c637b
[ "Mathematics", "Bits", "Performance" ]
https://www.codewars.com/kata/65d81be5ac0d2ade3a6c637b
6 kyu
## Overview Jack's chemistry teacher gave him piles of homework to complete in just ONE day and he just can't seem to get it done! All the questions are of the same type, making the homework both tedious and time-consuming. He has been given the chemical formula of an element and is required to find out how many mole...
games
from preloaded import atomic_masses def count_the_moles(mass_of_substance: float, chemical_formula: str): mole_mass = 0 for i, x in enumerate(chemical_formula): if x . isalpha(): if i + 1 <= len(chemical_formula) - 1 and chemical_formula[i + 1]. isdigit(): mole_mass += atomic_masses[x] * i...
Count the moles!
65d5cf1eac0d2a6c4f6c60e6
[ "Logic", "Mathematics" ]
https://www.codewars.com/kata/65d5cf1eac0d2a6c4f6c60e6
7 kyu
You are given a positive integer **n** greater than one. How many ways are there to represent it as a product of some **Fibonacci numbers** greater than one? *(Fibonacci sequence: 1, 1, 2, 3, 5, 8...).* For example, there are two ways for **n = 40**: 1) 2 * 2 * 2 * 5 2) 5 * 8 But you can't represent **n = 7** in an...
algorithms
def fibs(limit): a, b, res = 2, 3, [] while a <= limit: res . append(a) a, b = b, a + b return res FIB = fibs(10 * * 36) from functools import cache @ cache def fib_prod(n: int, m: int = 1) - > int: return 1 if n == 1 else sum(fib_prod(n / / d, d) for d in FIB if d >=...
Fibonacci's Product
65d4d2c4e2b49c3d1f3c3aec
[ "Recursion", "Performance" ]
https://www.codewars.com/kata/65d4d2c4e2b49c3d1f3c3aec
5 kyu
You are given a string "strng" Perform the following operation until "strng" becomes empty: For every alphabet character from 'a' to 'z', remove the first occurrence of that character in "strng" (if it exists). Example, let initially strng = "aabcbbca". We do the following operations: Remove the underlined ...
algorithms
from collections import Counter def last_non_empty_string(s: str) - > str: x = Counter(s) l = max(x . values()) - 1 for w in x: s = s . replace(w, '', l) return s
Perform operation to make string empty
65d2460f512ea70058594a3d
[ "Algorithms", "Logic", "Puzzles", "Fundamentals", "Strings", "Performance" ]
https://www.codewars.com/kata/65d2460f512ea70058594a3d
6 kyu
You are given a positive integer *n*. The task is to calculate how many binary numbers without leading zeros (such that their length is *n* and they do *not* contain two zeros in a row) there are. Note that zero itself ("0") *meets* the conditions (for n = 1). For example, there are three eligible binary numbers o...
algorithms
def zeros(n: int) - > int: a, b = 1, 1 for _ in range(n - 2): a, b = a + b, a return a + b
Without two zeros in a row
65cf8417e2b49c2ecd3c3aee
[ "Dynamic Programming" ]
https://www.codewars.com/kata/65cf8417e2b49c2ecd3c3aee
6 kyu
**<center><big>Big thanks to @dfhwze for the approval.</big></center>** *<center>This kata is inspired by @Voile's <a href="https://www.codewars.com/kata/65cdd06eac0d2ad8ee6c6067">One Line Task: Hard Fibonacci Numbers</a>.</center>* # Task Write a function that takes two **non-negative integers** `n` and `k`, a...
games
def comb(n, k): return (b: = 2 << n | 1) * * n >> n * k + k & b - 2
One Line Task: Mathematical Combination
65d06e5ae2b49c47ee3c3fec
[ "Restricted", "Performance", "Mathematics" ]
https://www.codewars.com/kata/65d06e5ae2b49c47ee3c3fec
4 kyu
Laurence is on vacation at the tropics and wants to impress Juliet and her friends by making them the best cocktail he can from the island's bountiful fruits. ## Taste and flavour - Each ingredient has a unique integer **taste** representing its **sweetness** (if positive) or **bitterness** (if negative). - The tastes...
algorithms
def find_n(d, t, l): if l == 1: r = d . get(t) return [r] if r else [] for k, v in d . items(): if k >= t: continue r = find_n(d, t - k, l - 1) if r: return r + [v] return [] def make_cocktail(ingr: dict[int], flav: int, bittersw: int) - > list[str]: ...
Prepare the Cocktails
65c9562f4e43b28c4c426c93
[ "Algorithms", "Functional Programming", "Performance", "Recursion", "Set Theory" ]
https://www.codewars.com/kata/65c9562f4e43b28c4c426c93
4 kyu
# Task Compute the `n`-th Fibonacci number, where ```math F(0) = 0\newline F(1) = 1\newline F(n) = F(n-1) + F(n-2) ``` . # The Catch 1. Your solution will be tested against all inputs in range `0 - 49`, and `50` inputs in range `50000 - 100000`. 1. The function name to be implemented is `nth_term_of_the_fibonacci...
reference
def nth_term_of_the_fibonacci_sequence(n): return pow(m: = 2 << n, n, m * m + ~ m) / / m
One Line Task: Hard Fibonacci Numbers
65cdd06eac0d2ad8ee6c6067
[ "Restricted", "Performance", "Mathematics" ]
https://www.codewars.com/kata/65cdd06eac0d2ad8ee6c6067
3 kyu
Want to play some solitaire? Welcome to 52 card pick up. I always wondered why they never made an online version of the game. So I made one, [try it](https://sagefirellc.net/solitaire/). However, I feel it's time for you to enjoy the pain as well. I have "thrown" your deck of cards into a "pile" (a list with rows of ...
games
A = {x + y for y in "1 2 3 4 5 6 7 8 9 10 J Q K" . split() for x in "HSDC"} def pick_em_up(pile): p = {y for x in pile for y in x} return all(c in p for c in A)
52 Card Pick Up
65cb9ddfac0d2a5d6e6c6150
[ "Puzzles" ]
https://www.codewars.com/kata/65cb9ddfac0d2a5d6e6c6150
6 kyu
# Task You are given a **target word** and a **collection of strings**. Your task is to **count in how many ways you can build up a target word from the strings in the collection.** You can use any string in the collection _**as many times**_ as needed, but you need to use that string **as it is** (meaning you can't r...
reference
def get_options_count(target, arr): options = [1] for n in range(1, len(target) + 1): options . append(sum(options[- len(s)] for s in arr if target[- n:]. startswith(s))) return options[- 1]
Number of options to build up a word
65cb0451ac0d2a381c6c617f
[ "Dynamic Programming" ]
https://www.codewars.com/kata/65cb0451ac0d2a381c6c617f
5 kyu
# Background This exercise assumes basic knowledge of generators, including passing familiarity with the `yield` keyword. ## Catching You Up on Generators While it is obvious that you can obtain items from generators, it is less known that you can also **send** data into generators in languages like Python and JavaScri...
reference
from itertools import cycle def round_robin(* gens): msg = None for gen in cycle(gens): msg = yield gen . send(msg)
Sending Data into Generators: The Basics
65c8e72d63fd290058026075
[ "Fundamentals", "Language Features" ]
https://www.codewars.com/kata/65c8e72d63fd290058026075
6 kyu
A digital, 24-hour clock is hung on my classrooms wall, displaying, well, the time in `hh:mm:ss` format. There are multiple types of `good times`. It could be if ... 1. `[hh, mm, ss]` is an arithmetic progression where the difference of consecutive numbers is 0, 1, or 2. e.g. `(11:12:13, 13:15:17)` but NOT `23:21:19`...
reference
import datetime def next_good_time(current_time): d = datetime . datetime . strptime(current_time, "%H:%M:%S") while True: d += datetime . timedelta(seconds=1) if any([ d . minute * 2 == d . hour + d . second and d . minute - d . hour in [1, 2], d . minute * 2 == d . ...
Next good time
65c6fa8551327e0ac12a191d
[]
https://www.codewars.com/kata/65c6fa8551327e0ac12a191d
6 kyu
# Task Imagine you have a 3D matrix with the size given as 3 integers: width, depth, height (x,y,z). You start at a corner point `(1,1,1)` and in each step you can move just in one direction: * x -> x+1 * or y -> y+1 * or z -> z+1. You **can not** go diagonally or backwards. Your task is to calculate in **how ma...
reference
from itertools import accumulate def ways_in_3d_matrix(x, y, z): x, y, z = sorted((x, y, z)) layer = [[int(j == 0 or k == 0) for k in range(z)] for j in range(y)] for j in range(1, y): for k in range(1, z): layer[j][k] = layer[j - 1][k] + layer[j][k - 1] seq = [1] * (y + z - 1) ...
Number of ways to go in 3D matrix
65c6836293e1c2b881e67f33
[ "Dynamic Programming" ]
https://www.codewars.com/kata/65c6836293e1c2b881e67f33
6 kyu
*Inspired by https://www.youtube.com/watch?v=eW_bMqcJXv0/* You are speedrunning a game with `N` successive levels. For each level `i = 1,...,N`, you have a target time `t_i` based on the "strats" you're going for, and a success probability `p_i` of achieving the respective target time (i.e., pulling off the strats). ...
reference
def expected_speedrun_time(times, probs): tot_prob, tot_time, expected = 1, 0, 0 for t, p in zip(times, probs): expected += (tot_time + t / 2) * (tot_prob) * (1 - p) tot_time += t tot_prob *= p expected /= tot_prob expected += tot_time return expected
Speedrunning: Expected time until completion
65c06522275fa5b2169e9998
[ "Mathematics", "Probability", "Statistics" ]
https://www.codewars.com/kata/65c06522275fa5b2169e9998
6 kyu
You are given two integers `x` and `y`, each an integer from `0` through `9`. You want to get from `x` to `y` by adding an integer `z` to `x`. Addition will be modulo 10, i.e., adding `1` to `9` results in `0`; and adding a `-1` to `0` results in `9`. Create a function `f` that, given the `x` and `y` defined above, re...
reference
def f(x, y): return (y - x + 5) % 10 - 5
[Code Golf] Rotate The Dial
6590b70c3109bcf9c12624a5
[ "Mathematics", "Restricted" ]
https://www.codewars.com/kata/6590b70c3109bcf9c12624a5
6 kyu
Note: Based off Minecraft, hopefully you at least know the game! Story: You want to create a giant mine shaft, but you're a little stingy with your iron and diamonds and would not mine out all of the stone with iron or diamond pickaxes. Instead, you rely on less durable but cheaper stone pickaxes! You will need a lot ...
reference
def stone_pick(arr): stick = arr . count('Sticks') + arr . count('Wood') * 4 cobble = arr . count('Cobblestone') return (min(cobble / / 3, stick / / 2))
Stone Pickaxe Crafting
65c0161a2380ae78052e5731
[ "Fundamentals" ]
https://www.codewars.com/kata/65c0161a2380ae78052e5731
7 kyu
## Theoretical Material You are given two vectors starting from the origin (x=0, y=0) with coordinates (x1,y1) and (x2,y2). Your task is to find out if these vectors are collinear. Collinear vectors are vectors that lie on the same straight line. They can be directed in the same or opposite directions. One vector can ...
reference
def collinearity(x1, y1, x2, y2): return x1 * y2 == x2 * y1
Collinearity
65ba420888906c1f86e1e680
[ "Fundamentals", "Geometry", "Mathematics", "Data Science", "Games" ]
https://www.codewars.com/kata/65ba420888906c1f86e1e680
8 kyu
## The Challenge > This kata is inspired by one of Shortcat's (*Mario Kart* YouTuber) most recent videos. If anyone's interested, here's the [video](https://www.youtube.com/watch?v=BKSG9NieybE). **Boot up** whichever your latest *Nintendo* console was, be it the *Wii* for the OG's or *Switch* for the bourgois! We're ...
algorithms
from collections import deque def find_win(placements, total): c, t, q = 0, ((1 << total) - 1) << 1, deque(maxlen=total) for i, v in enumerate(placements): c += 1 << v if i >= total: c -= 1 << q[0] if c == t: return i q . append(v)
N in a row
65b745d697eea38e8bcfb470
[ "Iterators", "Performance" ]
https://www.codewars.com/kata/65b745d697eea38e8bcfb470
6 kyu
Write a function `cube_matrix_sum` that calculates the sum of the elements of a 3-dimensional array. The function should be one line long and less than 48 characters long. Imports are prohibited Example ``` cube_matrix = [ [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10,11,12],[13,14,15],[16,17,18]], [[19,20,21],[22...
algorithms
def cube_matrix_sum(x): return sum(sum(sum(x, []), []))
One Line Task: The sum of a 3-dimensional array
65b3fdc2df771d0010b9c3d0
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/65b3fdc2df771d0010b9c3d0
6 kyu
## Introduction It's **Christmas** (a bit late, I know), and you finally decide to do something nice for once in your life. As you're going to meet up with your family, you think to give them a little something, and what's a better gift than **money**? I mean, it's kind of hard to find something that both a **geriatr...
algorithms
from gmpy2 import is_prime M, L = 1000000007, 3000000 PRIMES = [n for n in range(L) if is_prime(n)] def smallest_multiple(n): t = 1 for p in PRIMES: if p > n: break for q in range(1, n + 1): if p * * q > n: t = (t * pow(p, q - 1, M)) % M break return t
Smallest Multiple of 1 to n
65ad9094c5a34200245f3a8f
[ "Mathematics", "Performance", "Number Theory" ]
https://www.codewars.com/kata/65ad9094c5a34200245f3a8f
5 kyu
# Balanced? Usually when we talk about converting between bases, we assume that the value assigned to the *characters* within the base are always the same; '3' in base 7 is the same as '3' in base 16. However, we could just as easily pick a different selection of values. So, in balanced base nine, the characters will...
algorithms
def balanced_base_nine(num): base_nine = [] while num: d = num % 9 base_nine . append('01234^%$£' [d]) num = num / / 9 + (d > 4) return '' . join(reversed(base_nine)) or '0'
Base Nine But Balanced
65a1cc718041f7000f928457
[ "Mathematics" ]
https://www.codewars.com/kata/65a1cc718041f7000f928457
6 kyu
## Description Three-cushion billiards, also called three-cushion carom, is a form of carom billiards. The object of the game is to carom the cue ball off both object balls while contacting the rail cushions at least three times before contacting the second object ball. - The table consists of 4 cushions (north, east...
reference
def has_scored(s): balls = sorted(s . find(b) for b in 'RWY') return balls[1] >= 0 and sum(c in 'nesw' for c in s[: balls[2]]) >= 3
Three-cushion billiards
65a024af6063fb0ac8c0f0b5
[ "Fundamentals", "Games" ]
https://www.codewars.com/kata/65a024af6063fb0ac8c0f0b5
7 kyu
### Problem Statement You're given a string of digits representing a sequence of consecutive natural numbers concatenated together. Your task is to find the smallest possible first number in the sequence. The sequence starts with a single or multi-digit number and continues with numbers each incremented by 1. If multi...
algorithms
def find(string): num = int(string[0]) ans = num i = 1 test = str(num) while test != string: if test == string[: len(test)]: num += 1 test += str(num) else: i += 1 num = int(string[: i]) ans = num test = str(num) return ans
The lost beginning
659af96994b858db10e1675f
[ "Fundamentals", "Algorithms", "Strings", "Mathematics" ]
https://www.codewars.com/kata/659af96994b858db10e1675f
6 kyu
## Introduction It's finally the day for the *314th* edition of the **International Integer Sequences Olimpiad**, where various sequences of integers compete for the number one spot by trying to reach the **highest score**. However, the **old scoring system** of merely **adding up the numbers** for the score has bee...
algorithms
def score(numbers): sn = sum(numbers) return sum(x * (sn - x) for x in numbers) / / 2
Add 'Em Pairs!
658fb5effbfb3ad68ab0951d
[ "Mathematics", "Combinatorics", "Performance" ]
https://www.codewars.com/kata/658fb5effbfb3ad68ab0951d
6 kyu
You are given a `string` of lowercase letters and spaces that you need to type out. However, there are some arrow keys inside. What do you do then? Here are a few examples: ``` abcdefgh<<xyz -> abcdefxyzgh Walkthrough: v type this: abcdefgh go back two characters such that the pointer is right in ...
algorithms
def type_out(s): res, pointer, i = [], 0, 0 while i < len(s): if s[i] in '<>': func = s[i] i += 1 times = 1 if i < len(s) and s[i] == '*': i += 1 times = 0 while i < len(s) and s[i]. isdigit(): times = times * 10 + int(s[i]) i += 1 if func == '<': po...
Typing series #4 --> left and right arrow keys
6582ce1afbfb3a604cb0b798
[]
https://www.codewars.com/kata/6582ce1afbfb3a604cb0b798
6 kyu
# Converging Journeys In the domain of **converging journeys**, numbers progress based on a unique formula. Specifically, following `n` is `n` plus the sum of its digits. For example, `12345` is followed by `12360`, since `1+2+3+4+5 = 15`. If the first number is `k` we will call it journey `k`. For example, journey `...
reference
def converging_journeys(n): j = {1: 1, 3: 3, 9: 9} while n: for k in j: while j[k] < n: j[k] += sum(map(int, str(j[k]))) if j[k] == n: return (k, n) n += sum(map(int, str(n)))
Converging Journeys
6585960dfbfb3afd22b0a1fe
[]
https://www.codewars.com/kata/6585960dfbfb3afd22b0a1fe
6 kyu
# Lojban Numbers Counting in **Lojban**, an artificial language developed over the last forty years, is easier than in most languages. The numbers from `zero` to `nine` are: ```javascript 1 pa 4 vo 7 ze 2 re 5 mu 8 bi 0 no 3 ci 6 xa 9 so ``` Larger numbers are created by gluing the digits together. For example, `123...
reference
def convert_lojban(lojban): return int(lojban . translate(str . maketrans('nprcvmxzbs', '0123456789', 'aeiou')))
Lojban Numbers
6584b7cac29ca91dd9124009
[]
https://www.codewars.com/kata/6584b7cac29ca91dd9124009
7 kyu
# ISBN An **ISBN** (International Standard Book Number) is a `ten digit` code which uniquely identifies a book. The first nine digits represent the book and the last digit is used to make sure the ISBN is correct. To verify an ISBN you calculate `10` times the first digit, plus `9` times the second digit, plus `8` tim...
reference
def checksum(isbn): # calculate checksum return sum((10 - i) * (10 if d == "X" else int(d)) for i, d in enumerate(isbn)) def fix_code(isbn): # try all possible digits for digit in "0123456789X": fixed_isbn = isbn . replace("?", digit) if checksum(fixed_isbn) % 11 == 0: retu...
ISBN Corruption
6582206efbfb3a604cb0a6fe
[]
https://www.codewars.com/kata/6582206efbfb3a604cb0a6fe
7 kyu
# Mayan Calendar The Mayan civilisation used three different calendars. In their long count calendar there were `20` days (called kins) in a uinal, `18` uinals in a tun, `20` tuns in a katun and `20` katuns in a baktun. In our calendar, we specify a date by giving the day, then month, and finally the year. The Maya sp...
algorithms
from datetime import datetime, timedelta REF = datetime(2000, 1, 1) def convert_mayan(date): baktun, katun, tun, uinal, kin = [int(x) for x in date . split()] return (REF + timedelta(days=kin + 20 * (uinal + 18 * (tun + 20 * (katun + 20 * baktun))) - 2018843)). strftime('%-d %-m %Y')
Mayan Calendar
657e2e36fbfb3ac3c3b0a1fb
[ "Date Time" ]
https://www.codewars.com/kata/657e2e36fbfb3ac3c3b0a1fb
6 kyu
## Task Write a function that takes the string and finds a repeating character in this string (there may or may not be several of them), returns the minimum difference between the indices of these characters and the character itself. > For example, in the string “aabcba” the minimum position difference of repeated ch...
reference
def min_repeating_character_difference(text): for i in range(1, len(text)): for a, b in zip(text, text[i:]): if a == b: return i, a
Minimum difference in duplicate characters
6574d1bde7484b5a56ec8f29
[ "Strings" ]
https://www.codewars.com/kata/6574d1bde7484b5a56ec8f29
6 kyu
## Introduction In some societies, you receive a name around your birth and people use it to refer to you while you don't have any children. Once you have at least one child, people give you a [teknonym](https://en.wikipedia.org/wiki/Teknonymy). A teknonym is a way to refer to someone according to some of its descend...
algorithms
def teknonymize(t) - > None: if t['children']: g, d = min([teknonymize(c) for c in t['children']], key=lambda a: (- a[0], a[1]['date_of_birth'])) t['teknonym'] = 'great-' * (g - 2) + 'grand' * (g > 1) + \ ['mother', 'father'][t['sex'] == 'm'] + ' of ' + d['name'] return g + ...
Teknonymy
65781071e16df9dcbded1520
[ "Trees", "Data Structures", "Recursion" ]
https://www.codewars.com/kata/65781071e16df9dcbded1520
5 kyu
You are given a ```string``` of lowercase letters and spaces that you need to type out. You may notice some square brackets inside the string. - If it contains letters, type out the text inside then copy it. - If it is empty, paste the copied text - If it contains a number, paste the copied text that number of times....
reference
import re def type_out(s): clipboard = "" def paste(m): nonlocal clipboard copy = m[1] if not copy: return clipboard if copy . isdigit(): return int(copy) * clipboard return (clipboard := copy) return re . sub(r'\[([^]]*)\]', paste, s)
Typing series #3 --> copy and paste
6573331997727a18c8f82030
[ "Regular Expressions" ]
https://www.codewars.com/kata/6573331997727a18c8f82030
6 kyu
The cuckoo bird pops out of the cuckoo clock and chimes once on the quarter hour, half hour, and three-quarter hour. At the beginning of each hour (1-12), it chimes out the hour. Given the current time and a number *n*, determine the time when the cuckoo bird has chimed *n*&nbsp; times. Input Parameters: <br> *initia...
reference
def cuckoo_clock(t, n): # around-the-clock optimization (=> O(1) runtime) n = n % 114 if n > 114 + 15 else n h, m = map(int, t . split(':')) t = h % 12 * 60 + m while True: k = t / / 60 or 12 if t % 60 == 0 else t % 15 == 0 if n <= k: return f" { t / / 60 or 12 :0 2 d } : { t % 60 :0...
Cuckoo Clock
656e4602ee72af0017e37e82
[ "Strings", "Date Time" ]
https://www.codewars.com/kata/656e4602ee72af0017e37e82
6 kyu
## Introduction In the land of *Mathtopia*, *King Euler I* embarks on his inaugural **crusade** to purge the holy soil of *NerdLand* from the unworthy scholars of humanities, reinstating its former glory in STEM. Yet, **only honorable knights** may join this esteemed quest. Thus, he must devise a scheme to discern w...
algorithms
def divisors(n: int) - > list[int]: solution: list[int] = [1] currentDivisor: int = 2 while n > 1: index: int = 0 while not n % currentDivisor: n / /= currentDivisor length: int = len(solution) for i in range(index, length): index = length solution . append(currentDivisor * solut...
Divisors Of Really Big Numbers
656f6f96db71be286d8f5c6b
[ "Mathematics", "Number Theory", "Performance" ]
https://www.codewars.com/kata/656f6f96db71be286d8f5c6b
5 kyu
In this kata you are given two integers: `initial number`, `target number` two arrays and fixed set of instructions: 1. Add 3 to the number 2. Add the sum of its digits to a number, if number is not 0 3. Add the number reduced modulo 4 to the number, if the modulus is not 0 Your task is to find amount of...
algorithms
from collections import Counter from itertools import pairwise from math import prod def find_ways(initial_num, target_num, must_include=None, must_avoid=None): numbers = [initial_num, * sorted(must_include or []), target_num] must_avoid = {* must_avoid} if must_avoid else set() return prod(ways(s...
Ways from one number to another
6565070e98e6731c13882aa0
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/6565070e98e6731c13882aa0
5 kyu
As you sit in your university math lecture, your professor introduces the Gauss-Seidel method, an iterative technique for solving systems of linear equations. The method itself was quite elegant, but the idea of manually solving equations repeatedly until convergence was daunting. That's when you decided to take matter...
algorithms
def gauss_seidel(c): x = y = z = i = 0 while i == 0 or any(abs(d) > 0.0001 for d in (x - ox, y - oy, z - oz)): ox, oy, oz = x, y, z x = (c[0][3] - c[0][1] * y - c[0][2] * z) / c[0][0] y = (c[1][3] - c[1][0] * x - c[1][2] * z) / c[1][1] z = (c[2][3] - c[2][0] * x - c[2][1] * y) / c[2][2] ...
Gauss-Seidel Method
6562d61a9b55884c720e2556
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/6562d61a9b55884c720e2556
6 kyu
### Background Consider a 8-by-8 chessboard containing only a knight and a king. The knight wants to check the king. The king wants to avoid this. The knight has a cloaking shield, so it moves invisibly. Help the king escape the knight! ### Task You are given the initial king position, initial knight position, and t...
games
def choose_king_moves(king, knight, n): c = king[0]. translate(str . maketrans('abcdefgh', 'babcdefg')) r = (int(king[1]) - 1) & 6 | (ord(c) ^ ord(knight[0]) ^ ord(knight[1])) & 1 return [f' { c }{( r ^ ( k & 1 )) + 1 } ' for k in range(n)]
Escape the knight!
653888111746620b77a3ccd5
[ "Games" ]
https://www.codewars.com/kata/653888111746620b77a3ccd5
6 kyu
# Background Three-valued logic is a multiple-valued logic system in which there are three truth values; for this kata they will be `True`, `False` and `Unknown`. In this kata, `T` stands for `True`, `F` stands for `False` and `U` stands for `Unknown`. They are also represented as `1`, `-1` and `0` respectively. This...
algorithms
from functools import reduce from collections import deque import re OPS = { 'not': lambda x: 'T' if x == 'F' else 'F' if x == 'T' else 'U', 'xor': lambda a, b: 'U' if 'U' in (a, b) else 'F' if a == b else 'T', 'and': lambda a, b: 'T' if 'T' == a == b else 'F' if 'F' in (a, b) else 'U', 'or': lam...
Three-valued logic
65579292e361e60e202906f4
[ "Interpreters", "Logic" ]
https://www.codewars.com/kata/65579292e361e60e202906f4
5 kyu
# Task Sorting is one of the most basic computational devices used in Computer Science. Given a sequence (length ≤ 1000) of 3 different key values (7, 8, 9), your task is to find the minimum number of exchange operations necessary to make the sequence sorted. One operation is the switching of 2 key values in th...
algorithms
def exchange_sort(sequence): x = 0 y = 0 for f, g in zip(sequence, sorted(sequence)): if f < g: x += 1 elif f > g: y += 1 return max(x, y)
Simple Fun #148: Exchange Sort
58aa8b0538cf2eced5000115
[ "Algorithms", "Sorting" ]
https://www.codewars.com/kata/58aa8b0538cf2eced5000115
4 kyu
A Golomb-type sequence describes itself: based on a given infinite subsequence of the natural numbers, every number in the resulting sequence is the number of times the corresponding number from the given sequence appears, and it is the _least possible_ such number. An example: ```haskell input sequence : 1 2 3 4 5 ....
algorithms
def golomb(given, n): res, idx, seq = [], 0, iter(given) if (x := next(seq)) != 0: res, idx = [x] * x, 1 elif (x := next(seq)) != 1: res, idx = [x] * 2 + [0] * x + [x] * (x - 2), 2 else: res, idx = [1, (x := next(seq)), 1, 0] + [1] * (x - 2), 3 while len(res) < n and (x := next(s...
Golomb-type sequences
5d06938fcac0a5001307ce57
[ "Algorithms" ]
https://www.codewars.com/kata/5d06938fcac0a5001307ce57
3 kyu
**Translations Welcome!** --- Most fonts nowadays, including the one you are reading now, stores each glyph in the form of a [Scalable Vector Format](https://www.w3schools.com/graphics/svg_intro.asp). Each line, curve, and shape are plotted out with corrdinates that are then traced using complex math formulas we won...
algorithms
from textwrap import fill def hex_to_bitmap(h): return fill(f' { int ( h , 16 ):0 128 b } ', 8)
Bitmap Glyph Forger
65553172219a8c8e263b58ff
[ "Strings" ]
https://www.codewars.com/kata/65553172219a8c8e263b58ff
7 kyu
# Task You are given a `chessBoard`, a 2d integer array that contains only `0` or `1`. `0` represents a chess piece and `1` represents a empty grid. It's always square shape. Your task is to count the number of squares made of empty grids. The smallest size of the square is `2 x 2`. The biggest size of the square is...
algorithms
from collections import defaultdict def count(chessBoard): # Initialize: board = chessBoard . copy() tally = defaultdict(int) # Compute Longest square ending in bottom right corner of each element and tally up: for i, row in enumerate(board): for j, element in enumerate(row): ...
Count Squares In the Chess Board
5bc6f9110ca59325c1000254
[ "Algorithms", "Dynamic Programming" ]
https://www.codewars.com/kata/5bc6f9110ca59325c1000254
4 kyu
_yet another easy kata!_ _Bored of usual python katas? me too;_ <hr> ## Overview &ensp;&ensp;&ensp;&ensp; As you have guessed from the title of the kata you are going to implement a class that supports ***function overloading***. You might be thinking python doesn't support that thing... Of course python doesn't s...
reference
from collections import defaultdict def setter(prep, k, v, supSetter): if callable(v): def wrap(* args): f = prep . d[k][len(args)] if isinstance(f, int): raise AttributeError() return f(* args) prep . d[k][v . __code__ . co_argcount] = v v = wrap supSetter(k, v) ...
Python Recipes #1 : Function Overloading
5f24315eff32c4002efcfc6a
[ "Metaprogramming" ]
https://www.codewars.com/kata/5f24315eff32c4002efcfc6a
4 kyu
<details open> <summary style=" padding: 3px; width: 100%; border: none; font-size: 18px; box-shadow: 1px 1px 2px #bbbbbb; cursor: pointer;"> Task</summary> ##### "Given an array of queues, how many times must you perform dequeueing operations, for each number to end up in its associated q...
algorithms
def dequeue_count(queues): return sum(len(q) - next((j for j, v in enumerate(q) if v != i), len(q)) for i, q in enumerate(queues))
Perfect Queues
63cb1c38f1504e1deca0f282
[ "Algorithms", "Arrays", "Puzzles", "Performance" ]
https://www.codewars.com/kata/63cb1c38f1504e1deca0f282
6 kyu
This Kata is the first in the [Rubiks Cube collection](https://www.codewars.com/collections/rubiks-party). [This](https://ruwix.com/the-rubiks-cube/notation/) or [this](https://ruwix.com/the-rubiks-cube/notation/advanced/) websites will be very usefull for this kata, if there will be some lack of understanding after t...
games
''' WARNING: EXTREMELY BAD PRACTICE ALERT DO NOT DO THIS IF YOU ARE WORKING ON A PROJECT ALTHOUGH HARD CODING CAN SOMETIMES MAKE CODE RUN FASTER, IT MAKES IT MESSY AND UNREADABLE ''' rotate_face_idx = [* zip(range(1, 10), [7, 4, 1, 8, 5, 2, 9, 6, 3])] def increase_idx(idx, n): return [ (start + n...
The Rubik's Cube
5b3bec086be5d8893000002e
[ "Puzzles", "Algorithms", "Geometry" ]
https://www.codewars.com/kata/5b3bec086be5d8893000002e
5 kyu
# What is a happy number? A happy number is defined as an integer in which the following sequence ends with the number 1. - Calculate the sum of the square of each individual digit. - If the sum is equal to 1, then the number is `happy`. - If the sum is not equal to 1, then repeat from steps 1. - A number is consid...
bug_fixes
happy = {1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97} sums = {0: [0]} for _ in range(7): new_sums = {} for x, terms in sums . items(): for d in range(10): new_sums . setdefault(x + d * d, []). extend(term * ...
Happy Numbers. Another performance edition.
5ecef4a6640dbb0032bc176d
[ "Performance", "Algorithms" ]
https://www.codewars.com/kata/5ecef4a6640dbb0032bc176d
4 kyu
Description: Write a method that takes a field for well-known board game "Battleship" as an argument and returns true if it has a valid disposition of ships, false otherwise. Argument is guaranteed to be 10*10 two-dimension array. Elements in the array are numbers, 0 if the cell is free and 1 if occupied by ship. Bat...
algorithms
import numpy as np from itertools import combinations def validate_battlefield(field): return validate(np . array(field), [(1, 4), (2, 3), (3, 2)], 20) def validate(field, ships, expected): if field . sum() != expected: return False elif not ships: return True # single-uni...
Battleship field validator II
571ec81d7e8954ce1400014f
[ "Algorithms", "Puzzles" ]
https://www.codewars.com/kata/571ec81d7e8954ce1400014f
3 kyu
_Yet another easy kata!_ # Task: - Let's write a sequence starting with `seq = [0, 1, 2, 2]` in which - 0 and 1 occurs 1 time - 2 occurs 2 time and sequence advances with adding next natural number `seq[natural number]` times so now, 3 appears 2 times and so on. ### Input - You ...
reference
idx, n, seq = 2, 6, [1, 2, 4, 6] while n < 2 * * 41: idx += 1 seq . extend(range(n + idx, n + (seq[idx] - seq[idx - 1]) * idx + 1, idx)) n += (seq[idx] - seq[idx - 1]) * idx from bisect import bisect def find(n): return bisect(seq, n)
Repetitive Sequence - Easy Version
5f134651bc9687000f8022c4
[ "Algorithms", "Data Structures" ]
https://www.codewars.com/kata/5f134651bc9687000f8022c4
4 kyu
# Task Write a function `three_powers()` to accept a number, to check can it represent as sum of 3 powers of 2.(`n == 2**i + 2**j + 2**k, i, j, k >= 0`) For example: ```python three_powers(2) # False three_powers(3) # True, 3 = 2**0 + 2**0 + 2**0 three_powers(5) # True, 5 = 2**0 + 2**1 + 2**1 three_powers(15) # Fa...
algorithms
def three_powers(n): return n > 2 and n . bit_count() <= 3
3 powers of 2
6545283611df271da7f8418c
[ "Mathematics" ]
https://www.codewars.com/kata/6545283611df271da7f8418c
7 kyu
## Problem statement Packing multiple rectangles of varying widths and heights in an enclosing rectangle of minimum area. Given 3 rectangular boxes, find minimal area that they can be placed. Boxes can not overlap, these can only be placed on the floor. ## Input 3 pairs of numbers come to the input - the lengths(a1,...
algorithms
from itertools import permutations def packing_rectangles(* args): result, inputs = float("inf"), { args[: 2], args[2: 4], args[4:], args[1:: - 1], args[3: 1: - 1], args[: 3: - 1]} for a, b, c, d, e, f in permutations(args): if (a, b) in inputs and (c, d) in inputs and (e, f) in inputs: ...
packing rectangles
5eee6c930514550026cefe9e
[ "Algorithms" ]
https://www.codewars.com/kata/5eee6c930514550026cefe9e
6 kyu
Given the lists with suppliers' production, consumers' demand, and the matrix of supplier-to-consumer transportation costs, calculate the minimum cost of the products transportation which satisfied all the demand. ## Notes * Costs-matrix legend: `costs[i][j]` is the cost of transporting 1 unit of produce from `suppli...
algorithms
import numpy as np class Basis: # stores the active basis def __init__(self, A, basis_list, Binv): self . A = np . copy(A) self . Binv = np . copy(Binv) self . basis_list = np . copy(basis_list) self . is_basis = np . array([False] * A . shape[1]) self . is_basis[basis_list] = True...
Optimal Transportation
5e90f0544af7f400102675ca
[ "Algorithms", "Mathematics", "Performance" ]
https://www.codewars.com/kata/5e90f0544af7f400102675ca
1 kyu
_NOTE: Unlike other Kata in the series, this one is not a golfing Kata._ ### Number Pyramid: Image a number pyramid starts with `1`, and the numbers increasing by `1`. Today, it has total `n` levels. For example, the top 5 levels of the pyramid looks like: ``` Pyramid with 5 levels: 01 02 03 0...
games
def vertical_sum(n, i): idx = abs(i) + 1 top = idx * (idx + 1) / / 2 if i < 0: top += i hgt = (n - idx) / / 2 return hgt * (hgt + 1) * (n - 1 - (n + idx) % 2) - hgt * (hgt + 1) * (hgt - 1) * 4 / / 3 + (hgt + 1) * top
Number Pyramid Series 7 - Vertical Sum
65382cfc5396a5bc37d19395
[ "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/65382cfc5396a5bc37d19395
6 kyu
## Background Let `$G$` be an undirected graph. Suppose we start with three coins on three arbitrarily chosen vertices of `$G$`, and we want to move the coins so that they lie on the same vertex using as few moves as possible. At every step, each coin must move across an edge. ## Task Write a function `converge(g, u1...
algorithms
from itertools import count from functools import reduce def converge(g, * us): floods = [frozenset({u}) for u in us] vus = set() for step in count(0): if all(s in vus for s in floods): break vus . update(floods) overlap = reduce(set . intersection, floods[1:], set(floods[0]...
Topology #0: Converging Coins
5f5bef3534d5ad00232c0fa8
[ "Algorithms", "Graph Theory" ]
https://www.codewars.com/kata/5f5bef3534d5ad00232c0fa8
4 kyu
<div style="width: 100%; margin: 16px 0; border-top: 1px solid grey;" /> - If you like cryptography and playing cards, have also a look at [Card-Chameleon, a Cipher with Playing cards](https://www.codewars.com/kata/59c2ff946bddd2a2fd00009e). - And if you just like playing cards, have a look at [Playing Cards Draw Orde...
algorithms
import math import string from functools import cached_property from itertools import count class Deck: def __init__(self): self . suits = tuple('CDHS') self . ranks = tuple('A23456789TJQK') self . cards = tuple(r + s for s in self . suits for r in self . ranks) def __len__(self) - > ...
Hide a message in a deck of playing cards
59b9a92a6236547247000110
[ "Cryptography", "Mathematics", "Games", "Permutations", "Algorithms" ]
https://www.codewars.com/kata/59b9a92a6236547247000110
4 kyu
<div style="width: 100%; margin: 16px 0; border-top: 1px solid grey;" /> - If you like cryptography and playing cards, have also a look at [Hide a message in a deck of playing cards](https://www.codewars.com/kata/59b9a92a6236547247000110). - And if you just like playing cards, have a look at [Playing Cards Draw Order]...
algorithms
from string import ascii_uppercase class CardChameleon: __slots__ = ('deck', 'is_valid', 'text') ALPHABET = ascii_uppercase + ' ' BLACK_CARDS = [ rank + suit for suit in 'CS' for rank in 'A23456789TJQK'] + ['XB'] RED_CARDS = [ rank + suit for suit in 'DH' for rank in 'A234...
Card-Chameleon, a Cipher with Playing Cards
59c2ff946bddd2a2fd00009e
[ "Cryptography", "Games", "Algorithms" ]
https://www.codewars.com/kata/59c2ff946bddd2a2fd00009e
5 kyu
__Introduction__ We live in the woods. In the autumn, we have many leaves to rake... while the leaves keep falling... and we keep raking, over and over. In fact, we just keep raking until the first snow falls. The only reasonable way to dispose of these leaves is by burning them. We have limited space for the burn pil...
reference
def rake_and_burn(days): rain = yard = pile = 0 for p, ws, wd in days: if p == 'snow': return yard / / 12 if p != 'rain' and not rain: if pile == 2 and ws <= 10 and 'S' not in wd: pile = 0 yard += 3 elif pile < 2 and ws <= 12: pile += 1 yard += 4 rain = p == '...
Autumn Ritual: Rake and Burn
653db02b1eca91b474817307
[]
https://www.codewars.com/kata/653db02b1eca91b474817307
7 kyu
Crazy rabbit is in a coffee field with boundries in an initial given cell (`pos = 0` in example). Each field cell might have coffee beans. ```bash | | |R____________| 2 2 4 1 5 2 7 # Crazy rabbit at the start" ``` Crazy rabbit eats all coffee beans that available in the cell. And his jump power in...
reference
import copy # Modifica el poder de salto y el arreglo según la dirección de salto e índice dado def Jump(): global jumpPower, array, index, direction, length global indexSequense, jumpPowerSequense, arraySequense, directionSequense global contador jumpPower += array[index] array[index] = ...
Crazy rabbit
6532414794f1d24774f190ae
[]
https://www.codewars.com/kata/6532414794f1d24774f190ae
5 kyu
The musical scales are constructed by a series of whole tones (W) and half tones (H). Between each two notes we have a whole tone, except for E to F and B to C that we have a half tone. For the major scale with key (root note) in C (C D E F G A B) we have the following mode (distances formula): W W H W W W H ...
algorithms
steps_up = { 'Cb': ('Dbb', 'Db'), 'C': ('Db', 'D'), 'C#': ('D', 'D#'), 'Db': ('Ebb', 'Eb'), 'D': ('Eb', 'E'), 'D#': ('E', 'E#'), 'Eb': ('Fb', 'F'), 'E': ('F', 'F#'), 'E#': ('F#', 'FX'), 'Fb': ('Gbb', 'Gb'), 'F': ('Gb', 'G'), 'F#': ('G', 'G#'), 'Gb': ('Abb...
Musical Scales and Modes
59a07c8810963911ca000090
[ "Algorithms" ]
https://www.codewars.com/kata/59a07c8810963911ca000090
6 kyu
Consider the following array: ``` [1, 12, 123, 1234, 12345, 123456, 1234567, 12345678, 123456789, 12345678910, 1234567891011...] ``` If we join these blocks of numbers, we come up with an infinite sequence which starts with `112123123412345123456...`. The list is infinite. You will be given an number (`n`) and your ...
reference
def solve(n): def length(n): s = 0 for i in range(20): o = 10 * * i - 1 if o > n: break s += (n - o) * (n - o + 1) / / 2 return s def binary_search(k): n = 0 for p in range(63, - 1, - 1): if length(n + 2 * * p) < k: n += 2 * * p return n ...
Block sequence
5e1ab1b9fe268c0033680e5f
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5e1ab1b9fe268c0033680e5f
4 kyu
### Tim's Fruit Shop Challenge Tim runs a fruit shop, and he has a unique way of processing orders. Customers send orders in a specific format: they specify the number of fruit units they want, followed by a lowercase letter (a-z) representing the fruit itself. For example, '30a4b' means 30 apples and 4 bananas. ...
reference
import re def fruit_pack(orders): arr = [] for order in orders: shelf = ['', '', ''] for num, fruit in re . findall('(\d+)(\D)', order): pallet, box, bag = int(num) / / 50, (int(num) % 50) / / 10, int(num) % 10 if pallet: shelf[2] += ('[' + fruit + ']') * pallet if box: ...
Tim's Fruit Shop Challenge
652643925c042100247fffc6
[ "Algorithms" ]
https://www.codewars.com/kata/652643925c042100247fffc6
6 kyu
You are running a race on a circular race track against the ghost of your past self. Each time you lap your ghost, you get a confidence boost because you realize how much faster you got. Given your speed (km/h), your ghosts speed (km/h), the length of the circular race track (km) and the time you run (h), predict how...
games
from math import ceil def number_lappings(my_speed, ghost_speed, time, round_length): if my_speed <= ghost_speed: return 0 return ceil((my_speed - ghost_speed) * time / round_length) - 1
Outrun your past self
6525caefd77c582baf678ddf
[ "Puzzles", "Mathematics" ]
https://www.codewars.com/kata/6525caefd77c582baf678ddf
7 kyu
A number is Esthetic if, in any base from `base2` up to `base10`, the absolute difference between every pair of its adjacent digits is constantly equal to `1`. ``` num = 441 (base10) // Adjacent pairs of digits: // |4, 4|, |4, 1| // The absolute difference is not constant // 441 is not Esthetic in base10 441 in base4...
reference
from gmpy2 import digits def esthetic(num, max_base=10): return [base for base in range(2, max_base + 1) if (dig := digits(num, base)) and all(abs(int(a) - int(b)) == 1 for a, b in zip(dig, dig[1:]))]
Esthetic Numbers
6523a71df7666800170a1954
[]
https://www.codewars.com/kata/6523a71df7666800170a1954
7 kyu
The principle is pretty simple: - Given a integer (n) - Find the next palindromic number after (excluding) n Implement this in the function nextPalin However, due to some constraints, the implementation is not: - 0 < n < 10^1000 - 0 < t < 0.175s <h3>A.K.A</h3> - n is between 1 and 1001 digits - total time for all t...
algorithms
def next_palin(n): s = str(n) l = len(s) h = l / / 2 r = l % 2 t = s[: h + r] + s[: h][:: - 1] if t > s: return int(t) elif t == '9' * l: return 10 * * l + 1 else: m = str(int(s[: h + r]) + 1) return int(m + m[: h][:: - 1])
Next Palindrome (Large Numbers 0 - 10^1000)
6521bbf23256e8e5801d64f1
[ "Algorithms", "Mathematics", "Performance" ]
https://www.codewars.com/kata/6521bbf23256e8e5801d64f1
6 kyu
Given a set of integers _S_, the _closure of S under multiplication_ is the smallest set that contains _S_ and such that for any _x, y_ in the closure of _S_, the product _x * y_ is also in the closure of _S_. Example 1: Given `S = {2}`, the closure of `S` is the set `{2, 4, 8, 16, 32, 64, ... }`. Example 2: Given `...
algorithms
from heapq import heappush, heappop def closure_gen(* s): q = sorted(s) m = set(s) while q: curr = heappop(q) yield curr for i in s: t = curr * i if t not in m: heappush(q, t) m . add(t)
Set Closure Generator
58febc23627d2f48de000060
[ "Streams", "Algorithms" ]
https://www.codewars.com/kata/58febc23627d2f48de000060
4 kyu
To solve this kata, you need to create a character class that can be used for a roguelike game. Instances of this class must have the characteristics strength, dexterity and intelligence and can call some test-generated methods that will change these characteristics or give the character a new weapon. The Character c...
games
class Weapon: def __init__(self, factors): self . factors = factors self . enhanced = False def enhance(self, factors): self . factors = [max(a, b) for a, b in zip(self . factors, factors)] self . enhanced = True def damage(self, characteristics): return sum(c * f for c, f in zip...
Roguelike game 1 - stats and weapon
651bfcbd409ea1001ef2c3cb
[ "Puzzles", "Games", "Object-oriented Programming", "Metaprogramming" ]
https://www.codewars.com/kata/651bfcbd409ea1001ef2c3cb
5 kyu
When two blocks of the same "type" are adjacent to each other, the entire contiguous block disappears (pops off). If this occurs, this can allow previously separated blocks to be in contact with each other, setting off a chain reaction. After each pop, the remaining items get pushed back before popping the next consecu...
reference
def pop_blocks(lst): stk, popping = [], None for v in lst: if v == popping: continue if stk and stk[- 1] == v: popping = stk . pop() else: stk . append(v) popping = None return stk
Popping Blocks
651bfcbcdb0e8b104175b97e
[ "Algorithms", "Arrays" ]
https://www.codewars.com/kata/651bfcbcdb0e8b104175b97e
6 kyu
You are given an array `asteroids` of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. There won't be any `0` in the given list. Find out th...
reference
def asteroid_collision(asteroids): i = 0 while i < len(asteroids): if asteroids[i] > 0: if i + 1 < len(asteroids) and asteroids[i + 1] < 0: s = asteroids[i] + asteroids[i + 1] if s > 0: asteroids . pop(i + 1) else: asteroids . pop(i) if s == 0: asteroids . pop(i) ...
Asteroid Collision
651ab89e80f7c46fc482ba12
[]
https://www.codewars.com/kata/651ab89e80f7c46fc482ba12
6 kyu
### Finding a Binary Tree from Traversals A binary tree is a tree where each node has either 0, 1 or 2 children. Such a tree is usually represented recursively using a class where each node has a value and left and right subtrees (either of which can be None). ``` class TreeNode: def __init__(self, value, left = N...
algorithms
from preloaded import TreeNode def build_tree(inorder, postorder): if not inorder or not postorder: return None # Create a hashmap to store the indices of elements in the inorder list idx_map = {val: idx for idx, val in enumerate(inorder)} def helper(in_start, in_end, post_start, post_en...
From Traversals to Tree
651478c7ba373c338a173de6
[ "Trees", "Recursion" ]
https://www.codewars.com/kata/651478c7ba373c338a173de6
5 kyu
_This Kata is intend to introduce one of the basic Python Golfing skill._ # Task: In this Golfing Kata, you are going to receive 2 positive integers `a` and `b`, you need to return the result of `math.ceil(a/b)`. But `import math` is too long, your code has to be as short as possible. Can you avoid the `math.ceil`? ...
games
def f(a, b): return 0 - - a / / b
[Code Golf] Avoid the math.ceil
6515e6788f32503cd5b1ee51
[ "Mathematics", "Restricted" ]
https://www.codewars.com/kata/6515e6788f32503cd5b1ee51
7 kyu
Given a string indicating a range of letters, return a string which includes all the letters in that range, *including* the last letter. Note that if the range is given in *capital letters*, return the string in capitals also! ### Examples ``` "a-z" ➞ "abcdefghijklmnopqrstuvwxyz" "h-o" ➞ "hijklmno" "Q-Z" ➞ "QRSTUVW...
reference
def gimme_the_letters(rng): a, b = map(ord, rng . split('-')) return '' . join(map(chr, range(a, b + 1)))
From A to Z
6512b3775bf8500baea77663
[ "Algorithms", "Strings" ]
https://www.codewars.com/kata/6512b3775bf8500baea77663
7 kyu
You have a pack of 5 randomly numbered cards, which can range from 0-9. You can win if you can produce a higher **two-digit** number from your cards, than your opponent. Return `True` if your cards win that round. ### Worked Example ``` ([2, 5, 2, 6, 9], [3, 7, 3, 1, 2]) ➞ True # Your cards can make the number 96 # Yo...
reference
def win_round(you, opp): return sorted(you)[: 2: - 1] > sorted(opp)[: 2: - 1]
Numbered Cards
65128d27a5de2b3539408d83
[]
https://www.codewars.com/kata/65128d27a5de2b3539408d83
7 kyu
Given two strings comprised of `+` and `-`, return a new string which shows how the two strings interact in the following way: - When positives and positives interact, they *remain positive*. - When negatives and negatives interact, they *remain negative*. - But when negatives and positives interact, they *become neutr...
reference
def neutralise(s1, s2): return '' . join('0' if i != j else i for i, j in zip(s1, s2))
Neutralisation
65128732b5aff40032a3d8f0
[ "Algorithms", "Strings" ]
https://www.codewars.com/kata/65128732b5aff40032a3d8f0
8 kyu
Two players draw a pair of numbered cards so that both players can form a *2 digit number*. A winner can be decided if one player's number is larger than the other. However, there is a rule where a player can swap any one of their cards with any one of the other player's cards in a gamble to get a higher number! Note ...
reference
def swap_cards(a, b): p, q = a / / 10, a % 10 r, s = b / / 10, b % 10 return p > q or (r, q) > (p, s)
Swapping Cards
65127302a5de2b11c940973d
[]
https://www.codewars.com/kata/65127302a5de2b11c940973d
7 kyu
Given a list of directions to spin, `"left"` or `"right"`, return an integer of how many full **360°** rotations were made. Note that each word in the array counts as a **90°** rotation in that direction. ### Worked Example ``` ["right", "right", "right", "right", "left", "right"] ➞ 1 # You spun right 4 times (90 * 4 ...
reference
def spin_around(lst): return abs(2 * lst . count("left") - len(lst)) / / 4
Spin Around, Touch the Ground
65127141a5de2b1dcb40927e
[ "Algorithms", "Arrays" ]
https://www.codewars.com/kata/65127141a5de2b1dcb40927e
7 kyu
Create a function that returns the sum of the digits formed from the first and last digits, all the way to the center of the number. ### Worked Example ``` 2520 ➞ 72 # The first and last digits are 2 and 0. # 2 and 0 form 20. # The second digit is 5 and the second to last digit is 2. # 5 and 2 form 52. # 20 + 52 = 7...
reference
def closing_in_sum(n): n_str = str(n) left = 0 right = len(n_str) - 1 total = 0 while left <= right: left_number = n_str[left] right_number = n_str[right] if left_number == right_number and left == right: total += int(f" { right_number } ") else: total += int(f...
Closing in Sum
65126d52a5de2b11c94096d2
[ "Algorithms", "Strings" ]
https://www.codewars.com/kata/65126d52a5de2b11c94096d2
7 kyu
Given a number, insert duplicate digits on both sides of all digits which appear in a group of 1. ### Worked Example ``` 22733 ➞ 2277733 # The number can be split into groups 22, 7, and 33. # 7 appears on its own. # Put 7s on both sides to create 777. # Put the numbers together and return the result. ``` ### Example...
reference
import re def numbers_need_friends_too(n): return int(re . sub(r'(.)\1*+(?<!\1.)', r'\1' * 3, str(n)))
Lonely Numbers
65126a26597b8597d809de48
[]
https://www.codewars.com/kata/65126a26597b8597d809de48
7 kyu
# Minimum number of moves There're two list: * [5, 1, 3, 2, 4] * [4, 5, 2, 1, 3] Your goal is to change the first list to the second list Each modification consists of choosing a single number and moving it some number of positions to the left. Your task is to write a function `min_move`, which has 2 argument `a` ...
algorithms
def min_move(a, b): count = 0 seen = set() i = 0 j = 0 while j < len(b): if a[i] == b[j]: i += 1 j += 1 elif a[i] in seen: i += 1 else: seen . add(b[j]) j += 1 count += 1 return count
Minimum number of moves
622e4b5028bf330017cd772f
[ "Algorithms", "Performance" ]
https://www.codewars.com/kata/622e4b5028bf330017cd772f
5 kyu
Due to a huge scandal about the Laddersons Ladder Factory creating faulty ladders, the Occupational Safety and Health Administration require your help in determining whether a ladder is safe enough for use in the work place! It is vital that a ladder passes all criterea: - There will be exactly one character space wit...
reference
import re def is_ladder_safe(ldr): s = ldr[0] base = f'# { " " * ( len ( s ) - 2 ) } #' full = "#" * len(s) O, C = '{}' reg = rf" { base } o { full } o((?: { base } o) { O } ,2 { C }{ full } o)\1* { base } " return len(s) > 4 and bool(re . fullmatch(reg, 'o' . join(ldr)))
An OSHA Approved Ladder?
65116501a5de2bc51f409c1a
[]
https://www.codewars.com/kata/65116501a5de2bc51f409c1a
6 kyu
Matryoshka dolls are traditionally wooden dolls that can be nested by fitting smaller dolls into larger ones. Similarly, we can nest lists by placing smaller lists into larger ones, following specific rules. **Rules for Nesting:** - List A can be nested inside List B if: - The minimum value in List A is greater than...
games
from itertools import pairwise def matryoshka(ls): return all(a[0] < b[0] and a[- 1] > b[- 1] for a, b in pairwise(sorted(map(sorted, ls), key=lambda l: (l[0], - l[- 1]))))
Matryoshka Dolls
6510238b4840140017234427
[]
https://www.codewars.com/kata/6510238b4840140017234427
7 kyu
# Weird Sequence This weird sequence is an expansion of the integer sequence (`1,2,3,..`). It starts with `1` and it is expanded (an infinite number of times) by adding the number `k` before every `k`<sup>th</sup> (`1`-based) term of this weird sequence. For example: ```python [ ...
algorithms
def weird(n): return weird(n / / 2) if n % 2 else (n / / 2 + 1)
Weird Sequence
650c7503a5de2be5b74094bf
[ "Mathematics" ]
https://www.codewars.com/kata/650c7503a5de2be5b74094bf
6 kyu
Your task is to implement a function that examines a given string composed of binary digits (0s and 1s). The function should return `True` if: - Every consecutive sequence of ones is immediately followed by an equal-length consecutive sequence of zeroes, and the number of ones is equal to the number of zeroes. - A le...
reference
from re import compile REGEX = compile(r"(1*)(0*)"). findall def same_length(txt): return all(len(x) == len(y) for x, y in REGEX(txt))
Ones and Zeroes
650a86e8404241005fc744ca
[]
https://www.codewars.com/kata/650a86e8404241005fc744ca
7 kyu
**Problem Description** Find how many reflective prime pairs exist in a given range for each base in a given range. You'll be given two integers as parameters — ceiling range for primes and ceiling range for bases **(ranges include the parameters)**. By "reflective" I mean two distinct numbers who are each other's refl...
reference
PRIMES = {n for n in range(2, 10 * * 4 + 1) if all(n % p for p in range(2, int(n * * .5) + 1))} def rev(n, b): r = 0 while n: r, n = r * b + n % b, n / / b return r def prime_reflections(mp, mb): return {b: sum(rev(p, b) < p <= mp and rev( p, b) in PRIMES for p in PRIMES) fo...
Reflective Prime Pairs for a Range of Bases
650850aa0b700930130c7981
[]
https://www.codewars.com/kata/650850aa0b700930130c7981
6 kyu
One of the basic [chess endgames](https://en.wikipedia.org/wiki/Chess_endgame) is where only three pieces remain on the board: the two kings and one rook. By 1970 it was proved that the player having the rook can win the game in at most 16 moves. Can you write code that plays this endgame that well? # Short Overview ...
algorithms
import csv import shutil import urllib . request from collections import defaultdict from enum import Enum from zipfile import ZipFile # constants and helper functions FILES = 'abcdefgh' RANKS = '12345678' ALPHA_NUMS = 'zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifte...
Chess - checkmate with rook in 16 moves
5b9ecec33c5b95e2b00000ba
[ "Games", "Performance", "Algorithms" ]
https://www.codewars.com/kata/5b9ecec33c5b95e2b00000ba
2 kyu
Create a function that takes two times of day (hours, minutes, seconds) and returns the number of occurences of palindrome timestamps within that range, inclusive. A palindrome timestamp should be read the same hours : minutes : seconds as seconds : minutes : hours, keeping in mind the seconds and hours digits will re...
reference
from bisect import bisect_left, bisect_right # Only 96 total memo = [t for t in range(24 * 3600) if (s := f" { t / / 3600 :0 2 d } : { t / / 60 % 60 :0 2 d } : { t % 60 :0 2 d } ") == s[:: - 1]] def palindrome_time(lst): h1, m1, s1, h2, m2, s2 = lst t1, t2 = 3600 * h1 + 60 * m1 + s1, 3600 * h2 + 60 * m2 + s2 ...
Palindrome Timestamps
65080590b6b5ee01db990ca1
[]
https://www.codewars.com/kata/65080590b6b5ee01db990ca1
7 kyu
A prison can be represented as an array of cells, where each cell contains exactly one prisoner. A 'True' represents an unlocked cell, and 'False' represents a locked cell. ``` [True, True, False, False, False, True, False] ``` Starting inside the leftmost cell, you are tasked with determining how many prisoners you ...
games
def freed_prisoners(prison): unlocked, freed = prison[0], 0 if unlocked: for cell in prison: if cell is unlocked: freed += 1 unlocked = not unlocked return freed
Prison Break
6507e3170b7009117e0c7865
[]
https://www.codewars.com/kata/6507e3170b7009117e0c7865
7 kyu
Jack and Jill are twins. When they are 10 years of age, Jack leaves earth in his spaceship bound for Altair IV, some 17 light-years distant. Though not equipped with warp drive, Jack's ship is still capable of attaining near light speed. When he returns to earth he finds that Jill has grown to adulthood while he, Jac...
reference
def twins(age, distance, velocity): α = (1 - velocity * * 2) * * 0.5 t = 2 * distance / velocity return age + α * t, age + t
The Twins Paradox
6502ea6bd504f305f3badbe3
[ "Physics" ]
https://www.codewars.com/kata/6502ea6bd504f305f3badbe3
7 kyu
Traditional safes use a three-wheel locking mechanism, with the safe combination entered using a dial on the door of the safe. The dial is marked with clockwise increments between 0 and 99. The three-number combination is entered by first dialling to the right (clockwise), then to the left (anti-clockwise), and then to...
algorithms
def safecracker(start, incs): a = (start - incs[0]) % 100 b = (a + incs[1]) % 100 c = (b - incs[2]) % 100 return (a, b, c)
Safecracker
6501aa820038a6b0bd098afb
[]
https://www.codewars.com/kata/6501aa820038a6b0bd098afb
7 kyu
Ava, Mark, Sheila, and Pete are at a party. However, Ava and Sheila are only staying if there are at least 4 people, Pete is only staying if there's at least 1 person, and Mark is only staying if there are at least 5 people. Therefore, Mark leaves, which makes Ava and Sheila leave, and Pete is left alone. Given an arr...
reference
def party_people(lst): lst = sorted(lst) while lst and lst[- 1] > len(lst): lst . pop() return len(lst)
Party People
65013fc50038a68939098dcf
[ "Algorithms", "Arrays" ]
https://www.codewars.com/kata/65013fc50038a68939098dcf
7 kyu