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 |
|---|---|---|---|---|---|---|---|
# Task
Given a point in a [Euclidean plane](//en.wikipedia.org/wiki/Euclidean_plane) (`x` and `y`), return the quadrant the point exists in: `1`, `2`, `3` or `4` (integer). `x` and `y` are non-zero integers, therefore the given point never lies on the axes.
# Examples
```
(1, 2) => 1
(3, 5) => 1
(-10, 100) => ... | reference | def quadrant(x, y): return ((1, 2), (4, 3))[y < 0][x < 0]
| Quadrants | 643af0fa9fa6c406b47c5399 | [
"Fundamentals",
"Mathematics",
"Geometry"
] | https://www.codewars.com/kata/643af0fa9fa6c406b47c5399 | 8 kyu |
### Background:
[Wikidata](https://www.wikidata.org/wiki/Wikidata:Main_Page) is a public database with over a hundred million entries in it. You can find almost anything documented, from scientific articles to new species scientists have found.
To help developers use the site better, the website provides accessible J... | algorithms | import requests
def wikidata_scraper(url):
res = requests . get(url). json()
entry = list(res['entities']. values())[0]
return {
"ID": entry['id'],
"LABEL": entry['labels']. get('en', {'value': 'No Label'})['value'],
"DESCRIPTION": entry['descriptions']. get('en', {'valu... | Wikidata Json Scraper | 643869cb0e7a563b722d50ad | [
"Algorithms",
"Web Scraping",
"Searching",
"JSON",
"Filtering"
] | https://www.codewars.com/kata/643869cb0e7a563b722d50ad | 6 kyu |
# Binary with unknown bits:
You received a string of a __binary number__, but there are some `x` in it. It cannot be used, so the solution is to get the average of all possible numbers.
___
# Rule:
* The string consists of `0`, `1` and `x`, if it has 2 or more bits, it would have at least one `x`.
* Unless the nu... | algorithms | def binary_average(binary):
if len(binary) > 1 and binary[0] == 'x':
binary = '1' + binary[1:]
a = int(binary . replace('x', '1'), 2)
b = int(binary . replace('x', '0'), 2)
return (a + b) / 2
| Binary with unknown bits: the average | 64348795d4d3ea00196f5e76 | [
"Mathematics",
"Binary",
"Performance"
] | https://www.codewars.com/kata/64348795d4d3ea00196f5e76 | 6 kyu |
You know you can convert a floating-point value to an integer, and you can round up, down, etc? How about going the other way around, converting an integer to floating-point, rounding up/down?
# Task description
Define two functions, each one taking an integer `n` and returning a double-precision (officially, 'binary... | reference | from gmpy2 import RoundDown, RoundUp, context
from sys import float_info
def ifloor(n: int) - > float:
return float(context(round=RoundDown, emax=float_info . max_exp). rint(n))
def iceil(n: int) - > float:
return float(context(round=RoundUp, emax=float_info . max_exp). rint(n))
| Convert integer to float while rounding up and down | 642eba25b8c5c20031058225 | [
"Language Features",
"Big Integers"
] | https://www.codewars.com/kata/642eba25b8c5c20031058225 | 6 kyu |
For a long time little Annika had wanted to contribute to the ARM64 port of the Factor language. One day she finally could grasp where to start and fell into a rabbit hole learning ARM assembly and started finishing the non-optimizing compiler.
In the process of debugging an unrelated segfault, she realized that the 1... | algorithms | def logical_immediate(imm64):
b = f' { imm64 :0 64 b } '
for i in range(1, 7):
l = 2 * * i
for w in range(1, l):
for immr in range(l):
z = '0' * (l - w) + '1' * w
y = (z[- immr:] + z[: - immr]) * (64 / / l)
if y == b:
r = f' { 2 * * ( 7 - i ) - 2 : 0 b }{ w - 1 : 0 { i } b }... | Logical immediates | 6426b201e00c7166d61f2028 | [
"Binary",
"Algorithms"
] | https://www.codewars.com/kata/6426b201e00c7166d61f2028 | 5 kyu |
# Task:
In this Golfing Kata, you are going to receive 2 non-negative numbers `a` and `b`, `b` is equal to or greater than `a`.
Then do the following procedure:
* Add `a` to `b`, then divide it by `2` with __integer division__.
* Repeat the procedure until `b` is equal to `a`.
* Return how many times it took to ma... | games | def f(a, b): return (b - a). bit_length()
| [Code Golf] How many times of getting closer until it is the same? | 642b375dca15841d3aaf1ede | [
"Mathematics",
"Restricted"
] | https://www.codewars.com/kata/642b375dca15841d3aaf1ede | 7 kyu |
This is a challenge version of [Sudoku board validator](https://www.codewars.com/kata/sudoku-board-validator); if you haven't already, you should do that first.
The rules stay mostly the same: Your task is to write a function that takes a 9x9 sudoku board as input and returns a boolean indicating if the board is valid... | games | def validate_sudoku(b, R=range): return all({* r} == {* R(1, 10)} for r in [* zip(* b)] + b + [[b[i / / 3 * 3 + j / / 3][i % 3 * 3 + j % 3] for j in R(9)] for i in R(9)])
| Sudoku board validator - Code Golf | 63e5119516648934be4c98bd | [
"Algorithms",
"Games",
"Restricted"
] | https://www.codewars.com/kata/63e5119516648934be4c98bd | 5 kyu |
You've found yourself a magic box, which seems to break the laws of physics.
You notice that if you put some money in it, it seems to spit out more money than was put in. Free money right?
In time you notice the following facts:
- If you start with N dollars, using the box twice yields exactly 3*N dollars
- You never... | games | from math import log
# 6kyu????????????????
def f(n):
if not n:
return 0
k = 3 * * int(log(n) / log(3))
z = 2 * max(0, n - 2 * k)
return n + z + k
| Triple your Money! | 64294e2be00c71422d1f59c2 | [
"Mathematics",
"Number Theory",
"Performance"
] | https://www.codewars.com/kata/64294e2be00c71422d1f59c2 | 6 kyu |
Same task as [Total area covered by rectangles][kata-easier] but now there are more rectangles.
[kata-easier]: https://www.codewars.com/kata/55dcdd2c5a73bdddcb000044
# Task
Write a function `calculate` that, given a list of rectangles, finds the area of their union.
Each rectangle is represented by four integers <c... | algorithms | from math import log2, ceil
def calculate(rectangles):
if not rectangles:
return 0
events = []
ys = set()
for x0, y0, x1, y1 in rectangles:
events . append((x0, y0, y1, 1))
events . append((x1, y0, y1, - 1))
ys . add(y0)
ys . add(y1)
events . sort()
ys = sor... | Total area covered by more rectangles | 6425a1463b7dd0001c95fad4 | [
"Algorithms",
"Data Structures",
"Geometry",
"Performance"
] | https://www.codewars.com/kata/6425a1463b7dd0001c95fad4 | 2 kyu |
## Task
Your task is to write a function that accept a single parameter - a whole number `N` and generates an array with following properties.
1. There are exactly 2 * N + 1 elements in this array
2. There is only one 0 (zero) in array
3. Other elements are pairs of natural numbers from 1 to N
4. Number of elements ... | algorithms | def generate(n):
return [0] if n <= 0 else [
* reversed(range(2, n, 2)),
n, 0,
* range(2, n, 2),
* reversed(range(1, n, 2)),
n,
* range(1, n, 2),
]
| Array with distance of N | 6421c6b71e5beb000fc58a3e | [
"Algorithms",
"Arrays",
"Performance"
] | https://www.codewars.com/kata/6421c6b71e5beb000fc58a3e | 5 kyu |
You are in the process of creating a new framework. In order to enhance flexibility, when your user assigns value to an instance attribute, you want to give them the option to supply a callable without arguments instead. When the attribute is accessed, either the assigned value (as usual), or the result of the call (if... | reference | from inspect import ismethod
class Setting:
def __getattribute__(self, name):
attr = super(). __getattribute__(name)
return attr() if callable(attr) and not ismethod(attr) else attr
| Optionally callable attributes | 641c4d0e88ce6d0065531b88 | [
"Object-oriented Programming",
"Language Features"
] | https://www.codewars.com/kata/641c4d0e88ce6d0065531b88 | 6 kyu |
<h1> Situation </h1>
After giving out the final Calculus II exam, you come to a frightening realization. Only 4 of your 100 students passed.
How could this be?!? Maybe you're not a such great teacher? No, that can't be; your iΜΆnΜΆfΜΆeΜΆrΜΆiΜΆoΜΆrΜΆsΜΆ students are definitely the problem here. How **dare** they not know how t... | algorithms | def curve(g): return g * * .5 / / .0999
| [Code Golf] Save Your Students | 641d08d7a544092654a8b29c | [
"Mathematics",
"Restricted",
"Statistics"
] | https://www.codewars.com/kata/641d08d7a544092654a8b29c | 7 kyu |
# Async Request Manager | Don't let server down!
**Note**: this kata is slightly extended version of this kata:
https://www.codewars.com/kata/62c702489012c30017ded374
Feel free to check it out first if you wish or if you
have problems with solving this little bit harder one.
Original requirements:
---
Your task is... | reference | import asyncio
async def send_request_politely(s: asyncio . Semaphore) - > str:
async with s:
return await send_request()
async def request_manager(n: int) - > str:
s = asyncio . Semaphore(150)
return "" . join(await asyncio . gather(* (send_request_politely(s) for _ in range(n))))
| Async Requests | Don't let server down! | 6417797d022e4c003ebbd575 | [
"Asynchronous"
] | https://www.codewars.com/kata/6417797d022e4c003ebbd575 | 6 kyu |
Write a function that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return `true` if the string is valid, and `false` if it's invalid.
## Examples
```
"()" => true
")(()))" => false
"(" => false
"(())((()())())" => ... | algorithms | def valid_parentheses(x):
while "()" in x:
x = x . replace("()", "")
return x == ""
| Valid Parentheses | 6411b91a5e71b915d237332d | [
"Strings",
"Parsing",
"Algorithms"
] | https://www.codewars.com/kata/6411b91a5e71b915d237332d | 7 kyu |
Task
----
Write a function that reflects a point over a given line and returns the reflected point as a tuple.
Arguments:
- point: a tuple of the form `$(x, y)$` representing the coordinates of the point to be reflected.
- line: a tuple of the form `$(m, b)$` representing the slope-intercept equation of the line `$y... | games | def reflect(point, line):
x, y = point
a, c = line
return x - 2 * a * (a * x - y + c) / (a * * 2 + 1), y + 2 * (a * x - y + c) / (a * * 2 + 1)
| Reflect Point Over Line | 64127b25114de109258fb6fe | [
"Mathematics",
"Geometry"
] | https://www.codewars.com/kata/64127b25114de109258fb6fe | 7 kyu |
You have a square shape of 4x4, you need to find out by what criterion there are cute and not cute patterns in these cases:
[](https://www.linkpicture.com/view.php?img=LPic640875a1a4c02163944404)
According to the given arrangement of tiles, it is required to determine... | games | import re
def cute_pattern(tiles):
return not re . search(r"BB...BB|WW...WW", tiles, re . DOTALL)
| [Mystery #1] - Cute Pattern | 64087fd72daf09000f60dc26 | [
"Puzzles"
] | https://www.codewars.com/kata/64087fd72daf09000f60dc26 | 7 kyu |
## Pythagorean Triples
A Pythagorean triple consists of three positive integers _a, b, c_, which satisfy the Pythagorean formula for the sides of a right-angle triangle: _aΒ² + bΒ² = cΒ²_. For simplicity we assume _a < b < c_.
A easy way of generating Pythagorean triples is to rewrite the equation as _aΒ² = cΒ² - bΒ² = (c-... | reference | def create_pythagorean_triples(diff, low, high):
return [(a, a * a / / diff - diff >> 1, a * a / / diff + diff >> 1) for a in range(low, high + 1)
if not a * a % diff and a * a / / diff % 2 == diff % 2 and 2 * a + diff < a * a / / diff]
| A Fun Way of Finding Pythagorean Triples | 640aa37b431f2da51c7f27ae | [
"Geometry",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/640aa37b431f2da51c7f27ae | 6 kyu |
<strong>Task</strong>
Find the volume of the largest cube that will fit inside a cylinder of given height <code>h</code> and radius <code>r</code>.
Don't round your result. The result needs to be within <code>0.01</code> error margin of the expected result.
HINT: There are two cases to consider. Will it be the cylin... | games | def cube_volume(h, r):
return min(h, r * 2 * * .5) * * 3
| Volume of the Largest Cube that Fits Inside a Given Cylinder | 581e09652228a337c20001ac | [
"Geometry",
"Mathematics"
] | https://www.codewars.com/kata/581e09652228a337c20001ac | 7 kyu |
**Description**:
To get to the health camp, the organizers decided to order buses. It is known that some children `kids` and adults `adults` are going to go to the camp. Each bus has a certain number of seats `places`. There must be at least two adults on each bus in which children will travel.
Determine whether it w... | reference | from math import ceil
import math
def buses(kids, adults, places):
if places == 0:
return 0
buses_by_people = math . ceil((kids + adults) / places)
if adults < (buses_by_people * 2) and kids > 0:
return 0
else:
return buses_by_people
| Buses! | 640dee7cbad3aa002e7c7de4 | [
"Mathematics"
] | https://www.codewars.com/kata/640dee7cbad3aa002e7c7de4 | 7 kyu |
This is a rather simple but interesting kata. Try to solve it using logic. The shortest solution can be fit into one line.
## Task
The point is that a natural number N (1 <= N <= 10^9) is given. You need to write a function which finds the number of natural numbers not exceeding N and not divided by any of the number... | algorithms | def real_numbers(n):
return n - n / / 2 - n / / 3 - n / / 5 + n / / 6 + n / / 10 + n / / 15 - n / / 30
| Mysterious Singularity Numbers | 6409aa6df4a0b773ce29cc3d | [
"Fundamentals",
"Logic",
"Mathematics",
"Arrays",
"Algorithms",
"Performance"
] | https://www.codewars.com/kata/6409aa6df4a0b773ce29cc3d | 7 kyu |
Imagine a honeycomb - a field of hexagonal cells with side `N`. There is a bee in the top left cell `A`. In one move it can crawl one cell down, one cell down-right or one cell up-right (the bee does not crawl up or left).
<!-- Embed Image as SVG -->
<svg width="106.97mm" height="53.56mm" version="1.1" viewBox="0 0 10... | algorithms | def the_bee(n):
cells = [0] * (2 * n + 1)
cells[n] = 1
for i in range(1, 4 * n - 2):
for j in range(i % 2 + 1, 2 * n, 2):
cells[j - 1] += cells[j]
cells[j + 1] += cells[j]
return cells[n]
| The Bee | 6408ba54babb196a61d66a65 | [
"Algorithms",
"Mathematics",
"Matrix",
"Puzzles",
"Performance",
"Dynamic Programming"
] | https://www.codewars.com/kata/6408ba54babb196a61d66a65 | 5 kyu |
Your task is to find the maximum number of queens that can be put on the board so that there would be one single unbeaten square (ie. threatened by no queen on the board).
The Queen can move any distance vertically, horizontally and diagonally.
## Input
The queens(n) function takes the size of the chessboard.
`$n... | games | def queens(n):
return (n - 2) * (n - 1) if n >= 3 else 0
| Finding queens on the board | 64060d8ab2dd990058b7f8ee | [
"Algorithms"
] | https://www.codewars.com/kata/64060d8ab2dd990058b7f8ee | 7 kyu |
To earn a huge capital, you need to have an unconventional mindset. Of course, with such a complex job, there must also be special mechanisms for recreation and entertainment. For this purpose, the casino came up with a special domino set. Ordinary dominoes are a set of different combinations of two tiles, each display... | algorithms | def dots_on_domino_bones(n):
if n < 0:
return - 1
return (n + 2) * (n + 1) * n / / 2
| Dots on Domino's Bones | 6405f2bb2894f600599172fd | [
"Mathematics",
"Games",
"Algorithms"
] | https://www.codewars.com/kata/6405f2bb2894f600599172fd | 7 kyu |
# Problem Description
```
,@@@@@@@@@@@@@@@,
@@@& @@@@
*@@ (@@@@@* /@@@@@/ @@,
@@ @@@ ... | games | from functools import reduce
def number_of_coins(tips):
# Let's do some math magic to get our total coin count
M = reduce(lambda x, y: x * y[1], tips, 1)
# Time to collect all these shiny coins!
s = sum([coin * (M / / tip) * pow((M / / tip), - 1, tip) for coin, tip in tips])
return s % M # We got... | Find Out the Number of Gold Coins! | 6402d27bf4a0b7d31c299043 | [
"Mathematics",
"Number Theory"
] | https://www.codewars.com/kata/6402d27bf4a0b7d31c299043 | 5 kyu |
You need to hire a catering company out of three for lunch in a birthday party. The first caterer offers only a `basic buffet` which costs $15 per person. The second one has an `economy buffet` at $20 per person and the third one has a `premium buffet` at $30 per person. The third one gives a 20% discount if the number... | reference | def find_caterer(budget, people):
if people != 0:
pp = budget / people
if pp < 15:
return - 1
elif pp < 20:
return 1
elif pp < 24 or (pp < 30 and people <= 60):
return 2
else:
return 3
return - 1
| Find your caterer | 6402205dca1e64004b22b8de | [
"Fundamentals"
] | https://www.codewars.com/kata/6402205dca1e64004b22b8de | 7 kyu |
# Adjust barbell
## Kata overview
Olympic weightlifting is a sport in which athletes compete in lifting a barbell from the ground to overhead, with the aim of successfully lifting the heaviest weights.
The purpose of this kata is to simulate a Olympic barbell loader, changing the weights from lift to lift.
### Task
W... | reference | disc_weight = {"R": 25, "B": 20, "Y": 15, "G": 10, "W": 5,
"r": 2.5, "b": 2, "y": 1.5, "g": 1, "w": .5, "c": 2.5, "-": 0}
def adjust_barbell(weight_start, weight_end):
discs, discs_stb = get_discs(weight_start - 25), get_discs(weight_end - 25)
while discs and discs_stb and discs[- 1] == d... | Adjust barbell | 6400caeababb193c64d664d1 | [
"Strings",
"Mathematics"
] | https://www.codewars.com/kata/6400caeababb193c64d664d1 | 6 kyu |
# Load a barbell
## Kata overview
Olympic weightlifting is a sport in which athletes compete in lifting a barbell from the ground to overhead, with the aim of successfully lifting the heaviest weights.
The purpose of this kata is to load an Olympic barbell.
### Task
Write a function that returns a string representati... | reference | ELEMENTS = [('R', 25), ('B', 20), ('Y', 15), ('G', 10), ('W', 5),
('r', 2.5), ('c', 0), ('b', 2), ('y', 1.5), ('g', 1), ('w', 0.5)]
SIDE, CENTER = 10, 20
BAR, COLLAR = 20, 2.5
def load_barbell(W):
W -= BAR + 2 * COLLAR
side = []
for c, w in ELEMENTS:
n, W = divmod(W, 2 * w) if w ... | Load a barbell | 6400c3ebf4a0b796602988a6 | [
"Strings",
"Mathematics"
] | https://www.codewars.com/kata/6400c3ebf4a0b796602988a6 | 6 kyu |
# Barbell weight
## Kata overview
Olympic weightlifting is a sport in which athletes compete in lifting a barbell from the ground to overhead, with the aim of successfully lifting the heaviest weights.
The purpose of this kata is to compute the weight of an Olympic barbell.
### Task
Write a function that computes the... | reference | ELEMENTS = {'-': 0, 'c': 2.5, 'R': 25, 'B': 20, 'Y': 15, 'G': 10,
'W': 5, 'r': 2.5, 'b': 2, 'y': 1.5, 'g': 1, 'w': 0.5, }
BAR = 20
def barbell_weight(barbell):
return BAR + sum(map(ELEMENTS . __getitem__, barbell))
| Barbell weight | 6400aa17431f2d89c07eea75 | [
"Strings",
"Mathematics"
] | https://www.codewars.com/kata/6400aa17431f2d89c07eea75 | 7 kyu |
In this kata, you need to write a function that takes a string and a letter as input and then returns the index of the second occurrence of that letter in the string. If there is no such letter in the string, then the function should return -1. If the letter occurs only once in the string, then -1 should also be return... | reference | def second_symbol(s, c):
return s . find(c, s . find(c) + 1)
| Find the index of the second occurrence of a letter in a string | 63f96036b15a210058300ca9 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/63f96036b15a210058300ca9 | 7 kyu |
# Jumps in a cycle
A cycle `$[a_1, \dots, a_n]$` can be written in a extended form with a jump rate equal to 1 as `$a_1 \rightarrow a_2\rightarrow ... \rightarrow a_n\rightarrow a_1 \rightarrow ... \rightarrow a_n ...$`
Given a jump rate `k` and starting in the first element, you must find the number of jumps you hav... | games | from math import gcd
def get_jumps(cycle_list, k):
l = len(cycle_list)
return l / / gcd(l, k)
| Jumps in a cycle #1 | 63f844fee6be1f0017816ff1 | [
"Mathematics",
"Puzzles",
"Performance"
] | https://www.codewars.com/kata/63f844fee6be1f0017816ff1 | 7 kyu |
# The Challenge
Given two musical note names between A0 and C8, return the interval separating them as a positive integer.
## Examples
`getInterval('F4', 'B4')` should return `4`.
`getInterval('G3', 'G4')` should return `8`.
`getInterval('A7', 'B6')` should return `7`.
# Some Background
Musicians often refer to pi... | algorithms | def get_interval(* notes):
n1, n2 = ('CDEFGAB' . index(n[0]) + 7 * int(n[1]) for n in notes)
return 1 + abs(n1 - n2)
| Music Theory: Find the Melodic Interval Between Two Notes | 63fa8aafe6be1f57ad81729a | [
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/63fa8aafe6be1f57ad81729a | 7 kyu |
#### In this Kata you must calulate the number of bounces a ball makes when shot between two walls
---
# Task Details:
+ Mr Reecey has bought a new ball cannon and he lives in a tower block
+ He wants to calulate the number of bounces between the two towers before he shoots his shot
+ The gun is set up to fire with a... | games | g = 9.81
def bounce_count(h, w, v):
t = (2 * h / g) * * 0.5 # time it takes to reach the floor
return (v * t) / / w # number of bounces between walls
| Tower Bouncing | 63f9ec524362170065e5c85b | [
"Physics"
] | https://www.codewars.com/kata/63f9ec524362170065e5c85b | 7 kyu |
Django is a famous back-end framework written in Python. It has a vast list of features including the creation of database tables through "models". You can see an example of such model below:
```
class Person(models.Model):
first_name = models.CharField()
last_name = models.CharField()
```
Apart from creating... | reference | import datetime
import re
class ValidationError (Exception):
pass
class Field:
def __init__(self, default=None, blank=False):
self . name = ''
self . _default = default
self . blank = blank
@ property
def default(self):
if callable(self . _default):
return self . ... | Metaclasses - Simple Django Models | 54b26b130786c9f7ed000555 | [
"Object-oriented Programming",
"Metaprogramming",
"Backend"
] | https://www.codewars.com/kata/54b26b130786c9f7ed000555 | 3 kyu |
We are storing numbers in the nodes of a binary tree. The tree starts at the root node. The root has two child nodes, its leftchild and rightchild. Each of those nodes also has two child nodes, and so on, until we reach the leaf nodes, nodes that have no children. Each node stores one nonnegative integer. The value at ... | reference | def find_incorrect_value(T):
troubles, end = [], len(T) / / 2
for i, v in enumerate(T[: end]):
l = 2 * i + 1
if T[l] + T[l + 1] != v:
troubles . append((i, l + 1))
match troubles:
case[(0, r)]: return 0, T[1] + T[2] # wrong root
case[(i, r)]: return r, T[i] - T[r - 1] # wrong... | Finding the Incorrect Value in a Binary Tree | 63f13a354a828b0041979359 | [
"Binary Trees",
"Arrays"
] | https://www.codewars.com/kata/63f13a354a828b0041979359 | 6 kyu |
You are given 2 two-digit numbers. You should check if they are similar by comparing their numbers, and return the result in %.
Example:
1) compare(13,14)=50%;
2) compare(23,22)=50%;
3) compare(15,51)=100%;
4) compare(12,34)=0%.
~~~if:c
In C language you should return P_100, P_50 and P_0 instead of strings ... | algorithms | def compare(a, b):
fir = sorted(str(a))
sec = sorted(str(b))
return '100%' if fir == sec else '50%' if fir[0] in sec or fir[1] in sec else '0%'
| Compare 2 digit numbers | 63f3c61dd27f3c07cc7978de | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/63f3c61dd27f3c07cc7978de | 7 kyu |
## intro
The D'Hondt method, also called the Jefferson method or the greatest divisors method, is a method for allocating seats in parliaments among federal states, or in party-list proportional representation systems.
It belongs to the class of highest-averages methods.
You can read more about that [here](https://en... | algorithms | def distribute_seats(num_seats, votes):
res = [0 for _ in votes]
for z in range(num_seats):
mi, _ = max(enumerate(votes), key=lambda p: p[1] / (res[p[0]] + 1))
res[mi] += 1
return res
| D'Hondt method | 63ee1d8892cff420d2c869af | [
"Algorithms"
] | https://www.codewars.com/kata/63ee1d8892cff420d2c869af | 6 kyu |
# Clustering corrupted banks
You work in the Fraud Tracking Organization (FTO) and one of the teams have found a list of corrupted banks. A corrupted bank, in simple words, is a bank that has been tracked lending money to itself. These banks will suffered a penalty fee based on the amount of banks that are in the same... | algorithms | def get_reward(banks: list[tuple[int, int]]):
fees = 0
G = dict(banks)
while G:
n, (i, j) = 1, G . popitem()
while j != i:
n, j = n + 1, G . pop(j)
fees += n * 2 * * n
return fees
| Clustering corrupted banks | 63e9a2ef7774010017975438 | [
"Data Structures",
"Algorithms",
"Set Theory"
] | https://www.codewars.com/kata/63e9a2ef7774010017975438 | 6 kyu |
# The area between the vertex of the parabola and x-axis
## 1-) Warning
If you don't know about the following topics, you will have problems in this kata.
- _Quadratic equations_
- _Parabola_
- _Integral_
## 2-) Explanation
- I will give you 3 values as input in the kata.
These are a , b , c. The value of a will ne... | algorithms | def area(a, b, c):
return (d := b * * 2 - 4 * a * c) > 0 and d * * 1.5 / (6 * a * a)
| The area between the vertex of the parabola and x-axis | 63ecc21e12797b06519ad94f | [
"Mathematics"
] | https://www.codewars.com/kata/63ecc21e12797b06519ad94f | 6 kyu |
A researcher is studying cell division in a large number of samples. Counting the cells in each sample is automated, but when she looks at the data, she immediately notices that something is wrong.
The data are arrays of integers corresponding to the number of cells in the sample over time. The first element `data[0]`... | reference | from itertools import accumulate
def cleaned_counts(data):
return [* accumulate(data, max)]
| Noisy Cell Counts | 63ebadc7879f2500315fa07e | [
"Arrays",
"Logic"
] | https://www.codewars.com/kata/63ebadc7879f2500315fa07e | 7 kyu |
In atomic chess (https://en.wikipedia.org/wiki/Atomic_chess) all captures result in an "explosion" which destroys all pieces other than pawns in the 9 squares around and including the square where the capture takes place. The capturing piece and the captured piece are destroyed, whether they are pawns or not.
For exa... | games | def make_atomic_move(position, move):
j, i, x, l, k = move
i, j, k, l = 8 - int(i), ord(j) - 97, 8 - int(k), ord(l) - 97
position[i][j], position[k][l] = '.', position[i][j]
if x == 'x':
for u in range(max(0, k - 1), min(8, k + 2)):
for v in range(max(0, l - 1), min(8, l + 2)):
if k =... | Atomic Chess | 63deb6b0acb668000f87f01b | [
"Strings",
"Lists"
] | https://www.codewars.com/kata/63deb6b0acb668000f87f01b | 6 kyu |
# Background
After being inspired by Marie Kondo's teachings on minimalism, you've decided to apply her principles to your computer science work. You've noticed that while keyboard has 104 keys your hands only have ten fingers, and two palms. and so you've made the decision to write code that contains no more than 12 u... | games | exec(bytes((0b1101010, 0b1101111, 0b1111001, 0b111101, 0b1101100, 0b1100001, 0b1101101, 0b1100010, 0b1100100, 0b1100001, 0b100000, 0b1000011, 0b111010, 0b100111, 0b1100101, 0b1111000, 0b1100101, 0b1100011, 0b101000, 0b1100010, 0b1111001, 0b1110100, 0b1100101, 0b1110011, 0b101000, 0b101000, 0b100111, 0b101011, 0b100111,... | Joyful Transpiler | 63d4b700bce90f0024a9ca19 | [
"Puzzles",
"Restricted"
] | https://www.codewars.com/kata/63d4b700bce90f0024a9ca19 | 5 kyu |
## <span style="color:#0ae">Task</span>
There is a single-digit [seven segment display](https://en.wikipedia.org/wiki/Seven-segment_display). The display has a problem: there is exactly one dead segment. The dead segment is either always on or always off (we don't know in advance the type of defect).
The display can ... | reference | def dead_segment(d): return (h: = [None] + [e[0] for e in zip(' a \nfgb\nedc', * d) if len({* e}) == 2])[len(h) < 3]
| Broken 7-segment display - dead segment [code golf] | 63b9e30e29ba4400317a9ede | [
"Logic",
"Fundamentals",
"Restricted"
] | https://www.codewars.com/kata/63b9e30e29ba4400317a9ede | 5 kyu |
In https://www.codewars.com/kata/63d6dba199b0cc0ff46b5d8a, you were given an integer `n >= 1` and asked to find the determinant of the `n`-by-`n` matrix `m` with elements `m[i][j] = i * j, 1 <= i,j <= n`.
This task is identical, but the matrix elements are given by `m[i][j] = i ** j`; that is, with power instead of mu... | reference | ritual = r = lambda n, p = 1: n < 2 or n * * p * r(n - 1, p + 1) % (10 * * 9 + 7)
| [Code Golf] A Powerful Ritual | 63dab5bfde926c00245b5810 | [
"Mathematics",
"Matrix",
"Restricted"
] | https://www.codewars.com/kata/63dab5bfde926c00245b5810 | 6 kyu |
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Story</summary>
As a child, <a href="https://en.wikipedia.org/wiki/Monsieur_Hulot">Mr. Hulot </a> was a happy boy who loved playing games all by h... | reference | def count_rooms(Ps):
for i in range(2):
if len(Ps[i][0]) == 1:
return sum(map(sum, Ps[i ^ 1]))
return sum(sum(sum(i and v for i, v in enumerate(row))
for row in face)
for face in Ps)
| Hulot's Playtime | 63d53ca9cce9531953e38b6e | [
"Fundamentals",
"Arrays",
"Geometry"
] | https://www.codewars.com/kata/63d53ca9cce9531953e38b6e | 6 kyu |
## Task
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Task</summary>
##### "Given a positive integer <code>n</code>, return a string representing the front side of a wigwam (Cheyenne style) ass... | games | def draw_wigwam(n):
def colons(x): return f':-: { ":" * x } ' [: x]
def zigs(x): return ':_' * (x + 1 >> 1)
def fold(left): return f'/ { left } : { left [:: - 1 ] } \\'
def on_side(i): return n > 4 and i > 2
def above_door(i): return i < n
def dots(i, j, di, dj, go):
while go(i):
... | Cheyenne Wigwam | 63ca4b3af1504e005da0f25c | [
"Algorithms",
"Puzzles",
"ASCII Art",
"Strings"
] | https://www.codewars.com/kata/63ca4b3af1504e005da0f25c | 5 kyu |
## Problem
Given a list of linear or affine functions `$y_i=a_i x + c_i$` (represented as tuples `$(a_i,c_i)$`), compute the sum of absolute value of the functions: `$\Sigma\lvert y_i \lvert$` and return the result as a series of sorted intervals, defined as 4-uples: `$(x_{start,j} ,x_{end,j},a_j,c_j)$`.
## Example:
... | algorithms | from math import inf
def expand(lst):
intervals = [(- inf, inf, 0.0, 0.0)]
for a, c in lst:
x0, a, c = (inf, 0.0, abs(c)) if a == 0 else (- c /
a, - a, - c) if a > 0 else (- c / a, a, c)
i, o = next((i, o) for i, o in enumerate(intervals) if o[... | Expand Absolute Values | 60bcabf6b3a07c00195f774c | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/60bcabf6b3a07c00195f774c | 5 kyu |
### Sudoku Background
Sudoku is a game played on a 9x9 grid. The goal of the game is to fill all cells of the grid with digits from 1 to 9, so that each column, each row, and each of the nine 3x3 sub-grids (also known as blocks) contain all of the digits from 1 to 9.
More info at: http://en.wikipedia.org/wiki/Sudoku... | reference | def validate_sudoku(board):
elements = set(range(1, 10))
# row
for b in board:
if set(b) != elements:
return False
# column
for b in zip(* board):
if set(b) != elements:
return False
# magic squares
for i in range(3, 10, 3):
for j in range(3, 10, 3):
... | Sudoku board validator | 63d1bac72de941033dbf87ae | [
"Algorithms",
"Games"
] | https://www.codewars.com/kata/63d1bac72de941033dbf87ae | 6 kyu |
# Set Reducer
### Intro
These arrays are too long! Let's reduce them!
### Description
Write a function that takes in an array of integers from 0-9, and returns a new array:
* Numbers with no identical numbers preceding or following it returns a 1: ``2, 4, 9 => 1, 1, 1``
* Sequential groups of identical numbers re... | algorithms | from itertools import groupby
def set_reducer(inp):
while len(inp) > 1:
inp = [len(list(b)) for a, b in groupby(inp)]
return inp[0]
| Set Reducer | 63cbe409959401003e09978b | [
"Recursion",
"Algorithms",
"Logic",
"Arrays"
] | https://www.codewars.com/kata/63cbe409959401003e09978b | 7 kyu |
# Description
You can paint an asperand by pixels in three steps:
1. First you paint the inner square, with a side of ```k```.
2. Then you need to paint one pixel, that's laying diagonally relative to the inner square that you just painted ( _the bottom-right corner of the inner square is touching the top-left corner ... | games | def count_pixels(k): return 8 * k + 2 + (k < 2)
| Asperand pixel counting | 63d54b5d05992e0046752389 | [
"Algebra",
"Puzzles"
] | https://www.codewars.com/kata/63d54b5d05992e0046752389 | 7 kyu |
# Boole
[Wikipedia](https://en.wikipedia.org/wiki/George_Boole): George Boole ( 1815 β 1864 ) was a largely self-taught English mathematician, philosopher, and logician. He is best known as the author of _The Laws of Thought_ ( 1854 ), which contains Boolean algebra.
[More Wikipedia](https://en.wikipedia.org/wiki/Boo... | algorithms | def false(a): return lambda b: a
def true(a): return lambda b: b
def iff(x): return lambda a: lambda b: x(b)(a)
| Scott Booleans | 63d1ba782de94107abbf85c3 | [
"Data Structures",
"Functional Programming"
] | https://www.codewars.com/kata/63d1ba782de94107abbf85c3 | 7 kyu |
> Skip ```Situation``` and go straight to ```Task``` if you care not about the story (all you need to solve the kata will be contained under "Task").
> The answers are hidden to prevent users from figuring out the solution from the results of the tests.
<h1> Situation </h1>
Every year, in an ancient civilization, al... | algorithms | ritual = 1 . __eq__
| [Code Golf] An Interesting Ritual | 63d6dba199b0cc0ff46b5d8a | [
"Mathematics",
"Matrix",
"Restricted"
] | https://www.codewars.com/kata/63d6dba199b0cc0ff46b5d8a | 7 kyu |
[Previously in the paper and pencil series...](https://www.codewars.com/kata/639d78b09547e900647a80c7)
Story (Which you could skip)
------
As you finished researching the languages of humans, you walked across the maths history of humans. However, you have to prove yourself to the human beings that you are smart enoug... | games | # I hate formatting equations
def quadratic_formula(y1, y2, _):
b = y2 - y1 - 3
c = y1 - b - 1
s = f"x^2 { '' if b == 0 else '+x' if b == 1 else '-x' if b == - 1 else f' { b : + d } x' }{ '' if c == 0 else f' { c : + d } ' } "
return s, 16 + 4 * b + c, 25 + 5 * b + c
| #Paper and pencil 2: Finding the formula of a single 'x'^2 sequence and the next terms | 63bd8cc3a78e0578b608ac80 | [
"Puzzles",
"Mathematics",
"Algebra",
"Logic"
] | https://www.codewars.com/kata/63bd8cc3a78e0578b608ac80 | 6 kyu |
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Task</summary>
##### "There is a game, where four letters <code>A, B, C, D</code> are surrounded by numbers. Each letter wants to score as much po... | games | BORDERS = {'A': 2, 'B': 6, 'C': 10, 'D': 14}
def play(nums):
nums = nums[:]
center = nums . pop()
scores = {k: 0 for k in BORDERS}
while all(v < 100 for v in scores . values()) and (any(nums) or center):
scored = 0
for c, i in BORDERS . items():
b = nums[i]
if bool(center)... | Letters and Numbers Game | 63c1d93acdd8ca0065e35963 | [
"Puzzles",
"Games",
"Arrays"
] | https://www.codewars.com/kata/63c1d93acdd8ca0065e35963 | 6 kyu |
## SITUATION
One day, as you wake up, you have a terrible realization:<br>
*You have **magically**Β time-traveled, going all the way back to high school.*
Ignoring the weird scientific implications of this event, you focus on what's truly important: **HOMEWORK**
You see, your teacher has handed out hours' worth of ma... | algorithms | from collections import defaultdict
def extract(c: str, section: str) - > tuple[int, int]:
try:
return (0, int(section))
except ValueError:
pass
if section . startswith('-'):
mul = - 1
section = section . replace('-', '+')
else:
mul = 1
section = section . replace(... | Multiplying Polynomials | 63c05c1aeffe877458a15994 | [
"Mathematics",
"Strings",
"Regular Expressions"
] | https://www.codewars.com/kata/63c05c1aeffe877458a15994 | 4 kyu |
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Problem Description</summary>
When dealing with multidimensional coordinates in a kata, we sometimes want to keep track of which cells have alread... | algorithms | def encode(d: list[int], p: list[int]) - > int:
e = 0
for i in range(len(p)):
e = e * d[i] + p[i]
return e
def decode(d: list[int], e: int) - > list[int]:
p = [0] * len(d)
for i in range(len(d) - 1, - 1, - 1):
p[i] = e % d[i]
e / /= d[i]
return p
| Multidimensional Coordinate Encoding | 63be67b37060ec0a8b2fdcf7 | [
"Algorithms",
"Arrays",
"Mathematics"
] | https://www.codewars.com/kata/63be67b37060ec0a8b2fdcf7 | 6 kyu |
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Introduction</summary>
Let's draw mountain bike trails!
```
_--_ _
-__ _-βΎβΎβΎ- -
... | reference | from itertools import accumulate
TILES = "_-βΎ"
def draw_trail(trail):
hs = [* accumulate(trail)]
min_h = min(hs)
base = min_h - min_h % 3
but = min_h / / 3
up = max(hs) / / 3
H = up - but + 3
blank = ' ' * (len(trail) + 1)
board = [list(blank) for _ in range(H)]
for ... | Mountain Bike Trail | 63bd62e60634a6006a1b53c0 | [
"Fundamentals",
"Strings",
"ASCII Art",
"Geometry"
] | https://www.codewars.com/kata/63bd62e60634a6006a1b53c0 | 6 kyu |
<img align="right" alt="" style="margin: 1em" src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/LED_Digital_Display.jpg/320px-LED_Digital_Display.jpg">
## <span style="color:#0ae">Task</span>
There is a multi-digit [seven segment display](https://en.wikipedia.org/wiki/Seven-segment_display). The display ... | reference | def is_num(s):
try:
return str(int(s)) == s
except:
return not s
def dead_segment(displays):
A = (1, 5, 8, 7, 6, 3, 4)
B = {0: ' ', 64: '-', 63: 0, 6: 1, 91: 2, 79: 3,
102: 4, 109: 5, 125: 6, 7: 7, 127: 8, 111: 9}
def P(d): return is_num('' . join(str(B . get(... | Broken 7-segment display - challenge edition | 63b325618450087bfb48ff95 | [
"Logic",
"Fundamentals"
] | https://www.codewars.com/kata/63b325618450087bfb48ff95 | 3 kyu |
## Task
Given an non-empty list of non-empty uppercase words, compute the minimum number of words, which, when removed from the list, leaves the rest of the list in strictly ascending lexicographic order.
#### Examples:
["THE","QUICK","BROWN","FOX","JUMPS","OVER","THE","LAZY","DOG"] should return 4, because removing... | algorithms | from bisect import bisect_left
def sort_by_exclusion(words):
# last[i] represents the last element of
# the smallest subsequence of size i
last = ['']
for word in words:
idx = bisect_left(last, word)
if idx == len(last):
last . append(word)
else:
last[idx] = wor... | Sorting by Exclusion | 63bcd25eaeeb6a3b48a72dca | [
"Sorting",
"Algorithms",
"Dynamic Programming"
] | https://www.codewars.com/kata/63bcd25eaeeb6a3b48a72dca | 6 kyu |
<h2>Introduction</h2>
<p>Graphs are simply another way to represent data. There are many different kinds of graphs and innumerable applications for them. You can find many examples of graphs in your everyday life, from road maps to subway systems. One special type of graph that we will be focusing on is the star graph,... | reference | def center(edges):
a, b = edges[0]
return a if a in edges[1] else b
| Find Center of Star Graph | 63b9aa69114b4316d0974d2c | [
"Graph Theory"
] | https://www.codewars.com/kata/63b9aa69114b4316d0974d2c | 7 kyu |
## Task
Given two positive integers <code>m (width)</code> and <code>n (height)</code>, fill a two-dimensional list (or array) of size <code>m-by-n</code> in the following way:
- (1) All the elements in the first and last row and column are 1.
- (2) All the elements in the second and second-last row and column are 2... | reference | def create_box(m, n): # m and n positive integers
return [[min([x + 1, y + 1, m - x, n - y]) for x in range(m)] for y in range(n)]
| The 'spiraling' box | 63b84f54693cb10065687ae5 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/63b84f54693cb10065687ae5 | 7 kyu |
## tl;dr-
```
It's connect4 but optimized, the board is MxM and you need to connect N.
Given a game move by move, determine which move is a winning move.
Turn order is random.
```
The other day I programmed a connect four game, and I thought to myself- this is nice, but
faster = better... So how can I optimize t... | games | from collections import defaultdict
class MegaConnect4:
def __init__(self, board_size, win_condition):
self . height = [0] * board_size
self . lines = {k: defaultdict(lambda: defaultdict(dict)) for k in [
(1, 0), (0, 1), (1, 1), (- 1, 1)]}
self . get_coords = {
(1, 0): lambda ... | Mega Connect 4 | 6250122a983b3500358fb671 | [
"Games",
"Puzzles",
"Logic",
"Performance"
] | https://www.codewars.com/kata/6250122a983b3500358fb671 | 4 kyu |
<img align="right" alt="" style="margin: 1em" src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/Seven_segment_01_Pengo.jpg/243px-Seven_segment_01_Pengo.jpg">
## <span style="color:#0ae">Task</span>
There is a single-digit [seven segment display](https://en.wikipedia.org/wiki/Seven-segment_display). The d... | reference | SEGMENTS = {0b1111110, 0b0110000, 0b1101101, 0b1111001, 0b0110011,
0b1011011, 0b1011111, 0b1110000, 0b1111111, 0b1111011}
def segment_to_number(s): return int(
'' . join('01' [s[i] != ' '] for i in (1, 6, 10, 9, 8, 4, 5)), 2)
def number_to_letters(n): return '' . join(
c for c, b in zip... | Broken 7-segment display - reversed segments | 63b5ce67e226b309f87cdefe | [
"Logic",
"Fundamentals"
] | https://www.codewars.com/kata/63b5ce67e226b309f87cdefe | 6 kyu |
I have four positive integers, A, B, C and D, where A < B < C < D. The input is a list of the integers A, B, C, D, AxB, BxC, CxD, DxA in some order. Your task is to return the value of D.
~~~if:lambdacalc
### Encodings
purity: `LetRec`
numEncoding: `BinaryScott`
export constructors `nil, cons` for your `List` enc... | reference | def alphabet(ns):
a, b, c1, c2, _, _, _, cd = sorted(ns)
return cd / c2 if a * b == c1 else cd / c1
| The alphabet product | 63b06ea0c9e1ce000f1e2407 | [
"Logic"
] | https://www.codewars.com/kata/63b06ea0c9e1ce000f1e2407 | 7 kyu |
This kata wants you to perform a lattice multiplication. This is a box multiplication, which will be explained below. However, this has a twist. Instead of adding the diagonals together, you would return a 2D list cotaining the diagonals, for example, 13x28 would return:
[[4], [6, 2, 8], [0, 2, 0], [0]]
![An example,... | algorithms | def lattice(a, b):
res = {}
for i, x in enumerate(map(int, str(b))):
for j, y in enumerate(map(int, str(a))):
res[i + j] = res . get(i + j, []) + [x * y / / 10]
for j, y in enumerate(map(int, str(a))):
res[i + j + 1] = res . get(i + j + 1, []) + [x * y % 10]
return [res[k] for k in ... | Lattice multiplication | 63b5951092477b0b918ff24f | [
"Mathematics"
] | https://www.codewars.com/kata/63b5951092477b0b918ff24f | 6 kyu |
## Introduction
The game of Yahtzee is played by rolling five 6-sided dice, and scoring the results in a number of ways. For the purpose of this kata, the upper section of Yahtzee gives you six possible ways to score a roll. 1 times the number of 1s in the roll, 2 times the number of 2s, 3 times the number of 3s, an... | games | def yahtzee_upper(dice: list) - > int:
return max([dice . count(x) * x for x in set(dice)])
| Yahtzee upper section scoring | 63b4758f27f8e5000fc1e427 | [
"Algorithms",
"Arrays",
"Games",
"Game Solvers"
] | https://www.codewars.com/kata/63b4758f27f8e5000fc1e427 | 7 kyu |
# Story
It is the Chinese New Year Eve. You are at your Chinese friend's house.
When he says: "It is one hour left."
You look at your watch, it is `22:00`.
So you ask him, here is the reason.
___
# Using Earthly Branches for Time
In the traditional system using [Earthly Branches](https://en.wikipedia.org/wiki/Ea... | reference | def what_branch(time):
倩干ε°ζ― = "εδΈδΈε―
ε―
ε―ε―θΎ°θΎ°ε·³ε·³εεζͺζͺη³η³ι
ι
ζζδΊ₯δΊ₯ε"
m, s = map(int, time . split(":"))
t = m * 60 + s
return 倩干ε°ζ―[t / / 60]
| Using Earthly Branches for Time | 63b3cebaeb152e12268bdc02 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/63b3cebaeb152e12268bdc02 | 7 kyu |
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Story</summary>
Let's fast forward to the year 2048. Earth resources are scarcer then ever before. If humanity wants to survive, we need to migrate ... | algorithms | from itertools import count
from dataclasses import dataclass
ROCK_TO_SOLIDITY = dict(zip(".*xX@", range(5)))
@ dataclass
class Drill:
row: list[int]
damage: int
i: int = 0
_movable: bool = False
@ classmethod
def build(cls, s: str):
speed = s . count('>')
power = '-' i... | Lunar Drilling Operation | 63ada5a5779bac0066143fa0 | [
"Algorithms",
"Puzzles",
"Strings",
"Mathematics",
"ASCII Art"
] | https://www.codewars.com/kata/63ada5a5779bac0066143fa0 | 5 kyu |
# Maximum different differences
Assume `$A$` is a strictly increasing array of positive integers with `$n$` elements:
```math
A = [a_1, a_2, ..., a_n] \text{ such that } a_1 < a_2<a_3<\dots<a_n
```
The difference array of `$A$` is `$[a_2-a_1, a_3-a_2, \dots, a_n-a_{n-1}]$`
That is,
`$D = [d_1, d_2, \dots, d_{n-1}]$... | games | from math import isqrt
def max_df(a_n: int) - > int:
return (isqrt(8 * a_n) - 1) / / 2
| Maximum different differences | 63adf4596ef0071b42544b9a | [
"Mathematics",
"Puzzles",
"Performance"
] | https://www.codewars.com/kata/63adf4596ef0071b42544b9a | 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 a list walls closing in at you, can you make it past those walls without being hit?"
### Input
- walls: an array of 2-... | algorithms | def can_escape(walls):
return all(a > i < b for i, (a, b) in enumerate(walls, 1))
| Hurry up, the walls are closing in! | 63ab271e96a48e000e577442 | [
"Algorithms",
"Mathematics",
"Arrays"
] | https://www.codewars.com/kata/63ab271e96a48e000e577442 | 7 kyu |
### Intro
Your friend recently started learning how to play a guitar. He asked for your help to write a program that will help to find frets for each note on the guitar.
## Main task:
He wants to enter 2-4 parameters: `note, exact, string and position`.
All inputs will be valid.
1) note - "name" of the note. There ... | games | STRINGS = 'EBGDAE'
NOTES = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#']
def get_frets(note, exact, * string_position):
if exact:
s0, p = string_position
f0 = (NOTES . index(note) -
NOTES . index(STRINGS[s0 - 1])) % 12 + (p - 1) * 12
return [(s, f) for s in range... | Guitar #1: Find the frets | 5fa49cfb19923f00299eae22 | [
"Puzzles"
] | https://www.codewars.com/kata/5fa49cfb19923f00299eae22 | 6 kyu |
You and your friends want to rent a house for the new year, but the problem is that people can go for a different number of days. It is necessary to calculate the amount that each person must pay, depending on how many days he is going to live in this house. The amount per person is the rental price divided by the numb... | algorithms | from collections import Counter
from math import ceil
def calculate_cost_per_person(array: list[int], rental: int) - > dict[int, int]:
res, days, rest, last = {}, Counter(array), len(array), 0
for k in sorted(days):
res[k] = res . get(last, 0) + ceil(rental / rest * (k - last))
rest, last = rest - day... | New year house rental | 63aa7b499c53c5af68e86a86 | [
"Algorithms"
] | https://www.codewars.com/kata/63aa7b499c53c5af68e86a86 | 6 kyu |
# Underload interpreter
Underload is an esoteric programming language. It is a stack based, turing complete language that works based on strings. Strings are the only datatype in Underload.
## Commands
- `(x)`: An underload string:
- Starts with an opening parenthesis `(`, and pushes all characters after the starti... | algorithms | def matches_brackets(s):
c = 0
for v in s:
if v == "(":
c += 1
if v == ")":
c -= 1
if c < 0:
return False
return c == 0
def take_until_close(itr):
res, c = "", 0
for v in itr:
if v == ")" and not c:
return res
if v == ")":
... | Underload Interpreter | 632c4222a1e24b480d9aae0d | [
"Interpreters",
"Esoteric Languages",
"Algorithms",
"Tutorials"
] | https://www.codewars.com/kata/632c4222a1e24b480d9aae0d | 5 kyu |
## Description
You are given four tuples. In each tuple there is coordinates x and y of a point. There is one and only one line, that goes through two points, so with four points you can have two lines: first and second tuple is two points of a first line, thirs and fourth tuple is two points of the second line. Your t... | games | def find_the_crossing(a, b, c, d):
a11, a12, b1 = b[1] - a[1], a[0] - b[0], a[0] * \
(b[1] - a[1]) + a[1] * (a[0] - b[0])
a21, a22, b2 = d[1] - c[1], c[0] - d[0], c[0] * \
(d[1] - c[1]) + c[1] * (c[0] - d[0])
det = a11 * a22 - a12 * a21
return ((b1 * a22 - a12 * b2) / det, (a11 *... | Find the crossing ( graphic calculations ) | 63a5b74a9803f2105fa838f1 | [
"Algebra",
"Mathematics",
"Linear Algebra",
"Graphics"
] | https://www.codewars.com/kata/63a5b74a9803f2105fa838f1 | 6 kyu |
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Preface</summary>
This is the first of (hopefully) a series of kata's about military units in the Roman Army. This kata concerns the <a href="https:... | reference | def draw(formation):
def A(u, n):
u -= 1
if u == 1:
ls = ".." + ".Β΄\\." * n
d = n * ".Β¨\\." + ".."
else:
ls = n * ('.' + "Β΄\\" * u + '.')
d = n * ("Β¨\\" . center(u - 1 << 1, '.') + "....")
return (g := '.' * len(d)), ls, g, d, g
def M(u, n):
def line(i, is_g, is_... | Roman Army Formations: Contubernium | 63a489ce96a48e000e56dda0 | [
"Fundamentals",
"Strings",
"ASCII Art",
"Geometry",
"Mathematics"
] | https://www.codewars.com/kata/63a489ce96a48e000e56dda0 | 5 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 a positive integer <code>n</code>, return a string representing the box associated with it."
- Boxes can get huge fast,... | algorithms | def draw(n):
if n == 1:
return '\n' . join([" _ ", "|_|"])
inside = draw(n - 1). splitlines()
return "\n" . join(
"| " [i < 1] + "_ " [0 < i < 2 * len(inside) - 2] + "| " [i < len(inside)] +
row[1:] for i, row in enumerate(inside + inside[1:])
)
| Boxes in boxes | 63a2cf5bd11b1e0016c84b5a | [
"Algorithms",
"ASCII Art",
"Performance",
"Strings",
"Puzzles",
"Memoization",
"Recursion",
"Mathematics",
"Dynamic Programming"
] | https://www.codewars.com/kata/63a2cf5bd11b1e0016c84b5a | 5 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 a positive integer <code>n</code>, return a string representing the pyramid associated with it."
Pyramids can get huge,... | games | def draw_pyramid(n):
mid = ['', '__', '__:_'] + [['', '|_', '_'][i % 3] + '_|_' * (i * 2 / / 3) for i in range(3, n * 2)]
return '\n' . join(
[' ' * (n * 3 - i * 3 - 2) + '.' + ('Β΄\\ \\' + 'Β΄\\' * (i - 2) if i > 2 and i % 2 else 'Β΄\\' * i) + '/' + mid[i] + '\\' + ' ' * (n * 2 - i - 1) for i in range(... | Pyramide d'Azkee | 63a31f7d66ad15f77d5358b9 | [
"Algorithms",
"Puzzles",
"ASCII Art",
"Strings",
"Geometry"
] | https://www.codewars.com/kata/63a31f7d66ad15f77d5358b9 | 5 kyu |
Have you ever gotten tired of having to type out long function chains? I mean, seriously, look at this thing:
<!-- Translators - add something for your language! -->
```python
print(list(map(len,list(strings))))
```
What if there was a way to shorten the process, so we all can still be productive, even when we're lazy?... | games | from functools import reduce
# Kinda ironic isn't it?
def fn_shorthand(functions):
return ',' . join(reduce("{1}({0})" . format, map(str . strip, reversed(functions . split(">")))). split())
| Function Shorthand | 639f4307531bc600236012a2 | [
"Strings",
"Puzzles",
"Algorithms"
] | https://www.codewars.com/kata/639f4307531bc600236012a2 | 6 kyu |
Douglas Hofstadter is mainly known for his Pulitzer Prize winning book [GΓΆdel, Escher, Bach](https://en.wikipedia.org/wiki/G%C3%B6del,_Escher,_Bach). One common idea he explores in his books is self similarity and strange loops. He describes a unique sequence with special qualities as the composition of two known sequ... | algorithms | # see: https://oeis.org/A006338
from itertools import count
def special_sequence(sqrt2=2 * * 0.5):
for n in count(1):
yield round((n + 1) * sqrt2) - round(n * sqrt2)
| Number Sequence Rabbit Hole | 63a249a9e37cea004a72dee9 | [
"Puzzles",
"Mathematics"
] | https://www.codewars.com/kata/63a249a9e37cea004a72dee9 | 6 kyu |
Story
------
In 22022, a disaster wiped out human beings. A team of alien archaeologists wanted to find out more about languages of human beings. However, when it comes to English, they only see letters with numbers. You are the leader of this group, with your master-alien-mind, you figured out the numbers mean the sum... | games | from collections import Counter
tmp = """\
test.assert_equals(sum_words('i am fine thank you'), [24, 32, 73, 61, 32])
test.assert_equals(sum_words('do you have a clue yet'), [14, 32, 70, 13, 57, 52])
test.assert_equals(sum_words('i bet some of you guys still got no idea'), [24, 38, 78, 35, 32, 54, 106, 28, 11... | #Paper and pencil: Figure out the value of letters by sum of words. | 639d78b09547e900647a80c7 | [
"Strings",
"Logic",
"Ciphers",
"Puzzles"
] | https://www.codewars.com/kata/639d78b09547e900647a80c7 | 6 kyu |
## Description
You will have to write a function that takes ```total``` as an argument, and returns a list. In this list there should be one or more nested lists; in each of them - three natural numbers ( including 0 ), so that the sum of this three numbers equals ```total```, and the product of this numbers ends with ... | algorithms | def zero_count(sum):
most = 0
res = []
for x in range(sum / / 3 + 1):
for y in range(x, (sum - x) / / 2 + 1):
z = sum - x - y
count = len(p := str(x * y * z)) - len(p . rstrip("0"))
if count == most:
res . append([x, y, z])
elif count > most:
most = count
res =... | Zero count in product | 639dd2efd424cc0016e7a611 | [
"Fundamentals",
"Algebra"
] | https://www.codewars.com/kata/639dd2efd424cc0016e7a611 | 6 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 a plane and numbers on or around that plane, return the coordinates of those numbers."
### Input
- plane: a string, re... | algorithms | def find_coords(plane):
arr = plane . split('\n')
d = {}
for y, row in enumerate(arr[:: - 1]):
for x, char in enumerate(row, - y):
if char . isdigit():
d[int(char)] = ((y, (x - 1) / / 2))
return [d[i] for i in range(len(d))]
| 2D Coordinates Finder! | 639ac3ded3fb14000ed38f31 | [
"Algorithms",
"Strings",
"Geometry",
"Mathematics"
] | https://www.codewars.com/kata/639ac3ded3fb14000ed38f31 | 7 kyu |
Sami is practicing her aim with her bow and is shooting some balloons in the air. On each balloon, they have different numbers written on them which represent their size. She would like to pop the balloon highest in the air that also has the most balloons of the same size present. If there is a tie, then she will inste... | games | from collections import Counter
def freq_stack(pops, balloons):
lst = []
cntr = Counter()
for i, b in enumerate(balloons):
cntr[b] += 1
lst . append((- cntr[b], - i, b))
return [b for _, _, b in sorted(lst)[: pops]]
| Popping Balloons | 633b8be2b5203f003011d79e | [
"Algorithms",
"Puzzles",
"Data Structures"
] | https://www.codewars.com/kata/633b8be2b5203f003011d79e | 6 kyu |
```if-not:rust
<b>Write two functions, one that converts standard time to decimal time and one that converts decimal time to standard time.</b>
```
```if:csharp
<ul><li>One hour has 100 minutes (or 10,000 seconds) in decimal time, yet its duration is the same as in standard time. Thus a decimal minute consists of 36 s... | reference | def to_industrial(time):
if isinstance(time, str):
h, m = map(int, time . split(':'))
return h + round(m / 60, 2)
return round(time / 60, 2)
def to_normal(time):
return f' { int ( time )} : { str ( round ( time % 1 * 60 )). zfill ( 2 )} '
| Decimal Time Conversion | 6397b0d461067e0030d1315e | [
"Fundamentals",
"Algorithms",
"Date Time",
"Strings"
] | https://www.codewars.com/kata/6397b0d461067e0030d1315e | 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>
You're watching a swimming race and like to draw the current situation in the race. You are given the <i>indices </i> of each of the ... | games | def swimming_pool(indices, length):
def draw_lane(index):
k, r = divmod(index + 5 * (index < 0), length)
i, s = special_args[index] if - 5 < index < 8 else normal_args[r]
t, s = k & 1, [s, s . translate(str . maketrans("<>", "><"))][k & 1]
prefix = ["p.p" [t and 0 < r < 5:][: 2], ".."][- leng... | Swimming Race | 6394d7573c47cb003d3253ec | [
"Puzzles",
"ASCII Art",
"Strings",
"Logic"
] | https://www.codewars.com/kata/6394d7573c47cb003d3253ec | 5 kyu |
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Task</summary>
##### "You're standing on a cliff. Will you jump or not?"
#### Input
- setting: a string portraying the cliff and its surroundings.... | games | def evaluate_jump(setting):
res, setting = [], setting . split("\n")
h, w = len(setting), len(setting[0])
y0 = next(i for i, r in enumerate(setting) if 'Y' in r)
x0 = setting[y0]. index('Y')
if y0 + 1 == h:
return res
def invalid(y, x): return y < 0 or x < 0 or y >= h or x >... | Cliff Jumping | 639382e66d45a7004aaf67fe | [
"Puzzles",
"Algorithms",
"Strings"
] | https://www.codewars.com/kata/639382e66d45a7004aaf67fe | 5 kyu |
**No French knowledge is needed for this kata!**
*A note for the people who do know French: this kata will skip the step of turning the verb into it's Nous form, to maintain simplicity. That means verbs like Manger will be Mangais, instead of Mangeais. Oh, and no Γͺtre ;-)*
---
## Details ##
*(You may skip this part... | reference | endings = {
'Je': 'ais',
'Tu': 'ais',
'Il': 'ait',
'Elle': 'ait',
'On': 'ait',
'Nous': 'ions',
'Vous': 'iez',
'Ils': 'aient',
'Elles': 'aient'
}
def to_imparfait(verb_phrase):
return verb_phrase[: - 2] + endings[verb_phrase . split()[0]]
| French Imparfait Conjugation | 6394c1995e54bd00307cf768 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/6394c1995e54bd00307cf768 | 7 kyu |
While writing some code, you ran into a problem. Your code runs very slowly, because you need to run many functions.
You do a bit of troubleshooting and notice that you are not draining your system's resources.
Write a function that, given a list of "slow" functions, will return the sum of the results without waiting... | games | from concurrent . futures import *
def task_master(a):
with ThreadPoolExecutor(max_workers=len(a)) as executor:
return sum(executor . map(lambda f: f(), a))
| Task master | 639242518e28a700283f68ee | [
"Threads"
] | https://www.codewars.com/kata/639242518e28a700283f68ee | 6 kyu |
Create a tcp socket that listens on port 1111 on local host,
When a user connects to the socket, the following should happen:
- If the user sends a string containing only the word "exit", the socket and connection should close and the function should end.
- For any other string the user sends, the server should send... | reference | from socket import create_server
def socket_server():
with create_server(('127.0.0.1', 80), reuse_port=True) as s:
with s . accept()[0] as t:
while True:
bs = t . recv(0xDEAD)
if bs == b'exit':
break
t . send(bs)
| Basic socket server | 6390ea74913c7f000d2e95cd | [
"Backend"
] | https://www.codewars.com/kata/6390ea74913c7f000d2e95cd | 6 kyu |
There is a socket listening on port 1111 of local host.
The socket either belongs to a server that sends back anything you send to it,
or to a server that reverses anything you send to it.
Create a function that does the following:
- Connects to the socket on port 1111.
- Sends one packet to the server.
- Receives on... | reference | from socket import create_connection
def socket_client():
with create_connection(('127.0.0.1', 1111)) as s:
s . send(b'ab')
return s . recv(2) == b'ab'
| Simple Socket Client | 639107e0df52b9cb82720575 | [
"Networks"
] | https://www.codewars.com/kata/639107e0df52b9cb82720575 | 7 kyu |
You are given an input (n) which represents the amount of lines you are given, your job is to figure out what is the **maximum** amount of perpendicular bisectors you can make using these lines.
``Note: A perpendicular bisector is one that forms a 90 degree angle``
```
n will always be greater than or equal to 0
```
E... | reference | def perpendicular(n):
return n * n / / 4
| Perpendicular lines | 6391fe3f322221003db3bad6 | [
"Fundamentals",
"Algorithms",
"Geometry"
] | https://www.codewars.com/kata/6391fe3f322221003db3bad6 | 7 kyu |
<details open>
<summary style="
padding: 3px;
width: 100%;
border: none;
font-size: 18px;
box-shadow: 1px 1px 2px #bbbbbb;
cursor: pointer;">
Introduction</summary>
Everybody loves to code golf. Well, maybe not everybody, but some people do. This kata is <b>not</b> directed to such people.... | reference | from collections import defaultdict, Counter
from operator import itemgetter
def render_champions(submissions, n_min):
if len(submissions) < n_min:
return ''
best = min(map(itemgetter(1), submissions[: n_min]))
record = defaultdict(list)
order = defaultdict(list)
for name, n in s... | Render the Code Golf Champions | 638e399a2d712300309cf11c | [
"Arrays",
"Strings",
"Sorting"
] | https://www.codewars.com/kata/638e399a2d712300309cf11c | 5 kyu |
Let `$f(n) = \dbinom{n+1}{2}$`, with non-negative integer n.
`$\dbinom{n}{k}$` is [Binomial coefficient](https://en.wikipedia.org/wiki/Binomial_coefficient).
You need to represent the given number `N` like this:
`$N = f(i) + f(j) + f(k)$`, actually, it is possible `$\forall N \in β$`.
For example:
```
34 = f(0) + ... | algorithms | from itertools import count
from random import randint
from gmpy2 import is_prime
def represent(n: int) - > int:
"""
with some algebra I found that:
(i+1)C2 + (j+1)C2 + (k+1)C2 = N is equivalent to (2i+1)^2 + (2j+1)^2 + (2k+1)^2 = 8N+3
so the new goal is to find 3 odd squares (A^2 + B^2 + C^2) that sum of 8... | My favorite number is III, so... | 638f6152d03d8b0023fa58e3 | [
"Mathematics",
"Algorithms",
"Number Theory",
"Performance"
] | https://www.codewars.com/kata/638f6152d03d8b0023fa58e3 | 3 kyu |
A Carmichael number is defined as a number N that is composite and yet passes Fermat primality test, i.e. `M**(N-1) == 1 (mod N)`, for all M relatively prime to N.
Find a Carmichael number that satisfies the following:
* It is a product of *seven* prime numbers.
* Its prime factors are between `10**7` and `10**9`.
S... | games | # Most clutched solution I found: (p[-1] - 1) // (p[0] - 1) = 4 / 3
primes = [24284400 * k + 1 for k in (24, 30, 33, 36, 38, 39, 40)]
| A giant Carmichael number | 638edc41458b1b00165b138b | [
"Mathematics",
"Number Theory",
"Performance"
] | https://www.codewars.com/kata/638edc41458b1b00165b138b | 3 kyu |
You need to count the number of prime numbers less than or equal to some natural ```n```.
For example:
```
count_primes_less_than(34) = 11
count_primes_less_than(69) = 19
count_primes_less_than(420) = 81
count_primes_less_than(666) = 121
```
- In this kata all the tests will be with `$ 1 \leqslant n \leqslant 10^{10}... | algorithms | # https://en.wikipedia.org/wiki/Prime-counting_function
from math import isqrt
from functools import cache
from bisect import bisect
import sys
sys . setrecursionlimit(10 * * 5)
# https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
def rwh_primes(n):... | Prime counting | 638c92b10e43cc000e615a07 | [
"Mathematics",
"Recursion",
"Algorithms",
"Memoization",
"Performance",
"Number Theory"
] | https://www.codewars.com/kata/638c92b10e43cc000e615a07 | 3 kyu |
The code consists of four unique digits (from `0` to `9`).
Tests will call your solution; you should answer with an array of four digits.
Your input is number of matches (the same digit in the same place) with your previous answer. For the first call input value is `-1` (i.e. each new test starts with input `-1`) ... | games | import itertools
def guess(n):
if n == - 1:
# Start by guessing the first code in the list
guess . remaining_codes = list(itertools . permutations(range(10), 4))
guess . prev_guess = guess . remaining_codes[0]
else:
# Remove any code from the list that would not produce the sa... | Digits | 638b042bf418c453377f28ad | [
"Algorithms"
] | https://www.codewars.com/kata/638b042bf418c453377f28ad | 5 kyu |
You have a natural number ```m```.
You need to write a function ```f(m)``` which finds the smallest positive number ```n``` such that
`$
n^n\equiv 0 \mod m
$`.
In other words `$n^n$` is divisible by ```m```.
For example:
```
f(13) = 13
f(420) = 210
f(666) = 222
f(1234567890) = 411522630
```
In this kata all the te... | algorithms | from collections import Counter
from math import ceil, gcd, log, prod
from random import randrange
from gmpy2 import is_prime
def pollard_rho(n):
while True:
x, c = randrange(1, n), randrange(1, n)
def f(x): return (x * x + c) % n
y = f(x)
while (d := gcd(abs(x - y), n)) == 1:
x, y... | The smallest n such that n^n mod m = 0 | 638b4205f418c4ab857f2692 | [
"Mathematics",
"Algorithms",
"Number Theory",
"Performance"
] | https://www.codewars.com/kata/638b4205f418c4ab857f2692 | 3 kyu |
Let `$f(n) = \displaystyle\sum_{k=0}^{n} 2^k k^2$`
You need to calculate this sum, but since the answer can be large, return `$ f(n)$` mod `$m$`, where `$m = 10^9 + 7$`.
For example:
```
f(3) mod m = 90
f(420) mod m = 118277878
f(666) mod m = 483052609
f(1111111111111) mod m = 284194637
```
In this kata all the test... | reference | M = 10 * * 9 + 7
def f(n: int) - > int:
# g(x) = sum(x^k, k = 0..n)
# Then sum(k^2 * x^2, k = 0..n) = x^2 g''(x) + x(g'(x) - 1) + x
# g'(2) = (n - 1) * 2^n + 1
# g''(2) = ...
def g2(n): return (n * n * pow(2, n, M) - 3 * n *
pow(2, n, M) + pow(2, n + 2, M) - 4) * pow(2, M - ... | Can you sum? | 638bc5d372d41880c7a99edc | [
"Mathematics",
"Algorithms",
"Number Theory",
"Performance"
] | https://www.codewars.com/kata/638bc5d372d41880c7a99edc | 6 kyu |
You have a natural number ```d```.
You need to write a function ```f(d)``` which finds the smallest positive number ```n``` having ```d``` divisors .
For example:
```
f(1) = 1
f(3) = 4
f(60) = 5040
f(420) = 9979200
```
In this kata all the tests will be with ```1 <= d <= 10000```
Keep in mind that ```n``` can be o... | algorithms | from math import isqrt
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37,
41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
def g(n, i):
p = primes[i]
m = p * * (n - 1)
for d in range(2, isqrt(n) + 1):
if n % d == 0:
m = min(m, p * * (d - 1) * g(n / / d, i + 1), p * * ... | The smallest number with a given number of divisors | 638af78312eae9a23c9ec5d6 | [
"Mathematics",
"Recursion",
"Algorithms",
"Number Theory",
"Performance"
] | https://www.codewars.com/kata/638af78312eae9a23c9ec5d6 | 4 kyu |
Fractals are fun to code, so let's make some.
Your task is to write a function that recursively generates an ASCII fractal.
- The function will take a `list[str]` representing rows of a seed pattern and an `int` number of iterations
- The seed pattern will be a rectangle containing two types of characters, `*` and ... | algorithms | def fractalize(seed, i):
if i <= 1:
return seed
star = fractalize(seed, i - 1)
dot = [row . replace('*', '.') for row in star]
return [
'' . join(rowrow)
for row in seed
for rowrow in zip(* (star if c == '*' else dot for c in row))
]
| Recursive ASCII Fractals | 637874b78ee59349c87b018d | [
"Mathematics",
"Algorithms",
"Geometry",
"ASCII Art",
"Performance"
] | https://www.codewars.com/kata/637874b78ee59349c87b018d | 5 kyu |
We have an endless chessboard, and on each cell there is a number written in a spiral.
16γ
€γ
€15γ
€γ
€14γ
€γ
€13γ
€γ
€12
17γ
€γ
€4 γ
€γ
€3 γ
€γ
€2 γ
€γ
€11
18γ
€γ
€5 γ
€γ
€0 γ
€γ
€1 γ
€γ
€10
19γ
€γ
€6 γ
€γ
€7 γ
€γ
€8 γ
€γ
€9γ
€γ
€...
20γ
€γ
€21γ
€γ
€22γ
€γ
€23γ
€γ
€24γ
€γ
€25
And we have a knight. A normal chess knight moves +1 to one axis and +2 to the other. But this knight moves +n to one axis a... | games | def trapped_cell(n: int, m: int) - > int:
def spiral(x, y):
u, v = (x, y) if abs(x) <= abs(y) else (y, x)
return v * (4 * v - [1, 3][y < x]) + [- u, u][y < x]
x, y = 0, 0
visited = set([(x, y)])
while True:
ps = [(x + dx, y + dy) for dx, dy in ((- n, - m), (n, - m), (- n, m), (n, m),
... | The Trapped Odd Knight | 63890d2ef418c49d4c7f50cc | [
"Algorithms",
"Combinatorics",
"Puzzles",
"Performance"
] | https://www.codewars.com/kata/63890d2ef418c49d4c7f50cc | 5 kyu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.