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 |
|---|---|---|---|---|---|---|---|
# Background
I have stacked some pool balls in a triangle.
Like this,
<img src="https://i.imgur.com/RuDkTCH.png" title="pool balls" />
# Kata Task
Given the number of `layers` of my stack, what is the total height?
Return the height as multiple of the ball diameter.
## Example
The image above shows a stack of ... | reference | def stack_height_2d(layers):
return round((1 + 3 * * 0.5 * (layers - 1) / 2), 3) if layers > 0 else 0
| Stacked Balls - 2D | 5bb804397274c772b40000ca | [
"Fundamentals"
] | https://www.codewars.com/kata/5bb804397274c772b40000ca | 7 kyu |
Given a non-negative number, sum all its digits using the following rules:
1. If the number of digits is even, remove the last digit
2. a. If the middle digit is odd, subtract it instead of adding
b. If both the middle digit and the last digit are even, subtract the last digit instead of adding
c. If th... | games | def crazy_formula(n):
while n > 9:
a = list(map(int, str(n)))
if not len(a) % 2:
a . pop()
if a[len(a) / / 2] % 2:
a[len(a) / / 2] *= - 1
elif a[- 1] % 2:
a[0] * *= 2
else:
a[- 1] *= - 1
n = abs(sum(a))
return n
| Give me a Crazy Formula! | 5661cde807c4e28efa0000d0 | [
"Mathematics",
"Algorithms",
"Puzzles"
] | https://www.codewars.com/kata/5661cde807c4e28efa0000d0 | 7 kyu |
# Task
The game starts with `n` people standing in a circle. The presenter counts `m` people starting with the first one, and gives `1` coin to each of them. The rest of the players receive `2` coins each. After that, the last person who received `1` coin leaves the circle, giving everything he had to the next partici... | algorithms | def find_last(n, m):
num = 0
for i in range(2, n + 1):
num = (num + m) % i
return num + 1, n * (n + 1) + m * (m - 2) - n * m
| Last and rich in circle | 5bb5e174528b2908930005b5 | [
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/5bb5e174528b2908930005b5 | 6 kyu |
We have the integer `9457`.
We distribute its digits in two buckets having the following possible distributions (we put the generated numbers as strings and we add the corresponding formed integers for each partition):
```
- one bucket with one digit and the other with three digits
[['9'], ['4','5','7']] --> ['9','4... | reference | def subsets(collection):
if len(collection) == 1:
yield [collection]
return
first = collection[0]
for smaller in subsets(collection[1:]):
yield [first] + smaller
for n, subset in enumerate(smaller):
yield smaller[: n] + [first + subset] + smaller[n + 1:]
def bucket_digit_d... | Next Higher Value #2 | 5b74e28e69826c336e00002a | [
"Fundamentals",
"Data Structures",
"Arrays",
"Mathematics",
"Algebra",
"Combinatorics",
"Algorithms"
] | https://www.codewars.com/kata/5b74e28e69826c336e00002a | 5 kyu |
Your `distributeEvenly` function will take an array as an argument and needs to return a new array with the values distributed evenly.
Example:
Argument:
`['one', 'one', 'two', 'two', 'three', 'three', 'four', 'four']`
Result:
`['one', 'two', 'three', 'four', 'one', 'two', 'three', 'four']`
The underlying order wil... | algorithms | from collections import Counter
def distribute_evenly(lst):
count, result = Counter(lst), []
while count:
result . extend(count)
count -= Counter(count . keys())
return result
| Evenly distribute values in array | 5bb50eb68f8bbdb4b300021d | [
"Arrays",
"Sorting",
"Algorithms"
] | https://www.codewars.com/kata/5bb50eb68f8bbdb4b300021d | 7 kyu |
Meet the Ackermann function:
> <h3> A(m, n, f) = <br>
>   n + f         if m <= 0 <br>
>   A(m - f, 1, f)       if m > 0 and n <= 0 <br>
>   A(m - f, A(m, n - f, f), f)  if m > 0 and n > 0
The Ackermann function is proven to be tot... | games | def hackermann(m, n, f):
stack = []
stack . append(m)
while stack:
m = stack . pop()
if m <= 0:
n = n + f
elif n <= 0:
n = 1
stack . append(m - f)
else:
n = n - f
stack . append(m - f)
stack . append(m)
return n
| Hackermann | 5bb3a707945bd500450001cb | [
"Recursion",
"Puzzles"
] | https://www.codewars.com/kata/5bb3a707945bd500450001cb | 6 kyu |
Remember the triangle of balls in billiards? To build a classic triangle (5 levels) you need 15 balls. With 3 balls you can build a 2-level triangle, etc.
For more examples,
```
pyramid(1) == 1
pyramid(3) == 2
pyramid(6) == 3
pyramid(10) == 4
pyramid(15) == 5
```
Write a function that takes number of balls (β₯ 1)... | reference | def pyramid(n):
i = 1
while i <= n:
n = n - i
i += 1
return i - 1
| Billiards triangle | 5bb3e299484fcd5dbb002912 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/5bb3e299484fcd5dbb002912 | 7 kyu |
# Idea
In the world of graphs exists a structure called "spanning tree". It is unique because it's created not on its own, but based on other graphs. To make a spanning tree out of a given graph you should remove all the edges which create cycles, for example:
```
This can become this or this or ... | algorithms | def make_spanning_tree(edges, t):
edges = sorted(edges, key=lambda x: x[1], reverse=t == 'max')
span, vert = [], {}
for edge in edges:
((a, b), _), (subA, subB) = edge, map(vert . get, edge[0])
if a == b or subA is not None and subA is subB:
continue
if subA and subB:
subA |=... | Make a spanning tree | 5ae8e14c1839f14b2c00007a | [
"Algorithms",
"Trees",
"Graph Theory"
] | https://www.codewars.com/kata/5ae8e14c1839f14b2c00007a | 6 kyu |
There are pillars near the road. The distance between the pillars is the same and the width of the pillars is the same.
Your function accepts three arguments:
1. number of pillars (β₯ 1);
2. distance between pillars (10 - 30 meters);
3. width of the pillar (10 - 50 centimeters).
Calculate the distance between the first... | reference | def pillars(num_pill, dist, width):
return dist * 100 * (num_pill - 1) + width * (num_pill - 2) * (num_pill > 1)
| Pillars | 5bb0c58f484fcd170700063d | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/5bb0c58f484fcd170700063d | 8 kyu |
# Your Task
Before bridges were common, ferries were used to transport cars across rivers. River ferries, unlike their larger cousins, run on a guide line and are powered by the riverβs current. Cars drive onto the ferry from one end, the ferry crosses the river, and the cars exit from the other end of the ferry.
Ther... | reference | def ferry_loading(length, loads):
n, (l, r) = 0, ([t for t, side in loads if side == s]
for s in ['left', 'right'])
while l or r:
n += 1
loaded = 0
while l and loaded + l[0] <= length * 100:
loaded += l . pop(0)
l, r = r, l
return n
| Ferry Loading | 5b9a6d77d16ffeea92000102 | [
"Fundamentals"
] | https://www.codewars.com/kata/5b9a6d77d16ffeea92000102 | 6 kyu |
In this kata, you're required to simulate the movement of a snake in a given 2D field following a given set of moves. The simulation ends when either of the following conditions is satisfied:
+ All moves have been executed
+ Snake collides with the boundary or with itself.
### Concepts:
+ #### Growth
When the snake... | games | from collections import deque
d = {'U': (- 1, 0), 'D': (1, 0), 'L': (0, - 1), 'R': (0, 1)}
def snake_collision(field, moves):
field = [list(x) for x in field]
moves = ['R'] + moves . split()
current_snake = deque([(0, 0), (0, 1), (0, 2)])
HEIGHT, WIDTH = 13, 21
cur_head, step = (0, 2), 0
... | Snake Collision | 5ac616ccbc72620a6a000096 | [
"Arrays",
"Games",
"Algorithms",
"Simulation",
"Puzzles"
] | https://www.codewars.com/kata/5ac616ccbc72620a6a000096 | 5 kyu |
<center><img src="https://i.imgur.com/VE4Jstv.png"></center>
One of my favorite games I played in elementary school (that I may or may not still sometimes play) was <a href= "https://en.wikipedia.org/wiki/Heroes_of_Might_and_Magic_II">Heroes of Might and Magic II: The Succession Wars</a>, a 2D, turn-based RPG. One of ... | reference | from itertools import chain, cycle, islice
def chain_lightning(monsters, coordinates, spellpower):
r, c = coordinates
ms = chain . from_iterable(
row[slice_] for row, slice_ in zip(
islice(monsters, r, None),
chain([slice(c, None)], cycle(
[slice(None, ... | Heroes of Might & Magic II: Chain Lightning | 5b09cd44ee196bf290000082 | [
"Arrays",
"Games",
"Fundamentals"
] | https://www.codewars.com/kata/5b09cd44ee196bf290000082 | 6 kyu |
In a factory a printer prints labels for boxes. The printer uses colors which, for the sake of simplicity, are named with letters from a to z (except letters `u`, `w`, `x` or `z` that are for errors).
The colors used by the printer are recorded in a control string. For example a control string would be `aaabbbbhaijjjm... | reference | from collections import Counter
ERRORS = 'uwxz'
def hist(s):
cnts = Counter(s)
return '\r' . join(f' { c } { cnts [ c ]: < 6 }{ "*" * cnts [ c ]} ' for c in ERRORS if cnts[c])
| Errors : histogram | 59f44c7bd4b36946fd000052 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/59f44c7bd4b36946fd000052 | 6 kyu |
Inspired by another Kata - <a href="http://www.codewars.com/kata/heroes-of-might-and-magic-ii-chain-lightning">Heroes of Might & Magic II: Chain Lightning</a> by Firefly2002, I thought I might have a go at another Kata related to this game.
___
In this Kata, two groups of monsters will attack each other, and your job... | reference | from math import ceil
def who_would_win(mon1, mon2):
mon1['allhit'] = mon1['hitpoints'] * mon1['number']
mon2['allhit'] = mon2['hitpoints'] * mon2['number']
while True:
mon2['allhit'] = mon2['allhit'] - mon1['number'] * mon1['damage']
mon2['number'] = ceil(mon2['allhit'] / mon2['hitpoints'... | Heroes of Might & Magic II: One-on-One | 5b114e854de8651b6b000123 | [
"Fundamentals"
] | https://www.codewars.com/kata/5b114e854de8651b6b000123 | 6 kyu |
<style>
#sb {
width: 200px;
margin-bottom: 20px;
}
#sb #sbtd, #sbtitle {
text-align: right;
}
#sb #sbth, #sbtd {
background-color: #0a290a;
color: gold;
}
#sbtitle {
background-color: #0a290a;
color: white;
font-size: 1em;
border-collapse: collapse;
border: 2px solid gray;
padding: 0px 15px 0px 0p... | algorithms | PTS = ["0", "15", "30", "40", "AD"]
def formatScores(who, pts, games):
iScore = min(3, pts[who]) + (pts[who] > 3 and pts[who]
> pts[who ^ 1]) # Take care of "AD"
return [str(games[who]), PTS[iScore]]
def wimbledon(balls):
games, pts = [0, 0], [0, 0] # Games score / ... | Wimbledon Scoreboard - Game | 5b4bccfabeb865730d000062 | [
"Algorithms"
] | https://www.codewars.com/kata/5b4bccfabeb865730d000062 | 5 kyu |
Given a random bingo card and an array of called numbers, determine if you have a bingo!
*Parameters*: `card` and `numbers` arrays.
*Example input*:
```
card = [
['B', 'I', 'N', 'G', 'O'],
[1, 16, 31, 46, 61],
[3, 18, 33, 48, 63],
[5, 20, 'FREE SPACE', 50, 65],
[7, 22, 37, 52, 67],
[9, 24, 39, 54, 69]
]
... | reference | def bingo(card, numbers):
# rows count, columns count, diag counts
rc, cc, dc = [0] * 5, [0] * 5, [1] * 2
rc[2] = cc[2] = 1 # preaffect 'FREE SPACE'
s = set(numbers)
for x, line in enumerate(card[1:]):
for y, (c, n) in enumerate(zip(card[0], line)):
tile = f' { c }{ n } '
if... | Bingo! | 5af304892c5061951e0000ce | [
"Fundamentals",
"Games",
"Arrays"
] | https://www.codewars.com/kata/5af304892c5061951e0000ce | 6 kyu |
Yup!! The problem name reflects your task; just add a set of numbers. But you may feel yourselves condescended, to write a program just to add a set of numbers. Such a problem will simply question your erudition. So, let's add some flavor of ingenuity to it. Addition operation requires cost now, and the cost is the sum... | reference | from heapq import *
def add_all(lst):
heapify(lst)
total = 0
while len(lst) > 1:
s = heappop(lst) + heappop(lst)
total += s
heappush(lst, s)
return total
| Add All | 5b7d7ce57a0c9d86c700014b | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/5b7d7ce57a0c9d86c700014b | 6 kyu |
# Task
John is a programmer. He treasures his time very much. He lives on the `n` floor of a building. Every morning he will go downstairs as quickly as possible to begin his great work today.
There are two ways he goes downstairs: walking or taking the elevator.
When John uses the elevator, he will go through the f... | reference | def shorterest_time(n, m, speeds):
if n == 0:
return 0
a, b, c, d = speeds
return min(
n * d,
abs(n - m) * d + b * 2 + c + m * a,
abs(n - m) * a + b * 2 + c + n * a
)
| Simple Fun #326a: The Shorterest Time | 5953c6f8af7ac14fd4000021 | [
"Puzzles",
"Games",
"Fundamentals"
] | https://www.codewars.com/kata/5953c6f8af7ac14fd4000021 | 6 kyu |
# History
This kata is a sequel of my [Mixbonacci](https://www.codewars.com/kata/mixbonacci/python) kata. Zozonacci is a special integer sequence named after [**ZozoFouchtra**](https://www.codewars.com/users/ZozoFouchtra), who came up with this kata idea in the [Mixbonacci discussion](https://www.codewars.com/kata/mix... | reference | from itertools import cycle
ROOT = {'fib': [0, 0, 0, 1],
'jac': [0, 0, 0, 1],
'pad': [0, 1, 0, 0],
'pel': [0, 0, 0, 1],
'tet': [0, 0, 0, 1],
'tri': [0, 0, 0, 1]}
GEN = {'fib': lambda a: a[- 1] + a[- 2],
'jac': lambda a: a[- 1] + 2 * a[- 2],
'pad': lambda a:... | Zozonacci | 5b7c80094a6aca207000004d | [
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/5b7c80094a6aca207000004d | 6 kyu |
You are in the capital of Far, Far Away Land, and you have heard about this museum where the royal family's crown jewels are on display. Before you visit the museum, a friend tells you to bring some extra money that you'll need to bribe the guards. You see, he says, the crown jewels are in one of 10 rooms numbered from... | reference | def least_bribes(bribes):
mem = {}
def s(n1, n2):
if n1 >= n2:
return 0
if (n1, n2) in mem:
return mem[n1, n2]
r = min(bribes[i] + max(s(n1, i), s(i + 1, n2)) for i in range(n1, n2))
mem[n1, n2] = r
return r
return s(0, len(bribes))
| Bribe the Guards of the Crown Jewels | 56d5078e945d0d5d35001b74 | [
"Dynamic Programming",
"Algorithms"
] | https://www.codewars.com/kata/56d5078e945d0d5d35001b74 | 4 kyu |
SHA-1 is arguably the most widely used hash algorithm in the world at the moment. However, due to speculation that the hash algorithm will be broken soon, it will be eventually phased out (It has been broken; see https://www.theverge.com/2017/2/23/14712118/google-sha1-collision-broken-web-encryption-shattered). Nonethe... | algorithms | class SHA1:
def __init__(self):
self . message = []
self . H = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]
self . K = [0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6]
self . F = [lambda b, c, d: (b & c) | ((~ b) & d),
lambda b, c, d: b ^ c ^ d,
... | Implementing SHA-1 | 56f2f3dfe40b70a005001389 | [
"Cryptography",
"Algorithms"
] | https://www.codewars.com/kata/56f2f3dfe40b70a005001389 | 4 kyu |
In this Kata, you will be given boolean values and boolean operators. Your task will be to return the number of arrangements that evaluate to `True`.
`t,f` will stand for `true, false` and the operators will be `Boolean AND (&), OR (|), and XOR (^)`.
For example, `solve("tft","^&") = 2`, as follows:
* `"((t ^ f... | algorithms | from functools import lru_cache
from operator import and_, or_, xor
FUNCS = {'|': or_, '&': and_, '^': xor}
def solve(s, ops):
@ lru_cache(None)
def evaluate(s, ops):
c = [0, 0]
if not ops:
c[s == 't'] += 1
else:
for i in range(len(ops)):
for v, n in enumerate(evaluate(s... | The boolean order | 59eb1e4a0863c7ff7e000008 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/59eb1e4a0863c7ff7e000008 | 3 kyu |
# Telephone numbers
When you start to enter a phone number, the smartphone proposes you some choices of possible phone numbers from your repertory.
The goal of this kata is to save the phone numbers by keeping in common the same parts of the phone numbers thus reducing the total size of the repertory.
# Goal
Your f... | games | def phone_number(phone_numbers):
return len({num[: i] for num in phone_numbers for i in range(1, len(num) + 1)})
| Phone numbers | 582b59f45ad9526ae6000249 | [
"Puzzles",
"Graph Theory"
] | https://www.codewars.com/kata/582b59f45ad9526ae6000249 | 5 kyu |
Your wizard cousin works at a Quidditch stadium and wants you to write a function that calculates the points for the Quidditch scoreboard!
# Story
Quidditch is a sport with two teams. The teams score goals by throwing the Quaffle through a hoop, each goal is worth **10 points**.
The referee also deducts 30 points (... | reference | def quidditch_scoreboard(teams, actions):
teams = {i: 0 for i in teams . split(' vs ')}
for i in actions . split(', '):
team, action = i . split(': ')
if 'goal' in action:
teams[team] += 10
elif 'foul' in action :
teams [ team ] -= 30
elif 'Snitch' in action :
teams [ team ] += 150
... | Quidditch Scoreboard | 5b62f8a5b17883e037000136 | [
"Fundamentals",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5b62f8a5b17883e037000136 | 6 kyu |
We are interested in obtaining two scores from a given integer:
**First score**: The sum of all the integers obtained from the power set of the digits of the given integer that have the same order
E.g:
```
integer = 1234 ---> (1 + 2 + 3 + 4) + (12 + 13 + 14 + 23 + 24 + 34) +
(123 + 124 + 134 + 234) + 1234 = 10 + 12... | reference | def score(sub_gen): return lambda n: sum(int('' . join(sub))
for length in range(1, len(str(n)) + 1) for sub in sub_gen(str(n), length))
score1 = score(__import__('itertools'). combinations)
score2 = score(lambda s, r: (s[i: i + r] for i in range(len(s) - r + 1)))
de... | What Would They Have in Common? | 58e8561f06db4d4cc600008c | [
"Mathematics",
"Strings",
"Data Structures",
"Sorting",
"Performance",
"Algorithms",
"Fundamentals"
] | https://www.codewars.com/kata/58e8561f06db4d4cc600008c | 5 kyu |
Based on [this kata, Connect Four.](https://www.codewars.com/kata/connect-four-1)
In this kata we play a modified game of connect four. It's connect X, and there can be multiple players.
Write the function ```whoIsWinner(moves,connect,size)```.
```2 <= connect <= 10```
```2 <= size <= 52```
Each column is identifi... | algorithms | from string import ascii_lowercase, ascii_uppercase
char_to_index = {c: i for i, c in enumerate(ascii_uppercase + ascii_lowercase)}
# assumes a space character isn't used to represent a player
def who_is_winner(moves, connect_size, size):
board, winner = [[' ' for i in range(size)] for j in range(size)], ''... | NxN Connect X | 5b442a063da310049b000047 | [
"Games",
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/5b442a063da310049b000047 | 5 kyu |
Given an array of integers, find the minimum number of elements to remove from the array so that the square root of the largest integer in the array is less or equal to the smallest number in the same array.
`x` = smallest integer in the array
`y` = largest integer in the array
Find the minimum number of elements to... | algorithms | from bisect import bisect_left
from math import sqrt
def min_remove(xs):
xs = sorted(xs)
return min(bisect_left(xs, sqrt(x)) + nr for nr, x in enumerate(reversed(xs)))
| Minimum Reduction | 5ba47374b18e382069000052 | [
"Algorithms"
] | https://www.codewars.com/kata/5ba47374b18e382069000052 | 6 kyu |
This kata was seen in programming competitions with a wide range of variations.
A strict bouncy array of numbers, of length three or longer, is an array that each term (neither the first nor the last element) is strictly higher or lower than its neighbours.
For example, the array:
```
arr = [7,9,6,10,5,11,10,12,13,4,2... | reference | def longest_bouncy_list(arr):
sub, maxSub = [], []
for v in arr:
if not sub or v != sub[- 1] and (len(sub) == 1 or (sub[- 1] - sub[- 2]) * (sub[- 1] - v) > 0):
sub . append(v)
else:
sub = sub[- 1:] + [v] if v != sub[- 1] else [v]
if len(sub) > len(maxSub):
maxSub = sub
... | Longest Strict Bouncy Subarray | 5b483e70a4bc16eda40000f9 | [
"Performance",
"Algorithms",
"Mathematics",
"Data Structures",
"Arrays"
] | https://www.codewars.com/kata/5b483e70a4bc16eda40000f9 | 6 kyu |
Implement a function which takes a string, and returns its hash value.
Algorithm steps:
* `a` := sum of the ascii values of the input characters
* `b` := sum of every difference between the consecutive characters of the input (second char minus first char, third minus second, ...)
* `c` := (`a` OR `b`) AND ((NOT `a`)... | reference | def string_hash(s):
a = sum(ord(c) for c in s)
b = sum(ord(b) - ord(a) for a, b in zip(s, s[1:]))
c = (a | b) & (~ a << 2)
return c ^ (32 * (s . count(" ") + 1))
| BAD Hash - String to Int | 596d93bd9b6a5df4de000049 | [
"Fundamentals"
] | https://www.codewars.com/kata/596d93bd9b6a5df4de000049 | 7 kyu |
# Your Task
You have a cuboid with dimensions x,y,z β β. The values of x, y, and z are between 1 and 10^9. A subcuboid of this cuboid has dimensions length, width, height β β where 1β€lengthβ€x, 1β€widthβ€y, 1β€heightβ€z. If two subcuboids have the same length, width, and height, but they are at different positions within th... | games | def subcuboids(x, y, z):
return x * y * z * (x + 1) * (y + 1) * (z + 1) / / 8
| Subcuboids | 5b9e29dc1d5ed219910000a7 | [
"Mathematics",
"Puzzles",
"Performance"
] | https://www.codewars.com/kata/5b9e29dc1d5ed219910000a7 | 7 kyu |
Find the most adjacent integers of the same value in a grid (2D array). Integers are only considered adjacent to their neighbors vertically and horizontally, not diagonally.
If there are different integers with the same amount of adjacent neighbors, choose the smallest integer for the answer.
Input:
N x N 2D array ... | algorithms | from collections import defaultdict
def find_most_adjacent(grid):
seeds, seens, N = defaultdict(list), set(), len(grid)
for x, row in enumerate(grid):
for y, v in enumerate(row):
if (x, y) in seens:
continue # Already filled, go to the next
seeds[v]. append(0) # Initiate the new seed ... | Find the most adjacent integers of the same value in a grid | 5b258cf6d74b5b7105000035 | [
"Algorithms"
] | https://www.codewars.com/kata/5b258cf6d74b5b7105000035 | 5 kyu |
You are given a (small) check book as a - sometimes - cluttered (by non-alphanumeric characters) string:
```
"1000.00
125 Market 125.45
126 Hardware 34.95
127 Video 7.45
128 Book 14.32
129 Gasoline 16.10"
```
The first line shows the original balance.
Each other line (when not blank) gives information: check number, ... | reference | import re
PATTERN = re . compile(r'([\d.]+)[^\w\n]*([a-zA-Z]+)[^\w\n]*([\d.]+)')
def balance(book):
balance, lst, (b, s) = 0, [], book . split('\n', 1)
iBal = balance = float(next(re . finditer(r'[\d.]+', b)). group())
lst . append("Original Balance: {:.2f}" . format(balance))
for num, item,... | Easy Balance Checking | 59d727d40e8c9dd2dd00009f | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/59d727d40e8c9dd2dd00009f | 6 kyu |

The walker
The walker starts from point O, walks along OA, AB and BC. When he is in C (C will be in the upper half-plane), what is the distance `CO`? What is the angle `tOC` in positive degrees, minutes, seconds?
Angle `tOA` is `alpha` (here 45 degrees), angle `... | reference | from cmath import rect, polar
from math import degrees, radians
def solve(a, b, c, alpha, beta, gamma):
dist, angle = polar(rect(a, radians(alpha)) + rect(b,
radians(beta + 90)) + rect(c, radians(gamma + 180)))
degree, temp = divmod(degrees(angle) * 60, 60)
minute, temp = d... | The Walker | 5b40b666dfb4291ad9000049 | [
"Fundamentals",
"Geometry"
] | https://www.codewars.com/kata/5b40b666dfb4291ad9000049 | 6 kyu |
You are given a *small* extract of a catalog:
```
s = "<prod><name>drill</name><prx>99</prx><qty>5</qty></prod>
<prod><name>hammer</name><prx>10</prx><qty>50</qty></prod>
<prod><name>screwdriver</name><prx>5</prx><qty>51</qty></prod>
<prod><name>table saw</name><prx>1099.99</prx><qty>5</qty></prod>
<prod><name>saw... | reference | import xml . etree . ElementTree as ET
def catalog(s, article):
root = ET . fromstring('<cat>' + s + '</cat>')
resp = []
for child in root:
name = child . find('name'). text
price = child . find('prx'). text
quantity = child . find('qty'). text
if article in name:
resp .... | Catalog | 59d9d8cb27ee005972000045 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/59d9d8cb27ee005972000045 | 6 kyu |
A wildlife study involving ducks is taking place in North America. Researchers are visiting some wetlands in a certain area taking a survey of what they see. The researchers will submit reports that need to be processed by your function.
## Input
The input for your function will be an array with a list of common duc... | reference | def create_report(names):
result = {}
for name in names:
if name . startswith("Labrador Duck"):
return ["Disqualified data"]
name = name . upper(). replace("-", " "). split()
count = int(name . pop())
if len(name) == 1:
code = name[0][: 6]
elif len(name) == 2:
... | Process Waterfowl Survey Data Results | 5b0737c724c0686bf8000172 | [
"Arrays",
"Regular Expressions",
"Fundamentals",
"Data Science"
] | https://www.codewars.com/kata/5b0737c724c0686bf8000172 | 6 kyu |
I got lots of files beginning like this:
```
Program title: Primes
Author: Kern
Corporation: Gold
Phone: +1-503-555-0091
Date: Tues April 9, 2005
Version: 6.7
Level: Alpha
```
Here we will work with strings like the string data above and not with files.
The function `change(s, prog, version)` given:
`s=data, prog="La... | reference | import re
def change(data, new_program, new_version):
try:
curr_phone = re . search(
r'^Phone\: (\+1-\d{3}-\d{3}-\d{4})$', data, re . M). group(1)
curr_version = re . search(
r'^Version\: (\d+\.\d+)$', data, re . M). group(1)
except:
return 'ERROR: VERSION or PHONE'
... | Matching And Substituting | 59de1e2fe50813a046000124 | [
"Fundamentals"
] | https://www.codewars.com/kata/59de1e2fe50813a046000124 | 5 kyu |
Removed due to copyright infringement.
<!---
 You are given a set of `n` sections on a number line, each segment has integer endpoints between `0` and `m` inclusive.<br>
 Sections may intersect, overlap or even coincide with each other. Each section is characterized by two integers l<sub>i</sub> and r<sub>i... | algorithms | def segments(m, arr):
return [i for i in range(m + 1) if not any(a <= i <= b for a, b in arr)]
| Points in Segments | 5baa25f3246d071df90002b7 | [
"Algorithms",
"Logic"
] | https://www.codewars.com/kata/5baa25f3246d071df90002b7 | 7 kyu |
Remove the duplicates from a list of integers, keeping the last ( rightmost ) occurrence of each element.
### Example:
For input: `[3, 4, 4, 3, 6, 3]`
* remove the `3` at index `0`
* remove the `4` at index `1`
* remove the `3` at index `3`
Expected output: `[4, 6, 3]`
More examples can be found in the test cases.... | reference | def solve(arr):
re = []
for i in arr[:: - 1]:
if i not in re:
re . append(i)
return re[:: - 1]
| Simple remove duplicates | 5ba38ba180824a86850000f7 | [
"Fundamentals"
] | https://www.codewars.com/kata/5ba38ba180824a86850000f7 | 7 kyu |
In the web we have many available colours that we may use with html. The different variations or arrangements, for a design in the web may climb up if we increase the amount of used colours, specially because the order matters for the different designs.
An "expert" uses a formula that relates the amount of designs wit... | reference | from bisect import bisect
a = [0]
for n in range(1, 150):
a . append((a[- 1] + 1) * n)
total_var = lambda n , c : [bisect (a , n ), a [len (c )]] | Counting the Webdesigns based on Used Colours | 5b3cdb419c9a75664e00013e | [
"Performance",
"Algorithms",
"Mathematics",
"Machine Learning",
"Combinatorics",
"Number Theory"
] | https://www.codewars.com/kata/5b3cdb419c9a75664e00013e | 5 kyu |
<a href="https://imgur.com/Z7HiIU4"><img src="https://i.imgur.com/Z7HiIU4.jpg?1" title="source: imgur.com" /></a>
Cramer (1704 -1752), the swiss mathematician that created a method to solve systems of n linear equations with n variables.
We have a linear system of ```n Equations``` with ```n Variables``` like the fol... | reference | import numpy as np
def cramer_solver(* args):
m, v = map(np . array, args)
if set(m . shape) != {len(v)}:
return "Check entries"
det = round(np . linalg . det(m))
subDets = []
for y in range(len(v)):
stored = list(m[:, y])
m[:, y] = v
subDets . append(round(np . l... | Cramer, thanks for your contribution! | 5b4a9158f1d553b3be0000c0 | [
"Fundamentals",
"Data Structures",
"Arrays",
"Mathematics",
"Algebra"
] | https://www.codewars.com/kata/5b4a9158f1d553b3be0000c0 | 6 kyu |
If we multiply the integer `717 (n)` by `7 (k)`, the result will be equal to `5019`.
Consider all the possible ways that this last number may be split as a string and calculate their corresponding sum obtained by adding the substrings as integers. When we add all of them up,... surprise, we got the original number `7... | reference | def sum_part(n):
m, p, q, r, s = 1, 1, 1, 0, n
while n > 9:
n, d = divmod(n, 10)
r += d * p
p *= 10
if d:
m = 1
else:
m *= 2
s += q * n + m * memo[r]
q *= 2
return s
from collections import defaultdict
qualified = defaultdict(list)
memo ... | Next Higher Value # 1 | 5b713d7187c59b53e60000b0 | [
"Fundamentals",
"Data Structures",
"Arrays",
"Mathematics",
"Algebra"
] | https://www.codewars.com/kata/5b713d7187c59b53e60000b0 | 5 kyu |
You are given the head node of a singly-linked list. Write a method that swaps each pair of nodes in the list, then returns the head node of the list.
You have to swap the nodes themselves, not their values.
Example:
`(A --> B --> C --> D) => (B --> A --> D --> C)`
The swapping should be done left to right, so if th... | algorithms | from preloaded import Node
def swap_pairs(head):
if head == None or head . next == None:
return head
A, B, C = head, head . next, head . next . next
B . next = A
A . next = swap_pairs(C)
return B
| Swap Node Pairs In Linked List | 59c6f43c2963ecf6bf002252 | [
"Algorithms",
"Data Structures",
"Linked Lists"
] | https://www.codewars.com/kata/59c6f43c2963ecf6bf002252 | 5 kyu |
We define a range with two positive integers ```n1``` and ```n2``` and an integer factor ```k```, ```[n1, n1 + k*n2]```, the bounds of the defined range are included.
~~~if:ruby,rust,python
We will be given two arrays: ```prime_factors``` and ```digits```.
```
prime_factors = [p1, p2, ..., pl] # p1, p2, ... and pl a... | algorithms | from math import lcm
def find_us(n1, n2, k, prime_factors, digits):
step, digits, end = 1, '' . join(map(str, digits)), 1 + n1 + k * n2
for p in prime_factors:
step = lcm(step, p)
while n1 % step:
n1 += 1
return [i for i in range(n1, end, step) if all(j in str(i) for j in digits)]
| Find a Very Special Set Of Numbers In a Certain Range | 569df0bc5565b243d500002b | [
"Fundamentals",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/569df0bc5565b243d500002b | 6 kyu |
We are given a sequence of coplanar points and see all the possible triangles that may be generated which all combinations of three points.
We have the following list of points with the cartesian coordinates of each one:
```
Points [x, y]
A [1, 2]
B [3, 3]
C [4, 1]
D [1, 1]
E [4, -1]
```
With ... | reference | from itertools import combinations
def isRect(a, b, c):
X, Y, Z = sorted(sum((q - p) * * 2 for p, q in zip(p1, p2)) for p1, p2 in [(a, b), (a, c), (b, c)])
return X + Y == Z
def count_rect_triang(points):
return sum(isRect(* c) for c in combinations(set(map(tuple, points)), 3))
| Counting Rectangle Triangles | 57d99f6bbfcdc5b3b0000286 | [
"Fundamentals",
"Mathematics",
"Geometry",
"Algorithms",
"Logic"
] | https://www.codewars.com/kata/57d99f6bbfcdc5b3b0000286 | 6 kyu |
**1. - You are given an array of positive integers as argument. You must generate all the possible divisions between each pair of its elements that outputs an integer value.**
For example:
```
arr = [2, 4, 27, 16, 9, 15, 25, 6, 12, 83, 24, 49, 7, 5, 94, 12, 6]
```
You must then create a list, sorted by the quotient va... | reference | def sel_quot(a, m, s=0): return sorted((n / d, (n, d)) for d, n in __import__('itertools'). combinations(
sorted(set(a)), 2) if n % d == 0 and n / d >= m and (not s or n / d % 2 == (s[1] == "d")))
| Selecting Quotients From an Array | 569f6ad962ff1dd52f00000d | [
"Fundamentals",
"Data Structures",
"Algorithms",
"Sorting",
"Mathematics",
"Logic"
] | https://www.codewars.com/kata/569f6ad962ff1dd52f00000d | 6 kyu |
The ```digit root``` of a number ```(dr)``` is the sum of the digits of a number.
For example, the integer ```749```, has a digit root equals to ```20```.
In effect: ```7 + 4 + 9 = 20```.
We define here the ```deeper square double digit root``` of an integer ```n```, ```(dsddr)```, the sum of the squares of every dig... | reference | def f(n):
dr = sum(map(int, str(n)))
deep = sum(d * d for d in map(int, str(dr)))
return (- dr - deep, n)
def sorted_comm_by_digs(arr1, arr2):
return sorted(set(arr1) & set(arr2), key=f)
| Warm Up for Speed. | 5b4dee5d05f04bba43000138 | [
"Performance",
"Algorithms",
"Mathematics",
"Data Structures",
"Arrays",
"Sorting",
"Fundamentals"
] | https://www.codewars.com/kata/5b4dee5d05f04bba43000138 | 6 kyu |
# Your task
X and Y are playing a game. A list will be provided which contains `n` pairs of strings and integers. They have to add the integer<sub>i</sub> to the ASCII values of the string<sub>i</sub> characters. Then they have to check if any of the new added numbers is prime or not. If for any character of the word t... | reference | from gmpy2 import is_prime as ip
def ok(w):
a, b = w
return any(ip(ord(j) + b) for j in a)
def prime_word(a):
return [1 if ok(i) else 0 for i in a]
| Prime Word | 5b1e2c04553292dacd00009e | [
"Fundamentals"
] | https://www.codewars.com/kata/5b1e2c04553292dacd00009e | 6 kyu |
We have got a gun that shoots little balls of painting of different colours. We want to calculate the probability in having a certain number of shots with certain colours in a specific order.
Before start shooting, the balls are mixed in such way that each ball has the same probabilty of being selected to be shot. Thi... | reference | from collections import Counter
from math import gcd
def find_prob(balls_set, event):
cntr = Counter(balls_set)
nm, dn, ln = 1, 1, len(balls_set)
for vtn in map(ABBREVIATIONS . get, event):
nm *= cntr[vtn]
dn *= ln
cntr[vtn] -= 1
ln -= 1
g = gcd(nm, dn)
return [nm / ... | "Shoot But As I've Seen It In My Imagination" | 5b8ea6bbcc7c0335f80001a9 | [
"Arrays",
"Mathematics",
"Algebra",
"Probability",
"Data Science"
] | https://www.codewars.com/kata/5b8ea6bbcc7c0335f80001a9 | 6 kyu |
We have two consecutive integers k<sub>1</sub> and k<sub>2</sub>, k<sub>2</sub> = k<sub>1</sub> + 1
We need to calculate the lowest strictly positive integer `n`, such that:
the values nk<sub>1</sub> and nk<sub>2</sub> have the same digits but in different order.
E.g.# 1:
```
k1 = 100
k2 = 101
n = 8919
#Because 8919 ... | reference | def find_lowest_int(k1):
k2, n = k1 + 1, 1
def digits(n):
return sorted(str(n))
while digits(n * k1) != digits(n * k2):
n += 1
return n
| Multiples By Permutations II | 5ba178be875de960a6000187 | [
"Fundamentals",
"Data Structures",
"Strings",
"Mathematics",
"Algebra",
"Sorting",
"Combinatorics"
] | https://www.codewars.com/kata/5ba178be875de960a6000187 | 7 kyu |
# Your Task
You have a Petri dish with bacteria, and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them.
You know that you have `n` bacteria in the Petri dish and size of the i-th bacteria is bacteria<sub>i</sub>. Also you know interg... | reference | def micro_world(bacteria, k):
return sum(1 for e in bacteria if not [j for j in bacteria if e < j <= e + k])
| Micro-World | 5ba068642ab67b95da00011d | [
"Fundamentals"
] | https://www.codewars.com/kata/5ba068642ab67b95da00011d | 6 kyu |
## Welcome
In this kata, we'll play a mini-game `Flou`.

## Task
You are given a `gameMap`, like this:
```
+----+
|.B..| +,-,| --> The boundary of game map
|....| B --> The initial color block
|....| . --> The empty block
|..B.| It is always a ... | games | from itertools import permutations
def play_flou(game_map):
flou = Flou(parse_grid(game_map))
moves = flou . solve()
return format_moves(moves) if moves else False
def format_moves(moves):
dirs = {1: 'Right', 1j: 'Down', - 1: 'Left', - 1j: 'Up'}
return [[int(pos . imag), int(pos . rea... | Flou--Play game Series #9 | 5a93754d0025e98fde000048 | [
"Puzzles",
"Games",
"Game Solvers"
] | https://www.codewars.com/kata/5a93754d0025e98fde000048 | 2 kyu |
You are Cody Block, pro skater, and you are about to enter the competition that will define your career. You must decide what tricks will make up your "run," or routine, to **maximize its expected point value**.
You will be given a list of tricks, and you must return a dictionary indicating how many times each trick s... | reference | def run(tricks):
def score(attempt):
total_points = 0
total_probability = 1
for trick in tricks:
points = trick["points"]
mult_base = trick["mult_base"]
quantity = attempt[trick["name"]]
probability = trick["probability"]
total_points += points * (mult_base * * quantity - ... | Cody Block's Pro Skater | 5ba0adafd6b09fd23c000255 | [
"Statistics",
"Probability",
"Fundamentals",
"Data Science"
] | https://www.codewars.com/kata/5ba0adafd6b09fd23c000255 | 6 kyu |
<h1><u>Theory</u></h1>
<p> <i>This section does not need to be read and can be skipped, but it does provide some clarity into the inspiration behind the problem.</i></p>
<p>In music theory, <a href = "https://en.wikipedia.org/wiki/Major_scale">a major scale</a> consists of seven notes, or <a href = "https://en.wikipe... | algorithms | def is_tune(notes):
return bool(notes) and any(
all((n + i) % 12 in {0, 2, 4, 5, 7, 9, 11} for n in notes)
for i in range(12)
)
| intTunes | 5b8dc84b8ce20454bd00002e | [
"Arrays",
"Lists",
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/5b8dc84b8ce20454bd00002e | 7 kyu |
# Your Task
The city of Darkishland has a strange hotel with infinite rooms. The groups that come to this hotel follow the following rules:
* At the same time only members of one group can rent the hotel.
* Each group comes in the morning of the check-in day and leaves the hotel in the evening of the check-out day.
... | reference | from math import sqrt, ceil
# 1st group spends in the hotel s days,
# 2nd group - s + 1 days,
# 3rd group - s + 2 days,
# ...,
# nth group - s + n - 1 days.
#
# The total number of days for n groups: n * (s + s + n - 1) / 2
# (by the formula of arithmetic series).
# Let d be the last day of the nth group. Then
# n * (s... | The Hotel with Infinite Rooms | 5b9cf881d6b09fc9ee0002b1 | [
"Fundamentals",
"Mathematics",
"Performance"
] | https://www.codewars.com/kata/5b9cf881d6b09fc9ee0002b1 | 7 kyu |
## Welcome
In this kata, we'll playing with a mini game `Switch the Bulb`.
<div style="max-width: 800px; margin: 0 auto;">
<img alt="Switch the Bulb" src="https://files.gitter.im/myjinxin2015/XP36/blob" style="max-width: 480px; margin: 0 auto;">
</div>
## Rule
<!--
:
def __init__(self, x, y): super(). __init__(); self . pos = x, y
def __hash__(self): return hash(self . pos)
def __eq__(self, o): return self . pos == o . pos
def __str__(self): return "({},{})" . format(* self . pos)
def switch_bulbs(s):
... | Switch the Bulb--Play game Series #10 | 5a96064cfd57777828000187 | [
"Puzzles",
"Games",
"Game Solvers"
] | https://www.codewars.com/kata/5a96064cfd57777828000187 | 3 kyu |
The King and Queen of FarFarAway are going to pay Shrek and Fiona a visit at their swamp. However, Shrek is afraid that Donkey is going to be naughty *again*, so he decides to tie him up so he will not disturb the royal dinner. Shrek grows a circular patch of delicious grass, and decides to rope Donkey to a fence post ... | reference | from math import acos, pi, sqrt
def area(r, R):
# http://mathworld.wolfram.com/Circle-CircleIntersection.html
return (
r * * 2 * acos(r / 2 / R)
+ R * * 2 * acos(1 - r * r / 2 / R / R)
- sqrt(r * r * (R + R - r) * (R + R + r)) / 2
)
def get_rope_length(diameter, rat... | Grazing Donkey | 5b5ce2176d0db7331f0000c0 | [
"Geometry",
"Performance"
] | https://www.codewars.com/kata/5b5ce2176d0db7331f0000c0 | 4 kyu |
You've just entered a programming contest and have a chance to win a million dollars. This is the last question you have to solve, so your victory (and your vacation) depend on it. Can you guess the function just by looking at the test cases? There are two numerical inputs and one numerical output. Goodluck!
hint:... | games | TABLE = str . maketrans('0123456789', '9876543210')
def code(* args):
return sum(map(lambda n: int(str(n). translate(TABLE)), args))
| can you guess what it is ? | 5b1fa8d92ae7540e700000f0 | [
"Puzzles"
] | https://www.codewars.com/kata/5b1fa8d92ae7540e700000f0 | 6 kyu |
Suppose you have 4 numbers: `0, 9, 6, 4` and 3 strings composed with them:
```
s1 = "6900690040"
s2 = "4690606946"
s3 = "9990494604"
```
Compare `s1` and `s2` to see how many positions they have in common:
`0` at index 3, `6` at index 4, `4` at index 8 : 3 common positions out of ten.
Compare `s1` and `s3` to see how... | reference | from statistics import mean
from itertools import combinations
def pos_average(s):
return mean(a == b for combo in combinations(s . split(', '), 2) for a, b in zip(* combo)) * 100.
| Positions Average | 59f4a0acbee84576800000af | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/59f4a0acbee84576800000af | 6 kyu |
Given a two-dimensional array of non negative integers ```arr```, a value ```val```, and a coordinate ```coord``` in the form ```(row, column)```, return an iterable (depending on the language) of all of the coordinates that contain the given value and are connected to the original coordinate by the given value. Connec... | algorithms | def connected_values(mat, val, coord):
if mat[coord[0]][coord[1]] != val:
return set()
Q, seen = [coord], {coord}
while Q:
r, c = Q . pop()
for i, j in ((0, 1), (1, 0), (0, - 1), (- 1, 0), (1, 1), (1, - 1), (- 1, 1), (- 1, - 1)):
if (0 <= r + i <= len(mat) - 1) and (0 <= c + j... | Connecting Values | 5562aa03004710f3ab0001d5 | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/5562aa03004710f3ab0001d5 | 5 kyu |
> If you've finished this kata, you can try the [more difficult version](https://www.codewars.com/kata/5b256145a454c8a6990000b5).
## Taking a walk
A promenade is a way of uniquely representing a fraction by a succession of βleft or rightβ choices.
For example, the promenade `"LRLL"` represents the fraction `4/7`.
... | games | def promenade(choices):
def compute(): return l + r, m + s
l, m, r, s = 1, 0, 0, 1
for c in choices:
if c == 'L':
l, m = compute()
else:
r, s = compute()
return compute()
| Promenade Fractions (from BIO 2016) | 5b254b2225c2bb99c500008d | [
"Puzzles"
] | https://www.codewars.com/kata/5b254b2225c2bb99c500008d | 6 kyu |
Imagine you run a business selling some products. Every evening, you run a program that generates a report on the day's sales. The products are grouped into product groups and the report tells you the day's revenue for each product, group, and the grand total. The program takes as input a sequence of tuples `(product_i... | reference | PRODUCT_STRING = " Product: {} Value: {:>6}"
TOTAL_STRING = "Total:{:>32}"
GROUP_STRING = """Group: {}
{}
Group total:{:>22}
"""
def generate_report(records):
ansLst, cGrp, cProd, cTot = [], 0, 0, 0
grpLst, records = [], list(records)
for (prod, grp, val), (nextProd, nextGrp, _) in zip(records, lis... | Sales report | 577f57d7e555335c0d0003a9 | [
"Fundamentals"
] | https://www.codewars.com/kata/577f57d7e555335c0d0003a9 | 6 kyu |
In this Kata, you will be given a series of times at which an alarm sounds. Your task will be to determine the maximum time interval between alarms. Each alarm starts ringing at the beginning of the corresponding minute and rings for exactly one minute. The times in the array are not in chronological order. Ignore dupl... | algorithms | from datetime import datetime
def solve(arr):
dts = [datetime(2000, 1, 1, * map(int, x . split(':')))
for x in sorted(arr)]
delta = max(int((b - a). total_seconds() - 60)
for a, b in zip(dts, dts[1:] + [dts[0]. replace(day=2)]))
return '{:02}:{:02}' . format(* divmod(del... | Simple time difference | 5b76a34ff71e5de9db0000f2 | [
"Algorithms",
"Date Time",
"Strings"
] | https://www.codewars.com/kata/5b76a34ff71e5de9db0000f2 | 6 kyu |
# Background
My TV remote control has arrow buttons and an `OK` button.
I can use these to move a "cursor" on a logical screen keyboard to type words...
# Keyboard
The screen "keyboard" layout looks like this
<style>
#tvkb {
width : 400px;
border: 5px solid gray; border-collapse: collapse;
}
#tvkb t... | algorithms | import re
H, W = 6, 8
KEYBOARD = "abcde123fghij456klmno789pqrst.@0uvwxyz_/* "
MAP = {c: (i / / W, i % W) for i, c in enumerate(KEYBOARD)}
def manhattan(* pts):
dxy = [abs(z2 - z1) for z1, z2 in zip(* pts)]
return 1 + sum(min(dz, Z - dz) for dz, Z in zip(dxy, (H, W)))
def toggle(m):
ups, en... | TV Remote (wrap) | 5b2c2c95b6989da552000120 | [
"Algorithms"
] | https://www.codewars.com/kata/5b2c2c95b6989da552000120 | 6 kyu |
# Background
My TV remote control has arrow buttons and an `OK` button.
I can use these to move a "cursor" on a logical screen keyboard to type words...
# Keyboard
The screen "keyboard" layout looks like this
<style>
#tvkb {
width : 400px;
border: 5px solid gray; border-collapse: collapse;
}
#tvkb td... | algorithms | import re
def tv_remote(words):
letters = {c: (x, y)
for y, row in enumerate((
"abcde123",
"fghij456",
"klmno789",
"pqrst.@0",
"uvwxyz_/",
"β§ "))
for x, c in ... | TV Remote (shift and space) | 5b277e94b6989dd1d9000009 | [
"Algorithms"
] | https://www.codewars.com/kata/5b277e94b6989dd1d9000009 | 6 kyu |
In this Kata, you will be given a number and your task will be to rearrange the number so that it is divisible by `25`, but without leading zeros. Return the minimum number of digit moves that are needed to make this possible. If impossible, return `-1` ( `Nothing` in Haskell ).
For example:
```c
solve(521) = 3 becaus... | reference | def solve(n):
moves = []
for a, b in ["25", "75", "50", "00"]:
s = str(n)[:: - 1]
x = s . find(a)
y = s . find(b, x + 1 if a == "0" else 0)
if x == - 1 or y == - 1:
continue
moves . append(x + y - (x > y) - (a == b))
s = s . replace(a, "", 1). replace(b, "", 1)
l = len(... | Simple number divisibility | 5b165654c8be0d17f40000a3 | [
"Fundamentals"
] | https://www.codewars.com/kata/5b165654c8be0d17f40000a3 | 6 kyu |
<!--Range of Integers in an Unsorted String-->
<p>In this kata, your task is to write a function that returns the smallest and largest integers in an unsorted string. In this kata, a range is considered a finite sequence of consecutive integers.</p>
<h2 style='color:#f88'>Input</h2>
Your function will receive two argu... | games | from collections import Counter
def mystery_range(s, n):
counts = Counter(s)
for num in range(1, 100):
if counts == Counter('' . join(map(str, range(num, num + n)))):
if all(str(i) in s for i in range(num, num + n)):
return [num, num + n - 1]
| Range of Integers in an Unsorted String | 5b6b67a5ecd0979e5b00000e | [
"Algorithms",
"Puzzles"
] | https://www.codewars.com/kata/5b6b67a5ecd0979e5b00000e | 5 kyu |
# Background
Every time you photocopy something the quality of the copy is never quite as good as the original.
But then you make a copy of copy, and then a copy of that copy, et cetera... And the results get worse each time.
This kind of degradation is called <a href="https://en.wikipedia.org/wiki/Generation_loss"... | algorithms | from string import ascii_uppercase, ascii_lowercase
s, D = "#+:. ", {}
for i, c in enumerate(s):
D[c] = s[i:]
for c in ascii_uppercase:
D [c] = c + c . lower () + s
for c in ascii_lowercase:
D[c] = c + s
def generation_loss (orig, copy):
return len (orig ) == len (copy ) and... | Photocopy decay | 5b6fcd9668cb2e282d00000f | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5b6fcd9668cb2e282d00000f | 6 kyu |
# Your task
Oh no... more lemmings!! And in Lemmings Planet a huge battle
is being fought between the two great rival races: the green
lemmings and the blue lemmings. Everybody was now assigned
to battle and they will fight until one of the races completely
dissapears: the Deadly War has begun!
Every single lemming ha... | reference | from heapq import *
def lemming_battle(battlefield, green, blue):
hg, hb = ([- v for v in lst] for lst in (green, blue))
heapify(hg)
heapify(hb)
while hb and hg:
tmp_b, tmp_g = [], []
for _ in range(min(battlefield, len(hg), len(hb))):
cmp = heappop(hg) - heappop(hb)
if cm... | Lemmings Battle! | 5b7d2cca7a2013f79f000129 | [
"Fundamentals",
"Games"
] | https://www.codewars.com/kata/5b7d2cca7a2013f79f000129 | 6 kyu |
We have an array of unique elements. A special kind of permutation is the one that has all of its elements in a different position than the original.
Let's see how many of these permutations may be generated from an array of four elements. We put the original array with square brackets and the wanted permutations with... | reference | def all_permuted(n):
a, b = 0, 1
for i in range(1, n):
a, b = b, (i + 1) * (a + b)
return a
| Shuffle It Up | 5b997b066c77d521880001bd | [
"Performance",
"Algorithms",
"Mathematics",
"Machine Learning",
"Combinatorics",
"Number Theory"
] | https://www.codewars.com/kata/5b997b066c77d521880001bd | 5 kyu |
# Task
Write a function that accepts `msg` string and returns local tops of string from the highest to the lowest.
The string's tops are from displaying the string in the below way:
```
7891012
TUWvXY 6 3
ABCDE S ... | reference | def tops(msg):
n = len(msg)
res, i, j, k = "", 2, 2, 7
while i < n:
res = msg[i: i + j] + res
i, j, k = i + k, j + 1, k + 4
return res
| Square string tops | 5aa3e2b0373c2e4b420009af | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/5aa3e2b0373c2e4b420009af | 6 kyu |
Many years ago, Roman numbers were defined by only `4` digits: `I, V, X, L`, which represented `1, 5, 10, 50`. These were the only digits used. The value of a sequence was simply the sum of digits in it. For instance:
```
IV = VI = 6
IX = XI = 11
XXL = LXX = XLX = 70
```
It is easy to see that this system is ambiguous,... | reference | INITIAL = [0, 4, 10, 20, 35, 56, 83, 116, 155, 198, 244, 292]
def solve(n):
return INITIAL[n] if n < 12 else 292 + (49 * (n - 11))
| Strange roman numbers | 5b983dcd660b1227d00002c9 | [
"Fundamentals"
] | https://www.codewars.com/kata/5b983dcd660b1227d00002c9 | 6 kyu |
There are some perfect squares with a particular property.
For example the number ```n = 256``` is a perfect square, its square root is ```16```. If we change the position of the digits of n, we may obtain another perfect square``` 625``` (square root = 25).
With these three digits ```2```,```5``` and ```6``` we can ge... | reference | from itertools import count, permutations
def next_perfectsq_perm(limit_below, k):
for n in count(int(limit_below * * .5) + 1):
s = str(n * * 2)
if '0' not in s:
sq_set = {x for x in (int('' . join(p)) for p in permutations(s)) if (x * * .5). is_integer()}
if len(sq_set) == k:
return ... | Highest Perfect Square with Same Digits | 5b2cd515553292a4ff0000c2 | [
"Fundamentals",
"Data Structures",
"Algorithms",
"Mathematics",
"Performance",
"Permutations"
] | https://www.codewars.com/kata/5b2cd515553292a4ff0000c2 | 6 kyu |
In this Kata, you will be given directions and your task will be to find your way back.
```Perl
solve(["Begin on Road A","Right on Road B","Right on Road C","Left on Road D"]) = ['Begin on Road D', 'Right on Road C', 'Left on Road B', 'Left on Road A']
solve(['Begin on Lua Pkwy', 'Right on Sixth Alley', 'Right on 1st ... | algorithms | DIRS = {'Left': 'Right', 'Right': 'Left'}
def solve(arr):
lst, prevDir = [], 'Begin'
for cmd in arr[:: - 1]:
d, r = cmd . split(' on ')
follow = DIRS . get(prevDir, prevDir)
prevDir = d
lst . append(f' { follow } on { r } ')
return lst
| Simple directions reversal | 5b94d7eb1d5ed297680000ca | [
"Algorithms"
] | https://www.codewars.com/kata/5b94d7eb1d5ed297680000ca | 7 kyu |
Jack and Jill are playing a game. They have balls numbered from `0` to `n - 1`. Jack looks the other way and asks Jill to reverse the position of the balls, for instance, to change the order from say, `0,1,2,3` to `3,2,1,0`. He further asks Jill to reverse the position of the balls `n` times, each time starting from on... | games | def solve(count, ball_number):
"""
Return the position of the `ball_number` after the game with `count` balls
:param count: Number of balls
:type count: int
:param ball_number: Number of ball to be found in the end
:type ball_number: int
:return: Return the index of the ball `ball_numb... | Simple reversal game | 5b93636ba28ce032600000b7 | [
"Puzzles",
"Mathematics"
] | https://www.codewars.com/kata/5b93636ba28ce032600000b7 | 7 kyu |
The snail crawls up the column. During the day it crawls up some distance. During the night she sleeps, so she slides down for some distance (less than crawls up during the day).
Your function takes three arguments:
1. The height of the column (meters)
2. The distance that the snail crawls during the day (meters)
3. T... | reference | from math import ceil
def snail(column, day, night):
return max(ceil((column - night) / (day - night)), 1)
| Snail crawls up | 5b93fecd8463745630001d05 | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/5b93fecd8463745630001d05 | 7 kyu |
An eviternity number is a number which:
* contains only digits 8, 5 and 3, and
* the count of the digit `8` >= count of digit `5` >= count of digit `3`.
The first few eviternity numbers are as follows.
```Haskell
[8, 58, 85, 88, 358, 385, 538, 583, 588, 835, 853, 858, 885, 888]
```
You will be given two integers, `... | reference | def ever(n):
s = str(n)
C = [s . count('3'), s . count('5'), s . count('8')]
if sum(C) == len(s) and sorted(C) == C:
return True
return False
D = {i for i in range(1000000) if ever(i)}
def solve(a, b):
return len({e for e in D if e >= a and e <= b})
| Simple eviternity numbers | 5b93f268563417c7ed0001bd | [
"Fundamentals"
] | https://www.codewars.com/kata/5b93f268563417c7ed0001bd | 7 kyu |
<img src="https://upload.wikimedia.org/wikipedia/commons/d/d5/UPC-A.png" />
Your task is to convert a string representing the lines/spaces in a 12 digit barcode/UPC-A into a string of numbers 0-9.
A black line represents a `1` and a space represents `0`. The string you are returning is the decimal representation of t... | algorithms | tbl = str . maketrans('β ', '10')
def read_barcode(barcode):
txt = barcode . translate(tbl)
l = (LEFT_HAND['' . join(xs)]
for xs in zip(* [iter(txt[3: 7 * 6 + 3])] * 7))
r = (RIGHT_HAND['' . join(xs)]
for xs in zip(* [iter(txt[- 7 * 6 - 3: - 3])] * 7))
return '{} {}{}{}{}{} ... | Read a UPC/Barcode | 5b7dfd8cbfae24e5f200004d | [
"Algorithms"
] | https://www.codewars.com/kata/5b7dfd8cbfae24e5f200004d | 6 kyu |
Many items that are available for sale have a barcode somewhere on them - this allows them to be scanned at a checkout.
Your task is to create an algorithm to convert a series of ones and zeroes from the scanner into an Universal Product Code (UPC). You can learn more about UPC from [Wikipedia](https://en.wikipedia.or... | algorithms | import re
L_DIGITS = {
"0001101": "0",
"0011001": "1",
"0010011": "2",
"0111101": "3",
"0100011": "4",
"0110001": "5",
"0101111": "6",
"0111011": "7",
"0110111": "8",
"0001011": "9"}
def barcode_scanner(barcode):
leftized = barcode[3: 45] + barcode[50: -
... | Simple Barcode Scanner | 55f4ad47ada1dd22f1000088 | [
"Regular Expressions",
"Algorithms"
] | https://www.codewars.com/kata/55f4ad47ada1dd22f1000088 | 6 kyu |
>When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said
In this kata, No algorithms, only funny ;-)
# Description:
"All the people hurry up! We need to take a picture. The tallest standing in the middle, and then left and rig... | algorithms | from collections import deque
from itertools import chain
blueprint = [* map('' . join, zip(* '''\
+ +
+o o+
+ u +
+ ~ +
|
+-o-+
/| o |\\
+-o-+
''' . splitlines()))]
def person(leg):
yield from (col + ('I' . rjust(leg, '|') if i in (2, 4) else ' ' * leg) for i, col in enumerate(bl... | Complete the photo pattern | 58477f76ad2567b465000153 | [
"Algorithms",
"ASCII Art"
] | https://www.codewars.com/kata/58477f76ad2567b465000153 | 4 kyu |
> When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said
# Description:
Give you two number `m` and `n`(two positive integer, m < n), make a triangle pattern with number sequence `m to n`. The order is clockwise, starting from... | games | from itertools import cycle
from math import sqrt
def make_triangle(start, end):
rows = sqrt(8 * (end - start) + 9) / 2 - .5
if not rows . is_integer():
return ''
rows = int(rows)
row, col, value = - 1, - 1, start
directions = cycle([(1, 0), (0, - 1), (- 1, 1)])
triangle = [['']... | Complete the triangle pattern | 58281843cea5349c9f000110 | [
"Puzzles"
] | https://www.codewars.com/kata/58281843cea5349c9f000110 | 5 kyu |
The goal of this kata is to implement [trie](https://en.wikipedia.org/wiki/Trie) (or prefix tree) using dictionaries (aka hash maps or hash tables), where:
1. the dictionary keys are the prefixes
2. the value of a leaf node is `None` in Python, `nil` in Ruby, `null` in Groovy, JavaScript and Java, and `Nothing` in Has... | reference | def build_trie(* words):
root = {}
for word in words:
branch = root
length = len(word)
for i in range(1, length + 1):
length -= 1
key = word[: i]
if key not in branch:
branch[key] = None
if length and not branch[key]:
branch[key] = {}
branch = branch[key]
... | Build a Trie | 5b65c47cbedf7b69ab00066e | [
"Data Structures",
"Fundamentals"
] | https://www.codewars.com/kata/5b65c47cbedf7b69ab00066e | 6 kyu |
## Task
Find the sum of the first `n` elements in the RecamΓ‘n Sequence.
Input range:
```javascript
1000 tests
0 <= n <= 1,000,000
```
```python
1000 tests
0 <= n <= 2,500,000
```
```haskell
0 <= n <= 1 000 000
1 000 tests
```
---
## Sequence
The sequence is formed using the next formula:
* We start with `0`
* At... | algorithms | S, SS, SUM = [0], {0}, [0]
def rec(n):
while len(S) <= n:
v = S[- 1] - len(S)
if v <= 0 or v in SS:
v += 2 * len(S)
S . append(v)
SS . add(v)
SUM . append(SUM[- 1] + v)
return SUM[n - 1]
| RecamΓ‘n Sequence Sum | 5b8c055336332fce3d00000e | [
"Algorithms"
] | https://www.codewars.com/kata/5b8c055336332fce3d00000e | 5 kyu |
Consider the string `"1 2 36 4 8"`. Lets take pairs of these numbers, concatenate each pair and determine how many of them of divisible by `k`.
```Pearl
If k = 3, we get following numbers ['12', '18', '21', '24', '42', '48', '81', '84'], all divisible by 3.
Note:
-- 21 and 12 are different pairs.
-- Elements mus... | algorithms | from itertools import permutations
def solve(s, k):
return sum(not v % k for v in map(int, map('' . join, permutations(s . split(), 2))))
| Simple string division II | 5b8be3ae36332f341e00015e | [
"Algorithms"
] | https://www.codewars.com/kata/5b8be3ae36332f341e00015e | 7 kyu |
You are given a string representing a website's address. To calculate the IP4 address you must convert all the characters into ASCII code, then calculate the sum of the values.
* the first part of the IP number will be the result mod 256
* the second part of the IP number will be the double of the sum mod 256
* the th... | games | def f(u): return [sum(map(ord, u)) * i % 256 for i in [1, 2, 3, 4]]
| IP address finder [Code-golf] | 5b883cdecc7c03c0fa00015a | [
"Strings",
"Arrays",
"Restricted",
"Puzzles"
] | https://www.codewars.com/kata/5b883cdecc7c03c0fa00015a | 6 kyu |
Your function takes two arguments:
1. current father's age (years)
2. current age of his son (years)
Π‘alculate how many years ago the father was twice as old as his son (or in how many years he will be twice as old). The answer is always greater or equal to 0, no matter if it was in the past or it is in the future. | reference | def twice_as_old(dad_years_old, son_years_old):
return abs(dad_years_old - 2 * son_years_old)
| Twice as old | 5b853229cfde412a470000d0 | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/5b853229cfde412a470000d0 | 8 kyu |
In this Kata, you will be given a number in form of a string and an integer `k` and your task is to insert `k` commas into the string and determine which of the partitions is the largest.
```
For example:
solve('1234',1) = 234 because ('1','234') or ('12','34') or ('123','4').
solve('1234',2) = 34 because ('1','2','3... | reference | def solve(st, k):
length = len(st) - k
return max(int(st[i: i + length]) for i in range(k + 1))
| Simple string division | 5b83c1c44a6acac33400009a | [
"Fundamentals"
] | https://www.codewars.com/kata/5b83c1c44a6acac33400009a | 7 kyu |
While most devs know about [big/little-endianness](https://en.wikipedia.org/wiki/Endianness), only a selected few know the secret of real hard core coolness with mid-endians.
Your task is to take a number and return it in its mid-endian format, putting the most significant couple of bytes in the middle and all the oth... | algorithms | import re
def mid_endian(n):
h = hex(n)[2:]. upper()
r = re . findall('..', '0' * (len(h) % 2) + h)
return "" . join(r[1:: 2][:: - 1] + r[0:: 2])
| Mid-Endian numbers | 5b3e3ca99c9a75a62400016d | [
"Algorithms"
] | https://www.codewars.com/kata/5b3e3ca99c9a75a62400016d | 6 kyu |
Lets play some Pong!

For those who don't know what Pong is, it is a simple arcade game where two players can move their paddles to hit a ball towards the opponent's side of the screen, gaining a point for each opponent's miss. You can read more a... | algorithms | from itertools import cycle
class Pong:
def __init__(self, max_score):
self . max_score = max_score
self . scores = {1: 0, 2: 0}
self . players = cycle((1, 2))
def game_over(self):
return any(score >= self . max_score for score in self . scores . values())
def play(self, ball... | Pong! [Basics] | 5b432bdf82417e3f39000195 | [
"Fundamentals",
"Games",
"Algorithms",
"Object-oriented Programming"
] | https://www.codewars.com/kata/5b432bdf82417e3f39000195 | 6 kyu |
# Introduction
This kata is yet another version of Avanta's [Coloured Triangles](/kata/coloured-triangles), once again focused on performance.
It takes Bubbler's ["Insane" version](/kata/insane-coloured-triangles) a step further, hence the name "Ludicrous".
I highly recommend having a close look at these other versi... | algorithms | import itertools
import operator
def triangle(row):
# Explanation of approach:
# We associate each of the 3 colours/characters with a unique code: 0, 1, or 2.
# With this encoding and the rules given,
# we see that a pair of neighbours in one row will give rise in the next row
# to a colour whose ... | Ludicrous Coloured Triangles | 5b84d6d6b2f82f34d00000d7 | [
"Puzzles",
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5b84d6d6b2f82f34d00000d7 | 2 kyu |
I advise you to do some of the previous katas from the: [Neighbourhood collection](https://www.codewars.com/collections/5b2f4db591c746349d0000ce).
___
This is the next step. We are going multidimensional.
You should build a function that return the neighbourhood of a cell within a matrix with the given distance and t... | algorithms | def genNeigh(isNeum, arr, coords, d, var=0, idx=()):
depth = len(idx)
x = coords[depth]
if not (0 <= x < len(arr)):
raise IndexError()
low, up = - d + isNeum * var, d - isNeum * var + 1
for j in range(max(0, low + x), min(up + x, len(arr))):
indexes = idx + (j,)
if 0 <= j... | Multidimensional Neighbourhood | 5b47ba689c9a7591e70001a3 | [
"Algorithms",
"Logic",
"Data Structures",
"Arrays",
"Performance"
] | https://www.codewars.com/kata/5b47ba689c9a7591e70001a3 | 5 kyu |
```
NOTE: To solve this Kata you need a minimum knowlege of probability theory
https://en.wikipedia.org/wiki/Probability_theory
```
# Description
Alice and Bob decided to have a quick tennis match. The rules a simple:
```
A game consists of a sequence of points played with the same
player serving. A game is won by th... | reference | def match_probability(p, q):
# 4 Ways to Win:
# 1st = 4 - 0
# 2nd = 4 - 1
# 3rd = 4 - 2
# 4th = two in a row during "overtime" after 3-3
# Chance of p winning 4 - 0
prob_1 = p * * 4
# Chance of p winning 4 - 1
prob_2 = (4 * p * * 4 * (1 - p))
# Chance of p winning 4 - 2
prob... | Probability to Win an Infinite Tennis Game | 5b756dc4049416c24f000762 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/5b756dc4049416c24f000762 | 5 kyu |
We are interested in collecting the triples of positive integers ```(a, b, c)``` that fulfill the following equation:
```python
aΒ² + bΒ² = cΒ³
```
The first triple with the lowest values that satisfies the equation we have above is (2, 2 ,2).
In effect:
```python
2Β² + 2Β² = 2Β³
4 + 4 = 8
```
The first pair of triples tha... | reference | from bisect import bisect_right as bisect
RES = [[] for _ in range(11)]
for c in range(1, 1001):
c3 = c * * 3
nSol = sum(((c3 - a * * 2) * * .5). is_integer() for a in range(1, int((c3 / / 2) * * .5 + 1)))
if 0 < nSol < 11:
RES[nSol]. append(c)
def find_abc_sumsqcube(c_max, nSol):
... | Square Cubic Triples | 5618716a738b95cee8000062 | [
"Fundamentals",
"Algorithms",
"Data Structures",
"Mathematics",
"Memoization"
] | https://www.codewars.com/kata/5618716a738b95cee8000062 | 6 kyu |
You are given an input string.
For each symbol in the string if it's the first character occurrence, replace it with a '1', else replace it with the amount of times you've already seen it.
___
## Examples:
```
input = "Hello, World!"
result = "1112111121311"
input = "aaaaaaaaaaaa"
result = "1234567891011... | algorithms | def numericals(s):
dictio = {}
t = ""
for i in s:
dictio[i] = dictio . get(i, 0) + 1
t += str(dictio[i])
return t
| Numericals of a String | 5b4070144d7d8bbfe7000001 | [
"Puzzles",
"Performance",
"Algorithms"
] | https://www.codewars.com/kata/5b4070144d7d8bbfe7000001 | 6 kyu |
# Description
Write a function that accepts the current position of a knight in a chess board, it returns the possible positions that it will end up after 1 move. The resulted should be sorted.
## Example
"a1" -> ["b3", "c2"] | reference | def possible_positions(p):
r, c = ord(p[0]) - 96, int(p[1])
moves = [(- 2, - 1), (- 2, 1), (- 1, - 2), (- 1, 2),
(1, - 2), (1, 2), (2, - 1), (2, 1)]
return ['' . join((chr(r + i + 96), str(c + j))) for i, j in moves if 1 <= r + i <= 8 and 1 <= c + j <= 8]
| Knight position | 5b5736abf1d553f844000050 | [
"Fundamentals"
] | https://www.codewars.com/kata/5b5736abf1d553f844000050 | 7 kyu |
# Parentheses are loud !
As a spy python object, you have been sent to a remote memory location to gather information about some anonymous functions. Unfortunately, they caught wind of this and are on the lookout for any parentheses to prevent you from making any calls for help. But you are a proffesional and you don't... | games | @ help_me
class _:
pass
| Parentheses are loud ! | 5b6711e86d0db7519a000112 | [
"Logic",
"Puzzles"
] | https://www.codewars.com/kata/5b6711e86d0db7519a000112 | 6 kyu |
## Task
Implement a function which finds the numbers less than `2`, and the indices of numbers greater than `1` in the given sequence, and returns them as a pair of sequences.
Return a nested array or a tuple depending on the language:
* The first sequence being only the `1`s and `0`s from the original sequence.
*... | reference | def binary_cleaner(seq):
res = ([], [])
for i, x in enumerate(seq):
if x < 2:
res[0]. append(x)
else:
res[1]. append(i)
return res
| Not above the one! | 5b5097324a317afc740000fe | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/5b5097324a317afc740000fe | 7 kyu |
You have a string of numbers; starting with the third number each number is the result of an operation performed using the previous two numbers.
Complete the function which returns a string of the operations in order and separated by a comma and a space, e.g. `"subtraction, subtraction, addition"`
The available opera... | algorithms | def sayMeOperations(stringNumbers):
nums = [int(i) for i in stringNumbers . split()]
return ', ' . join({
a * b: 'multiplication',
a - b: 'subtraction',
a + b: 'addition',
}. get(c, 'division') for a, b, c in zip(nums, nums[1:], nums[2:]))
| Say Me Please Operations | 5b5e0c0d83d64866bc00001d | [
"Algorithms",
"Logic",
"Strings",
"Lists"
] | https://www.codewars.com/kata/5b5e0c0d83d64866bc00001d | 7 kyu |
## Task
You will be given a list of objects. Each object has `type`, `material`, and possibly `secondMaterial`. The existing materials are: `paper`, `glass`, `organic`, and `plastic`.
Your job is to sort these objects across the 4 recycling bins according to their `material` (and `secondMaterial` if it's present), by... | reference | def recycle(a):
bins = {"paper": [], "glass": [], "organic": [], "plastic": []}
for i in a:
bins[i["material"]]. append(i["type"])
if "secondMaterial" in i:
bins[i["secondMaterial"]]. append(i["type"])
return tuple(bins . values())
| Let's Recycle! | 5b6db1acb118141f6b000060 | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/5b6db1acb118141f6b000060 | 6 kyu |
Do you have in mind the good old TicTacToe?
Assuming that you get all the data in one array, you put a space around each value, `|` as a columns separator and multiple `-` as rows separator, with something like `["O", "X", " ", " ", "X", " ", "X", "O", " "]` you should be returning this structure (inclusive of new lin... | reference | def display_board(board, width):
board = [c . center(3) for c in board]
rows = ["|" . join(board[n: n + width])
for n in range(0, len(board), width)]
return ("\n" + "-" * (4 * width - 1) + "\n"). join(rows)
| Tic-Tac-Toe-like table Generator | 5b817c2a0ce070ace8002be0 | [
"ASCII Art",
"Fundamentals"
] | https://www.codewars.com/kata/5b817c2a0ce070ace8002be0 | 6 kyu |
## [Every](https://www.codewars.com/kata/every-possible-sum-of-two-digits/) [possible](https://www.codewars.com/kata/every-possible-sum-of-two-digits/) [sum](https://www.codewars.com/kata/every-possible-sum-of-two-digits/) [of](https://www.codewars.com/kata/every-possible-sum-of-two-digits/) [two](https://www.codewars.... | algorithms | def find_number(a): return int(str(l := a[0] + a[1] - a[n] >> 1 if ~ - (n := int((2 * len(a)) * * .5)) else (a[0] > 9) * 9) + '' . join(str(d - l) for d in a[: n]))
| Going backwards: Number from every possible sum of two digits | 5b4fd549bdd074f9a200005f | [
"Algorithms"
] | https://www.codewars.com/kata/5b4fd549bdd074f9a200005f | 6 kyu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.