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 |
|---|---|---|---|---|---|---|---|
Given a `Date` (in JS and Ruby) or `hours` and `minutes` (in C and Python), return the angle between the two hands of a 12-hour analog clock in **radians**.
### Notes:
* The minute hand always points to the exact minute (there is no seconds hand).
* The hour hand does not "snap" to the tick marks: e.g. at `6:30` the... | algorithms | from math import radians
def hand_angle(hours, minutes):
angle = abs(hours * 30 - 11 * minutes / 2)
return radians(min(angle, 360 - angle))
| Angle Between Clock Hands | 543ddf69386034670d000c7d | [
"Mathematics",
"Date Time",
"Algorithms"
] | https://www.codewars.com/kata/543ddf69386034670d000c7d | 6 kyu |
Your job is to group the words in anagrams.
## What is an anagram ?
`star` and `tsar` are anagram of each other because you can rearrange the letters for *star* to obtain *tsar*.
## Example
A typical test could be :
```javascript
// input
["tsar", "rat", "tar", "star", "tars", "cheese"]
// output
[
["tsar", "s... | algorithms | def group_anagrams(words):
groups = dict()
for word in words:
key = tuple(sorted(word))
try:
groups[key]. append(word)
except:
groups[key] = [word]
return [v for v in groups . values()]
| Group Anagrams | 537400e773076324ab000262 | [
"Algorithms",
"Data Structures"
] | https://www.codewars.com/kata/537400e773076324ab000262 | 6 kyu |
Write a function that takes an integer `n` and returns the `n`th iteration of the fractal known as [*Sierpinski's Gasket*](http://en.wikipedia.org/wiki/Sierpinski_triangle).
Here are the first few iterations. The fractal is composed entirely of `L` and white-space characters; each character has one space between it a... | algorithms | def sierpinskiRows(n):
if not n:
return ['L']
last = sierpinskiRows(n - 1)
return last + [row . ljust(2 * * n) + row for row in last]
def sierpinski(n):
"""Returns a string containing the nth iteration of the Sierpinsky Gasket fractal"""
return '\n' . join(sierpinskiRows(n))
| Sierpinski's Gasket | 53ea3ad17b5dfe1946000278 | [
"Mathematics",
"ASCII Art"
] | https://www.codewars.com/kata/53ea3ad17b5dfe1946000278 | 5 kyu |
In this task you have to code process planner.
You will be given initial thing, target thing and a set of processes to turn one thing into another (in the form of _[process\_name, start\_thing, end\_thing]_). You must return names of shortest sequence of processes to turn initial thing into target thing, or empty seq... | algorithms | def processes(start, end, processes):
'''Dijkstra's shortest path algorithm'''
q = [(start, [])]
visited = set()
while q:
s, path = q . pop(0)
if s == end:
return path
visited . add(s)
for p in filter(lambda x: x[1] == s, processes):
if not p[2] in visited:
q... | Processes | 542ea700734f7daff80007fc | [
"Algorithms"
] | https://www.codewars.com/kata/542ea700734f7daff80007fc | 5 kyu |
The AKS algorithm for testing whether a number is prime is a polynomial-time test based on the following theorem:
A number p is prime if and only if all the coefficients of the polynomial expansion of `(x − 1)^p − (x^p − 1)` are divisible by `p`.
For example, trying `p = 3`:
(x − 1)^3 − (x^3 − 1) = (x^3 − 3x^2... | reference | def aks_test(p):
coeff = 1
for i in xrange(p / 2):
coeff = coeff * (p - i) / (i + 1)
if coeff % p:
return False
return p > 1
| Simple AKS Primality Test | 5416d02d932c1df3a3000492 | [
"Mathematics",
"Algorithms",
"Fundamentals"
] | https://www.codewars.com/kata/5416d02d932c1df3a3000492 | 5 kyu |
Gray code is a form of binary encoding where transitions between consecutive numbers differ by only one bit. This is a useful encoding for reducing hardware data hazards with values that change rapidly and/or connect to slower hardware as inputs. It is also useful for generating inputs for Karnaugh maps.
Here is an e... | algorithms | def bin2gray(bits):
bits . reverse()
return list(reversed([x if i >= len(bits) - 1 or bits[i + 1] == 0 else 1 - x for i, x in enumerate(bits)]))
def gray2bin(bits):
for i, x in enumerate(bits):
if i > 0 and bits[i - 1] != 0:
bits[i] = 1 - x
return bits
| Gray Code | 5416ce834c2460b4d300042d | [
"Algorithms"
] | https://www.codewars.com/kata/5416ce834c2460b4d300042d | 6 kyu |
Imagine the following situations:
- A truck loading cargo
- A shopper on a budget
- A thief stealing from a house using a large bag
- A child eating candy very quickly
All of these are examples of ***The Knapsack Problem***, where there are more things that you ***want*** to take with you than you ***can*** take with... | algorithms | def knapsack(capacity, items):
ratios = [float(item[1]) / item[0] for item in items]
collection = [0] * len(items)
space = capacity
while any(ratios):
best_index = ratios . index(max(ratios))
if items[best_index][0] <= space:
collection[best_index] += 1
space -= items[best_index]... | Knapsack Part 1 - The Greedy Solution | 53ffbba24e9e1408ee0008fd | [
"Algorithms",
"Mathematics",
"Sorting"
] | https://www.codewars.com/kata/53ffbba24e9e1408ee0008fd | 5 kyu |
Write a synchronous function that makes a directory and recursively makes all of its parent directories as necessary.
A directory is specified via a sequence of arguments which specify the path. For example:
```javascript
mkdirp('/','tmp','made','some','dir')
```
```coffeescript
mkdirp '/','tmp','made','some','dir'... | reference | import os
def mkdirp(* directories):
"""Recursively create all directories as necessary"""
try:
os . makedirs(os . path . join(* directories))
except OSError:
pass
| mkdir -p | 53e248c9af0d91a45b000e71 | [
"Fundamentals"
] | https://www.codewars.com/kata/53e248c9af0d91a45b000e71 | 6 kyu |
### Overview
Write a helper function that accepts an argument (Ruby: a Time object / Others: number of seconds) and converts it to a more human-readable format. You need only go up to '_ weeks ago'.
```python
to_pretty(0) => "just now"
to_pretty(40000) => "11 hours ago"
```
```ruby
to_pretty(Time.now) => "just now"
... | reference | def to_pretty(seconds):
if seconds == 0:
return "just now"
elif seconds == 1:
return "a second ago"
elif seconds == 60:
return f"a minute ago" # 59
elif seconds == 3600:
return f"an hour ago"
elif seconds == 86400:
return f"a day ago"
elif seconds == 6048... | Pretty date | 53988ee02c2414dbad000baa | [
"Date Time",
"Fundamentals"
] | https://www.codewars.com/kata/53988ee02c2414dbad000baa | 6 kyu |
[Goldbach's conjecture](http://en.wikipedia.org/wiki/Goldbach%27s_conjecture) is amongst the oldest and well-known unsolved mathematical problems out there. In correspondence with [Leonhard Euler](http://en.wikipedia.org/wiki/Leonhard_Euler) in 1742, German mathematician [Christian Goldbach](http://en.wikipedia.org/wik... | algorithms | def isprime(n): # True if n is prime. This is a pretty efficient implementation
for i in range(2, int(n * * 0.5) + 1):
if n % i == 0:
return False
return True
def check_goldbach(n):
if n <= 2:
return []
if n % 2:
return []
for i in range(2, n / / 2 + 1):
... | Goldbach's Conjecture | 537ba77315ddd92659000fec | [
"Algorithms",
"Number Theory"
] | https://www.codewars.com/kata/537ba77315ddd92659000fec | 6 kyu |
Cascading Style Sheets (CSS) is a style sheet language used for describing the look and formatting of a document written in a markup language. A style sheet consists of a list of rules. Each rule or rule-set consists of one or more selectors, and a declaration block. Selector describes which element it matches.
Someti... | algorithms | import re
def compare(a, b):
return a if specificity(a) > specificity(b) else b
def specificity(s):
return [len(re . findall(r, s)) for r in (r'#\w+', r'\.\w+', r'(^| )\w+')]
| Simple CSS selector comparison | 5379fdfad08fab63c6000a63 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/5379fdfad08fab63c6000a63 | 5 kyu |
For a general presentation of Cycle detection Problem see this kata: http://www.codewars.com/kata/5416f1834c24604c46000696
The greedy algorithm for cycle detection is trivial but ask for storing at least `$\mu + \lambda$` values and perform a comparison on each pair of values, resulting in an overall quadratic complex... | algorithms | def floyd(f, x0):
tortoise = f(x0)
hare = f(f(x0))
while tortoise != hare:
tortoise = f(tortoise)
hare = f(f(hare))
mu = 0
tortoise = x0
while tortoise != hare:
tortoise = f(tortoise)
hare = f(hare)
mu += 1
lam = 1
hare = f(tortoise)
while to... | Cycle Detection: Floyd's The Tortoise and the The Hare | 5416f1b54c24607e4c00069f | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5416f1b54c24607e4c00069f | 5 kyu |
# Introduction
<pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;">
Fish are an integral part of any ecosystem. Unfortunately, fish are often seen as high maintenance. Contrary to popular belief, fish actually reduce pond maintenance as t... | reference | def fish(shoal):
eaten, size, target = 0, 1, 4
for f in sorted(map(int, shoal)):
if f > size:
break
eaten += f
if eaten >= target:
size += 1
target += 4 * size
return size
| Plenty of Fish in the Pond | 5904be220881cb68be00007d | [
"Fundamentals"
] | https://www.codewars.com/kata/5904be220881cb68be00007d | 6 kyu |
Well here you are again, still staring blankly at the same arrivals/departures flap display...
<div style="width:75%"><img src="http://www.airport-arrivals-departures.com/img/meta/1200_630_arrivals-departures.png"></div>
# Kata Task
## Part #1
In <a style="color:green" href="https://www.codewars.com/kata/57feb00f08d... | algorithms | def flat_rotors(lines_before, lines_after):
ln = len(ALPHABET)
def nxt_rotor(wb, wa):
rot = []
for lb, la in zip(wb, wa):
rot . append((ALPHABET . index(la) - ALPHABET . index(lb) - sum(rot)) % ln)
return rot
return [nxt_rotor(lnb, lna) for lnb, lna in zip(lines_before, lines_after)]
... | Airport Arrivals/Departures - #2 | 584cfd7e2609c8ab4d0000e3 | [
"Algorithms"
] | https://www.codewars.com/kata/584cfd7e2609c8ab4d0000e3 | 6 kyu |
Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, `134468`.
Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, `66420`.
We shall call a positive integer that is neither increasing nor decr... | games | def inc(x): return all(str(x)[p] <= str(x)[p + 1]
for p in range(len(str(x)) - 1))
def dec(x): return all(str(x)[p] >= str(x)[p + 1]
for p in range(len(str(x)) - 1))
def bouncy(x): return not (inc(x) or dec(x))
def bouncy_ratio(percent):
n, bouncy_coun... | Ratio of Bouncy Numbers | 562b099becfe844f3800000a | [
"Mathematics",
"Puzzles"
] | https://www.codewars.com/kata/562b099becfe844f3800000a | 5 kyu |
You and your friends have been battling it out with your Rock 'Em, Sock 'Em robots, but things have gotten a little boring. You've each decided to add some amazing new features to your robot and automate them to battle to the death.
Each robot will be represented by an object. You will be given two robot objects, and ... | reference | def fight(robot_1, robot_2, tactics):
attack, defend = (robot_1, robot_2) if robot_1['speed'] >= robot_2['speed'] else (
robot_2, robot_1)
while attack['health'] > 0:
if attack['tactics']:
defend['health'] -= tactics[attack['tactics']. pop()]
elif not defend['tactics']:
break
... | 80's Kids #6: Rock 'Em, Sock 'Em Robots | 566b490c8b164e03f8000002 | [
"Fundamentals"
] | https://www.codewars.com/kata/566b490c8b164e03f8000002 | 5 kyu |
Don't Drink the Water
Given a two-dimensional array representation of a glass of mixed liquids, sort the array such that the liquids appear in the glass based on their density. (Lower density floats to the top) The width of the glass will not change from top to bottom.
```
======================
| Density Chart ... | algorithms | def separate_liquids(glass):
chain = sorted(sum(glass, []), key='HWAO' . index)
return [[chain . pop() for c in ro] for ro in glass]
| Don't Drink the Water | 562e6df5cf2d3908ad00019e | [
"Algorithms",
"Arrays",
"Sorting",
"Lists"
] | https://www.codewars.com/kata/562e6df5cf2d3908ad00019e | 5 kyu |
Sir Bobsworth is a custodian at a local data center. As he suspected, Bobsworth recently found out he is to be fired on his birthday after years of pouring his soul into maintaining the facility.
Bobsworth, however, has other plans.
Bobsworth knows there are `1` to `n` switches in the breaker box of the data center.... | games | def off(n):
return [i * i for i in range(1, int(n * * 0.5) + 1)]
| Disgruntled Employee | 541103f0a0e736c8e40011d5 | [
"Logic",
"Mathematics",
"Sorting",
"Arrays",
"Puzzles"
] | https://www.codewars.com/kata/541103f0a0e736c8e40011d5 | 6 kyu |
Create the function `fridayTheThirteenths` that accepts a `start` year and an `end` year (*inclusive*), and returns all of the dates where the 13th of a month lands on a Friday in the given range of year(s).
The return value should be a string where each date is *seperated by a space*. The date should be formatted li... | reference | from datetime import date
def friday_the_thirteenths(start, end=None):
return ' ' . join(f' { m } /13/ { y } ' for y in range(start, 1 + (end or start)) for m in range(1, 13) if date(y, m, 13). weekday() == 4)
| Friday the 13ths | 540954232a3259755d000039 | [
"Date Time",
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/540954232a3259755d000039 | 6 kyu |
# Making Change
Complete the method that will determine the minimum number of coins needed to make change for a given amount in American currency.
Coins used will be half-dollars, quarters, dimes, nickels, and pennies, worth 50¢, 25¢, 10¢, 5¢ and 1¢, respectively. They'll be represented by the symbols `H`, `Q`, `D`, ... | algorithms | BASE = {"H": 50, "Q": 25, "D": 10, "N": 5, "P": 1}
def make_change(n):
r = {}
for x, y in BASE . items():
if n >= y:
r[x], n = divmod(n, y)
return r
| Making Change | 5365bb5d5d0266cd010009be | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5365bb5d5d0266cd010009be | 6 kyu |
Finish the function ```numberToOrdinal```, which should take a number and return it as a string with the correct ordinal indicator suffix (in English). That is:
* ```numberToOrdinal(1) ==> '1st'```
* ```numberToOrdinal(2) ==> '2nd'```
* ```numberToOrdinal(3) ==> '3rd'```
* ```numberToOrdinal(4) ==> '4th'```
* ```... ... | algorithms | def numberToOrdinal(n):
if not (11 <= n % 100 <= 13):
if n % 10 == 1:
return f' { n } st'
elif n % 10 == 2:
return f' { n } nd'
elif n % 10 == 3:
return f' { n } rd'
return f' { n } th' if n else '0'
| Adding ordinal indicator suffixes to numbers | 52dca71390c32d8fb900002b | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/52dca71390c32d8fb900002b | 6 kyu |
A [Word Square](https://en.wikipedia.org/wiki/Word_square) is a set of words written out in a square grid, such that the same words can be read both horizontally and vertically. The number of words, equal to the number of letters in each word, is known as the *order* of the square.
For example, this is an *order* `5` ... | games | from collections import Counter
def word_square(ls):
n = int(len(ls) * * 0.5)
return n * n == len(ls) and sum(i % 2 for i in Counter(ls). values()) <= n
| WordSquare | 578e07d590f2bb8d3300001d | [
"Puzzles"
] | https://www.codewars.com/kata/578e07d590f2bb8d3300001d | 5 kyu |
# Introduction:
Reversi is a game usually played by 2 people on a 8x8 board.
Here we're only going to consider a single 8x1 row.
Players take turns placing pieces, which are black on one side and white on the
other, onto the board with their colour facing up. If one or more of the
opponents pieces are sandwiched by ... | algorithms | from re import sub
def reversi_row(moves):
current = '.' * 8
for i, x in enumerate(moves):
c1, c2 = "Ox" if i & 1 else "xO"
left = sub(r"(?<={}){}+$" . format(c1, c2),
lambda r: c1 * len(r . group()), current[: x])
right = sub(r"^{}+(?={})" . format(c2, c1), lambda r: c1 *
... | Reversi row rudiments | 55aa92a66f9adfb2da00009a | [
"Games",
"Algorithms"
] | https://www.codewars.com/kata/55aa92a66f9adfb2da00009a | 5 kyu |
Rule 30 is a one-dimensional binary cellular automaton. You can have some information here: https://en.wikipedia.org/wiki/Rule_30
Complete the function that takes as input an array of `0`s and `1`s and a non-negative integer `n` that represents the number of iterations. This function has to perform the n<sup>th</sup> ... | games | def rule30(a, n):
for _ in range(n):
a = [int(0 < 4 * x + 2 * y + z < 5) for x, y, z in
zip([0, 0] + a, [0] + a + [0], a + [0, 0])]
return a
| Rule 30 | 5581e52ac76ffdea700000c1 | [
"Lists",
"Arrays",
"Binary",
"Puzzles"
] | https://www.codewars.com/kata/5581e52ac76ffdea700000c1 | 5 kyu |
Your task is to finish two functions, `minimumSum` and `maximumSum`, that take 2 parameters:
- `values`: an array of integers with an arbitrary length; may be positive and negative
- `n`: how many integers should be summed; always 0 or bigger
### Example:
```javascript
var values = [5, 4, 3, 2, 1];
minimumSum(values... | reference | def minimum_sum(values, n):
'''sum the n smallest integers in the array values (not necessarily ordered)'''
return sum(sorted(values)[: n])
def maximum_sum(values, n):
'''sum the n largest integers in the array values (not necessarily ordered)'''
return sum(sorted(values, reverse=True)[: n])
... | Exercise in Summing | 52cd0d600707d0abcd0003eb | [
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/52cd0d600707d0abcd0003eb | 6 kyu |
Your friend won't stop texting his girlfriend. It's all he does. All day. Seriously. The texts are so mushy too! The whole situation just makes you feel ill.
Being the wonderful friend that you are, you hatch an evil plot. While he's sleeping, you take his phone and change the autocorrect options so that every time ... | algorithms | import re
def autocorrect(input):
return re . sub(r'(?i)\b(u|you+)\b', "your sister", input)
| Evil Autocorrect Prank | 538ae2eb7a4ba8c99b000439 | [
"Strings",
"Regular Expressions",
"Algorithms"
] | https://www.codewars.com/kata/538ae2eb7a4ba8c99b000439 | 6 kyu |
It's a Pokemon battle! Your task is to calculate the damage that a particular move would do using the following formula (not the actual one from the game):
```javascript
damage = 50 * (attack / defense) * effectiveness
```
Where:
* attack = your attack power
* defense = the opponent's defense
* effectiveness = the e... | games | import math
effectiveness = {
"electric": {
"electric": 0.5,
"fire": 1,
"grass": 1,
"water": 2
},
"fire": {
"electric": 1,
"fire": 0.5,
"grass": 2,
"water": 0.5
},
"grass": {
"electric": 1,
"fire": 0.5,
... | Pokemon Damage Calculator | 536e9a7973130a06eb000e9f | [
"Arrays",
"Games",
"Strings",
"Puzzles"
] | https://www.codewars.com/kata/536e9a7973130a06eb000e9f | 6 kyu |
Previously on Codewars...
"[Triangular numbers](http://en.wikipedia.org/wiki/Triangular_number) are so called because of the equilateral triangular shape that they occupy when laid out as dots. i.e.
```
1st (1) 2nd (3) 3rd (6)
* ** ***
* **
*
```
In the ```... | reference | def tetrahedron(size):
return size * (size + 1) * (size + 2) / / 6
| A tetrahedron of cannonballs | 530e259c7bc88a4ab9000754 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/530e259c7bc88a4ab9000754 | 6 kyu |
You are given a sequence of valid words and a string. Test if the string is made up by one or more words from the array.
<h3>Task</h3>
Test if the string can be entirely formed by consecutively concatenating words of the dictionary.
For example:
```
dictionary: ["code", "wars"]
s1: "codewars" => true -... | algorithms | def valid_word(seq, word):
return not word or any(valid_word(seq, word[len(x):]) for x in seq if word . startswith(x))
| Valid string | 52f3bb2095d6bfeac2002196 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/52f3bb2095d6bfeac2002196 | 6 kyu |
## Help the frog to find a way to freedom
---
You have an array of integers and have a frog at the first position
`[Frog, int, int, int, ..., int]`
The integer itself may tell you the length and the direction of the jump
```
For instance:
2 = jump two indices to the right
-3 = jump three indices to the left... | algorithms | def solution(a):
if (len(a) == 0):
return - 1
pos = 0
jump = 0
while pos >= 0 and pos < len ( a ):
if ( a [ pos ] == 0 ): return - 1
step = a [ pos ]
a [ pos ] = 0
pos += step
jump += 1
return jump | Frog jumping | 536950ffc8a5ca9982001371 | [
"Fundamentals",
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/536950ffc8a5ca9982001371 | 6 kyu |
**Step 1:** Create a function called `encode()` to replace all the lowercase vowels in a given string with numbers according to the following pattern:
```
a -> 1
e -> 2
i -> 3
o -> 4
u -> 5
```
For example, `encode("hello")` would return `"h2ll4"`. There is no need to worry about uppercase vowels in this kata.
**Step... | reference | def encode(s, t=str . maketrans("aeiou", "12345")):
return s . translate(t)
def decode(s, t=str . maketrans("12345", "aeiou")):
return s . translate(t)
| The Vowel Code | 53697be005f803751e0015aa | [
"Arrays",
"Strings",
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/53697be005f803751e0015aa | 6 kyu |
A prime number is an integer greater than 1 that is only evenly divisible by itself and 1.
Write your own Primes class with class method <code>Primes.first(n)</code> that returns an array of the first n prime numbers.
For example:
<pre><code>Primes.first(1)
# => [2]
Primes.first(2)
# => [2, 3]
Primes.first(5)
# =>... | algorithms | def rwh_primes2(n):
# http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
""" Input n>=6, Returns a list of primes, 2 <= p < n """
correction = (n % 6 > 1)
n = {0: n, 1: n - 1, 2: n + 4, 3: n + 3, 4: n + 2, 5: n + 1}[n % 6]
sieve = [True] ... | First n Prime Numbers | 535bfa2ccdbf509be8000113 | [
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/535bfa2ccdbf509be8000113 | 5 kyu |
### The task
Your task, is to calculate the minimal number of moves to win the game "Towers of Hanoi", with given number of disks.
### What is "Towers of Hanoi"?
Towers of Hanoi is a simple game consisting of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with th... | games | def hanoi(disks):
return 2 * * disks - 1
| Hanoi record | 534eb5ad704a49dcfa000ba6 | [
"Fundamentals",
"Algorithms",
"Mathematics",
"Puzzles"
] | https://www.codewars.com/kata/534eb5ad704a49dcfa000ba6 | 6 kyu |
Write a function that returns a (custom) [FizzBuzz](https://en.wikipedia.org/wiki/Fizz_buzz) sequence of the numbers `1 to 100`.
The function should be able to take up to 4 arguments:
* The 1st and 2nd arguments are strings, `"Fizz"` and `"Buzz"` by default;
* The 3rd and 4th arguments are integers, `3` and `5` by def... | reference | def fizz_buzz_custom(string_one="Fizz", string_two="Buzz", num_one=3, num_two=5):
result = []
for i in range(1, 101):
x = ""
if i % num_one == 0:
x += string_one
if i % num_two == 0:
x += string_two
result . append(x or i)
return result
| Custom FizzBuzz Array | 5355a811a93a501adf000ab7 | [
"Arrays",
"Logic",
"Fundamentals"
] | https://www.codewars.com/kata/5355a811a93a501adf000ab7 | 6 kyu |
We want to approximate the `sqrt` function. Usually this function takes a floating point number and returns another floating point number, but in this kata we're going to work with _integral_ numbers instead.
Your task is to write a function that takes an integer `n` and returns either
- an integer `k` if `n` is a sq... | algorithms | def sqrt_approximation(number):
i = 0
while i * i < number:
i += 1
return i if i * i == number else [i - 1, i]
| Sqrt approximation | 52ecde1244751a799b00018a | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/52ecde1244751a799b00018a | 6 kyu |
Write a function that outputs the transpose of a matrix - a new matrix
where the columns and rows of the original are swapped.
For example, the transpose of:
| 1 2 3 |
| 4 5 6 |
is
| 1 4 |
| 2 5 |
| 3 6 |
The input to your function will be an array of matrix rows. You can
assume that each row... | algorithms | def transpose(matrix):
return list(map(list, zip(* matrix)))
| Matrix Transpose | 52fba2a9adcd10b34300094c | [
"Mathematics",
"Algebra",
"Matrix",
"Algorithms"
] | https://www.codewars.com/kata/52fba2a9adcd10b34300094c | 6 kyu |
Given a standard english sentence passed in as a string, write a method that will return a sentence made up of the same words, but sorted by their first letter. However, the method of sorting has a twist to it:
* All words that begin with a lower case letter should be at the beginning of the sorted sentence, and sorted... | algorithms | from string import punctuation
t = str . maketrans("", "", punctuation)
def pseudo_sort(s):
a = s . translate(t). split()
b = sorted(x for x in a if x[0]. islower())
c = sorted((x for x in a if x[0]. isupper()), reverse=True)
return " " . join(b + c)
| Sort sentence pseudo-alphabetically | 52dffa05467ee54b93000712 | [
"Sorting",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/52dffa05467ee54b93000712 | 6 kyu |
An Arithmetic Progression is defined as one in which there is a constant difference between the consecutive terms of a given series of numbers. You are provided with consecutive elements of an Arithmetic Progression. There is however one hitch: exactly one term from the original series is missing from the set of number... | algorithms | def find_missing(sequence):
t = sequence
return (t[0] + t[- 1]) * (len(t) + 1) / 2 - sum(t)
| Find the missing term in an Arithmetic Progression | 52de553ebb55d1fca3000371 | [
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/52de553ebb55d1fca3000371 | 6 kyu |
**Introduction**
Ordinal numbers are used to tell the position of something in a list. Unlike regular numbers, they have a special suffix added to the end of them.
**Task**
Your task is to write the `ordinal(number, brief)` function. `number` will be an integer. You need to find the ordinal suffix of said number.
... | algorithms | def ordinal(n, brief=False):
n %= 100
if 9 < n < 20:
return "th"
n %= 10
if n == 1:
return "st"
if n == 2:
return "nd" [brief:]
if n == 3:
return "rd" [brief:]
return "th"
| Ordinal Numbers | 52dda52d4a88b5708f000024 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/52dda52d4a88b5708f000024 | 6 kyu |
We will use the Flesch–Kincaid Grade Level to evaluate the readability of a piece of text. This grade level is an approximation for what schoolchildren are able to understand a piece of text. For example, a piece of text with a grade level of 7 can be read by seventh-graders and beyond.
The way to calculate the grade ... | algorithms | from re import compile as reCompile
SENTENCE = reCompile(r'[.!?]')
SYLLABLE = reCompile(r'(?i)[aeiou]+')
def count(string, pattern):
return len(pattern . findall(string))
def flesch_kincaid(text):
nWords = text . count(' ') + 1
return round(0.39 * nWords / count(text, SENTENCE) + 11.8 * cou... | Readability is King | 52b2cf1386b31630870005d4 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/52b2cf1386b31630870005d4 | 5 kyu |
Pirates have notorious difficulty with enunciating. They tend to blur all the letters together and scream at people.
At long last, we need a way to unscramble what these pirates are saying.
Write a function that will accept a jumble of letters as well as a dictionary, and output a list of words that the pirate might ... | algorithms | def grabscrab(said, possible_words):
return [word for word in possible_words if sorted(word) == sorted(said)]
| Arrh, grabscrab! | 52b305bec65ea40fe90007a7 | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/52b305bec65ea40fe90007a7 | 6 kyu |
Write a method that takes an array of signed integers, and returns the longest contiguous subsequence of this array that has a total sum of elements of exactly `0`.
If more than one equally long subsequences have a zero sum, return the one starting at the highest index.
For example:
`maxZeroSequenceLength([25, -35,... | algorithms | from itertools import accumulate
def max_zero_sequence(arr):
memo, start, stop = {0: 0}, 0, 0
for i, x in enumerate(accumulate(arr), 1):
if x in memo:
if start + i > stop + memo[x]:
start, stop = memo[x], i
else:
memo[x] = i
return arr[start: stop]
| Longest sequence with zero sum | 52b4d1be990d6a2dac0002ab | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/52b4d1be990d6a2dac0002ab | 5 kyu |
In elementary arithmetic a "carry" is a digit that is transferred from one column of digits to another column of more significant digits during a calculation algorithm.
This Kata is about determining the number of carries performed during the addition of multi-digit numbers.
You will receive an input string containin... | algorithms | def ok(s):
a, b = s . split()
a, b = a[:: - 1], b[:: - 1]
d = 0
c = 0
for i, j in zip(a, b):
if (int(i) + int(j) + c) > 9:
c = 1
d += 1
else:
c = 0
return "{} carry operations" . format(d) if d > 0 else "No carry operation"
def solve(s):
return '\n' . joi... | Elementary Arithmetic - Carries Count | 529fdef7488f509b81000061 | [
"Algorithms"
] | https://www.codewars.com/kata/529fdef7488f509b81000061 | 5 kyu |
Create a darkroom function that when first called takes an integer (no need to protect yourself in this kata), this is the master screaming where the crotch kick is going to come from (or possibly to tell the attacker where to kick from, no one really knows). Then a 1 will be used as an argument to one of the chaining ... | algorithms | class dark_room:
def __init__(self, direction):
self . d = direction
self . blocked = False
def __call__(self, n=0):
self . d -= 1
if n:
self . blocked = not self . d
self . d = - 1
return self
def end(self):
return ('CROTCH KICK', 'BLOCK')[self . blocked]
| The "CROTCH KICK OR BLOCK" kata | 528aa29bd8a0399fc5000cae | [
"Algorithms"
] | https://www.codewars.com/kata/528aa29bd8a0399fc5000cae | 5 kyu |
Two Joggers
===
Description
---
Bob and Charles are meeting for their weekly jogging tour. They both start at the same spot called "Start" and they each run a different lap, which may (or may not) vary in length. Since they know each other for a long time already, they both run at the exact same speed.
Illustration
-... | algorithms | from fractions import gcd
def nbr_of_laps(x, y):
return (y / gcd(x, y), x / gcd(x, y))
| Two Joggers | 5274d9d3ebc3030802000165 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5274d9d3ebc3030802000165 | 6 kyu |
Consider a deck of 52 cards, which are represented by a string containing their suit and face value.
Your task is to write two functions ```encode``` and ```decode``` that translate an array of cards to/from an array of integer codes.
* function ```encode``` :
input : array of strings (symbols)
output : array... | reference | str = "A23456789TJQK"
card = "cdhs"
def encode(cards):
return sorted([card . index(x[1]) * 13 + str . index(x[0]) for x in cards])
def decode(cards):
return [f" { str [ x % 13 ]}{ card [ x / / 13 ]} " for x in sorted(cards)]
| Poker cards encoder/decoder | 52ebe4608567ade7d700044a | [
"Strings",
"Games",
"Algorithms"
] | https://www.codewars.com/kata/52ebe4608567ade7d700044a | 5 kyu |
#SKRZAT
Geek Challenge [SKRZAT] is an old, old game from Poland that uses a game console with two buttons plus a joy stick. As is true to its name, the game communicates in binary, so that one button represents a zero and the other a one. Even more true to its name, the game chooses to communicate so that the base o... | algorithms | from math import log
from math import ceil
def skrzat(base, number):
if base == 'b':
return 'From binary: ' + number + ' is ' + str(toDecimal(number))
if base == 'd':
return 'From decimal: ' + str(number) + ' is ' + toWBinary(number)
def toDecimal(number):
if len(number) == 1:
return in... | SKRZAT!!! | 528a0762f51e7a4f1800072a | [
"Binary",
"Algorithms"
] | https://www.codewars.com/kata/528a0762f51e7a4f1800072a | 4 kyu |
Create a function that accepts dimensions, of Rows x Columns, as parameters in order to create a multiplication table sized according to the given dimensions. **The return value of the function must be an array, and the numbers must be Fixnums, NOT strings.
Example:
multiplication_table(3,3)
1 2 3
2 4 6
3 6 9
--... | reference | def multiplication_table(row, col):
return [[(i + 1) * (j + 1) for j in range(col)] for i in range(row)]
| Multiplication Tables | 5432fd1c913a65b28f000342 | [
"Fundamentals",
"Mathematics",
"Algorithms",
"Logic",
"Numbers",
"Data Types"
] | https://www.codewars.com/kata/5432fd1c913a65b28f000342 | 6 kyu |
Sam is an avid collector of numbers. Every time he finds a new number he throws it on the top of his number-pile. Help Sam organise his collection so he can take it to the International Number Collectors Conference in Cologne.
Given an array of numbers, your function should return an array of arrays, where each subar... | reference | def group(arr): return [[n] * arr . count(n)
for n in sorted(set(arr), key=arr . index)]
| Organise duplicate numbers in list | 5884b6550785f7c58f000047 | [
"Arrays",
"Sorting",
"Fundamentals"
] | https://www.codewars.com/kata/5884b6550785f7c58f000047 | 6 kyu |
We need the ability to divide an unknown integer into a given number of even parts - or at least as even as they can be. The sum of the parts should be the original value, but each part should be an integer, and they should be as close as possible.
Complete the function so that it returns an array of integers represen... | algorithms | def splitInteger(n, pp):
p, bb = divmod(n, pp)
return (pp - bb) * [p] + bb * [p + 1]
| Almost Even | 529e2e1f16cb0fcccb000a6b | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/529e2e1f16cb0fcccb000a6b | 6 kyu |
Complete the function/method so that it takes a `PascalCase` string and returns the string in `snake_case` notation. Lowercase characters can be numbers. If the method gets a number as input, it should return a string.
## Examples
```
"TestController" --> "test_controller"
"MoviesAndBooks" --> "movies_and_books"
"... | algorithms | import re
def to_underscore(string):
return re . sub(r'(.)([A-Z])', r'\1_\2', str(string)). lower()
| Convert PascalCase string into snake_case | 529b418d533b76924600085d | [
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/529b418d533b76924600085d | 5 kyu |
Here you will create the classic [Pascal's triangle](https://en.wikipedia.org/wiki/Pascal%27s_triangle).
Your function will be passed the depth of the triangle and your code has to return the corresponding Pascal's triangle up to that depth.
The triangle should be returned as a nested array. For example:
pascal... | algorithms | def pascal(p):
t = [[1]]
for _ in range(2, p + 1):
t . append([1] + [a + b for a, b in zip(t[- 1][: - 1], t[- 1][1:])] + [1])
return t
| Pascal's Triangle #2 | 52945ce49bb38560fe0001d9 | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/52945ce49bb38560fe0001d9 | 6 kyu |
Complete the `greatestProduct` method so that it'll find the greatest product of five consecutive digits in the given string of digits.
For example: the greatest product of five consecutive digits in the string `"123834539327238239583"` is 3240.
The input string always has more than five digits.
Adapted from Project... | algorithms | from itertools import islice
from functools import reduce
def greatest_product(n):
numbers = [int(value) for value in n]
result = [reduce(lambda x, y: x * y, islice(numbers, i, i + 5), 1)
for i in range(len(numbers) - 4)]
return max(result)
| Largest product in a series | 529872bdd0f550a06b00026e | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/529872bdd0f550a06b00026e | 5 kyu |
Implement a function that normalizes out of range sequence indexes (converts them to 'in range' indexes) by making them repeatedly 'loop' around the array. The function should then return the value at that index. Indexes that are not out of range should be handled normally and indexes to empty sequences should return u... | algorithms | def norm_index_test(a, n):
if a:
return a[n % len(a)]
| Normalizing Out of Range Array Indexes | 5285bf61f8fc1b181700024c | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/5285bf61f8fc1b181700024c | 6 kyu |
Write a function that gets a sequence and value and returns `true/false` depending on whether the variable exists in a multidimentional sequence.
Example:
```
locate(['a','b',['c','d',['e']]],'e'); // should return true
locate(['a','b',['c','d',['e']]],'a'); // should return true
locate(['a','b',['c','d',['e']]],'f');... | algorithms | def locate(seq, value):
for s in seq:
if s == value or (isinstance(s, list) and locate(s, value)):
return True
return False
| search in multidimensional array | 52840d2b27e9c932ff0016ae | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/52840d2b27e9c932ff0016ae | 6 kyu |
Finish the solution so that it takes an input `n` (integer) and returns a string that is the decimal representation of the number grouped by commas after every 3 digits.
Assume: `0 <= n < 2147483647`
## Examples
```
1 -> "1"
10 -> "10"
100 -> "100"
1000 -> "... | algorithms | def group_by_commas(n):
return '{:,}' . format(n)
| Grouped by commas | 5274e122fc75c0943d000148 | [
"Algorithms"
] | https://www.codewars.com/kata/5274e122fc75c0943d000148 | 6 kyu |
Scientists working internationally use metric units almost exclusively. Unless that is, they wish to crash multimillion dollars worth of equipment on Mars.
Your task is to write a simple function that takes a number of meters, and outputs it using metric prefixes.
In practice, meters are only measured in "mm" (thousa... | algorithms | def meters(x):
# your code here
arr = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
count = 0
while x >= 1000:
x /= 1000.00
count += 1
if int(x) == x:
x = int(x)
return str(x) + arr[count] + 'm'
| Metric Units - 1 | 5264f5685fda8ed370000265 | [
"Algorithms"
] | https://www.codewars.com/kata/5264f5685fda8ed370000265 | 5 kyu |
> NOTE: This kata requires a decent knowledge of Regular Expressions. As such, it's best to learn about it _before_ tackling this kata. Some good places to start are: the [MDN pages](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp), and [Regular-Expressions.info](http://www.regular-... | reference | import re
class Mod:
mod4 = re . compile('.*\[[+-]?([048]|\d*([02468][048]|[13579][26]))\]')
| Mod4 Regex | 54746b7ab2bc2868a0000acf | [
"Regular Expressions",
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/54746b7ab2bc2868a0000acf | 5 kyu |
Pete and his mate Phil are out in the countryside shooting clay pigeons with a shotgun - amazing fun.
They decide to have a competition. 3 rounds, 2 shots each. Winner is the one with the most hits.
Some of the clays have something attached to create lots of smoke when hit, guarenteed by the packaging to generate 'r... | reference | def shoot(results):
pete = phil = 0
for shots, double in results:
pete += shots["P1"]. count("X") * (1 + double)
phil += shots["P2"]. count("X") * (1 + double)
return "Pete Wins!" if pete > phil else "Phil Wins!" if phil > pete else "Draw!"
| Clay Pigeon Shooting | 57fa9bc99610ce206f000330 | [
"Fundamentals",
"Arrays",
"Strings"
] | https://www.codewars.com/kata/57fa9bc99610ce206f000330 | 6 kyu |
# Task
You have two sorted arrays `a` and `b`, merge them to form new array of unique items.
If an item is present in both arrays, it should be part of the resulting array if and only if it appears in both arrays the same number of times.
# Example
For `a = [1, 3, 40, 40, 50, 60, 60, 60]` and `b = [2, 40, 40, 50... | algorithms | def merge_arrays(a, b):
out = []
for n in a + b:
if n in a and n in b:
if a . count(n) == b . count(n):
out . append(n)
else:
out . append(n)
return sorted(set(out))
| Challenge Fun #17: Merge Arrays | 58b665c891e710a3ec00003f | [
"Algorithms"
] | https://www.codewars.com/kata/58b665c891e710a3ec00003f | 6 kyu |
Each element in the periodic table has a symbol associated with it. For instance, the symbol for the element Yttrium is `Y`. A fun thing to do is see if we can form words using symbols of elements strung together. The symbol for Einsteinium is `Es`, so the symbols for Yttrium and Einsteinium together form:
`Y + Es = Y... | algorithms | def elemental_forms(word):
return list(get_elem_form(word . lower()))
def get_elem_form(word, parents=[]):
if word == '':
yield parents
for elem, name in ELEMENTS . items():
if word . startswith(elem . lower()):
yield from get_elem_form(word[len(elem):], parents + [f' { name } ( { e... | Elemental Words | 56fa9cd6da8ca623f9001233 | [
"Strings",
"Algorithms",
"Recursion",
"Arrays"
] | https://www.codewars.com/kata/56fa9cd6da8ca623f9001233 | 4 kyu |
For a new 3D game that will be released, a team of programmers needs an easy function. (Then it will be processed as a method in a Class, forget this concept for Ruby)
We have an sphere with center <b>O</b>, having in the space the coordinates `[α, β, γ]` and radius `r` and a list of points, `points_list`, each one w... | reference | from collections import defaultdict
from itertools import combinations
def norme(vect): return sum(v * * 2 for v in vect) * * .5
def vectorize(pt1, pt2): return [b - a for a, b in zip(pt1, pt2)]
def isInCircle(d, r): return d < r and (r - d) / r > 1e-10
def crossProd(v1, v2): return [v1[0] * v2[1] ... | Helpers For a 3DGame I: Biggest Triangle in a Sphere | 57deba2e8a8b8db0a4000ad6 | [
"Data Structures",
"Algorithms",
"Mathematics",
"Logic",
"Strings",
"Geometry",
"Games"
] | https://www.codewars.com/kata/57deba2e8a8b8db0a4000ad6 | 4 kyu |
Once upon a time, a CodeWarrior, after reading a [discussion on what can be the plural](http://www.codewars.com/kata/plural/discuss/javascript), took a look at [this page](http://en.wikipedia.org/wiki/Grammatical_number#Types_of_number
) and discovered that **more than 1** "kind of plural" may exist.
For example [Sur... | reference | import re
def sursurungal(txt):
txt = re . sub(r'\b2\s(\S+)s', r'2 bu\1', txt)
txt = re . sub(r'\b([3-9])\s(\S+)s', r'\1 \2zo', txt)
return re . sub(r'(\d+\d)\s(\S+)s', r'\1 ga\2ga', txt)
| Pig Sursurunga | 5536aba6e4609cc6a600003d | [
"Strings",
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/5536aba6e4609cc6a600003d | 6 kyu |
Implement `String#parse_mana_cost`, which parses [Magic: the Gathering mana costs](http://mtgsalvation.gamepedia.com/Mana_cost) expressed as a string and returns a `Hash` with keys being kinds of mana, and values being the numbers.
Don't include any mana types equal to zero.
Format is:
* optionally natural number re... | reference | import re
def parse_mana_cost(mana):
retval = {}
mana = mana . lower()
m = re . match(r'\A(\d*)([wubrg]*)\Z', mana)
if m:
if m . group(1) and int(m . group(1)) > 0:
retval['*'] = int(m . group(1))
if m . group(2):
l = list(m . group(2))
print l
if l . count('w') > ... | Regexp basics - parsing mana cost | 5686004a2c7fade6b500002d | [
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/5686004a2c7fade6b500002d | 6 kyu |
Magic The Gathering is a collectible card game that features wizards battling against each other with spells and creature summons. The game itself can be quite complicated to learn. In this series of katas, we'll be solving some of the situations that arise during gameplay. You won't need any prior knowledge of the gam... | algorithms | def battle(player1, player2):
l1 = []
l2 = []
x = min(len(player1), len(player2))
for i in range(x):
if player1[i][0] < player2[i][1]:
l2 . append(player2[i])
if player2[i][0] < player1[i][1]:
l1 . append(player1[i])
l1 += player1[x:]
l2 += player2[x:]
return {... | Magic The Gathering #1: Creatures | 567af2c8b46252f78400004d | [
"Algorithms",
"Fundamentals",
"Arrays",
"Games"
] | https://www.codewars.com/kata/567af2c8b46252f78400004d | 6 kyu |
For any given linear sequence, calculate the function [f(x)] and return it as a string.
Assumptions for this kata are:
- the sequence argument will always contain 5 values equal to f(0) - f(4).
- the function will always be in the format "nx +/- m", "x +/- m", "nx', "x" or "m"
- if a non-linear sequence simply return... | reference | def get_function(seq):
m = seq[0]
n = seq[1] - m
if any(s != n * x + m for x, s in enumerate(seq)):
return "Non-linear sequence"
return "f(x) = {}{}{}{}{}{}" . format(
"-" * (n < 0),
str(abs(n)) * (abs(n) > 1),
"x" * (n != 0),
" + " * (m > 0 and n != 0),
... | Calculate the function f(x) for a simple linear sequence (Easy) | 5476f4ca03810c0fc0000098 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/5476f4ca03810c0fc0000098 | 6 kyu |
The Collatz conjecture is one of the most famous one. Take any positive integer n, if it is even divide it by 2, if it is odd multiply it by 3 and add 1 and continue indefinitely.The conjecture is that whatever is n the sequence will reach 1. There is many ways to approach this problem, each one of them had given beaut... | algorithms | from functools import lru_cache
@ lru_cache(maxsize=None)
def rec(n): return 1 + (0 if n == 1 else rec(3 * n + 1) if n & 1 else rec(n / / 2))
memo = [[0, None], [1, 1]]
def max_collatz_length(n):
if not (type(n) == int and n > 0):
return []
while n >= len(memo):
x = rec(len(memo)... | Max Collatz Sequence Length | 53a9ee602f150d5d6b000307 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/53a9ee602f150d5d6b000307 | 5 kyu |
Create your own mechanical dartboard that gives back your score based on the coordinates of your dart.
<b style='font-size:16px'>Task:</b>
<ul>
<li>Use the <a href="https://en.wikipedia.org/wiki/Darts#Scoring">scoring rules</a> for a standard dartboard:<br>
<img style="height:264px" src="https://upload.wikimedia.org/... | algorithms | from math import atan2, degrees
def get_score(x, y):
r, a = (x * x + y * y) * * 0.5, degrees(atan2(y, x)) + 9
t = str([6, 13, 4, 18, 1, 20, 5, 12, 9, 14, 11, 8, 16, 7, 19, 3, 17, 2, 15, 10][int(a + 360 if a < 0 else a) / / 18])
for l, s in [(6.35, 'DB'), (15.9, 'SB'), (99, t), (107, 'T' + t), (162, t), (1... | Let's Play Darts! | 5870db16056584eab0000006 | [
"Games",
"Algorithms"
] | https://www.codewars.com/kata/5870db16056584eab0000006 | 5 kyu |
Write a function that given an array of numbers >= 0, will arrange them such that they form the biggest number. <br/>
For example:
```
[1, 2, 3] --> "321" (3-2-1)
[3, 30, 34, 5, 9] --> "9534330" (9-5-34-3-30)
```
The results will be large so make sure to return a string. | algorithms | from functools import cmp_to_key
KEY = cmp_to_key(lambda a, b: int(b + a) - int(a + b))
def biggest(numbers: list) - > str:
return '' . join(sorted(map(str, numbers), key=KEY)). lstrip('0') or '0'
| I love big nums and I cannot lie | 56121f3312baa28c8500005b | [
"Strings",
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/56121f3312baa28c8500005b | 6 kyu |
Write a function that will take in any `array` and reverse it. <br/>
Sounds simple doesn't it? <br/>
<b>NOTES:</b>
* Array should be reversed in place! (no need to return it)
* Usual builtins have been deactivated. Don't count on them.
* You'll have to do it fast enough, so think about performances | algorithms | def reverse(seq):
for i in range(len(seq) >> 1):
seq[i], seq[- i - 1] = seq[- i - 1], seq[i]
| I need more speed! | 55de9c184bb732a87f000055 | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/55de9c184bb732a87f000055 | 6 kyu |
Complete the function that takes a string as an input, and return a list of all the unpaired characters (i.e. they show up an odd number of times in the string), in the order they were encountered as an array.
In case of multiple appearances to choose from, take the last occurence of the unpaired character.
**Notes:... | algorithms | from collections import Counter
def odd_one_out(s):
d = Counter(reversed(s))
return [x for x in d if d[x] % 2][:: - 1]
| What will be the odd one out? | 55b080eabb080cd6f8000035 | [
"Strings",
"Arrays",
"Performance",
"Algorithms"
] | https://www.codewars.com/kata/55b080eabb080cd6f8000035 | 6 kyu |
The <a href="https://www.codewars.com/kata/57d6b40fbfcdc5e9280002ee">Spelling Bee</a> bees are back...
# How many bees are in the beehive?
* bees can be facing UP, DOWN, LEFT, RIGHT, and now also <span style='color:orange'>_diagonally_</span> up/down/left/right
* bees can share parts of other bees
<hr>
## Examples
... | reference | def how_many_bees(h):
if not h:
return 0
v = list(zip(* h))
b = [None] * len(h)
sf = (b[i:] + l + b[: i] for i, l in enumerate(h))
sb = (b[: i] + l + b[i:] for i, l in enumerate(h))
df = [[n for n in l if n is not None] for l in zip(* sf)]
db = [[n for n in l if n is not None... | Spelling Bee II | 58f290d0b48966547f00014c | [
"Fundamentals"
] | https://www.codewars.com/kata/58f290d0b48966547f00014c | 6 kyu |
Write
```javascript
function wordStep(str)
```
that takes in a string and creates a step with that word. <br/>
E.g<br/>
```javascript
wordStep('SNAKES SHOE EFFORT TRUMP POTATO') ===
[['S','N','A','K','E','S',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '],
[' ',' ',' ',' ',' ','H',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '],... | algorithms | def word_step(s):
res = [s[0]]
for i, word in enumerate(s . split()):
if i % 2:
res += [str . rjust(c, len(res[- 1])) for c in word[1:]]
else:
res[- 1] += word[1:]
return [list(str . ljust(line, len(res[- 1]))) for line in res]
| Get your steppin' on son | 55e00266d494ce5155000032 | [
"Algorithms"
] | https://www.codewars.com/kata/55e00266d494ce5155000032 | 6 kyu |
Write
```javascript
String.prototype.hashify()
```
that will turn a string into a hash/object. Every character in the string will be the key for the next character. <br/>
E.g. <br/>
```
'123456'.hashify() == {"1":"2","2":"3","3":"4","4":"5","5":"6","6":"1"} // The last char will be key for 1st
char
'11223'.hashify() =... | algorithms | def hashify(string):
out = dict()
for c1, c2 in zip(string, string[1:] + string[0]):
try:
try:
out[c1]. append(c2)
except:
out[c1] = [out[c1], c2]
except:
out[c1] = c2
return out
| Objectify all the strings | 55dd54631827120dd800002b | [
"Algorithms"
] | https://www.codewars.com/kata/55dd54631827120dd800002b | 6 kyu |
Complete the function that takes 3 numbers `x, y and k` (where `x ≤ y`), and returns the number of integers within the range `[x..y]` (both ends included) that are divisible by `k`.
More scientifically: `{ i : x ≤ i ≤ y, i mod k = 0 }`
## Example
Given ```x = 6, y = 11, k = 2``` the function should return `3`, bec... | algorithms | def divisible_count(x, y, k):
return y / / k - (x - 1) / / k
| Count the divisible numbers | 55a5c82cd8e9baa49000004c | [
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/55a5c82cd8e9baa49000004c | 6 kyu |
Design a data structure that supports the following two operations:
* `addWord` (or `add_word`) which adds a word,
* `search` which searches a literal word or a regular expression string containing lowercase letters `"a-z"` or `"."` where `"."` can represent any letter
You may assume that all given words contain only... | algorithms | import re
class WordDictionary:
def __init__(self):
self . data = []
def add_word(self, x):
self . data . append(x)
def search(self, x):
for word in self . data:
if re . match(x + "\Z", word):
return True
return False
| Urban Dictionary | 5631ac5139795b281d00007d | [
"Algorithms",
"Object-oriented Programming"
] | https://www.codewars.com/kata/5631ac5139795b281d00007d | 6 kyu |
Write
```javascript
function wordPattern(pattern, str)
```
```csharp
WordPattern(string pattern, string str)
```
```ruby
word_pattern(pattern, string)
```
```python
word_pattern(pattern, string)
```
that given a ```pattern``` and a string ```str```, find if ```str``` follows the same sequence as ```pattern```. <br/>
F... | algorithms | def word_pattern(pattern, string):
x = list(pattern)
y = string . split(" ")
return (len(x) == len(y) and
len(set(x)) == len(set(y)) == len(set(zip(x, y)))
)
| Word Patterns | 562846dd1f77ab7c00000033 | [
"Algorithms"
] | https://www.codewars.com/kata/562846dd1f77ab7c00000033 | 6 kyu |
Given a sorted array of numbers, return the summary of its ranges.
## Examples
```javascript
summaryRanges([1, 2, 3, 4]) === ["1->4"]
summaryRanges([1, 1, 1, 1, 1]) === ["1"]
summaryRanges([0, 1, 2, 5, 6, 9]) === ["0->2", "5->6", "9"]
summaryRanges([0, 1, 2, 3, 3, 3, 4, 5, 6, 7]) === ["0->7"]
summaryRanges([0, 1, 2, ... | algorithms | def summary_ranges(nums):
ret, s = [], float('-inf')
for e, n in zip([s] + nums, nums + [- s]):
if n - e > 1:
ret . append(['{}', '{}->{}'][s < e]. format(s, e))
s = n
return ret[1:]
| Summarize ranges | 55fb6537544ae06ccc0000dc | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/55fb6537544ae06ccc0000dc | 6 kyu |
Write
```javascript
function repeatingFractions(numerator, denominator)
```
```python
function repeating_fractions(numerator, denominator)
```
```ruby
function repeating_fractions(numerator, denominator)
```
that given two numbers representing the numerator and denominator of a fraction, return the fraction in string f... | reference | import re
def repeating_fractions(n, d):
(i, d) = str(n * 1.0 / d). split('.')
return i + '.' + re . sub(r'([0-9])\1+', r'(\1)', d)
| Group Repeating Fractions | 5613475e4778aab4d600004f | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5613475e4778aab4d600004f | 6 kyu |
Write a function ```x(n)``` that takes in a number ```n``` and returns an ```nxn``` array with an ```X``` in the middle. The ```X``` will be represented by ```1's``` and the rest will be ```0's```. <br/>
E.g.<br/>
```javascript
x(5) === [[1, 0, 0, 0, 1],
[0, 1, 0, 1, 0],
[0, 0, 1, 0, 0],
[... | algorithms | def x(n):
d = [[0] * n for i in range(n)]
for i in range(n):
d[i][i] = 1
d[i][- i - 1] = 1
return d
| X marks the spot! | 55cc20eb943f1d8b11000045 | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/55cc20eb943f1d8b11000045 | 6 kyu |
Write a function
```csharp
TripleDouble(long num1, long num2)
```
```java
TripleDouble(long num1, long num2)
```
```javascript
tripledouble(num1,num2)
```
```python
triple_double(num1, num2)
```
```ruby
triple_double(num1, num2)
```
```scala
tripleDouble(num1: Long, num2: Long): Int
```
which takes numbers `num1` and... | algorithms | def triple_double(num1, num2):
return any([i * 3 in str(num1) and i * 2 in str(num2) for i in '0123456789'])
| Triple trouble | 55d5434f269c0c3f1b000058 | [
"Algorithms"
] | https://www.codewars.com/kata/55d5434f269c0c3f1b000058 | 6 kyu |
Write
```javascript
function combine()
```
```python
function combine()
```
```ruby
function combine()
```
```haskell
combine :: [[a]] -> [a]
```
that combines arrays by alternatingly taking elements passed to it.
E.g
```javascript
combine(['a', 'b', 'c'], [1, 2, 3]) == ['a', 1, 'b', 2, 'c', 3]
combine(['a', 'b', '... | algorithms | def combine(* args):
out = list()
for i in range(len(max(args, key=len))): # Sometimes you just have to love python
for arr in args:
if i < len(arr):
out . append(arr[i])
return out
| Alternating Loops | 55e529bf6c6497394a0000b5 | [
"Fundamentals",
"Algorithms"
] | https://www.codewars.com/kata/55e529bf6c6497394a0000b5 | 6 kyu |
Many websites use weighted averages of various polls to make projections for elections. They’re weighted based on a variety of factors, such as historical accuracy of the polling firm, sample size, as well as date(s). The weights, in this kata, are already calculated for you. All you need to do is convert a set of poll... | reference | def predict(candidates, polls):
x = zip(* [list(map(lambda i: i * weight, poll))
for poll, weight in polls])
x = list(
map(round1, (map(lambda i: sum(i) / sum([i[1] for i in polls]), x))))
return dict(zip(candidates, x))
| Elections: Weighted Average | 5827d31b86f3b0d9390001d4 | [
"Fundamentals"
] | https://www.codewars.com/kata/5827d31b86f3b0d9390001d4 | 6 kyu |
# Explanation
It's your first day in the robot factory and your supervisor thinks that you should start with an easy task. So you are responsible for purchasing raw materials needed to produce the robots.
A complete robot weights `50` kilogram. Iron is the only material needed to create a robot. All iron is inserted ... | algorithms | from math import ceil
def calculate_scrap(arr, n):
x = 50
for i in arr:
x /= (1 - i / 100)
return ceil(n * x)
| Manage the Robot Factory: Day 1 | 5898a7208b431434e500013b | [
"Algorithms"
] | https://www.codewars.com/kata/5898a7208b431434e500013b | 6 kyu |
You get an array of arrays.<br>
If you sort the arrays by their length, you will see, that their length-values are consecutive.<br>
But one array is missing!<br>
<br><br>
You have to write a method, that return the length of the missing array.<br>
```
Example:
[[1, 2], [4, 5, 1, 1], [1], [5, 6, 7, 8, 9]] --> 3
```
<br>... | algorithms | def get_length_of_missing_array(arrays):
arrays = [len(a) if a is not None else 0 for a in arrays]
arrays . sort()
if 0 in arrays or len(arrays) == 0:
return 0
for i in range(len(arrays)):
if arrays[i + 1] != arrays[i] + 1:
return arrays[i] + 1
| Length of missing array | 57b6f5aadb5b3d0ae3000611 | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/57b6f5aadb5b3d0ae3000611 | 6 kyu |
In Germany we have "LOTTO 6 aus 49". That means that 6 of 49 numbers are drawn as winning combination.<br>
There is also a "Superzahl", an additional number, which can increase your winning category.
In this kata you have to write two methods.
```csharp
public static int[] NumberGenerator()
public static int CheckFo... | algorithms | def number_generator():
from random import randrange, sample
return sorted(sample(range(1, 50), 6)) + [randrange(10)]
def check_for_winning_category(your_numbers, winning_numbers):
matches = len(set(your_numbers[: - 1]) & set(winning_numbers[: - 1]))
category = 14 - 2 * matches - (your_number... | LOTTO 6 aus 49 - 6 of 49 | 57a98e8172292d977b000079 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/57a98e8172292d977b000079 | 6 kyu |
You're a programmer in a SEO company. The SEO specialist of your company gets the list of all project keywords everyday, then he looks for the longest keys to analyze them.
You will get the list with keywords and must write a simple function that returns the biggest search keywords and sorts them in lexicographical or... | reference | def the_biggest_search_keys(* keys):
mx = max(map(len, keys), default=0)
return ', ' . join(sorted('\'{}\'' . format(k) for k in keys if len(k) == mx)) if mx else "''"
| What The Biggest Search Keys? | 58ac1abdff4e78738f000805 | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/58ac1abdff4e78738f000805 | 6 kyu |
We want to approximate the length of a curve representing a function `y = f(x)` with ` a <= x <= b`.
First, we split the interval `[a, b]` into n sub-intervals with widths
<code>h<sub>1</sub>, h<sub>2</sub>, ... , h<sub>n</sub></code>
by defining points
<code>x<sub>1</sub>, x<sub>2</sub> , ... , x<sub>n-1</sub></co... | reference | from math import sqrt
def len_curve(n):
return round(sum(sqrt((2 * k + 1) * * 2 / n / n + 1) for k in range(n)) / n, 9)
| Parabolic Arc Length | 562e274ceca15ca6e70000d3 | [
"Fundamentals"
] | https://www.codewars.com/kata/562e274ceca15ca6e70000d3 | 6 kyu |
In the drawing below we have a part of the Pascal's triangle, lines are numbered from **zero** (top).
The left diagonal in pale blue with only numbers equal to 1 is diagonal **zero**, then in dark green
(1, 2, 3, 4, 5, 6, 7) is diagonal 1, then in pale green (1, 3, 6, 10, 15, 21) is
diagonal 2 and so on.
We want to c... | reference | from math import comb
def diagonal(n: int, p: int) - > int:
return comb(n + 1, p + 1)
| Easy Diagonal | 559b8e46fa060b2c6a0000bf | [
"Fundamentals"
] | https://www.codewars.com/kata/559b8e46fa060b2c6a0000bf | 6 kyu |
In order to prove it's success and gain funding, the wilderness zoo needs to prove to environmentalists that it has x number of mating pairs of bears.
### Task:
You must check within a string (s) to find all of the mating pairs, returning a list/array of the string containing valid mating pairs and a boolean indicati... | reference | from re import findall
def bears(x, s):
bears = "" . join(findall("8B|B8", s))
return [bears, len(bears) >= x]
| Pairs of Bears | 57d165ad95497ea150000020 | [
"Fundamentals",
"Strings",
"Arrays"
] | https://www.codewars.com/kata/57d165ad95497ea150000020 | 6 kyu |
You have to build a pyramid.<br>
<br>
This pyramid should be built from characters from a given string.<br>
<br>
You have to create the code for these four methods:
```csharp
public static string WatchPyramidFromTheSide(string characters)
public static string WatchPyramidFromAbove(string characters)
public static int... | reference | def watch_pyramid_from_the_side(characters):
if not characters:
return characters
baseLen = len(characters) * 2 - 1
return '\n' . join(' ' * (i) + characters[i] * (baseLen - 2 * i) + ' ' * (i) for i in range(len(characters) - 1, - 1, - 1))
def watch_pyramid_from_above(characters):
if... | String Pyramid | 5797d1a9c38ec2de1f00017b | [
"Mathematics",
"Strings",
"Algorithms",
"ASCII Art"
] | https://www.codewars.com/kata/5797d1a9c38ec2de1f00017b | 6 kyu |
Frank just bought a new calculator.
But, this is no normal calculator.
This is a **'Sticky Calculator**.
Whenever you add add, subtract, multiply or divide two numbers the two numbers first stick together:
For instance:
```javascript
50 + 12 becomes 5012
```
and then the operation is carried out as usual:
```java... | reference | def sticky_calc(operation, val1, val2):
return round(eval("{0}{1}{2}{1}" . format(round(val1), round(val2), operation)))
| Frank's Sticky Calculator | 5900750cb7c6172207000054 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5900750cb7c6172207000054 | 7 kyu |
Find the number with the most digits.
If two numbers in the argument array have the same number of digits, return the first one in the array.
| reference | def find_longest(xs):
return max(xs, key=lambda x: len(str(x)))
| Most digits | 58daa7617332e59593000006 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/58daa7617332e59593000006 | 7 kyu |
**This Kata is intended as a small challenge for my students**
All Star Code Challenge #23
There is a certain multiplayer game where players are assessed at the end of the game for merit. Players are ranked according to an internal scoring system that players don't see.
You've discovered the formula for the scoring ... | reference | def scoring(array):
res = {}
for e in array:
score = e["norm_kill"] * 100 + e["assist"] * 50 + e["damage"] / / 2 + \
e["healing"] + 2 * * e["streak"] + e["env_kill"] * 500
res[e["name"]] = score
return sorted(res, key=res . get, reverse=True)
| All Star Code Challenge #23 | 5865dd726b56998ec4000185 | [
"Fundamentals"
] | https://www.codewars.com/kata/5865dd726b56998ec4000185 | 6 kyu |
If you reverse the word "emirp" you will have the word "prime". That idea is related with the purpose of this kata: we should select all the primes that when reversed are a **different** prime (so palindromic primes should be discarded).
For example: 13, 17 are prime numbers and the reversed respectively are 31, 71 wh... | algorithms | from gmpy2 import is_prime
def find_emirp(n):
a = [i for i in range(13, n + 1, 2) if is_prime(i)
and is_prime(int(str(i)[:: - 1])) and str(i) != str(i)[:: - 1]]
return [0, 0, 0] if not a else [len(a), max(a), sum(a)]
| Emirps | 55de8eabd9bef5205e0000ba | [
"Fundamentals",
"Mathematics",
"Algorithms",
"Data Structures"
] | https://www.codewars.com/kata/55de8eabd9bef5205e0000ba | 5 kyu |
We need a function ```prime_bef_aft()``` that gives the largest prime below a certain given value ```n```,
```befPrime or bef_prime``` (depending on the language),
and the smallest prime larger than this value,
```aftPrime/aft_prime``` (depending on the language).
The result should be output in a list like the f... | reference | def prime(a):
if a < 2:
return False
if a == 2 or a == 3:
return True
if a % 2 == 0 or a % 3 == 0:
return False
maxDivisor = a * * 0.5
d, i = 5, 2
while d <= maxDivisor:
if a % d == 0:
return False
d += i
i = 6 - i
return True
def prime_bef_aft... | Surrounding Primes for a value | 560b8d7106ede725dd0000e2 | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/560b8d7106ede725dd0000e2 | 6 kyu |
An integral:
```math
\int_{a}^{b}f(x)dx
```
can be approximated by the so-called Simpson’s rule:
```math
\dfrac{b-a}{3n}(f(a)+f(b)+4\sum_{i=1}^{n/2}f(a+(2i-1)h)+2\sum_{i=1}^{n/2-1}f(a+2ih))
```
Here
`h = (b - a) / n`, `n` being an even integer and `a <= b`.
We want to try Simpson's rule with the function f:
```ma... | reference | def simpson(n):
from math import sin, pi
a = 0
b = pi
h = (b - a) / n
def f(x): return (3 / 2) * sin(x) * * 3
integral = 0
integral += f(a) + f(b)
integral += 4 * sum(f(a + (2 * i - 1) * h) for i in range(1, n / / 2 + 1))
integral += 2 * sum(f(a + 2 * i * h) for i in range(1, n / / 2... | Simpson's Rule - Approximate Integration | 565abd876ed46506d600000d | [
"Mathematics"
] | https://www.codewars.com/kata/565abd876ed46506d600000d | 6 kyu |
Given two numbers `x` and `n`, calculate the (positive) nth root of `x`; this means that being `r = result`, `r^n = x`
## Examples
```
x = 4 n = 2 --> 2 # the square root of 4 is 2 2^2 = 4
x = 8 n = 3 --> 2 # the cube root of 8 is 2 2^3 = 8
x = 256 n = 4 --> 4 # the 4th root of 256 ... | reference | def root(x, n):
return x * * (1.0 / n)
| Nth Root of a Number | 5520714decb43308ea000083 | [
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/5520714decb43308ea000083 | 7 kyu |
# Task
Given an array of positive integers `a` and an integer `k`, find the first and last index of the longest subarray of a that consists only of `k`.
If the array contains multiple subarrays of the same length, return indices of the last one.
If `k` doesn't exist in `a`, return `(-1, -1)`.
# Input/Output
... | reference | from itertools import groupby
def find_subarray_with_same_element(a, k):
return (s := 0) or max((i for x, g in groupby(a) if (i := (s, (s := s + len(list(g))) - 1)) and x == k),
key=lambda r: (r[1] - r[0], r), default=(- 1, - 1))
| Simple Fun #208: Find Sub Array With Same Element | 58feb7ac627d2fdadf000111 | [
"Fundamentals"
] | https://www.codewars.com/kata/58feb7ac627d2fdadf000111 | 6 kyu |
# Task
Pero has been into robotics recently, so he decided to make a robot that checks whether a deck of poker cards is complete.
He’s already done a fair share of work - he wrote a programme that recognizes the suits of the cards. For simplicity’s sake, we can assume that all cards have a suit and a number.
The s... | reference | from collections import defaultdict
def cards_and_pero(s):
deck = defaultdict(set)
for n in range(0, len(s), 3):
card = s[n: n + 3]
if card[1:] in deck[card[0]]:
return [- 1, - 1, - 1, - 1]
deck[card[0]] |= {card[1:]}
return [13 - len(deck[suit]) for suit in "PKHT"]
| Simple Fun #201: Cards And Pero | 58fd4bbe017b2ed4e700001b | [
"Fundamentals"
] | https://www.codewars.com/kata/58fd4bbe017b2ed4e700001b | 6 kyu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.