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
R, a programming language used for Statistics and Data Analysis, has the function `rank`, which returns the rank for each value in a vector. For example: ``` my_arr = [1, 3, 3, 9, 8] # Ranked would be: [0, 1.5, 1.5, 4, 3] ``` When two or more values have the same rank, they are assigned the mean of their rankings. H...
games
def rank(lst): p = {} for i, v in enumerate(sorted(lst)): p . setdefault(v, []). append(i) return [sum(p[v]) / len(p[v]) for v in lst]
Sorting in R: Rank
65006177f534f65b2594df05
[ "Lists", "Puzzles", "Sorting" ]
https://www.codewars.com/kata/65006177f534f65b2594df05
7 kyu
**Task** Given a list of values, return a list with each value replaced with the empty value of the same type. **More explicitly** - Replace integers `(e.g. 1, 3)`, whose type is int, with `0` - Replace floats `(e.g. 3.14, 2.17)`, whose type is float, with `0.0` - Replace strings `(e.g. "abcde", "x")`, whose type is ...
reference
def empty_values(lst): return [type(x)() for x in lst]
Emptying the Values
650017e142964e000f19cac3
[]
https://www.codewars.com/kata/650017e142964e000f19cac3
7 kyu
In this challenge you will be given a list similar to the following: ``` [[3], 4, [2], [5], 1, 6] ``` In words, elements of the list are either an integer or a list containing a single integer. If you try to sort this list via sorted([[3], 4, [2], [5], 1, 6]), Python will whine about not being able to compare integers ...
reference
def sort_it(array): return sorted(array, key=lambda x: x[0] if isinstance(x, list) else x)
Sort the Unsortable
65001dd40038a647480989c8
[ "Algorithms", "Arrays", "Sorting", "Lists" ]
https://www.codewars.com/kata/65001dd40038a647480989c8
7 kyu
**Task** Create a function that calculates the **count of n-digit** strings with the same sum for the first half and second half of their digits. These digits are referred to as "lucky" digits. **Examples** ``` Input: 2 ➞ Output: 10 # "00", "11", "22", "33", "44", "55", "66", "77", "88", "99" Input: 4 ➞ Output: 670 ...
algorithms
from math import comb # https://oeis.org/A174061 def lucky_ticket(n): return sum((- 1) * * k * comb(n, k) * comb(n / / 2 * 11 - 10 * k - 1, n - 1) for k in range(n >> 1))
Digits of Lucky Tickets
64ffefcb3ee338415ec426c1
[ "Performance", "Combinatorics" ]
https://www.codewars.com/kata/64ffefcb3ee338415ec426c1
6 kyu
### Task Heading off to the **Tree Arboretum of Various Heights**, I bring along my camera to snap up a few photos. Ideally, I'd want to take a picture of as many trees as possible, but the taller trees may cover up the shorter trees behind it. A tree is hidden if it is **shorter than** or the **same height as** a ( ...
games
from math import inf def tree_photography(lst): a, b = count(lst), count(reversed(lst)) return 'left' if a > b else 'right' def count(it): n, m = 0, - inf for v in it: if v > m: n, m = n + 1, v return n
Tree Photography
64fd5072fa88ae669bf15342
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/64fd5072fa88ae669bf15342
7 kyu
# Task My friend Nelson loves number theory, so I decide to play this game with him. I have a hidden integer `$ N $`, that might be very large (perhaps even up to `$ 10^{10^{12}} $` :D ). In one turn, Nelson can ask me one question: he can choose a prime integer `$ p $` and a nonnegative integer `$ e $` and I will t...
games
from math import prod PRIMES = [n for n in range(2, 10 * * 5 + 1) if all(n % p for p in range(2, int(n * * .5) + 1))] def play(query): z = {} for p in PRIMES: if not query(p, 1): continue l, r = 1, 10 * * 9 + 1 while r - l > 1: m = (r + l) / / 2 if query(p, m): l = m el...
Nelson the Number Theorist
64fb5c7a18692c0876ebbac8
[ "Number Theory", "Mathematics", "Performance" ]
https://www.codewars.com/kata/64fb5c7a18692c0876ebbac8
4 kyu
You will be given an array of numbers which represent your character's **altitude** above sea level at regular intervals: * Positive numbers represent height above the water. * 0 is sea level. * Negative numbers represent depth below the water's surface. **Create a function which returns whether your character survive...
games
def diving_minigame(lst): breath_meter = 10 for x in lst: if x < 0: breath_meter -= 2 else: breath_meter = min(10, breath_meter + 4) if breath_meter <= 0: return False return True
Hold Your Breath!
64fbfa3518692c2ed0ebbaa2
[ "Lists", "Puzzles" ]
https://www.codewars.com/kata/64fbfa3518692c2ed0ebbaa2
7 kyu
Let's say that there exists a machine that gives out free coins, but with a twist! Separating two people is a wall, and this machine is placed in such a way that both people are able to access it. Spending a coin in this machine will give the person on the other side **3 coins** and vice versa. If both people continu...
reference
def get_coin_balances(lst1, lst2): x, y = lst1 . count("share"), lst2 . count("share") return 3 - x + 3 * y, 3 - y + 3 * x
Coin Co-Operation
64fc00392b610b1901ff0f17
[]
https://www.codewars.com/kata/64fc00392b610b1901ff0f17
7 kyu
### Task Given a string, return if all occurrences of a given letter are always immediately followed by the other given letter. ### Worked Example ``` ("he headed to the store", "h", "e") ➞ True # All occurences of "h": ["he", "headed", "the"] # All occurences of "h" have an "e" after it. # Return True ('abcdee', ...
reference
def best_friend(t, a, b): return t . count(a) == t . count(a + b)
A Letter's Best Friend
64fc03a318692c1333ebc04c
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/64fc03a318692c1333ebc04c
7 kyu
### Task Create a function that always returns `True`/`true` for every item in a given list. However, if an element is the word **'flick'**, switch to always returning the opposite boolean value. ### Examples ```python ['codewars', 'flick', 'code', 'wars'] ➞ [True, False, False, False] ['flick', 'chocolate', 'adv...
reference
def flick_switch(lst): res, state = [], True for i in lst : if i == 'flick' : state = not state res . append ( state ) return res
Flick Switch
64fbfe2618692c2018ebbddb
[ "Fundamentals", "Lists" ]
https://www.codewars.com/kata/64fbfe2618692c2018ebbddb
8 kyu
### Task A new 'hacky' phone is launched, which has the feature of connecting to any Wi-Fi network from any distance away, as long as there aren't any obstructions between the hotspot and the phone. Given a string, return how many Wi-Fi hotspots I'm able to connect to. * The phone is represented as a `P`. * A hotspot ...
games
import re def nonstop_hotspot(area): ans = re . search(r'[* ]*P[* ]*', area) return ans . group(). count('*')
Get Free Wi-Fi Anywhere You Go
64fbf7eb2b610b1a6eff0e44
[ "Algorithms", "Puzzles", "Strings" ]
https://www.codewars.com/kata/64fbf7eb2b610b1a6eff0e44
7 kyu
# It's Raining Tacos! A line of tacos is falling out of the sky onto the landscape. Your task is to predict what the landscape will look like when the tacos fall on it. ``` INPUT: ********* ``` ``` OUTPUT: TACOTACOT ********* ``` The landsc...
algorithms
def rain_tacos(landscape, word='TACO'): n = len(grid := landscape . splitlines()) grid = [('' . join(row). rstrip() + word[i % len(word)]). ljust(n, ' ')[: n] for i, row in enumerate(zip(* grid[:: - 1]))] return '\n' . join(map('' . join, list(zip(* grid))[:: - 1]))
It's Raining Tacos
64f4ef596f222e004b877272
[ "Algorithms" ]
https://www.codewars.com/kata/64f4ef596f222e004b877272
6 kyu
# Task Imagine you have a list of integers. You start at the first item and use each value as a guide to decide where to go next. Create a function that determines whether the input list forms a complete cycle or not. ![image](https://i.imgur.com/TRu0Bzk.png) # Examples ``` [1, 4, 3, 0, 2] ➞ True # When you follow ...
reference
def full_cycle(lst): return all((x := lst[i and x]) for i in range(len(lst) - 1))
Is This a Full Cycle?
64f41ad92b610b64c1067590
[ "Arrays" ]
https://www.codewars.com/kata/64f41ad92b610b64c1067590
7 kyu
# Perfect Binary Tree Traversal: In [tree traversal](https://en.wikipedia.org/wiki/Tree_traversal), there are two well-known methods: * Breadth-First Search (BFS) * Deep-First Search (DFS) And we are going to find out some relationship between them. ___ # Perfect Binary Tree: A perfect binary tree is a special ...
games
def convert_number(height, num): pre = 1 inoreder = 2 * * (height - 1) post = (2 * * height) - 1 depth = 1 while 2 * * depth <= num: depth += 1 while depth > 1: height -= 1 depth -= 1 if 2 * * (depth - 1) & num != 0: pre += 2 * * height inoreder += 2 * * (height - 1) ...
Perfect Binary Tree Traversal: BFS to DFS
64ebbfc4f1294ff0504352be
[ "Algorithms", "Binary", "Data Structures", "Mathematics", "Trees" ]
https://www.codewars.com/kata/64ebbfc4f1294ff0504352be
5 kyu
# Task Initially, the string consists of a single character. There are two operations: - `Copy` the entire string into a buffer. It is not allowed to copy a part of the current string. - `Paste` the buffer content at the end of the string. The string length increases. Each operation counts as one. The function is gi...
reference
from gmpy2 import next_prime def min_ops(n): k, p = 0, 2 while n > 1: while n % p: p = next_prime(p) n / /= p k += p return k
Minimum Number of Copy / Paste Operations
64f04307c6307f003106ac2c
[]
https://www.codewars.com/kata/64f04307c6307f003106ac2c
6 kyu
The Codewars Council meets at a circular table with `n` seats. Depending on the day `d` of the month, `d` people will be chosen as leaders of the council. These `d` leaders are spaced equidistantly from each other on the table, like spokes on a wheel. The leaders are chosen based on which grouping of `d` equidistant pe...
algorithms
def largest_radial_sum(arr, d): return max(sum(arr[i:: len(arr) / / d]) for i in range(len(arr) / / d))
Largest Radial Sum
64edf7ab2b610b16c2067579
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/64edf7ab2b610b16c2067579
6 kyu
## Preamble In Microsoft FreeCell (shipped with early Windows versions), each deal is generated by PRNG seeded by the deal number (see pseudocode below). There are 32000 deals numbered from 1 to 32000. This guarantees every deal is unique, but they are portable across computers, so #1 on one machine is exactly the sam...
reference
from preloaded import DECK def deal(n): deck = list(DECK) state = n dealt_cards = [] while (len(deck) != 0): state = (state * 214013 + 2531011) % (2 * * 31) next_value = int(state / (2 * * 16)) card_index = next_value % len(deck) if card_index != len(deck) - 1: last...
FreeCell Deal Generator
64eca9a7bc3127082b0bc7dc
[ "Games" ]
https://www.codewars.com/kata/64eca9a7bc3127082b0bc7dc
7 kyu
To almost all of us solving sets of linear equations is quite obviously the most exciting bit of linear algebra. Benny does not agree though and wants to write a quick program to solve his homework problems for him. Unfortunately Benny's lack of interest in linear algebra means he has no real clue on how to go about th...
algorithms
from decimal import Decimal as dec, getcontext import re getcontext(). prec = 28 def reduced(arr, comparator): def check_divider(arr, compare): for i, (x, y) in enumerate(zip(arr, compare)): try: if i == 0: test = x / y elif x / y != test: return False except: ...
Linear Equation Solver
56d6d927c9ae3f115b0008dd
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/56d6d927c9ae3f115b0008dd
4 kyu
Create a function which returns the state of a board after `n` moves. There are different types of blocks on the board, which are represented as strings. * `>` is a pusher which moves right every turn, and pushes a block to the right if it occupies the same space as it. * `'#'` is a block which can be pushed by the pu...
reference
import re def block_pushing(l, n): s = '' . join(l) for _ in range(n): s = re . sub('(>[>#]*)-', lambda g: '-' + g . group(1), s) return list(s)
Block Pusher
64e5e192f1294f96fd60a5ae
[]
https://www.codewars.com/kata/64e5e192f1294f96fd60a5ae
6 kyu
**Task** Imagine a lively dice game where four friends, affectionately known as `p1, p2, p3, and p4`, come together for an exciting gaming session. Here's how it unfolds: in each round, all players roll a pair of standard six-sided dice. The player with the lowest total score is promptly eliminated from the game. But...
games
def dice_game(scores): players = ['p1', 'p2', 'p3', 'p4'] while len(players) > 1: results = list(zip(players, scores)) scores = scores[len(players):] results . sort(key=lambda x: (sum(x[1]), x[1][0])) if results[0][1] != results[1][1]: players . remove(results[0][0]) return pla...
The Dice Game
64e5b47cc065e56fb115a5bf
[]
https://www.codewars.com/kata/64e5b47cc065e56fb115a5bf
6 kyu
**Task** This game is played with a random string of digits 0-9. The object is to reduce the string to zero length by removing digits from the left end of the string. Removals are governed by one simple rule. If the leftmost digit is `n`, you can remove up to `n` digits from the left end (inclusive). After doing t...
games
def solve(game): if game[0] == str(len(game)): return [(int(game[0]),)] solutions = [] for i in range(1, int(game[0]) + 1): if i >= len(game): break move_made = game[i:] if int(move_made[0]) <= i: continue move_made = str(int(move_made[0]) - i) + move_made[1...
The Simple Game
64e5bb63c065e575db15a3f1
[]
https://www.codewars.com/kata/64e5bb63c065e575db15a3f1
5 kyu
# Task Find pairs of elements from two input lists such that swapping these pairs results in equal sums for both lists. If no such pair exists, return an empty set. # Input Two lists of integers, `list1` and `list2`, with the same length. # Output A set of tuples, each containing two elements (`num_from_list1, num...
algorithms
def fair_swap(a, b): r = set() swap_size, odd_diff = divmod(sum(a) - sum(b), 2) if odd_diff: return r b = set(b) for n1 in set(a): if (n2 := n1 - swap_size) in b: r . add((n1, n2)) return r
Fair Swap between Two Lists
64b7bcfb0ca7392eca9f8e47
[ "Algorithms", "Lists" ]
https://www.codewars.com/kata/64b7bcfb0ca7392eca9f8e47
7 kyu
Some idle games use following notation to represent big numbers: |Number|Notation|Description| |-|-|-| |1|1|1| |1 000|1K|Thousand| |1 000 000|1M|Million| |1 000 000 000|1B|Billion| |1 000 000 000 000|1T|Trillion| |1 000 000 000 000 000|1aa|Quadrillion| |10¹⁸|1ab|Quintillion| |10²¹|1ac|Sextillion| |10²⁴|1ad|Octillion| ...
reference
from decimal import Context, Decimal, ROUND_DOWN from re import sub def format_number(x): dec = ( (Context(prec=3, rounding=ROUND_DOWN) . create_decimal_from_float(x * 100) . to_integral_exact(rounding=ROUND_DOWN) / 100) . normalize() . to_eng_string() ) ...
The "AA" Number Notation
64e4cdd7f2bfcd142a880011
[ "Mathematics" ]
https://www.codewars.com/kata/64e4cdd7f2bfcd142a880011
5 kyu
### Spark plugs, distributor wires, and firing order. Your car's engine operates by containing tiny explosions caused by gas being ignited by spark plugs, which compresses a pistion, causing the engine to turn. Spark plugs are sparked by receiving electrical signal through a wire connected to a distributing system. If...
reference
CARS = { enterprise: {model: ignition . split('-') for model, ignition in models . items()} for enterprise, models in CARS . items() } def find_misfire(fire_in_the_holes): enterprise, model, fire = fire_in_the_holes . split() return '-' . join(a for a, b in zip(CARS[enterpris...
Car Debugging: Misfire
64dbfcbcf9ab18004d15d17e
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/64dbfcbcf9ab18004d15d17e
7 kyu
# Task Your goal is to know the score of the hand, either by getting three cards of the same rank or the same suit. The value of your hand is calculated by adding up the total of your cards in **any one suit**. Regular cards are worth their number, face cards are worth 10, and Aces are worth 11, but remember, **only o...
algorithms
from collections import defaultdict def score31(c1, c2, c3): d = defaultdict(int) values = set() for c in c1, c2, c3: v = c[1:] values . add(v) d[c[0]] += int(v) if v . isdigit() else 10 + (v == "A") return max(d . values()) if len(values) > 1 else 30.5 + 1.5 * (v == "A")
Card Game 31 Score Validator
64e06b8f55bbb752ac2e66f5
[]
https://www.codewars.com/kata/64e06b8f55bbb752ac2e66f5
7 kyu
*How many squares can Chuck Norris cover in a single jump? All of them!* A grasshopper is jumping forward in a single-axis space represented as an array(list). It can cover `p` spaces in one jump, where `p` is any prime number. The grasshopper starts any distance *before* the initial item of the array and finishes a...
algorithms
from preloaded import PRIMES from itertools import chain, takewhile def prime_grasshopper(arr): dp = arr[:] for i, x in enumerate(dp): dp[i] = max( chain([x], [dp[i - p] + x for p in takewhile(i . __ge__, PRIMES)])) return max(chain([0], dp))
Prime Grasshopper
648b579a731d7526828173cc
[ "Dynamic Programming" ]
https://www.codewars.com/kata/648b579a731d7526828173cc
5 kyu
## This Kata is the second of three katas that I'm making on the game of hearts. We're getting started by simply scoring a hand, and working our way up to scoring a whole game! [Link for Kata #1](https://www.codewars.com/kata/64d16a4d8a9c272bb4f3316c) Now that we can sucessfully score a single hand, we're ready to sc...
games
def play_a_round(alex_cards, bob_cards, chris_cards, dave_cards): return_list = [] if '2C' in bob_cards: leader = 'bob' elif '2C' in chris_cards: leader = 'chris' elif '2C' in dave_cards: leader = 'dave' else: leader = 'alex' # Play until players have no more cards ...
Hearts (Card Game) Kata 2 of 3
64d1d067e58c0e0025860f4b
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/64d1d067e58c0e0025860f4b
5 kyu
## AST Series:<br> + [Your first use of ast: Inspecting Python Functions](https://www.codewars.com/kata/64d129a576bd58000f7fe97a) + AST Series #2: Your First NodeTransformer (this one!) + [AST Series #3: The Missing Link](https://www.codewars.com/kata/64dd031d9a9b8c1bc6972e9f) # Preamble Today you will learn how to...
reference
import ast class YourFirstNodeTransformer (ast . NodeTransformer): ... # you can do this ! def visit_Constant(self, node): return ast . Constant(node . value + 0.5)
AST Series #2: Your First NodeTransformer
64dbb4ab529cad81578c61e7
[]
https://www.codewars.com/kata/64dbb4ab529cad81578c61e7
6 kyu
# Task Given a string of digits, return the longest substring with alternating `odd/even` or `even/odd digits`. If two or more substrings have the same length, return the substring that occurs first. # Examples ```python longest_substring("225424272163254474441338664823") ➞ "272163254" # substrings = 254, 272163254, 4...
algorithms
import re def longest_substring(digits): regex = r'({e}?({o}{e})*{o}?)|({o}?({e}{o})*{e}?)' . format( e='[02468]', o='[13579]') return max((x[0] for x in re . findall(regex, digits)), key=len)
Longest Alternating Substring
64db008b529cad38938c6e28
[ "Algorithms", "Logic", "Regular Expressions", "Strings" ]
https://www.codewars.com/kata/64db008b529cad38938c6e28
6 kyu
<html> <body> Given two sets of integer numbers (domain and codomain), and a list of relationships (x, y) also integers, determine if they represent a function and its type:<br> <strong>1. Not a function:</strong> If there is at least one element in the domain set that is related to more than one element in the codomai...
reference
def type_of_function(d, c, r): return 'It is not a function' if len(k: = dict(r)) != len(r) else ('Bijective' if len(k) == len(d) == len(c) else 'Surjective') if set(k . values()) == set(c) else 'Injective' if len(set(k . values())) == len(k . values()) else 'General function'
Type Of Relation
64915dc9d40f96004319379a
[ "Mathematics", "Set Theory" ]
https://www.codewars.com/kata/64915dc9d40f96004319379a
7 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 positive integer <code>n</code> return an array of array of numbers, with the nested arrays representing all possible ways to...
algorithms
from itertools import combinations def pair_em_up(n): return sorted((list(x) for k in range(2, n + 1, 2) for x in combinations(range(n), k)), key=lambda x: x + [n] * (n - len(x)))
Pair 'em Up
64d4cd29ff58f0002301d5db
[ "Algorithms", "Arrays", "Recursion" ]
https://www.codewars.com/kata/64d4cd29ff58f0002301d5db
5 kyu
# Task Create a function that takes a list of integers and a group length as parameters. Your task is to determine if it's possible to split all the numbers from the list into groups of the specified length, while ensuring that consecutive numbers are present within each group. # Input `lst` / `arr`: A list / array o...
reference
from collections import Counter def consecutive_nums(lst, size): if len(lst) % size: return False cnt = Counter(lst) for v in sorted(cnt)[: - size + 1 or None]: if not cnt[v]: continue n = cnt[v] for x in range(v, v + size): if cnt[x] < n: return False cnt[x] -=...
Divide and Conquer
64d482b76fad180017ecef0a
[ "Algorithms", "Arrays", "Performance" ]
https://www.codewars.com/kata/64d482b76fad180017ecef0a
6 kyu
### Task Given an initial chess position and a list of valid chess moves starting from that position, compute the final position. (a) Positions are represented as 2-d lists of characters; uppercase letters denote white pieces and lowercase black. Empty squares are indicated using <code>.</code> (a single period). W...
reference
def compute_final_position(b, m): def pos(a, b): return (8 - int(b), 'abcdefgh' . index(a)) for t, e in enumerate(m): if e[2] in '-x': i, j = pos(* e[0: 2]) p, q = pos(* e[3: 5]) b[p][q] = b[i][j] b[i][j] = '.' # regular move if e[- 2:] == 'ep': b[i][q] = '.' ...
Find the Final Position
64cd52397a14d81a9f78ad3e
[ "Games" ]
https://www.codewars.com/kata/64cd52397a14d81a9f78ad3e
6 kyu
## This Kata is the first of three katas that I'm making on the game of hearts. We're getting started by simply scoring a hand, and working our way up to scoring a whole game! In this Kata, your goal is to evaluate a single hand of hearts, and determine the winning card. Follow this link (https://gamerules.com/rules/...
games
VALUES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] def score_a_hand(cards): suit = cards[0][- 1] in_suit = filter(lambda card: card . endswith(suit), cards) return max(in_suit, key=lambda card: VALUES . index(card[: - 1]))
Hearts (Card Game) Kata 1 of 3
64d16a4d8a9c272bb4f3316c
[ "Games", "Puzzles" ]
https://www.codewars.com/kata/64d16a4d8a9c272bb4f3316c
7 kyu
## Task You are given 3 positive integers `a, b, k`. Using one operation you can change `a` or `b` (but not both) by `k` (add or subtract are all ok). Count the minimum number of operations needed to make `a, b > 0` and `gcd(a, b) > 1`. You have to write a function `gcd_neq_one()` which receives 3 positive integers `...
algorithms
from math import gcd from itertools import count def gcd_neq_one(a, b, k): for n in count(0): for i in range(0, n * k + 1, k): for ai in (a + i, a - i): if ai > 1: j = n * k - i for bj in (b + j, b - j): if bj > 1 and gcd(ai, bj) > 1: return n
GCD not equal to 1
64d0f8fc8a9c270041f33a3c
[ "Mathematics", "Number Theory" ]
https://www.codewars.com/kata/64d0f8fc8a9c270041f33a3c
6 kyu
### Task The function is given a list of `prerequisites` needed to complete some jobs. The list contains pairs `(j, i)`, where job `j` can start after job `i` has been completed. A job can have multiple dependencies or have no dependencies at all. If a job has no dependencies, it can be completed immediately. The funct...
reference
from collections import defaultdict, deque def finish_all(edges): n_entrants = defaultdict(int) succs = defaultdict(list) for b, a in edges: n_entrants[b] += 1 n_entrants[a] += 0 succs[a]. append(b) q = deque(k for k, n in n_entrants . items() if not n) while q: a = q...
Dependable Jobs Schedule
64cf5ba625e2160051ad8b71
[]
https://www.codewars.com/kata/64cf5ba625e2160051ad8b71
5 kyu
You are given a positive integer n. For every operation, subtract n by the sum of its digits. Count the number of operations to make n = 0. For example, with n = 20, you have to use 3 operations. Firstly, n = 20 - (2 + 0) = 18. Secondly, n = 18 - (1 + 8) = 9. Finally, n = 9 - 9 = 0. You have to answer q such question...
algorithms
memo = [0] * (10 * * 7) def solve_using_prev(n): memo[n] = memo[n - sum(int(x) for x in str(n))] + 1 for n in range(1, 8): solve_using_prev(n) for n in range(9, 10 * * 7, 9): solve_using_prev(n) def jump_to_zero(a): return [memo[x - sum(int(x) ...
Jump to zero (Subtask 4)
64cfc5f033adb608e2aaedef
[ "Mathematics", "Algorithms", "Dynamic Programming", "Performance", "Number Theory" ]
https://www.codewars.com/kata/64cfc5f033adb608e2aaedef
5 kyu
### Task You are given a positive integer `n`. Your objective is to transform this number into another number with **all digits identical**, while _minimizing the number of changes_. Each step in the transformation involves incrementing or decrementing a digit by one. For example, if the given number is **399**, it ca...
reference
def smallest_transform(num): lst = [int(i) for i in str(num)] number = [] for i in range(min(lst), max(lst) + 1): total = 0 for k in lst: total += abs(k - i) number . append(total) return min(number)
Smallest Transform
64cf34314e8a905162e32ff5
[ "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/64cf34314e8a905162e32ff5
7 kyu
Find the sum of all positive integer roots up to (and including) the nth term of n, whose products are rational positive integers. Simple... Right? Examples: ```csharp function(1) => 1 as (1root 1 = 1); function(9) => 12 as (1root 9 = 9) + (2root 9 = 3); function(27) => 30 as (1root 27 = 27) + (3root 27 = 3); funct...
algorithms
from gmpy2 import iroot def root_sum(n): return sum(r[0] for k in range(1, n . bit_length() + 1) if (r := iroot(n, k))[1])
Root the Num and Find the Integer Sum
64cbc840129300011fa78108
[ "Mathematics" ]
https://www.codewars.com/kata/64cbc840129300011fa78108
6 kyu
You will be given an array of events, which are represented by strings. The strings are dates in HH:MM:SS format. It is known that all events are recorded in chronological order and two events can't occur in the same second. Return the minimum number of days during which the log is written. Example: ```python Inpu...
algorithms
def check_logs(log): return sum( a >= b for a, b in zip(log, log[1:])) + bool(log)
Log without dates
64cac86333ab6a14f70c6fb6
[ "Date Time", "Filtering" ]
https://www.codewars.com/kata/64cac86333ab6a14f70c6fb6
7 kyu
# Task A courthouse has a backlog of several cases that need to be heard, and is trying to set up an efficient schedule to clear this backlog. You will be given the following inputs: - A dictionary `cases` whose values are the number of court sessions each case needs to be concluded. - An integer `max_daily_sessions` ...
algorithms
from math import ceil def legal_backlog(cases, mds): return max(ceil(sum(cases . values()) / mds), max(cases . values()))
Legal Backlog
64c64be38f9e4603e472b53a
[]
https://www.codewars.com/kata/64c64be38f9e4603e472b53a
6 kyu
Write a function `revSub` which reverses all sublists where consecutive elements are even. Note that the odd numbers should remain where they are. # Example With `[1,2,4,5,9]` as input, we should get `[1,4,2,5,9]`. Here, because `[2,4]` is a sublist of consecutive even numbers, it should be flipped. There could be mor...
reference
from itertools import groupby def rev_sub(arr): r = [] for i in [list(g) for n, g in groupby(arr, key=lambda x: x % 2)]: if i[0] % 2: r += i else: r += i[:: - 1] return r
Reverse sublists of even numbers
64c7bbad0a2a00198657013d
[ "Lists" ]
https://www.codewars.com/kata/64c7bbad0a2a00198657013d
7 kyu
# Task Create a class that imitates a select screen. The cursor can move to left or right! In the display method, return a string representation of the list, but with square brackets around the currently selected element. Also, create the methods `to_the_right` and `to_the_left` which moves the cursor. The cursor sho...
reference
class Menu: def __init__(self, menu: list) - > None: self . menu = menu self . index = 0 self . length = len(menu) def to_the_right(self) - > None: self . index = (self . index + 1) % self . length def to_the_left(self) - > None: self . index = (self . index - 1) % self . lengt...
Menu Display
64c766dd16982000173d5ba1
[ "Fundamentals", "Object-oriented Programming" ]
https://www.codewars.com/kata/64c766dd16982000173d5ba1
7 kyu
Given a 2D array of some suspended blocks (represented as hastags), return another 2D array which shows the *end result* once gravity is switched on. ### Examples ``` switch_gravity([ ["-", "#", "#", "-"], ["-", "-", "-", "-"], ["-", "-", "-", "-"], ["-", "-", "-", "-"] ]) ➞ [ ["-", "-", "-", "-"], ["-", "...
algorithms
def switch_gravity(lst): return list(map(list, zip(* map(sorted, zip(* lst)))))[:: - 1]
Switch on the Gravity
64c743cb0a2a00002856ff73
[ "Algorithms", "Matrix", "Arrays" ]
https://www.codewars.com/kata/64c743cb0a2a00002856ff73
7 kyu
Given some class `A` with weirdly type-annotated class attributes: ```python class A: x: IncrementMe = 5 y: DoubleMe = 21 z: AmIEven = 3 xs: Map(IncrementMe) = [1, 2, 3] ys: Filter(AmIEven) = [0, 3, 4, 5] ``` and the "magical" function `do_the_magic(kls)` that takes a class (note: the actual class,...
games
class C: def __init__(self, fn): self . fn = fn def __call__(self, * args, * * kwargs): return self . fn(* args, * * kwargs) IncrementMe = C(lambda v: v + 1) DoubleMe = C(lambda v: v * 2) AmIEven = C(lambda v: v % 2 == 0) def Map(fn): return C(lambda l: list(map(fn, l))) def Filte...
Using type annotations the wrong way!
64c5886e24409ea62aa0773a
[ "Puzzles" ]
https://www.codewars.com/kata/64c5886e24409ea62aa0773a
6 kyu
Given a string of lowercase letters, find substrings that consist of consecutive letters of the lowercase English alphabet and return a similar string, but with these substrings in reversed alphabetical order. examples: ("x<font color='red'>abc</font>")=> "x<font color='red'>cba</font>" xa is not found in the alph...
reference
def solution(s): res, cur = [], [s[0]] for x in s[1:]: if ord(x) - ord(cur[- 1]) == 1: cur . append(x) else: res . extend(cur[:: - 1]) cur = [x] return '' . join(res + cur[:: - 1])
Alphabet Slices
64c45287edf1bc69fa8286a3
[ "Strings", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/64c45287edf1bc69fa8286a3
6 kyu
Your task is to write a function that takes a number as an argument and returns some number. But what's the problem? You need to guess what number should be returned. See the example test case. Good luck. Hint: You should be a bit careful when counting...
algorithms
def secret_number(n): return bin(n). count(str(n % 2)) * * 2
Secret problems with numbers
64bd5ff1bb8f1006708e545e
[ "Algorithms", "Logic", "Puzzles", "Fundamentals" ]
https://www.codewars.com/kata/64bd5ff1bb8f1006708e545e
7 kyu
**Introduction:** You've got a 16-bit calculating machine, but it's old and rusty. It has four 16-bit registers (`R0`, `R1`, `R2`, `R3`) and can do only a NAND operation. #### Machine Functions: This machine can perform these actions: - `read()`: Grabs the next number from a tape and stores it in `R0`. Returns true...
algorithms
def find_missing_number(m): L, s = 0, 0 while m . read(): L += 1 s ^= L m . nand(m . R1, m . R0, m . R3) m . nand(m . R2, m . R0, m . R1) m . nand(m . R1, m . R1, m . R3) m . nand(m . R3, m . R2, m . R1) m . nand(m . R0, m . R3, 65535) s ^= (~ m . output()) & 65535 ...
Find the Missing Number using NAND
64be81b50abf66c0147de761
[ "Logic", "Mathematics", "Restricted" ]
https://www.codewars.com/kata/64be81b50abf66c0147de761
5 kyu
A **hexagonal grid** is a commonly used **game board design** based on hexagonal tiling. In the following grid, the two marked locations have a minimum distance of 6 because at least 6 steps are needed to reach the second location starting from the first one. ![xx](https://i.imgur.com/MhsqNkt.png) Write a function th...
games
def hex_distance(grid): flat = "" . join(grid) size = len(grid[0]) # find start + end coordinates start = flat . find("x") end = flat[start + 1:]. find("x") + start + 1 x1, y1 = divmod(start, size) x2, y2 = divmod(end, size) # calculate distance dx = x2 - x1 dy = ab...
Hexagonal Grid: Distance
64be6f070381860017dba5ab
[ "Arrays", "Games", "Logic" ]
https://www.codewars.com/kata/64be6f070381860017dba5ab
6 kyu
# Task The **centered polygonal numbers** are a family of sequences of 2-dimensional figurate numbers, each formed by a central dot, sorrounded by polygonal layers with a constant number of sides. Each side of a polygonal layer contains one dot more than a side in the previous layer. ![i1](https://oeis.org/w/images/3/...
reference
def is_polygonal(n): a = 1 th = "4567890" poly = [] while (a * (a + 1) / 2) < n - 1: num_check = (n - 1) / (a * (a + 1) / 2) if num_check . is_integer() and num_check > 2: if 10 <= a % 100 <= 20 or str(a)[len(str(a)) - 1:] in th: poly . append(f" { int ( a )} th { int ( num_check...
Centered Polygonal Number
64be5c99c9613c0329bc7536
[ "Mathematics", "Performance" ]
https://www.codewars.com/kata/64be5c99c9613c0329bc7536
5 kyu
### Background **Nerdle** is like Wordle, but for arithmetic expressions rather than words. The idea is to identify a target expression using feedback from previous guesses. In this kata we play the simplest form of Nerdle, where the target expression consists of 5 characters: A digit, followed by an arithmetic operat...
games
TREE = {'guess': '1+2=3', 'feedback': {'GGGGG': {'val': '1+2=3'}, 'GGBGR': {'val': '1+3=4'}, 'GGBGB': {'guess': '1+2=3', 'feedback': {'GGBGB': {'guess': '1+3=4', 'feedback': {'GGBGR': {'val': '1+4=5'}, 'GGBGB': {'guess': '2+6=8', 'feedback': {'BGRGB': {'val': '1+5=6'}, 'BGGGB': {'val': '1+6=7'}, 'BGBGG': {'val': '1+7=8...
Play Nerdle - It's Wordle for Calculations
64b84ed4b46f91004b493d87
[ "Strings", "Games", "Artificial Intelligence" ]
https://www.codewars.com/kata/64b84ed4b46f91004b493d87
5 kyu
# Prelude The painting fence problem involves finding the number of ways to paint a fence with `n` posts and `k` colors, assuming that no more than two adjacent posts have the same color. # Task Your task is to implement a function named ways(n, k) that takes two BigInts as input: + `n` The number of posts in the fenc...
algorithms
import numpy as np MOD = 1000000007 def matrix_exp(Q, n): if n == 0: return np . array([[1, 0], [0, 1]], dtype=object) return (Q @ matrix_exp(Q, n - 1) if n & 1 else matrix_exp((Q @ Q) % MOD, n >> 1)) % MOD def ways(n, k): return (matrix_exp(np . array([[k - 1, k - 1], ...
Painting Fence Algorithm (Number of Ways To Paint A Fence)
64bc4a428e1e9570fd90ed0d
[ "Dynamic Programming", "Performance" ]
https://www.codewars.com/kata/64bc4a428e1e9570fd90ed0d
4 kyu
# Task In abstract set theory, a construction due to von Neumann represents the natural numbers by sets, as follows: - 0 = [ ] is the empty set - 1 = 0 ∪ [ 0 ] = [ 0 ] = [ [ ] ] - 2 = 1 ∪ [ 1 ] = [ 0, 1 ] = [ [ ], [ [ ] ] ] - n = n−1 ∪ [ n−1 ] = ... Write a function that receives an integer `n` and produces the repre...
reference
def rep_set(n): return [rep_set(k) for k in range(n)]
Natural Emptiness
64b8c6c09416795eb9fbdcbf
[]
https://www.codewars.com/kata/64b8c6c09416795eb9fbdcbf
7 kyu
## Introduction You are in charge of organizing a dinner for your team and you would like it to happen with as many participants as possible, as soon as possible. However, finding a date that works for everyone can be challenging due to their other commitments. In this case, a compromise, referred to as the best acce...
reference
from itertools import chain def team_dinner(available: list[list[int]]) - > int | None: res = list(chain . from_iterable(available)) res = {i: res . count(i) for i in res} result = [] for k, v in res . items(): if v >= len(available) / 2 and v == max(res . values()): result . append(k...
Team dinner: find the best acceptable date
64b1727867b45c41a262c072
[ "Fundamentals" ]
https://www.codewars.com/kata/64b1727867b45c41a262c072
6 kyu
# Task Create a function that returns a number which can block the player from reaching 3 in a row in a game of Tic Tac Toe. The number given as an argument will correspond to a grid of Tic Tac Toe: topleft is 0, topright is 2, bottomleft is 6, and bottomright is 8. Create a function that takes two numbers a, b and r...
algorithms
def block_player(a, b): y1, x1 = divmod(a, 3) y2, x2 = divmod(b, 3) y3 = (y2 + (y2 - y1)) % 3 x3 = (x2 + (x2 - x1)) % 3 return y3 * 3 + x3
Block the Square in Tic Tac Toe
64b7c3e6e0abed000f6cad6c
[ "Games", "Logic", "Algorithms" ]
https://www.codewars.com/kata/64b7c3e6e0abed000f6cad6c
7 kyu
# Task A staircase is given with a non-negative cost per each step. Once you pay the cost, you can either climb one or two steps. Create a solution to find the minimum sum of costs to reach the top (finishing the payments including `cost[-2]` or `cost[-1]`). You can either start at `cost[0]` or `cost[1]`. # Examples `...
algorithms
def climbing_stairs(cost): a = b = 0 for c in cost: a, b = b, min(a, b) + c return min(a, b)
Climbing Stairs
64b7c03910f916000f493f5d
[ "Logic", "Algorithms", "Dynamic Programming" ]
https://www.codewars.com/kata/64b7c03910f916000f493f5d
6 kyu
# Task The function is given a list of particles. The absolute value represents the particle mass. The sign of value represents the direction of movement: - Positive values move to the right. - Negative values move to the left. A positive value located on the left will collide with a negative value immediately locate...
algorithms
def moving_particles(lst): cur, ls = 0, lst[:] while cur < len(ls) - 1: if ls[cur] > 0 and ls[cur + 1] < 0: ls[cur: cur + 2] = [(ls[cur] - ls[cur + 1]) * (- 1 if ls[cur] < - ls[cur + 1] else 1)] cur = max(cur - 1, 0) else: cur += 1 return ls
Moving Particles
64b76b580ca7392eca9f886b
[ "Games", "Logic", "Algorithms" ]
https://www.codewars.com/kata/64b76b580ca7392eca9f886b
6 kyu
# Task The function is given a list of tuples. Each tuple has two numbers `tpl[0] < tpl[1]`. A chain can be made from these tuples that satisfies the condition: `(n1, n2) -> (n3, n4) -> ...` for each pair of consecutive tuples `n2 < n3`. Find the maximum length of such chain made from the given list. # Examples ``` l...
algorithms
from operator import itemgetter def len_longest_chain(pairs): res, x = 0, float('-inf') for a, b in sorted(pairs, key=itemgetter(1)): if x < a: res, x = res + 1, b return res
Find the Maximum Length of a Chain
64b779a194167920ebfbdd2e
[ "Arrays", "Logic" ]
https://www.codewars.com/kata/64b779a194167920ebfbdd2e
7 kyu
# Task The function is given a string consisting of a collection of three characters: - "(" open bracket - ")" closed bracket - "J" Joker, which can be replaced by "(", ")" or "" Develop a solution to determine if the given string represents a proper sequence of parenthesis; return `True / False`. Each open bracket o...
reference
def closed_brackets(s): a, b = 0, 0 for c in s: if c == ")" and b == 0: return False a = a + 1 if c == "(" else a and a - 1 b = b - 1 if c == ")" else b + 1 return not a
Closed Brackets String
64b771989416793927fbd2bf
[ "Algorithms", "Strings", "Recursion", "Stacks", "Dynamic Programming", "Data Structures" ]
https://www.codewars.com/kata/64b771989416793927fbd2bf
6 kyu
Been a while, but here's part 2! You are given a ```string``` of lowercase letters and spaces that you need to type out. In the string there is a special function: ```[shift]```. Once you encounter a ```[shift]``` , you ```capitalise``` the character right after it, as if you're actually holding the key. Return the f...
algorithms
import re def type_out(src): dst = src . split('[', 1)[0] for mo in re . finditer(r'\[(\w+)\]([^\[]+)', src): match mo[1]: case 'shift': dst += mo[2][0]. upper() + mo[2][1:] case 'holdshift': dst += mo[2]. upper() case 'unshift': dst += mo[2] return dst
Typing series #2 --> the [shift] function
64b63c024979c9001f9307e4
[]
https://www.codewars.com/kata/64b63c024979c9001f9307e4
6 kyu
# Task The function is given a string consisting of a mix of three characters representing which direction a domino is tilted: - "R" tilted to the right - "L" tilted to the left - "I" standing up, not tilted The string represents the initial state of the assembly. After a time click the overall state can change. The ...
games
from functools import partial from re import compile def helper(x): r, i, l = x . groups() if not (l or r): return i v = len(i) if not l: return "R" * (v + 1) if not r: return "L" * (v + 1) q, r = divmod(v, 2) return "R" * (q + 1) + "I" * r + "L" * (q ...
Let the Dominoes Fall Down
64b686e74979c90017930d57
[ "Algorithms", "Logic", "Regular Expressions", "Strings" ]
https://www.codewars.com/kata/64b686e74979c90017930d57
6 kyu
# Task The function is given a non-empty balanced parentheses string. Each opening `'('` has a corresponding closing `')'`. Compute the total score based on the following rules: - Substring `s == ()` has score `1`, so `"()"` should return `1` - Substring `s1s2` has total score as score of `s1` plus score of `s2`, s...
algorithms
def eval_parentheses(s): st = [0] for c in s: if c == '(': st . append(0) else: x = st . pop() st[- 1] += 2 * x or 1 return st . pop()
Evaluate the Group of Parentheses
64b6722493f1050058dc3f98
[ "Algorithms", "Logic", "Regular Expressions", "Strings" ]
https://www.codewars.com/kata/64b6722493f1050058dc3f98
6 kyu
# Task The function is given two equal size matrices of integers. Each cell holds a pixel: 1 represents a black pixel, 0 represents a white pixel. One of the images can be shifted in any two directions (up, down, left, right) relative to the other image by any number of cells, e.g. (2 up, 1 right) or (1 down, 0 left). ...
algorithms
from scipy . signal import correlate2d def max_overlap(img1, img2): return correlate2d(img1, img2). max()
Maximum Overlap of Two Images
64b6698c94167906c3fbd6c4
[ "Arrays", "Algorithms", "Data Structures" ]
https://www.codewars.com/kata/64b6698c94167906c3fbd6c4
6 kyu
Gymbro is at a Unique gym with unique bars for Bench pressing. Bars are made up of 40 hyphens ('-') each weighing 0.5kg, represented like this: ``----------------------------------------`` The plates are represented in the format '|Xkg|', where 'X' is the weight of the plate. For Example: ``['|4kg|', '|22kg|', '|10kg...
algorithms
from itertools import combinations as combs def configure_bar(goal, gym): d = {plate: 2 * int(plate[1: - 3]) - len(str(plate)) for plate in gym} w = sorted([d[plate] for plate in gym]) s = {v: k for k, v in d . items()} for n in [2, 4, 6]: for load in combs(w, n): if 40 + sum(load) ...
Gymbro's Unique Gym - Weight Calculator
64b41e7c1cefd82a951a303e
[ "Algorithms", "Performance", "Combinatorics" ]
https://www.codewars.com/kata/64b41e7c1cefd82a951a303e
4 kyu
**Intro:** Hear ye, hear ye! Brave programmers, wizards of the digital realm, I beseech thee to embark upon a quest of prime numbers and mystic algorithms! Prepare thine trusty Python 3.11 swords, for we shall traverse the mystical graph and unveil the **shortest path** betwixt two four-digit prime numbers, but thou sh...
algorithms
from collections import defaultdict from functools import reduce from itertools import pairwise from operator import or_ from gmpy2 import is_prime, next_prime def get_neighbours(): primes = {p for p in range(1000, 9999) if is_prime(p)} table = defaultdict(list) for n in primes: for a, b in...
Prime Path Finder
64b2b04e22ad520058ce22bd
[ "Graph Theory", "Number Theory", "Algorithms", "Data Structures", "Graphs" ]
https://www.codewars.com/kata/64b2b04e22ad520058ce22bd
5 kyu
## Introduction A [seven-segment display](https://en.wikipedia.org/wiki/Seven-segment_display) is an electronic device used to show decimal numerals. It consists of seven segments arranged in a rectangular shape. There are two vertical segments on each side and one horizontal segment at the top, middle, and bottom. By...
algorithms
segments = { ' ': 0b0000000, '0': 0b1111110, '1': 0b0110000, '2': 0b1101101, '3': 0b1111001, '4': 0b0110011, '5': 0b1011011, '6': 0b1011111, '7': 0b1110000, '8': 0b1111111, '9': 0b1111011 } def count_segment_switches(display_size, sequence): old = ' ' * ...
Seven-segment display: how many switches?
64a6e4dbb2bc0500171d451b
[ "Fundamentals" ]
https://www.codewars.com/kata/64a6e4dbb2bc0500171d451b
6 kyu
Telepathy: &nbsp;&nbsp; This is a simple magic trick. &nbsp;&nbsp; I find it fascinating after watching this magic trick. &nbsp;&nbsp; Here's how the trick goes: &nbsp;&nbsp; Firstly, the magician has 6 cards in hand. &nbsp;&nbsp; Then, the magician asks you to choose a number between 0 and 60 and remember it. &n...
games
f = magic_show = lambda a: len(a) and ( a[0] == 'Y') - ~ (a[0] in 'YN') * f(a[1:])
Telepathy
64ad571aa33413003e712168
[ "Puzzles", "Restricted", "Strings", "Mathematics" ]
https://www.codewars.com/kata/64ad571aa33413003e712168
6 kyu
The emperor of an archipelago nation has asked you to design a network of bridges to connect all the islands of his country together. But he wants to make the bridges out of gold. To see if he can afford it, he needs you to find the shortest total bridge length that can connect all the islands. Each island's bridges w...
algorithms
import math import heapq class DisjointSetUnion: def __init__(self, n): self . parent = list(range(n)) self . size = [1] * n def find(self, x): if self . parent[x] != x: self . parent[x] = self . find(self . parent[x]) return self . parent[x] def union(self, x, y): p...
Bridge the Islands
64a815e3e96dec077e305750
[ "Graph Theory", "Performance" ]
https://www.codewars.com/kata/64a815e3e96dec077e305750
4 kyu
&emsp; A space agency recently launched a new satellite with the primary goal of identifying the most suitable planet within a given solar system to support human life. The satellite is equipped to scan entire solar systems and add each detected planet to a list. The satellite uses the following format when inputting p...
reference
import re REQUIRED_ELEMENTS = {'H', 'C', 'N', 'O', 'P', 'Ca'} def best_planet(solar_system, max_size): candidates = [] for planet in solar_system: # Parse the planet elements, area = planet . split('_', 1) area = int(area) if area > max_size: continue elements = set...
Identify Best Planet
6474b8964386b6795c143fd8
[ "Strings", "Algorithms", "Searching" ]
https://www.codewars.com/kata/6474b8964386b6795c143fd8
6 kyu
# Squaredle solver ## Introduction [Squaredle](https://squaredle.app/) is a game in which players find words by connecting letters up, down, left, right and diagonally. Each square in the puzzle can be used only once. The purpose of this kata is to simulate a Squaredle player, finding all words in a puzzle. ### Task ...
games
from preloaded import WORDS from itertools import product DIRS = set(product(range(- 1, 2), repeat=2)) - {(0, 0)} class Trie: def __init__(self): self . root = {} def insert(self, word): cur = self . root for char in word: if char not in cur: cur[char] = {} cur = cur[c...
Squaredle solver
6495a5ad802ef5000eb70b91
[ "Puzzles", "Games", "Algorithms", "Strings" ]
https://www.codewars.com/kata/6495a5ad802ef5000eb70b91
4 kyu
Grayscale colors in RGB color model are colors that have the same values for Red, Green and Blue. For example, `#606060` is a grayscale color, while `#FF0055` is not. In order to correctly convert a color to grayscale, one has to use luminance Y for Red, Green and Blue components. One can calculate luminance Y through...
reference
def rgb_to_grayscale(color): """ #Assumes format: #RRGGBB Multiply and accumulate converted(str_hex->int) RR/GG/BB with corresponding luminance values. Convert the rounded result back to str_hex and remove the '0x' in front Add a '#' and use the str_hex result three times. """ return '...
Color to Grayscale
649c4012aaad69003f1299c1
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/649c4012aaad69003f1299c1
7 kyu
## Prologue: You get back from work late at night, roaming the streets of Japan (it has to be!). As you are headed home, starved after a long and grueling day at work, stumble upon a ramen shop still serving customers. You dash in, practically drooling for some ramen -- but as soon as you walk in, you realize just how ...
reference
from itertools import count NO_SWAP = (1, 3) def get_in_line(arr: list[int]) - > int: arr = [v for v in reversed(arr) if not v or v > 2] + \ [2] * arr . count(2) + [1] * arr . count(1) for time in count(1): match arr . pop(): case 1: for i in range(len(arr) >> 1): if arr[i...
LET ME IN!
6498aa0daff4420024ce2c88
[ "Fundamentals", "Performance" ]
https://www.codewars.com/kata/6498aa0daff4420024ce2c88
6 kyu
### Subsequences: [Subsequence](https://en.wikipedia.org/wiki/Subsequence) for the Kata is defined as following: __For a collection of numbers, a subsequence is one of the possible results you can get by removing some of the numbers from the collection, keep the original order.__ ``` Example: [1, 3, 5] All subseque...
algorithms
def no_adjacent_subsequences(lst): xs, ys = [[]], [[]] for v in lst: xs, ys = ys, ys + [x + [v] for x in xs] return ys
Subsequences with no adjacent items
6493682fbefb70000fc0bdff
[ "Algorithms", "Performance" ]
https://www.codewars.com/kata/6493682fbefb70000fc0bdff
6 kyu
# Description Below is described a skill tree: <!-- commented out this cool css tree since codewars broke css rendering --> <!-- <html> <body> <style> <!-- credit to codepen.io/Gerim :) > .body { } .tree ul { margin: 0; padding: 0; padding-top: 20px; position: relative; tran...
algorithms
def count_skills(tree, required): skils = set() for r in required: while r not in skils: skils . add(r) r = tree[r] return len(skils)
Skills Master
648f2033d52f51608e06c458
[ "Algorithms", "Data Structures", "Graph Theory", "Trees" ]
https://www.codewars.com/kata/648f2033d52f51608e06c458
6 kyu
_This Kata is intended to be a simple version of [Binary with unknown bits: average to binary](https://www.codewars.com/kata/6440554ac7a094000f0a4837)._ _The main difference is that in this Kata, input `n` will only be an __integer__, and only consider those binary string with exactly __one__ `x` (or cases of 0 and 1...
games
def average_to_binary(n): res, ln = {'x' + f' { n : b } ' [1:] } if n > 1 else {f' { n } '}, len(f' { n : b } ') for k in range(ln - 2): cand = f' { n - 2 * * k : b } ' if cand[- k - 2] == '0': res . add(cand[: - k - 2] + 'x' + cand[- k - 1:]) return res
Binary with an unknown bit: average to binary (Simple Version)
6484e0e4fdf80be241d85878
[ "Binary", "Strings", "Performance", "Mathematics" ]
https://www.codewars.com/kata/6484e0e4fdf80be241d85878
6 kyu
In [another Kata](https://www.codewars.com/kata/64348795d4d3ea00196f5e76) you calculated the `average number` from a string of binary with unknown bits, using the rules (see rules section below). We now define `average` as the result calculated in the way described in that Kata. ___ ### Average to Binary You need ...
games
from functools import cache from itertools import chain @ cache def f(n): match n: case 0.5: return [] case 0: return [''] case 1: return ['1', 'x'] match n % 1: case 0.5: return [s + 'x' for s in f((n - 0.5) / 2)] case 0: return [* chain([s + 'x' for s in f((n - 0.5) / 2)], ...
Binary with unknown bits: average to binary
6440554ac7a094000f0a4837
[ "Mathematics", "Binary", "Performance", "Strings", "Puzzles" ]
https://www.codewars.com/kata/6440554ac7a094000f0a4837
4 kyu
### Task If possible, divide the integers 1,2,…,n into two sets of equal sum. ### Input A positive integer n <= 1,000,000. ### Output If it's not possible, return [ ] (Python, Javascript, Swift, Ruby) or ( ) (Python) or [ [],[] ] (Java, C#, Kotlin) or None (Scala). <br> If it's possible, return two disjoint sets...
games
def create_two_sets_of_equal_sum(n): if n % 4 in {1, 2}: return [] return [[* range(1, n / / 4 + 1), * range(n * 3 / / 4 + 1, n + 1)], [* range(n / / 4 + 1, n * 3 / / 4 + 1)]]
Two Sets of Equal Sum
647518391e258e80eedf6e06
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/647518391e258e80eedf6e06
6 kyu
## Problem Statement *This kata is an easier version of&nbsp; [this kata](https://www.codewars.com/kata/60228a9f85a02c0022379542). If you like this kata, feel free to try the harder version.* You are given the outcomes of a repeated experiment in the form of a list of zeroes and ones,&nbsp; e.g.&nbsp; `[1, 0, 0, 1, 1...
reference
def solve(arr, k): max_mean = 0 tapir = () for i in range(len(arr) - k + 1): sum_slice = 0 for j in range(len(arr)): sum_slice += arr[j] if j + 1 >= k + i: if sum_slice / (k + i) >= max_mean: max_mean = sum_slice / (k + i) tapir = (j - (k + i - 1), k + i) sum_slice...
Longest Subarray with Maximum Average Value
60983b03bdfe880040c531d6
[ "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/60983b03bdfe880040c531d6
5 kyu
Consider the process of stepping from integer x to integer y. The length of each step must be a positive integer, and must be either one bigger, or equal to, or one smaller than, the length of the previous step. The length of the first and last steps must be 1. Create a function that computes the minimum number of ste...
games
def step(x, y): return int((4 * (y - x) - (y > x)) * * .5)
Steps
6473603854720900496e1c82
[ "Puzzles", "Mathematics", "Combinatorics" ]
https://www.codewars.com/kata/6473603854720900496e1c82
7 kyu
### Background Pat Programmer is worried about the future of jobs in programming because of the advance of AI tools like ChatGPT, and he decides to become a chef instead! So he wants to be an expert at flipping pancakes. A pancake is characterized by its diameter, a positive integer. Given a stack of pancakes, you ca...
reference
def flip_pancakes(stack): tp, st, res = len(stack) - 1, stack[:], [] while tp > 0: if st[tp] != max(st[: tp + 1]): ind = max(range(tp + 1), key=lambda k: st[k]) st = st[ind + 1: tp + 1][:: - 1] + st[: ind + 1] + st[tp + 1:] res . extend([ind] * (ind > 0) + [tp]) tp -= 1 return ...
Flip Your Stack (of Pancakes)
6472390e0d0bb1001d963536
[ "Arrays", "Sorting" ]
https://www.codewars.com/kata/6472390e0d0bb1001d963536
6 kyu
A Euler square (also called a Graeco-Latin square) is a pair of orthogonal latin squares. A latin square is an n × n array filled with the integers 1 to n each occurring once in each row and column - see [Latin Squares](https://www.codewars.com/kata/645fb55ecf8c290031b779ef). Two latin squares are orthogonal if each *r...
games
def create_euler_square(n): # Assume n is odd. return [[(i + j) % n + 1 for j in range(n)] for i in range(n)], \ [[(2 * i + j) % n + 1 for j in range(n)] for i in range(n)]
Euler Squares
6470e15f4f0b26052c6151cd
[ "Algorithms", "Arrays" ]
https://www.codewars.com/kata/6470e15f4f0b26052c6151cd
6 kyu
# Task Write a function which when given a non-negative integer `n` and an arbitrary base `b`, returns the number reversed in that base. # Examples - `n=12` and `b=2` return 3, because 12 in binary is "1100", which reverses to "0011", equivalent to 3 in decimal. - `n=10` and `b=5` return 2, because 10 in base-5 is ...
algorithms
def reverse_number(n, b): if b == 1: return n m = 0 while n: n, r = divmod(n, b) m = m * b + r return m
Reverse a number in any base
6469e4c905eaefffd44b6504
[ "Algorithms" ]
https://www.codewars.com/kata/6469e4c905eaefffd44b6504
7 kyu
### Background A **latin square** is an n × n array filled with the integers 1 to n, each occurring once in each row and column. Here are examples of latin squares of size 4 and 7: ``` [[1, 4, 3, 2], [[2, 3, 1, 7, 4, 6, 5], [4, 3, 2, 1], [7, 1, 6, 5, 2, 4, 3], [3, 2, 1, 4], [6, 7, 5, 4, 1, 3, 2], ...
algorithms
def verify_latin_square(array, m): def validate(): if not is_square(array): return "Array not square" if not is_correct_size(array, m): return "Array is wrong size" value_error = fail_not_correct_values() if value_error: return value_error return f"Valid latin square of size...
Latin Square Validator
646254375cee7a000ffaa404
[ "Strings", "Arrays" ]
https://www.codewars.com/kata/646254375cee7a000ffaa404
6 kyu
# Background Most numbers contain the digit `1`; some do not. The percentage of integers below `10^7` (ten million) containing the digit `1` is already 53%! As we consider larger and larger numbers, the percentage of integers containing the digit `1` tends towards 100%. # Problem Description In this kata, you are re...
algorithms
def nth_num_containing_ones(n, digit=1, base=10): assert 0 < digit < base n, a, nth = n - 1, [0], 0 while n >= a[- 1]: a . append((base - 1) * a[- 1] + base * * (len(a) - 1)) a . pop() while a: x = a . pop() l = base * * len(a) if 0 <= n - digit * x < l: nth = (base *...
N-th Integer Containing the Digit 1
64623e0ad3560e0decaeac26
[ "Number Theory", "Performance", "Mathematics" ]
https://www.codewars.com/kata/64623e0ad3560e0decaeac26
4 kyu
A **latin square** is an n × n array filled with the integers 1 to n, each occurring once in each row and column. Here are examples of latin squares of size 4 and 7: ``` [[1, 4, 3, 2], [[2, 3, 1, 7, 4, 6, 5], [4, 3, 2, 1], [7, 1, 6, 5, 2, 4, 3], [3, 2, 1, 4], [6, 7, 5, 4, 1, 3, 2], [2, 1, 4, 3]]...
algorithms
def make_latin_square(n): return [[(i + j) % n + 1 for i in range(n)] for j in range(n)]
Latin Squares
645fb55ecf8c290031b779ef
[ "Arrays" ]
https://www.codewars.com/kata/645fb55ecf8c290031b779ef
7 kyu
Given a train track with some trains on it, then the same train track after some time has passed, return True if the arrangement is valid, otherwise return False. For example, this is valid: ``` before: ">....." after: ".....>" ``` In this example, a train is facing right. In the `before` time, it is at the beginni...
algorithms
def is_valid_train_arrangement(before, after): if len(before) != len(after): return False l, r = 0, 0 for b, a in zip(before, after): if b == '>': if l != 0: return False r += 1 if a == '<': if r != 0: return False l -= 1 if b == '<': if r != 0 or l ==...
The Train Problem
645e541f3e6c2c0038a01216
[ "Algorithms", "Strings", "Performance" ]
https://www.codewars.com/kata/645e541f3e6c2c0038a01216
6 kyu
# Background Palindromes are a special type of number (in this case a non-negative integer) that reads the same backwards as forwards. A number defined this way is called __palindromic__. * The following numbers are palindromes: `0`, `252`, `769967`, `1111111`. * The following numbers are __not__ palindromes: `123...
algorithms
from math import floor, ceil def less_than(s): if s[0] == '-': return 0 n = int(s[0:(len(s) + 1) / / 2]) + 10 * * (len(s) / / 2) if s[- (len(s) / / 2):] < s[len(s) / / 2 - 1:: - 1]: return n - 1 return n def count_palindromes(a, b): a, b = ceil(a), floor(b) if a > b: ...
Palindrome Counter
64607242d3560e0043c3de25
[ "Number Theory", "Mathematics", "Performance" ]
https://www.codewars.com/kata/64607242d3560e0043c3de25
4 kyu
# Find all the dividers! You are given a list of prime numbers (e.g. ``[5, 7, 11]``) and a list of their associated powers (e.g. ``[2, 1, 1]``). The product of those primes at their specified power forms a number ``x`` (in our case ``x = 5^2 * 7^1 * 11^1 = 1925``). ### Your goal is to find all of the dividers for thi...
algorithms
from itertools import product from operator import pow from math import prod def get_dividers(values, powers): return sorted(prod(map(pow, values, x)) for x in product(* (range(p + 1) for p in powers)))
Dividers of primes
64600b4bbc880643faa343d1
[ "Mathematics" ]
https://www.codewars.com/kata/64600b4bbc880643faa343d1
6 kyu
### Background Suppose your doctor tells you that you have tested positive for a disease using a test that is 95% accurate. What's the probability that you actually have the disease? Surprisingly, the answer is much lower than 95%! Most doctors, not having much training in statistics, don't know this. The mathematica...
reference
import random import numpy def simulate(disease_rate, false_positive_rate, n): ntp = numpy . random . binomial(n, disease_rate) nfp = numpy . random . binomial(n - ntp, false_positive_rate) return [* random . sample(range(n), ntp)], ntp + nfp
Why You Shouldn't Believe Your Doctor
640f312ababb19a6c5d64927
[ "Simulation", "Statistics", "Tutorials" ]
https://www.codewars.com/kata/640f312ababb19a6c5d64927
6 kyu
# Warcraft Series I - Mining Gold Greetings! The kata is inspired by my favorite strategy game, Warcraft 3, where players control units to gather resources and build their base. In this kata, the goal is to create a program that simulates the process of gathering gold from a mine and transporting it to a base. The Wo...
reference
class Worker (): def __init__(self, position, direction, base): self . position = position self . direction = direction self . base = base def move(self): if self . position == 0: self . direction = 1 if self . position == self . base: self . direction = - 1 self . posi...
Warcraft Series I - Mining Gold
64553d6b1a720c030d9e5285
[ "Games", "Object-oriented Programming" ]
https://www.codewars.com/kata/64553d6b1a720c030d9e5285
6 kyu
# Intro: In this kata you will create a linear feedback shift register (LFSR). An LFSR is used to generate a stream of (pseudo) random numbers/bits. It is most commonly implemented directly in hardware but here we'll do a software implementation. # How does it work: The register has XOR gates at given bit-positions ...
algorithms
def lfsr(size, pos, seed): mask = sum(1 << i for i in pos) while True: yield seed seed = seed >> 1 | ((seed & mask). bit_count() & 1) << size - 1
Linear Feedback Shift Register
645797bd67ad1d92efea25a1
[ "Algorithms", "Binary", "Bits" ]
https://www.codewars.com/kata/645797bd67ad1d92efea25a1
6 kyu
The Fibonacci numbers are the numbers in the integer sequence: `0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, ...` Defined by the recurrence relation Fib(0) = 0 Fib(1) = 1 Fib(2) = 1 Fib(i) = Fib(i-1) + Fib(i-2) For an...
algorithms
def pisano(n): a, b, k = 1, 1, 1 while (a, b) != (0, 1): a, b = b, (a + b) % n k += 1 return k
Pisano Period
5f1360c4bc96870019803ae2
[ "Mathematics", "Algorithms", "Arrays" ]
https://www.codewars.com/kata/5f1360c4bc96870019803ae2
7 kyu
## <span style="color:#0ae">Introduction</span> A [look-and-say sequence](https://en.wikipedia.org/wiki/Look-and-say_sequence) is an integer sequence. To generate a member of the sequence from the previous member, read off the digits of the previous member, counting the number of digits in groups of the same digit. E...
reference
def starting_number(n): a, b = str(n), '' while a != b and len(a) % 2 == 0 and '0' not in a[:: 2] and all(x != y for x, y in zip(a[1:: 2], a[3:: 2])): a, b = '' . join(a[k + 1] * int(a[k]) for k in range(0, len(a), 2)), a if a[0] == '0' and len(a) > 1: return int(b) if '00' in a or (len(a)...
Reverse look and say
644ff2d6080a4001ff59a3b9
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/644ff2d6080a4001ff59a3b9
6 kyu
"Pits" and "lands" are physical features on the surface of a CD that represent binary data. Pits are small depressions or grooves on the surface of the CD, while lands are flat areas between two adjacent pits. The pits and lands themselves do not directly represent the zeros and ones of binary data. Instead, Non-retur...
reference
def encode_cd(n): if n > 255: return - 1 forma = format(n, '08b') form = forma[:: - 1] res = "P" p = 'P' l = 'L' for f in form: if f == '1': # 1 it is always change letter to another letter p, l = l, p res += p return res
Encode data on CD (Compact Disc) surface
643a47fadad36407bf3e97ea
[ "Binary" ]
https://www.codewars.com/kata/643a47fadad36407bf3e97ea
7 kyu
Many programming languages provide the functionality of converting a string to uppercase or lowercase. For example, `upcase`/`downcase` in Ruby, `upper`/`lower` in Python, and `toUpperCase`/`toLowerCase` in Java/JavaScript, `uppercase`/`lowercase` in Kotlin. Typically, these methods won't change the size of the string....
reference
STRANGE_STRING = 'ß'
Up and down, the string grows
644b17b56ed5527b09057987
[ "Strings", "Puzzles" ]
https://www.codewars.com/kata/644b17b56ed5527b09057987
8 kyu
```if:csharp Given 8 byte variable (Uint64) extract `length` of bits starting from least significant bit* and skipping `offset` of bits. ``` ```if:python Given `int` variable extract `length` of bits starting from least significant bit* and skipping `offset` of bits. For convenience sake only first 64 bits of input var...
reference
def extract_bits(o, _, O): return o >> _ & ~ - (1 << O)
Extract bits from integer
6446c0fe4e259c006511b75e
[ "Bits" ]
https://www.codewars.com/kata/6446c0fe4e259c006511b75e
7 kyu
Confusion, perplexity, a mild headache. These are just a sample of the things you have experienced in the last few minutes while trying to figure out what is going on in your code. The task is very simple: accept a list of values, and another value `n`, then return a new list with every value multiplied by `n`. For ex...
bug_fixes
def mul_by_n(lst, n): print("Inputs: ", lst, n) # Check our inputs result = [x * n for x in lst] print("Result: ", result) # Check our result return result
Vexing Vanishing Values
644661194e259c035311ada7
[ "Debugging", "Refactoring" ]
https://www.codewars.com/kata/644661194e259c035311ada7
8 kyu
# Rook Count Attack This kata is focused on counting the number of attacks between rooks that are attacking each other on a standard 8x8 chessboard. A <code>rook</code> is a chess piece that can move horizontally or vertically across any number of squares on the board. ### How the rook moves <img src="https://live.st...
reference
def count_attacking_rooks(rooks): s1 = set(item[0] for item in rooks) s2 = set(item[1] for item in rooks) return len(rooks) * 2 - len(s1) - len(s2)
Rook Count Attack
64416600772f2775f1de03f9
[ "Arrays" ]
https://www.codewars.com/kata/64416600772f2775f1de03f9
6 kyu
You have done some data collection today and you want the data to be well presented by a graph so you have decided to make a quick diagram. Suppose that for this kata your data is presented by an array by their value eg [10,5,3,1,4], then you must present your data as follows: ``` for data = [10,5,3,1,4] : ____ .......
games
def graph(arr): graph = [] top = max(arr, default=- 1) for y in range(top, - 1, - 1): row = [] for value in arr: if value == y: row . append(' ____ ') elif value < y: row . append('......') else: row . append('| |') row . append(f' { "^|" [ y < top...
Let's do a fun graph
6444f6b558ed4813e8b70d43
[ "Strings", "Arrays", "ASCII Art" ]
https://www.codewars.com/kata/6444f6b558ed4813e8b70d43
6 kyu
# Task Your task is to check whether a segment is completely in one quadrant or it crosses more. Return `true` if the segment lies in two or more quadrants. If the segment lies within only one quadrant, return `false`. There are two parameters: `A` _(coord)_ and `B` _(coord)_, the endpoints defining the segment `AB`. ...
reference
def quadrant_segment(A, B): A = A[0] < 0, A[1] < 0 B = B[0] < 0, B[1] < 0 return A != B
Quadrants 2: Segments
643ea1adef815316e5389d17
[ "Fundamentals", "Mathematics", "Geometry" ]
https://www.codewars.com/kata/643ea1adef815316e5389d17
7 kyu