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
There are five workers : James,John,Robert,Michael and William.They work one by one and on weekends they rest. Order is same as in the description(James works on mondays,John works on tuesdays and so on).You have to create a function **'task'** that will take 3 arguments(**w, n, c**): 1) Weekday 2) Number of trees th...
reference
def task(w, n, c): workers = {"Monday": "James", "Tuesday": "John", "Wednesday": "Robert", "Thursday": "Michael", "Friday": "William"} return f"It is { w } today, { workers [ w ]} , you have to work, you must spray { n } trees and you need { n * c } dollars to buy liquid"
Spraying trees
5981a139f5471fd1b2000071
[ "Fundamentals" ]
https://www.codewars.com/kata/5981a139f5471fd1b2000071
7 kyu
<video controls style='width:500px;' autoplay='autoplay' loop='loop'><source src="https://i.imgur.com/j36Kh64.mp4" type='video/mp4'></source></video> Background Story: ================= In the [*Dune* universe][1], a **spice harvester** is a large, heavy, mobile factory designed to harvest the spice *Melange*. It is ...
reference
import math def harvester_rescue(data): harvester = data['harvester'] worm, worm_speed = data['worm'] carryall, carryall_speed = data['carryall'] if distance(harvester, worm) / worm_speed > distance(harvester, carryall) / carryall_speed + 1: return 'The spice must flow! Rescue the harveste...
Save the Spice Harvester (Dune Universe)
587d7544f1be39c48c000109
[ "Fundamentals" ]
https://www.codewars.com/kata/587d7544f1be39c48c000109
6 kyu
Create a method **partition** that accepts a list and a method/block. It should return two arrays: the first, with all the elements for which the given block returned true, and the second for the remaining elements. Here's a simple Ruby example: animals = ["cat", "dog", "duck", "cow", "donkey"] partition(anim...
reference
def partition(list, classifier_method): listTrue = [] listFalse = [] for l in list: if classifier_method(l): listTrue . append(l) else: listFalse . append(l) return listTrue, listFalse
Enumerable Magic #30 - Split that Array!
545b342082e55dc9da000051
[ "Fundamentals" ]
https://www.codewars.com/kata/545b342082e55dc9da000051
8 kyu
Given an unsorted array of integers, find the smallest number in the array, the largest number in the array, and the smallest number between the two array bounds that is not in the array. For instance, given the array [-1, 4, 5, -23, 24], the smallest number is -23, the largest number is 24, and the smallest number be...
games
def minMinMax(arr): s, mi, ma = set(arr), min(arr), max(arr) return [mi, next(x for x in range(mi + 1, ma) if x not in s), ma]
MinMaxMin: Bounded Nums
58d3487a643a3f6aa20000ff
[ "Arrays" ]
https://www.codewars.com/kata/58d3487a643a3f6aa20000ff
7 kyu
Remember the spongebob meme that is meant to make fun of people by repeating what they say in a mocking way? !["Dont use that weird spongebob mocking meme" Me: DonT uSe thAt WeIrd SpoNgEboB MoCkinG MEme](data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwc...
reference
def sponge_meme(seq): return '' . join( c . lower() if i % 2 else c . upper() for i, c in enumerate(seq) )
sPoNgEbOb MeMe
5982619d2671576e90000017
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/5982619d2671576e90000017
7 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 arrays `arr1` and `arr2`. They have the same length(length>=2). The elements of two arrays always be integer. Sort `arr1` according to th...
reference
def sort_two_arrays(arr1, arr2): a1 = sorted([[arr1[i], i] for i in range(len(arr1))]) a2 = sorted([[arr2[i], i] for i in range(len(arr2))]) r1 = [arr1[a[1]] for a in a2] r2 = [arr2[a[1]] for a in a1] return [r1, r2]
Sort two arrays
5818c52e21a33314e00000cb
[ "Puzzles", "Fundamentals", "Sorting", "Algorithms", "Arrays" ]
https://www.codewars.com/kata/5818c52e21a33314e00000cb
6 kyu
Todd is looking for the best place to park in the grocery store parking lot. Todd knows that there's a sequence of events that happens whenever he buys groceries: * When he first arrives, he walks straight into the store (where the carts are kept). * After completing shopping, he will return to his car with his ...
algorithms
def best_parking_spot(arr): if arr . count("OPEN") == 1: return arr . index("OPEN") corrals = [i for i, v in enumerate(arr) if v == 'CORRAL'] opens = [i for i, v in enumerate(arr) if v == 'OPEN'] result = {} for i in range(0, len(opens)): for j in range(0, len(corrals)): resu...
Best Parking Spot
5859aaf04facfeb0d4002051
[ "Algorithms" ]
https://www.codewars.com/kata/5859aaf04facfeb0d4002051
6 kyu
<img src="https://i.imgur.com/ta6gv1i.png?1"/> --- # Story The <a href="https://en.wikipedia.org/wiki/Pied_Piper_of_Hamelin">Pied Piper</a> has been enlisted to play his magical tune and coax all the rats out of town. But some of the rats are deaf and are going the wrong way! # Kata Task How many deaf rats are th...
reference
def count_deaf_rats(town): return town . replace(' ', '')[:: 2]. count('O')
The Deaf Rats of Hamelin
598106cb34e205e074000031
[ "Fundamentals", "Strings", "Algorithms", "Queues", "Data Structures" ]
https://www.codewars.com/kata/598106cb34e205e074000031
6 kyu
#About Caesar Cipher Caesar Cipher is a simple encryption technique based on shifting each character by a fixed number of positions in the alphabet. For example, if the shift is 3, an encoded version of phrase "kata" will be: ``` k + 3 = n a + 3 = d t + 3 = w a + 3 = d ``` In a case when "z" is reached, the algorithm...
algorithms
def caesar_encode(s, n): return ' ' . join('' . join(chr((ord(c) - 97 + n + i) % 26 + 97) for c in w) for i, w in enumerate(s . split(' ')))
Caesar Cipher Encryption - Variation
55ec55323c89fc5fbd000019
[ "Algorithms", "Cryptography" ]
https://www.codewars.com/kata/55ec55323c89fc5fbd000019
6 kyu
*** Nova polynomial multiply*** This kata is from a series on polynomial handling. ( [#1](http://www.codewars.com/kata/nova-polynomial-1-add-1) [#2](http://www.codewars.com/kata/570eb07e127ad107270005fe) [#3](http://www.codewars.com/kata/5714041e8807940ff3001140 ) [#4](http://www.codewars.com/kata/571a2e2df24bdf...
algorithms
def poly_multiply(p1, p2): if not p1 or not p2: return [] n = len(p1) + len(p2) - 1 p = [0] * n for i, a in enumerate(p1): for j, b in enumerate(p2): p[i + j] += a * b return p
nova polynomial 2. multiply
570eb07e127ad107270005fe
[ "Algorithms" ]
https://www.codewars.com/kata/570eb07e127ad107270005fe
6 kyu
Sort array by last character Complete the function to sort a given array or list by last character of elements. ```if-not:haskell Element can be an integer or a string. ``` ### Example: ``` ['acvd', 'bcc'] --> ['bcc', 'acvd'] ``` The last characters of the strings are `d` and `c`. As `c` comes befo...
reference
def sort_me(arr): return sorted(arr, key=lambda elem: str(elem)[- 1])
sort array by last character
55aea0a123c33fa3400000e7
[ "Fundamentals", "Sorting", "Arrays", "Strings" ]
https://www.codewars.com/kata/55aea0a123c33fa3400000e7
7 kyu
## Description This is your first potion class in Hogwarts and professor gave you a homework to figure out what color potion will turn into if he'll mix it with some other potion. All potions have some color that written down as RGB color from `[0, 0, 0]` to `[255, 255, 255]`. To make task more complicated teacher wil...
algorithms
from math import ceil class Potion: def __init__(self, color, volume): self . color = color self . volume = volume def mix(self, other): ratio1 = self . volume / (self . volume + other . volume) ratio2 = other . volume / (self . volume + other . volume) r = ceil(self . color[...
Potion Class 101
5981ff1daf72e8747d000091
[ "Algorithms", "Object-oriented Programming" ]
https://www.codewars.com/kata/5981ff1daf72e8747d000091
6 kyu
In computer science and discrete mathematics, an [inversion](https://en.wikipedia.org/wiki/Inversion_%28discrete_mathematics%29) is a pair of places in a sequence where the elements in these places are out of their natural order. So, if we use ascending order for a group of numbers, then an inversion is when larger num...
algorithms
def count_inversion(nums): return sum(a > b for i, a in enumerate(nums) for b in nums[i + 1:])
Count inversions
5728a1bc0838ffea270018b2
[ "Algorithms" ]
https://www.codewars.com/kata/5728a1bc0838ffea270018b2
7 kyu
*** Nova polynomial derivative*** This kata is from a series on polynomial handling. ( [#1](http://www.codewars.com/kata/nova-polynomial-1-add-1) [#2](http://www.codewars.com/kata/570eb07e127ad107270005fe) [#3](http://www.codewars.com/kata/5714041e8807940ff3001140 ) [#4](http://www.codewars.com/kata/571a2e2df24b...
algorithms
def poly_derivative(p): return [i * x for i, x in enumerate(p)][1:]
nova polynomial 4. derivative
571a2e2df24bdfd4e20001f5
[ "Algorithms", "Recursion", "Arrays" ]
https://www.codewars.com/kata/571a2e2df24bdfd4e20001f5
7 kyu
*** Nova polynomial subtract*** This kata is from a series on polynomial handling. ( [#1](http://www.codewars.com/kata/nova-polynomial-1-add-1) [#2](http://www.codewars.com/kata/570eb07e127ad107270005fe) [#3](http://www.codewars.com/kata/5714041e8807940ff3001140 ) [#4](http://www.codewars.com/kata/571a2e2df24bdf...
algorithms
def poly_subtract(p, q): return poly_add(p, [- c for c in q])
nova polynomial 3. subtract
5714041e8807940ff3001140
[ "Algorithms", "Recursion", "Arrays" ]
https://www.codewars.com/kata/5714041e8807940ff3001140
7 kyu
## Nova polynomial add This kata is from a series on polynomial handling. ( [#1](http://www.codewars.com/kata/nova-polynomial-1-add-1) [#2](http://www.codewars.com/kata/570eb07e127ad107270005fe) [#3](http://www.codewars.com/kata/5714041e8807940ff3001140 ) [#4](http://www.codewars.com/kata/571a2e2df24bdfd4e20001f5) ) ...
algorithms
from itertools import zip_longest def poly_add(p1, p2): return [x + y for x, y in zip_longest(p1, p2, fillvalue=0)]
nova polynomial 1. add
570ac43a1618ef634000087f
[ "Algorithms", "Mathematics", "Recursion", "Arrays" ]
https://www.codewars.com/kata/570ac43a1618ef634000087f
7 kyu
I forgot what system I'm running on. Can you help me find my hostname? Each computer has a name associated with it. Your goal is to return a string version (case-sensitive) of the host that your kata code runs on.
games
def get_pid(): import socket return socket . gethostname()
Where am I?
560b000f56b4d8be9e000018
[ "Puzzles" ]
https://www.codewars.com/kata/560b000f56b4d8be9e000018
7 kyu
You are in a military mission in the middle of the jungle where your enemies are really hard to spot because of their camouflage. Luckily you have a device that shows the position of your enemies! Your device is a radar that computes the ```x``` and ```y``` coordinates of an enemy in meters ```every 5 seconds```. You ...
games
def distance(p1, p2): return ((p2[0] - p1[0]) * * 2 + (p2[1] - p1[1]) * * 2) * * 0.5 def calculate_time(p1, p2): return round(5 * distance(p2, [0, 0]) / distance(p1, p2), 3)
Approaching enemies
56d58a16e8f2d6957100093f
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/56d58a16e8f2d6957100093f
7 kyu
Implement something called `str_repeat` that repeats a string n-times. That something _must not_ be a function. Thanks `wichu` for the idea. Enjoy! :)
games
from operator import mul as str_repeat
String Repetition without Function
57a110eee298a737e2000283
[ "Restricted", "Puzzles" ]
https://www.codewars.com/kata/57a110eee298a737e2000283
6 kyu
Your goal is to create something called `puzzle` which is equivalent to function `n_time2_power_x(n, x)` (see below) where `n` and `x` are positive integers. __IMPORTANT__: `puzzle` must not be a `function` or `method` and your solution mustn't contain `return` keyword. Enjoy! :) ```python def n_time2_power_x(n, x)...
games
puzzle = int . __lshift__
n times 2 to the power of x without function or class method and return
57b971f68f58135e840001cc
[ "Language Features", "Restricted", "Puzzles" ]
https://www.codewars.com/kata/57b971f68f58135e840001cc
7 kyu
Imagine that you have an array of 3 integers each representing different person. Each number can be 0, 1, or 2 which represents the number of hands that person is holding up. Now imagine there is a sequence which follows these rules: * None of the people have their arms raised at first * Firstly, a person raises 1 han...
algorithms
def get_positions(n): return n % 3, n / / 3 % 3, n / / 9 % 3
Hands Up
56d8f14cba01a83cdb0002a2
[ "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/56d8f14cba01a83cdb0002a2
7 kyu
Here your task is to <font size="+1">Create a (nice) Christmas Tree</font>.<br><br> You don't have to check errors or incorrect input values, every thing is ok without bad tricks, only one int parameter as input and a string to return;-)...<br><br> <u>So what to do?</u><br><br>First three easy examples: <br> ```` Inpu...
reference
def christmas_tree(h): return "" if h < 3 else "\r\n" . join(["\r\n" . join([" " * (((5 - y) / / 2) + (h / / 3) - i - 1) + "*" * (y + i * 2) for y in [1, 3, 5]]) for i in range(h / / 3)]) + "\r\n" + " " * (h / / 3) + "###"
Pattern 01: Merry Christmas (sometimes little bit out of time;-))
56c30eaef85696bf35000ccf
[ "Strings", "ASCII Art", "Fundamentals" ]
https://www.codewars.com/kata/56c30eaef85696bf35000ccf
6 kyu
Create a function that finds the [integral](https://en.wikipedia.org/wiki/Integral) of the expression passed. In order to find the integral all you need to do is add one to the `exponent` (the second argument), and divide the `coefficient` (the first argument) by that new number. For example for `3x^2`, the integral ...
reference
def integrate(coefficient, exponent): return f' { coefficient / / ( exponent + 1 )} x^ { exponent + 1 } '
Find the Integral
59811fd8a070625d4c000013
[ "Fundamentals" ]
https://www.codewars.com/kata/59811fd8a070625d4c000013
8 kyu
A **bouncy number** is a positive integer whose digits neither increase nor decrease. For example, `1235` is an increasing number, `5321` is a decreasing number, and `2351` is a bouncy number. By definition, all numbers under `100` are non-bouncy, and `101` is the first bouncy number. To complete this kata, you must wr...
reference
def is_bouncy(n): return sorted(str(n)) != list(str(n)) and sorted(str(n)) != list(str(n))[:: - 1]
Bouncy Numbers
5769a78c6f2dea72b3000027
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5769a78c6f2dea72b3000027
7 kyu
**The scenario:** You have to complete a textbook assignment full of boring math problems as homework due in 5 days time. You want to find out how long you must spend on each of the 5 days to evenly spread the workload. You will create a program, ```time_per_day```, that will take a list of tuples. Each tuple represen...
algorithms
def time_per_day(l): sum = 0 for a in l: sum += a[1] * a[0] * 0.75 return round(sum / 300, 2)
Managing Homework Time
58cbc48930bcf09b7a000117
[ "Algorithms" ]
https://www.codewars.com/kata/58cbc48930bcf09b7a000117
7 kyu
If you have not ever heard the term **Arithmetic Progression**, refer to: http://www.codewars.com/kata/find-the-missing-term-in-an-arithmetic-progression/python And here is an unordered version. Try if you can survive lists of **MASSIVE** numbers (which means time limit should be considered). :D Note: Don't be afrai...
algorithms
def find(seq): return (min(seq) + max(seq)) * (len(seq) + 1) / 2 - sum(seq)
Missing number in Unordered Arithmetic Progression
568fca718404ad457c000033
[ "Algorithms", "Mathematics", "Performance" ]
https://www.codewars.com/kata/568fca718404ad457c000033
5 kyu
In this exercise, you will create a function that takes an integer, ```i```. With it you must do the following: - Find all of its multiples up to and including 100, - Then take the digit sum of each multiple (eg. 45 -> 4 + 5 = 9), - And finally, get the total sum of each new digit sum. **Note:** If the digit sum of...
algorithms
def procedure(n): return sum(int(d) for i in range(n, 101, n) for d in str(i))
Multiples and Digit Sums
58ca77b9c0d640ecd2000b1e
[ "Algorithms" ]
https://www.codewars.com/kata/58ca77b9c0d640ecd2000b1e
7 kyu
Build a function that can get all the integers between two given numbers. Example: `(2,9)` Should give you this output back: `[ 3, 4, 5, 6, 7, 8 ]` ~~~if:javascript,csharp If startNum is the same as endNum, return an empty array. ~~~ ~~~if:ruby,cpp If start_num is the same as end_num, return an empty array. ~~~ ...
algorithms
def function(start_num, end_num): return list(range(start_num + 1, end_num))
Get the integers between two numbers
598057c8d95a04f33f00004e
[ "Algorithms" ]
https://www.codewars.com/kata/598057c8d95a04f33f00004e
7 kyu
You have been hired by a company making speed cameras. Your mission is to write the controller software turning the picture taken by the camera into a license plate number. # Specification The sensor matrix outputs a 3-line string using pipes and underscores. We want to translate this into a string with regular digits...
reference
table = { ' _ _||_ ': '2', ' _ ||_ ': '2', ' _ _|| ': '2', ' _ _| _|': '3', ' _ | _|': '3', ' _ _| |': '3', ' |_| |': '4', ' | | |': '4', ' _ |_ _|': '5', ' _ | _|': '5', ' _ |_ |': '5', ' _ |_ |_|': '6', ' _ | |_|': '6', ' _ |_ | |': '6', ' _ | |': '7', ' _ |_||_|': '8', ' _ | ||_|':...
License Plate Recognition
58db721b2f449efaf5000038
[ "Fundamentals" ]
https://www.codewars.com/kata/58db721b2f449efaf5000038
5 kyu
&ensp;Returns the bank account number parsed from specified string. &ensp;You work for a bank, which has recently purchased an ingenious machine to assist in reading letters and faxes sent in by branch offices.<br> &ensp;The machine scans the paper documents, and produces a string with a bank account that looks like t...
games
def builder(s, isRef=0): out = {} for r in s . splitlines(): for i in range(len(r) / / 3): out[i] = out . get(i, '') + r[i * 3: i * 3 + 3] return {s: str(i) for i, s in out . items()} if isRef else out . values() DIGS = builder('''\ _ _ _ _ _ _ _ _ | | | _| _||_||_ |_ ||_||_| ...
Parse bank account number
597eeb0136f4ae84f9000001
[ "Strings", "Puzzles" ]
https://www.codewars.com/kata/597eeb0136f4ae84f9000001
6 kyu
&ensp;Return the most profit from stock quotes. &ensp;Stock quotes are stored in an array in order of date. The stock profit is the difference in prices in buying and selling stock. Each day, you can either buy one unit of stock, sell any number of stock units you have already bought, or do nothing. Therefore, the mos...
games
def get_most_profit_from_stock_quotes(quotes): gain, top = 0, - float('inf') for v in reversed(quotes): if top < v: top = v else: gain += top - v return gain
Most profit from stock quotes
597ef546ee48603f7a000057
[ "Puzzles" ]
https://www.codewars.com/kata/597ef546ee48603f7a000057
6 kyu
Given a positive integer `N`, return the largest integer `k` such that `3^k < N`. For example, ```python largest_power(3) == 0 largest_power(4) == 1 ``` ```haskell largestPower 3 = 0 largestPower 4 = 1 ``` ```csharp Kata.LargestPower(3) => 0 Kata.LargestPower(4) => 1 ``` ```ruby largest_power(3) => 0 largest_power(4)...
algorithms
from math import log, ceil def largest_power(N): return ceil(log(N, 3)) - 1
Powers of 3
57be674b93687de78c0001d9
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/57be674b93687de78c0001d9
7 kyu
Given a list of white pawns on a chessboard (any number of them, meaning from 0 to 64 and with the possibility to be positioned everywhere), determine how many of them have their backs covered by another. Pawns attacking upwards since we have only white ones. Please remember that a pawn attack(and defend as well) onl...
reference
def covered_pawns(pawns): pawns = set(pawns) return len({p for p in pawns for x, y in [map(ord, p)] if {chr(x - 1) + chr(y - 1), chr(x + 1) + chr(y - 1)} & pawns})
Covered pawns
597cfe0a38015079a0000006
[ "Fundamentals" ]
https://www.codewars.com/kata/597cfe0a38015079a0000006
6 kyu
### Introduction: There are two ice-cream sellers, Emily and Danny. They sell one flavour, vanilla, and their prices are the same. No advertising, no difference between their products. Emily and Danny can put their stall on any point in the town square, which is a five by five grid, with x and y coordinates. And is...
games
def most_customers(dannys_pitch): x, y = dannys_pitch def sign(n): return int(n / abs(n)) if n != 0 else 0 if abs(x) > 2 or abs(y) > 2: return [[0, 0]] if x == 0 and y == 0: return [[- 1, - 1], [- 1, 0], [- 1, 1], [0, - 1], [0, 1], [1, - 1], [1, 0], [1, 1]] if abs(x) == abs(y)...
The Ice Cream Vendors Dilema
597c82c5213e128eed000072
[ "Puzzles" ]
https://www.codewars.com/kata/597c82c5213e128eed000072
6 kyu
<img src="https://i.imgur.com/ta6gv1i.png?1" title="source: imgur.com" /> # Story You and a group of friends are earning some extra money in the school holidays by re-painting the numbers on people's letterboxes for a small fee. Since there are 10 of you in the group each person just concentrates on painting one dig...
reference
def paint_letterboxes(start, finish): xs = [0] * 10 for n in range(start, finish + 1): for i in str(n): xs[int(i)] += 1 return xs
Letterbox Paint-Squad
597d75744f4190857a00008d
[ "Fundamentals" ]
https://www.codewars.com/kata/597d75744f4190857a00008d
7 kyu
Conways game of life (https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life) is usually implemented without considering neigbouring cells that would be outside of the arrays range, but another way to do it is by considering the left and right edges of the array to be stitched together, and the top and bottom edges also...
games
# sumArround = 0 1 2 3 4 5 6 7 8 SURVIVAL_DICT = {0: [0, 0, 0, 1, 0, 0, 0, 0, 0], 1: [0, 0, 1, 1, 0, 0, 0, 0, 0]} def get_generation(cells, generation): maxI, maxJ = len(cells), len(cells[0]) def sumArround(i, j): return sum(cells[(i + a) % maxI][(j + b) % maxJ] for a in range(-...
Conways game of life on a toroidal array
57b988048f5813799600004f
[ "Puzzles", "Cellular Automata" ]
https://www.codewars.com/kata/57b988048f5813799600004f
5 kyu
You have to extract a portion of the file name as follows: * Assume it will start with date represented as long number * Followed by an underscore * You'll have then a filename with an extension * it will always have an extra extension at the end Inputs: --- ``` 1231231223123131_FILE_NAME.EXTENSION.OTHEREXTENSION 1_...
reference
class FileNameExtractor: @ staticmethod def extract_file_name(fname): return fname . split('_', 1)[1]. rsplit('.', 1)[0]
extract portion of file name
597770e98b4b340e5b000071
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/597770e98b4b340e5b000071
6 kyu
Given two words and a letter, return a single word that's a combination of both words, merged at the point where the given letter first appears in each word. The returned word should have the beginning of the first word and the ending of the second, with the dividing letter in the middle. You can assume both words will...
reference
def StringMerge(string1, string2, letter): return string1[: string1 . index(letter)] + string2[string2 . index(letter):]
String Merge!
597bb84522bc93b71e00007e
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/597bb84522bc93b71e00007e
7 kyu
# Story Due to lack of maintenance the minute-hand has fallen off Town Hall clock face. And because the local council has lost most of our tax money to an elaborate email scam there are no funds to fix the clock properly. Instead, they are asking for volunteer programmers to write some code that tell the time by on...
reference
def what_time_is_it(angle): hr = int(angle / / 30) mn = int((angle % 30) * 2) if hr == 0: hr = 12 return '{:02d}:{:02d}' . format(hr, mn)
Clocky Mc Clock-Face
59752e1f064d1261cb0000ec
[ "Fundamentals" ]
https://www.codewars.com/kata/59752e1f064d1261cb0000ec
6 kyu
# Task Imagine that you are standing near a lake and watching frog John trying to get to the other bank. You can see some stones in front of him, and you know that John can make short jumps and long jumps. But that's not it. You also know that John is a magic frog: he is afraid of water, so he can cross the lake only...
algorithms
def frogs_jumping(stones): path = [] i = len(stones) - 1 while i > 0: if i > 1 and stones[i] - stones[i - 2] == 2: dist = jmp = 2 else: dist, jmp = stones[i] - stones[i - 1], 1 i -= jmp path . append(dist) return "" . join(map(str, path[:: - 1]))
Simple Fun #211: Frog's Jumping
58fff63f4c5d026cc200000f
[ "Algorithms" ]
https://www.codewars.com/kata/58fff63f4c5d026cc200000f
5 kyu
Given an array with 3 subarrays, each containing hexadecimal color codes loosely defining red, green and blue colors based on their predominant byte value, return a string description of which of the three colors each array contains. Input is an array which contains 3 subarrays. These subarrays contain strings represe...
reference
from collections import Counter COLORS = 'Red', 'Green', 'Blue' IDX = 0, 1, 2 def get_major_minor(colors): c = Counter(max(IDX, key=lambda i: c[i * 2: i * 2 + 2]) for c in colors) return '+' . join(COLORS[i] for i, _ in c . most_common(2)) def get_colors(col_arr): return ',' . join(map(get_...
Arrays and hex color codes
597a660f59873cc353000061
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/597a660f59873cc353000061
6 kyu
On fictional islands of Matunga archipelage several different tribes use fictional currency - tung. One tung is a very small amount, so all payments are made with coins of different values. For example, one tribe use coins of 7 and 9 tungs, another - 6, 10 and 11 tungs. Every tribe has at least 2 different coins. Also ...
algorithms
from functools import reduce import math # The Money Changing Problem Revisited: Computing the Frobenius Number in Time O(k a1)* # https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.389.4933&rep=rep1&type=pdf def min_price(coins): # edge case if 1 in coins: return 1 if reduce(math . g...
Matunga coins
59799cb9429e83b7e500010c
[ "Algorithms", "Mathematics", "Combinatorics", "Performance" ]
https://www.codewars.com/kata/59799cb9429e83b7e500010c
4 kyu
Implement a function to calculate the distance between two points in n-dimensional space. The two points will be passed to your function as arrays of the same length (tuples in Python). Round your answers to two decimal places.
algorithms
def euclidean_distance(point1, point2): return round(sum((b - a) * * 2 for a, b in zip(point1, point2)) * * 0.5, 2)
Euclidean distance in n dimensions
595877be60d17855980013d3
[ "Mathematics", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/595877be60d17855980013d3
7 kyu
You just got done with your set at the gym, and you are wondering how much weight you could lift if you did a single repetition. Thankfully, a few scholars have devised formulas for this purpose (from [Wikipedia](https://en.wikipedia.org/wiki/One-repetition_maximum)) : ### Epley ```math \Large\text{1 RM} = w(1 + \fr...
algorithms
def calculate_1RM(w, r): if r == 0: return 0 if r == 1: return w return round(max([ w * (1 + r / 30), # Epley 100 * w / (101.3 - 2.67123 * r), # McGlothin w * r * * 0.10 # Lombardi ]))
1RM Calculator
595bbea8a930ac0b91000130
[ "Mathematics" ]
https://www.codewars.com/kata/595bbea8a930ac0b91000130
6 kyu
For this kata you will be using some meta-programming magic to create a new `Thing` object. This object will allow you to define things in a descriptive **sentence like format**. This challenge attempts to build on itself in an increasingly complex manner. ## Examples of what can be done with "Thing": ```ruby jane...
algorithms
from __future__ import annotations from collections . abc import Sequence import re class Being: def __init__(self, api): self . api = api def __getattr__(self, item): return self . api(item) class Relation: def __init__(self, name: str, api): self . name = name self . a...
The builder of things
5571d9fc11526780a000011a
[ "Metaprogramming", "Domain Specific Languages", "Algorithms", "Language Features" ]
https://www.codewars.com/kata/5571d9fc11526780a000011a
3 kyu
Given a string containing a list of integers separated by commas, write the function string_to_int_list(s) that takes said string and returns a new list containing all integers present in the string, preserving the order. For example, give the string "-1,2,3,4,5", the function string_to_int_list() should return [-1,2,...
algorithms
def string_to_int_list(s): return [int(n) for n in s . split(",") if n]
String to list of integers.
5727868888095bdf5c001d3d
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/5727868888095bdf5c001d3d
7 kyu
An NBA game runs 48 minutes (Four 12 minute quarters). Players do not typically play the full game, subbing in and out as necessary. Your job is to extrapolate a player's points per game if they played the full 48 minutes. Write a function that takes two arguments, ppg (points per game) and mpg (minutes per game) and ...
reference
def nba_extrap(ppg, mpg): return round(48.0 / mpg * ppg, 1) if mpg > 0 else 0
NBA full 48 minutes average
587c2d08bb65b5e8040004fd
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/587c2d08bb65b5e8040004fd
8 kyu
In this challenge, we'll be learning about the pseudocode `Display` command, and how to translate it to Python. The pseudocode standard used in this challenge is based on the book [Starting Out with Programming Logic and Design, 3rd Edition](http://www.pearsonhighered.com/product?ISBN=0132805456) by Tony Gaddis. If you...
reference
print "Hello World!" course = "CIS 122" name = "Intro to Software Design" print "Welcome to " + course + ": " + name a = 1.1 b = 3 c = a + b print "The sum of %s and %s is %s" % (a, b, c) x_print("Hello World!") language = "Python" adjective = "Fun" x_print("Learning", language, "is", adjective) pizzas = 10 slices_p...
CIS 122 #1 Simple Printing
55cd156ead636caae3000099
[ "Fundamentals" ]
https://www.codewars.com/kata/55cd156ead636caae3000099
8 kyu
Create a function that takes a string and separates it into a sequence of letters. The array will be formatted as so: ```javascript,python [['J','L','L','M'] ,['u','i','i','a'] ,['s','v','f','n'] ,['t','e','e','']] ``` The function should separate each word into individual letters, with the first word in the sentence ...
reference
from itertools import zip_longest def sep_str(st): return [[* cs] for cs in zip_longest(* st . split(), fillvalue='')]
Separating Strings
5977ef1f945d45158d00011f
[ "Fundamentals" ]
https://www.codewars.com/kata/5977ef1f945d45158d00011f
6 kyu
Create a function that takes an array of letters, and combines them into words in a sentence. The array will be formatted as so: ```javascript [ ['J','L','L','M'], ['u','i','i','a'], ['s','v','f','n'], ['t','e','e',''] ] ``` The function should combine all the 0th indexed letters to create the word 'just', al...
reference
def arr_adder(arr): return ' ' . join(map('' . join, zip(* arr)))
Adding Arrays
59778cb1b061e877c50000cc
[ "Fundamentals" ]
https://www.codewars.com/kata/59778cb1b061e877c50000cc
7 kyu
Help a fruit packer sort out the bad apples. There are 7 varieties of apples, all packaged as pairs and stacked in a fruit box. Some of the apples are spoiled. The fruit packer will have to make sure the spoiled apples are either removed from the fruit box or replaced. Below is the breakdown: Apple varieties are rep...
algorithms
def bad_apples(apples): lst, notFull = [], [] for a, b in apples: if (bool(a) ^ bool(b)) and notFull: # One bad and partially full box already present: fill it (as second element) lst[notFull . pop()]. append(a or b) elif a and b: lst . append([a, b]) # 2 good ones: keep as they...
Bad Apples
59766edb9bfe7cd5b000006e
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/59766edb9bfe7cd5b000006e
6 kyu
There is an implementation of quicksort algorithm. Your task is to fix it. All inputs are correct. See also: https://en.wikipedia.org/wiki/Quicksort
bug_fixes
quicksort = sorted
Bug Fix - Quick Sort
56bdaa2cbe8f29257c000085
[ "Sorting", "Algorithms", "Fundamentals", "Debugging" ]
https://www.codewars.com/kata/56bdaa2cbe8f29257c000085
6 kyu
In this kata you must determine the lowest floor in a building from which you cannot drop an egg without it breaking. You may assume that all eggs are the same; if one egg breaks when dropped from floor `n`, all eggs will. If an egg survives a drop from some floor, it will survive a drop from any floor below too. Y...
games
# THanks to easter eggs kata ;* def height(n, m): if n >= m: return (2 * * (min(n, m)) - 1) f = 1 res = 0 for i in range(n): f = f * (m - i) / / (i + 1) res += f return res def solve(emulator): m = emulator . drops n = emulator . eggs h = 0 tryh = 0 while n and m:...
Egg Drops
56d3f1743323a8399200063f
[ "Recursion", "Dynamic Programming", "Puzzles" ]
https://www.codewars.com/kata/56d3f1743323a8399200063f
4 kyu
You are given an array. Complete the function that returns the number of ALL elements within an array, including any nested arrays. ## Examples ```python [] --> 0 [1, 2, 3] --> 3 ["x", "y", ["z"]] --> 4 [1, 2, [3, 4, [5]]] --> 7 ``` The input will always be an array. ```if:php ...
reference
def deep_count(a): result = 0 for i in range(len(a)): if type(a[i]) is list: result += deep_count(a[i]) result += 1 return result
Array Deep Count
596f72bbe7cd7296d1000029
[ "Arrays", "Recursion", "Fundamentals" ]
https://www.codewars.com/kata/596f72bbe7cd7296d1000029
6 kyu
Your work is to write a method that takes a value and an index, and returns the value with the bit at given index flipped. The bits are numbered from the least significant bit (index 1). Example: ```cobol flipBit(15,4) = 7 * 15 in binary is 1111, after flipping 4th bit, it becomes 0111, i.e. 7 flipB...
reference
def flip_bit(value, bit_index): return value ^ (1 << (bit_index - 1))
Binary operations #1
560e80734267381a270000a2
[ "Fundamentals" ]
https://www.codewars.com/kata/560e80734267381a270000a2
7 kyu
Write a comparator for a list of phonetic words for the letters of the [greek alphabet](https://en.wikipedia.org/wiki/Greek_alphabet). A comparator is: > *a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is...
reference
def greek_comparator(lhs, rhs): return greek_alphabet . index(lhs) - greek_alphabet . index(rhs)
Greek Sort
56bc1acf66a2abc891000561
[ "Fundamentals", "Sorting" ]
https://www.codewars.com/kata/56bc1acf66a2abc891000561
8 kyu
## Description Welcome, Warrior! In this kata, you will get a message and you will need to get the frequency of each and every character! ## Explanation Your function will be called `char_freq`/`charFreq`/`CharFreq` and you will get passed a string, you will then return a dictionary (object in JavaScript) with as ke...
reference
from collections import Counter def char_freq(message): return Counter(message)
Character Frequency
548ef5b7f33a646ea50000b2
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/548ef5b7f33a646ea50000b2
8 kyu
Python is now supported on Codewars! For those of us who are not very familiar with Python, let's handle the very basic challenge of creating a class named `Python`. We want to give our Pythons a name, so it should take a name argument that we can retrieve later. For example: ```python bubba = Python('Bubba') bubba...
reference
class Python: def __init__(self, name): self . name = name
Name Your Python!
53cf459503f9bbb774000003
[ "Fundamentals" ]
https://www.codewars.com/kata/53cf459503f9bbb774000003
8 kyu
This series of katas will introduce you to basics of doing geometry with computers. ~~~if:csharp `Point` objects have fields `X` and `Y`. ~~~ ~~~if-not:csharp `Point` objects have attributes `x` and `y`. ~~~ Write a function calculating distance between `Point a` and `Point b`. Input coordinates fit in range `$ -50...
reference
def distance_between_points(a, b): return ((b . x - a . x) * * 2 + (b . y - a . y) * * 2) * * 0.5
Geometry Basics: Distance between points in 2D
58dced7b702b805b200000be
[ "Geometry", "Fundamentals" ]
https://www.codewars.com/kata/58dced7b702b805b200000be
8 kyu
You are a biologist working on the amino acid composition of proteins. Every protein consists of a long chain of 20 different amino acids with different properties. Currently, you are collecting data on the percentage, various amino acids make up a protein you are working on. As manually counting the occurences of am...
reference
def aa_percentage(seq, residues=["A", "I", "L", "M", "F", "W", "Y", "V"]): return round(sum(seq . count(r) for r in residues) / len(seq) * 100)
Percentage of amino acids
59759761e30a19cfe1000024
[ "Fundamentals" ]
https://www.codewars.com/kata/59759761e30a19cfe1000024
7 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: There is a infinite string. You can imagine it's a combination of numbers from 1 to n, like this: ``` "123456789101112131415....n-2n-1n" ``` Please...
algorithms
from itertools import count def num_index(n): if (n < 10): return n - 1 c = 0 for i in count(1): c += i * 9 * 10 * * (i - 1) if (n < 10 * * (i + 1)): return c + (i + 1) * (n - 10 * * i) def find_position(s): if not int(s): return num_index(int('1' + s...
The position of a digital string in a infinite digital string
582c1092306063791c000c00
[ "Algorithms", "Puzzles" ]
https://www.codewars.com/kata/582c1092306063791c000c00
2 kyu
----- ## CLEAR CUTTER'S NEEDS YOUR HELP! ----- The logging company Clear Cutter's makes its money by optimizing the price-to-length of each log they cut before selling them. An example of one of their price tables is included: ```python # So a price table p p = [ 0, 1, 5, 8, 9, 10] # Can be imagined as: # length...
refactoring
from functools import lru_cache # Not gonna reinvent the wheel # Now I can go on codewars while they think I'm still working on it # Be a smart intern def cut_log(p, n): @ lru_cache(maxsize=None) def rec(x): if not x: return 0 return max(p[i] + rec(x - i) for i in range(1, x + 1)) return r...
Memoized Log Cutting
54b058ce56f22dc6fe0011df
[ "Dynamic Programming", "Memoization", "Refactoring" ]
https://www.codewars.com/kata/54b058ce56f22dc6fe0011df
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: Given some pieces of wood. It given by an integer array `woods`(argument 1), each element is the length of wood. Cut them into small pieces to guarantee ...
games
def wood_cut(woods, n): x = sum(woods) / / n while x > 0 and sum(w / / x for w in woods) < n: x = max([w / / (w / / x + 1) for w in woods]) return x
Wood Cut
583dbc028bbc0446f500032b
[ "Puzzles", "Algorithms", "Arrays" ]
https://www.codewars.com/kata/583dbc028bbc0446f500032b
5 kyu
## Task In your favorite game, you must shoot a target with a water-gun to gain points. Each target can be worth a different amount of points. You are guaranteed to hit every target that you try to hit. You cannot hit consecutive targets though because targets are only visible for one second (one at a time) and...
algorithms
def target_game(values): a = b = 0 for n in values: a, b = b, max(a + n, b) return max(a, b)
Challenge Fun #14: Target Game
58acf858154165363c00004e
[ "Algorithms", "Arrays" ]
https://www.codewars.com/kata/58acf858154165363c00004e
5 kyu
Create a function that differentiates a polynomial for a given value of `x`. Your function will receive 2 arguments: a polynomial as a string, and a point to evaluate the equation as an integer. ## Assumptions: * There will be a coefficient near each `x`, unless the coefficient equals `1` or `-1`. * There will be an...
reference
from collections import defaultdict import re P = re . compile(r'\+?(-?\d*)(x\^?)?(\d*)') def differentiate(eq, x): derivate = defaultdict(int) for coef, var, exp in P . findall(eq): exp = int(exp or var and '1' or '0') coef = int(coef != '-' and coef or coef and '-1' or '1') if exp:...
Differentiate a polynomial
566584e3309db1b17d000027
[ "Algorithms", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/566584e3309db1b17d000027
4 kyu
**Steps** 1. Square the numbers that are greater than zero. 2. Multiply by 3 every third number. 3. Multiply by -1 every fifth number. 4. Return the sum of the sequence. **Example** `{ -2, -1, 0, 1, 2 }` returns `-6` ``` 1. { -2, -1, 0, 1 * 1, 2 * 2 } 2. { -2, -1, 0 * 3, 1, 4 } 3. { -2, -1, 0, 1, -1 * 4 } 4. -6 ```...
reference
def calc(a): return sum(x * * (1 + (x >= 0)) * (1 + 2 * (not i % 3)) * (- 1) * * (not i % 5) for i, x in enumerate(a, 1))
Operations with sequence
596ddaccdd42c1cf0e00005c
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/596ddaccdd42c1cf0e00005c
7 kyu
Given two strings, the first being a random string and the second being the same as the first, but with three added characters somewhere in the string (three same characters), Write a function that returns the added character ### E.g ``` string1 = "hello" string2 = "aaahello" // => 'a' ``` The above is just an exa...
games
from collections import Counter def added_char(s1, s2): return next((Counter(s2) - Counter(s1)). elements())
Three added Characters
5971b219d5db74843a000052
[ "Logic", "Strings" ]
https://www.codewars.com/kata/5971b219d5db74843a000052
6 kyu
My friend wants a new band name for her band. She like bands that use the formula: "The" + a noun with the first letter capitalized, for example: `"dolphin" -> "The Dolphin"` However, when a noun STARTS and ENDS with the same letter, she likes to repeat the noun twice and connect them together with the first and last...
reference
def band_name_generator(name): return name . capitalize() + name[1:] if name[0] == name[- 1] else 'The ' + name . capitalize()
Band name generator
59727ff285281a44e3000011
[ "Fundamentals" ]
https://www.codewars.com/kata/59727ff285281a44e3000011
7 kyu
# Unflatten a list (Harder than easy) This is the harder version of [Unflatten a list (Easy)](https://www.codewars.com/kata/57e2dd0bec7d247e5600013a) So you have again to build a method, that creates new arrays, that can be flattened! # Shorter: You have to unflatten a list/an array. You get an array of integers an...
algorithms
def unflatten(arr, depth, isLeft=1): lst, it = [], enumerate(arr if isLeft else reversed(arr)) for i, x in it: if isinstance(x, list): lst . append(unflatten(x, 1, isLeft)) continue n = x % (len(arr) - i) if n < 3: lst . append(x) else: gna = [x] + [next(it)[1] for _ in...
Unflatten a list (Harder than easy)
57e5aa1d7fbcc988800001ae
[ "Mathematics", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/57e5aa1d7fbcc988800001ae
4 kyu
## Task You will create an interpreter which takes inputs described below and produces outputs, storing state in between each input. If you're not sure where to start with this kata, check out my [Simpler Interactive Interpreter](http://www.codewars.com/dojo/katas/53005a7b26d12be55c000243) kata, which greatly simplif...
algorithms
import operator as op import re import string RE = re . compile( "\s*(=>|[-+*\/\%=\(\)]|[A-Za-z_][A-Za-z0-9_]*|[0-9]*\.?[0-9]+)\s*") def tokenize(e): return [s for s in RE . findall(e) if not s . isspace()] def is_ident(t): return t[0] in "_ " + string . ascii_letters class Interpreter: def ...
Simple Interactive Interpreter
52ffcfa4aff455b3c2000750
[ "Interpreters", "Algorithms" ]
https://www.codewars.com/kata/52ffcfa4aff455b3c2000750
1 kyu
# Simpler Interactive interpreter (or REPL) You will create an interpreter which takes inputs described below and produces outputs, storing state in between each input. This is a simplified version of the [Simple Interactive Interpreter](http://www.codewars.com/dojo/katas/52ffcfa4aff455b3c2000750) kata with functions ...
algorithms
from ast import parse, Expr, Assign, BinOp, Name, Num from operator import add, sub, mul, mod, truediv class Interpreter: def __init__(self): self . vars = {} def input(self, expression): op = {'Sub': sub, 'Add': add, 'Mult': mul, 'Div': truediv, 'Mod': mod} def _eval(node): ...
Simpler Interactive Interpreter
53005a7b26d12be55c000243
[ "Interpreters", "Parsing", "Algorithms" ]
https://www.codewars.com/kata/53005a7b26d12be55c000243
2 kyu
You will be given a sphere with radius `r`. Imagine that sphere gets cut with a plane, in this case the figure that is made with this cut is a circle. You will also be given the distance `h` between centres of sphere and circle.Your task is to return the surface area of the original sphere,area of circle and perimeter...
reference
from math import pi def stereometry(r, h): area_of_sphere = round(4 * pi * r * * 2, 3) area_of_circle = round(pi * (r * * 2 - h * * 2), 3) perimeter_of_circle = round(2 * pi * (r * * 2 - h * * 2) * * 0.5, 3) return (area_of_sphere, area_of_circle, perimeter_of_circle)
Some stereometry
5970915e54c27bd71000007b
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5970915e54c27bd71000007b
7 kyu
The alphabetized kata --------------------- Re-order the characters of a string, so that they are concatenated into a new string in "case-insensitively-alphabetical-order-of-appearance" order. Whitespace and punctuation shall simply be removed! The input is restricted to contain no numerals and only words containing ...
games
def alphabetized(s): return "" . join(sorted(filter(str . isalpha, s), key=str . lower))
Alphabetized
5970df092ef474680a0000c9
[ "Strings", "Sorting" ]
https://www.codewars.com/kata/5970df092ef474680a0000c9
6 kyu
Calculate the product of all elements in an array. ```if:csharp If the array is *null*, you should throw `ArgumentNullException` and if the array is empty, you should throw `InvalidOperationException`. As a challenge, try writing your method in just one line of code. It's possible to have only 36 characters within you...
reference
from functools import reduce from operator import mul def product(numbers): return reduce(mul, numbers) if numbers else None
Product of Array Items
5901f361927288d961000013
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/5901f361927288d961000013
7 kyu
Suzuki is preparing for a walk over fire ceremony high up in the mountains and the monks need coal for the fire. He must pack a basket of coal to the optimal level for each trip up the mountain. He must fit as much as possible into his basket. He can either take a piece of coal or leave it so he must chose which pieces...
algorithms
def pack_basket(basket, pile): charges = {0} for c in list(map(int, pile . replace('dust', ''). split())): charges |= {c + d for d in charges if c + d <= basket} return 'The basket weighs %d kilograms' % max(charges)
Help Suzuki pack his coal basket!
57f09d0bcedb892791000255
[ "Dynamic Programming", "Algorithms", "Data Structures", "Mathematics" ]
https://www.codewars.com/kata/57f09d0bcedb892791000255
5 kyu
Assume `"#"` is like a backspace in string. This means that string `"a#bc#d"` actually is `"bd"` Your task is to process a string with `"#"` symbols. ## Examples ``` "abc#d##c" ==> "ac" "abc##d######" ==> "" "#######" ==> "" "" ==> "" ```
algorithms
def clean_string(s): stk = [] for c in s: if c == '#' and stk: stk . pop() elif c != '#': stk . append(c) return '' . join(stk)
Backspaces in string
5727bb0fe81185ae62000ae3
[ "Fundamentals", "Strings", "Algorithms" ]
https://www.codewars.com/kata/5727bb0fe81185ae62000ae3
6 kyu
Construct a function that, when given a string containing an expression in infix notation, will return an identical expression in postfix notation. The operators used will be `+`, `-`, `*`, `/`, and `^` with left-associativity of all operators but `^`. The precedence of the operators (most important to least) are : 1...
algorithms
def LEFT(a, b): return a >= b def RIGHT(a, b): return a > b PREC = {'+': 2, '-': 2, '*': 3, '/': 3, '^': 4, '(': 1, ')': 1} OP_ASSOCIATION = {'+': LEFT, '-': LEFT, '*': LEFT, '/': LEFT, '^': RIGHT} def to_postfix(infix): stack, output = [], [] for c in infix: prec = PREC . get(c) ...
Infix to Postfix Converter
52e864d1ffb6ac25db00017f
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/52e864d1ffb6ac25db00017f
4 kyu
If `a = 1, b = 2, c = 3 ... z = 26` Then `l + o + v + e = 54` and `f + r + i + e + n + d + s + h + i + p = 108` So `friendship` is twice as strong as `love` :-) Your task is to write a function which calculates the value of a word based off the sum of the alphabet positions of its characters. The input will always...
reference
def words_to_marks(s): return sum(ord(c) - 96 for c in s)
Love vs friendship
59706036f6e5d1e22d000016
[ "Fundamentals" ]
https://www.codewars.com/kata/59706036f6e5d1e22d000016
7 kyu
Texas Hold'em is a Poker variant in which each player is given two "hole cards". Players then proceed to make a series of bets while five "community cards" are dealt. If there are more than one player remaining when the betting stops, a showdown takes place in which players reveal their cards. Each player makes the bes...
algorithms
class Poker: value_map = {r: v for r, v in zip( '2 3 4 5 6 7 8 9 10 J Q K A' . split(), range(2, 15))} class Card: def __init__(self, card): self . rank = card[: - 1] self . value = Poker . value_map[self . rank] self . suit = card[- 1] def __hash__(self): return h...
Texas Hold'em Hands
524c74f855025e2495000262
[ "Algorithms" ]
https://www.codewars.com/kata/524c74f855025e2495000262
3 kyu
A famous casino is suddenly faced with a sharp decline of their revenues. They decide to offer Texas hold'em also online. Can you help them by writing an algorithm that can rank poker hands? ## Task Create a poker hand that has a method to compare itself to another poker hand: ```csharp Result PokerHand.CompareWi...
algorithms
class PokerHand (object): CARD = "23456789TJQKA" RESULT = ["Loss", "Tie", "Win"] def __init__(self, hand): values = '' . join(sorted(hand[:: 3], key=self . CARD . index)) suits = set(hand[1:: 3]) is_straight = values in self . CARD is_flush = len(suits) == 1 self . score = (2 *...
Ranking Poker Hands
5739174624fc28e188000465
[ "Games", "Algorithms", "Object-oriented Programming" ]
https://www.codewars.com/kata/5739174624fc28e188000465
4 kyu
# ASC Week 1 Challenge 5 (Medium #2) Create a function that takes a 2D array as an input, and outputs another array that contains the average values for the numbers in the nested arrays at the corresponding indexes. Note: the function should also work with negative numbers and floats. ## Examples ``` [ [1, 2, 3, 4]...
reference
def avg_array(arrs): return [sum(a) / len(a) for a in zip(* arrs)]
Average Array
596f6385e7cd727fff0000d6
[ "Fundamentals" ]
https://www.codewars.com/kata/596f6385e7cd727fff0000d6
7 kyu
A list of integers is sorted in “Wave” order if alternate items are not less than their immediate neighbors (thus the other alternate items are not greater than their immediate neighbors). Thus, the array `[4, 1, 7, 5, 6, 2, 3]` is in **Wave** order because 4 >= 1, then 1 <= 7, then 7 >= 5, then 5 <= 6, then 6 >= 2, a...
algorithms
def wave_sort(a): a . sort() for i in range(1, len(a), 2): a[i], a[i - 1] = a[i - 1], a[i]
Wave Sorting
596f28fd9be8ebe6ec0000c1
[ "Algorithms", "Arrays", "Logic", "Sorting" ]
https://www.codewars.com/kata/596f28fd9be8ebe6ec0000c1
6 kyu
An AI has infected a text with a character!! This text is now **fully mutated** to this character. ~~~if-not:riscv If the text or the character are empty, return an empty string. There will never be a case when both are empty as nothing is going on!! **Note:** The character is a string of length 1 or an empty str...
reference
def contamination(text, char): return char * len(text)
Contamination #1 -String-
596fba44963025c878000039
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/596fba44963025c878000039
8 kyu
Gary likes pictures but he also likes words and reading. He has had a desire for a long time to see what words and books would look like if they could be seen as images. For this task you are required to take a continuous string that can consist of any combination of words or characters and then convert the words that...
reference
def words_to_hex(words): return [f"# { w [: 3 ]. hex (): 0 < 6 } " for w in words . encode(). split()]
Words to Hex
596e91b48c92ceff0c00001f
[ "Strings", "Arrays", "Recursion", "Fundamentals" ]
https://www.codewars.com/kata/596e91b48c92ceff0c00001f
6 kyu
# Task Write a function `deNico`/`de_nico()` that accepts two parameters: - `key`/`$key` - string consists of unique letters and digits - `message`/`$message` - string with encoded message and decodes the `message` using the `key`. First create a numeric key basing on the provided `key` by assigning each letter p...
reference
def de_nico(key, msg): ll, order, s = len(key), [sorted(key). index(c) for c in key], '' while msg: s, msg = s + '' . join(msg[i] for i in order if i < len(msg)), msg[ll:] return s . strip()
Basic DeNico
596f610441372ee0de00006e
[ "Fundamentals" ]
https://www.codewars.com/kata/596f610441372ee0de00006e
5 kyu
The aspect ratio of an image describes the proportional relationship between its width and its height. Most video shown on the internet uses a 16:9 aspect ratio, which means that for every pixel in the Y, there are roughly 1.77 pixels in the X (where 1.77 ~= 16/9). As an example, 1080p video with an aspect ratio of 16:...
reference
from typing import Tuple from math import ceil def aspect_ratio(x: int, y: int) - > Tuple[int, int]: return (ceil(y * 16 / 9), y)
Aspect Ratio Cropping - Part 1
596e4ef7b61e25981200009f
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/596e4ef7b61e25981200009f
8 kyu
# The Challenge You'll need to implement a simple lexer type `Simplexer`, which, when constructed with a given string containing an expression in a simple language, transforms that string into a stream of `Token`s. ## Simplexer Your `Simplexer` type is created with the expression it should tokenize. It should act li...
algorithms
from itertools import chain class Simplexer (object): BOOLS = ["true", "false"] KEYWORDS = ["if", "else", "for", "while", "return", "func", "break"] OPERATORS = "+-*/%()=" SPACE = " \n\t\c" NUMBER = "0123456789" CHAR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$" def ...
Simplexer
54b8204dcd7f514bf2000348
[ "Strings", "Parsing", "Algorithms" ]
https://www.codewars.com/kata/54b8204dcd7f514bf2000348
4 kyu
Generate a valid randomly generated hexadecimal color string. Assume all of them always have 6 digits. Valid Output --- #ffffff #FfFfFf #25a403 #000001 Non-Valid Output --- #fff #aaa #zzzzz cafebabe #a567567676576756A7
games
import random from string import hexdigits def generate_color_rgb(): return '#' + ''.join([random.choice(hexdigits) for i in range(6)])
HTML dynamic color string generation
56f1c6034d0c330e4a001059
[ "Puzzles" ]
https://www.codewars.com/kata/56f1c6034d0c330e4a001059
6 kyu
Given two numbers: 'left' and 'right' (1 <= 'left' <= 'right' <= 200000000000000) return sum of all '1' occurencies in binary representations of numbers between 'left' and 'right' (including both) ``` Example: countOnes 4 7 should return 8, because: 4(dec) = 100(bin), which adds 1 to the result. 5(dec) = 101(bin), wh...
algorithms
import math def count(n): if n is 0: return 0 x = int(math . log(n, 2)) return x * 2 * * (x - 1) + n - 2 * * x + 1 + count(n - 2 * * x) def countOnes(left, right): return count(right) - count(left - 1)
Count ones in a segment
596d34df24a04ee1e3000a25
[ "Binary", "Performance", "Algorithms" ]
https://www.codewars.com/kata/596d34df24a04ee1e3000a25
4 kyu
Not to brag, but I recently became the nexus of the Codewars universe! My honor and my rank were the same number. I cried a little. Complete the method that takes a hash/object/directory/association list of users, and find the *nexus*: the user whose rank is the closest is equal to his honor. Return the rank of this u...
algorithms
def nexus(d): return min(d, key=lambda x: (abs(x - d[x]), x))
Find the Nexus of the Codewars Universe
5453dce502949307cf000bff
[ "Algorithms" ]
https://www.codewars.com/kata/5453dce502949307cf000bff
6 kyu
Motivation --------- Natural language texts often have a very high frequency of certain letters, in German for example, almost every 5th letter is an E, but only every 500th is a Q. It would then be clever to choose a very small representation for E. This is exactly what the Huffman compression is about, choosing the l...
algorithms
from collections import Counter, namedtuple from heapq import heappush, heappop def frequencies(strng): return list(Counter(strng). items()) def freqs2tree(freqs): heap, Node = [], namedtuple('Node', 'letter left right') for char, weight in freqs: heappush(heap, (weight, Node(char, ...
Huffman Encoding
54cf7f926b85dcc4e2000d9d
[ "Algorithms" ]
https://www.codewars.com/kata/54cf7f926b85dcc4e2000d9d
3 kyu
This challenge is to compute a special set of <a href="https://en.wikipedia.org/wiki/Parasitic_number">parasitic numbers</a> for various number bases. >An n-parasitic number (in base 10) is a positive natural number which can be multiplied by n by moving the rightmost digit of its decimal representation to the front. H...
games
def calc_special(d, b): rep = {10: 'd', 8: 'o', 16: 'x'}[b] n = format(d, rep) while True: prod = format(d * int(n, b), rep) if n[- 1:] + n[: - 1] == prod: return n n = prod[- len(n):] + n[- 1:]
N-Parasitic Numbers Ending in N
55df87b23ed27f40b90001e5
[ "Algorithms", "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/55df87b23ed27f40b90001e5
3 kyu
In a grid of 7 by 7 squares you want to place a skyscraper in each square with only some clues: * The height of the skyscrapers is between 1 and 7 * No two skyscrapers in a row or column may have the same number of floors * A clue is the number of skyscrapers that you can see in a row or column from the outside * High...
algorithms
N = 7 perms = {i: set() for i in range(0, N + 1)} for row in __import__('itertools'). permutations(range(1, N + 1), N): c, s = 0, 0 for h in row: if h > c: c, s = h, s + 1 perms[0]. add(row) perms[s]. add(row) def solve_puzzle(clues): rows = [perms[r] & {p[:: - 1] for p i...
7×7 Skyscrapers
5917a2205ffc30ec3a0000a8
[ "Algorithms", "Games", "Performance" ]
https://www.codewars.com/kata/5917a2205ffc30ec3a0000a8
1 kyu
<style type="text/css"> table, tr, td { border: 0px; } </style> In a grid of 6 by 6 squares you want to place a skyscraper in each square with only some clues: <ul> <li>The height of the skyscrapers is between 1 and 6</li> <li>No two skyscrapers in a row or column may have the same number of flo...
games
from itertools import permutations def solve_puzzle(clues): size = 6 variants = {i: set() for i in range(size + 1)} for row in permutations(range(1, size + 1)): visible = sum(v >= max(row[: i + 1]) for i, v in enumerate(row)) variants[visible]. add(row) variants[0]. add(row) po...
6 By 6 Skyscrapers
5679d5a3f2272011d700000d
[ "Mathematics", "Puzzles", "Games", "Arrays", "Matrix", "Algorithms" ]
https://www.codewars.com/kata/5679d5a3f2272011d700000d
2 kyu
Create a function that finds the largest <a href="https://en.wikipedia.org/wiki/Palindromic_number" target="_blank">palindromic number</a> made from the product of **at least 2** of the given arguments. ### Notes * Only non-negative numbers will be given in the argument * You don't need to use all the digits of the p...
algorithms
from collections import Counter from itertools import combinations from functools import reduce from operator import mul def best_pal(array): outside, inside = [], '' for k, v in Counter(array). items(): if v > 1: outside . append(k * (v / / 2)) if v % 2: inside = max(insid...
Largest Numeric Palindrome
556f4a5baa4ea7afa1000046
[ "Algorithms", "Performance" ]
https://www.codewars.com/kata/556f4a5baa4ea7afa1000046
4 kyu
Your task in this Kata is to emulate text justification in monospace font. You will be given a single-lined text and the expected justification width. The longest word will never be greater than this width. Here are the rules: * Use spaces to fill in the gaps between words. * Each line should contain as many word...
algorithms
def justify(text, width): ''' Iterates through text, calculating 'n' words at a time that would fit in a line. Caluculates 'extra' remaining characters that would fit and spreads them throughout the line. ''' text = text . split() lengths = [len(word) for word in text] output = '' # end...
Text align justify
537e18b6147aa838f600001b
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/537e18b6147aa838f600001b
4 kyu
# Task A newspaper is published in Walrusland. Its heading is `s1` , it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in orde...
algorithms
import re def buy_newspaper(s1, s2): p = re . sub(r"(.)", r"\1?", s1) return - 1 if set(s2) - set(s1) else len(re . findall(p, s2)) - 1
Simple Fun #342: Buy Newspaper
596c26187bd547f3a6000050
[ "Algorithms" ]
https://www.codewars.com/kata/596c26187bd547f3a6000050
6 kyu
For a given chemical formula represented by a string, count the number of atoms of each element contained in the molecule and return an object (associative array in PHP, `Dictionary<string, int>` in C#, Map<String,Integer> in Java). For example: ```javascript var water = 'H2O'; parseMolecule(water); // return {H: 2, ...
algorithms
from collections import Counter import re COMPONENT_RE = ( r'(' r'[A-Z][a-z]?' r'|' r'\([^(]+\)' r'|' r'\[[^[]+\]' r'|' r'\{[^}]+\}' r')' r'(\d*)' ) def parse_molecule(formula): counts = Counter() for element, count in re . findall(COMPONENT_RE, formula): count = in...
Molecule to atoms
52f831fa9d332c6591000511
[ "Parsing", "Algorithms", "Strings" ]
https://www.codewars.com/kata/52f831fa9d332c6591000511
5 kyu
Given an array of numbers, calculate the largest sum of all possible blocks of consecutive elements within the array. The numbers will be a mix of positive and negative values. If all numbers of the sequence are nonnegative, the answer will be the sum of the entire array. If all numbers in the array are negative, your ...
algorithms
def largest_sum(arr): sum = max_sum = 0 for n in arr: sum = max(sum + n, 0) max_sum = max(sum, max_sum) return max_sum
Compute the Largest Sum of all Contiguous Subsequences
56001790ac99763af400008c
[ "Mathematics", "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/56001790ac99763af400008c
5 kyu
Your company **MRE Tech** has hired a spiritual consultant who advised on a new *Balance* policy: Don't take sides, don't favour, stay in the middle. This policy even applies to the software where all strings should now be centered. You are the poor soul to implement it. # Task ```if-not:c Implement a function `cente...
reference
def center(strng, width, fill=' '): width -= len(strng) right = width / / 2 left = width - right return "{}{}{}" . format(left * fill, strng, right * fill)
"Center yourself", says the monk.
596b8a3fc4cb1de46b000001
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/596b8a3fc4cb1de46b000001
7 kyu