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 |
|---|---|---|---|---|---|---|---|
The challenge is to efficiently find the largest [pronic number](https://en.wikipedia.org/wiki/Pronic_number) less than the method's input.
The initial solution passes the sample tests, but fails for larger numbers used in the acceptance tests.
Your algorithm should be fast as the acceptance tests will run 10,000 ran... | reference | def next_smaller_pronic(n):
k = int((- 1 + (1 + 4 * n) * * .5) / 2 - 10 * * - 5)
return k * (k + 1)
| Next smaller pronic | 5a90f6d457c5624ecc000012 | [
"Mathematics",
"Algorithms",
"Fundamentals"
] | https://www.codewars.com/kata/5a90f6d457c5624ecc000012 | 6 kyu |
In this Kata, you will be given a string and your task is to determine if that string can be a palindrome if we rotate one or more characters to the left.
```Haskell
solve("4455") = true, because after 1 rotation, we get "5445" which is a palindrome
solve("zazcbaabc") = true, because after 3 rotations, we get "abczazc... | algorithms | def solve(s):
return any(s[i + 1:] + s[: i + 1] == s[i:: - 1] + s[: i: - 1] for i in range(len(s)))
| Simple rotated palindromes | 5a8fbe73373c2e904700008c | [
"Algorithms"
] | https://www.codewars.com/kata/5a8fbe73373c2e904700008c | 7 kyu |
> [Learn about Sandpile numbers from Numberphile!](https://www.youtube.com/watch?v=1MtEUErz7Gg)
Let's learn about a new type of number: the Sandpile.
## What are Sandpiles?
A sandpile is a grid of piles of sand ranging from `0` to some max integer value. For simplicity's sake, we'll look at a `3x3` grid containing `... | algorithms | class Sandpile:
def __init__(self, piles: str = "000\n000\n000"):
self . piles = Sandpile . _to_list(piles)
self . _topple()
def __str__(self):
return Sandpile . _to_str(self . piles)
def add(self, sandpile):
return Sandpile(Sandpile . _to_str([[p1 + p2 for p1, p2 in zip(r1, r2)... | Playing with Sandpiles | 58c5fca35722de3493000081 | [
"Algorithms"
] | https://www.codewars.com/kata/58c5fca35722de3493000081 | 5 kyu |
We all know how to handle exceptions in Python. Just use:
try:
num = float(input())
except ValueError:
print("That's not a number!")
else:
print(num)
Code such as this
def factorial(x, n = 1):
if x == 0:
raise ValueError(n)
factorial(x - 1, n * x)
re... | reference | def handle(func, success, failure, * exceptions):
class manager:
def __enter__(self):
pass
def __exit__(self, type, value, traceback):
if isinstance(value, exceptions):
failure(func, value)
return True
return not value
with manager():
success(func, func())
| Bad Exception Handling | 5950eec3a100d72be100003f | [
"Fundamentals"
] | https://www.codewars.com/kata/5950eec3a100d72be100003f | 4 kyu |
RSA is a widely used public-key cryptosystem. Like other public-key encryption systems, RSA takes in data and encrypts it using a publicly available key. The private key is then used to decrypt the data. It is useful for sending data to servers because anyone can encrypt their own data, but only the server containing t... | algorithms | class RSA:
def __init__(self, p, q, e):
phi = (p - 1) * (q - 1)
self . n = p * q
self . e = e
self . d = pow(e, - 1, phi)
def encrypt(self, m):
return pow(m, self . e, self . n)
def decrypt(self, c):
return pow(c, self . d, self . n)
| Simple RSA Implementation | 56f1e42f0cd8bc1e6e001713 | [
"Cryptography",
"Algorithms",
"Number Theory"
] | https://www.codewars.com/kata/56f1e42f0cd8bc1e6e001713 | 5 kyu |
<p>You and a group of explorers have found a legendary ziggurat hidden in an obscure jungle. According to legend, the ancient structure houses portals to other worlds.</p>
<p>The outer west wall of the ziggurat consists of a series of entrance doors. When an explorer enters through a door, they sit in a mobile cart tha... | algorithms | class Ziggurate:
board = []
exit_gates = []
def __init__(self, x):
self . x = x
self . y = 0
self . axis_flag = 1
self . direction = 1
self . exit = None
def travers_ziggurate(self):
while self . is_exit(len(self . board), self . x, self . y):
field = self . boar... | Ziggurat Ride of Fortune | 5a8cacb2d5261f53ec0031f3 | [
"Arrays",
"Performance",
"Algorithms"
] | https://www.codewars.com/kata/5a8cacb2d5261f53ec0031f3 | 5 kyu |
Given the number pledged for a year, current value and name of the month, return string that gives information about the challenge status:
- ahead of schedule
- behind schedule
- on track
- challenge is completed
Examples:
`(12, 1, "February")` - should return `"You are on track."`
`(12, 1, "March")` - should retur... | reference | MONTH = ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December']
def check_challenge(pledged, current, month):
d, p = divmod(pledged, 12)
plg = [d + 1] * p + [d] * (12 - p)
diff = current - sum(plg[: MONTH . index(month)])
... | Progress of a challenge | 584acd331b8b758fe700000d | [
"Fundamentals"
] | https://www.codewars.com/kata/584acd331b8b758fe700000d | 6 kyu |
# Convergents of e
The square root of `$2$` can be written as an infinite continued fraction.
```math
\displaystyle{\sqrt{2} = 1 + \dfrac{1}{2 + \dfrac{1}{2 + \dfrac{1}{2 + \dfrac{1}{2 + ...}}}}}
```
The infinite continued fraction can be written, `$\sqrt{2} = [1; (2)]$`, `$(2)$` indicates that `$2$` repeats ad infinit... | reference | e = [1, 2]
for n in range(1, 10 * * 4):
for f in 1, 2 * n, 1:
e . append(f * e[- 1] + e[- 2])
def convergents_of_e(n): return sum(map(int, str(e[n])))
| Convergents of e | 5a8d63930025e92f4c000086 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a8d63930025e92f4c000086 | 5 kyu |
You are given a matrix of `m rows` and `n columns` having integer numbers, positive an negative ones. You have to rearrenge it in order to have `all the rows sorted from left to right` and `all the columns sorted from top to bottom.`
E.g.:
Case 1: Square Matrix 3x3
```
matrix1 = [[7, 1, 4],
[3, 2, 8],... | reference | def order(matrix):
matrix = [sorted(row) for row in matrix]
matrix = [sorted(row) for row in zip(* matrix)]
return list(zip(* matrix))
| #5 Matrices: Sort The Matrix | 590363d57e16c9b3c0000014 | [
"Algorithms",
"Matrix",
"Sorting",
"Data Structures",
"Fundamentals"
] | https://www.codewars.com/kata/590363d57e16c9b3c0000014 | 6 kyu |
In this kata, you will sort elements in an array by decreasing frequency of elements. If two elements have the same frequency, sort them by increasing value.
```haskell
solve([2,3,5,3,7,9,5,3,7]) = [3,3,3,5,5,7,7,2,9]
-- We sort by highest frequency to lowest frequency.
-- If two elements have same frequency, we sort... | algorithms | from collections import Counter
def solve(a):
c = Counter(a)
return sorted(a, key=lambda k: (- c[k], k))
| Simple frequency sort | 5a8d2bf60025e9163c0000bc | [
"Algorithms",
"Sorting",
"Arrays"
] | https://www.codewars.com/kata/5a8d2bf60025e9163c0000bc | 6 kyu |
In this Kata, you will be given a string and two indexes (`a` and `b`). Your task is to reverse the portion of that string between those two indices inclusive.
~~~if-not:fortran
```
solve("codewars",1,5) = "cawedors" -- elements at index 1 to 5 inclusive are "odewa". So we reverse them.
solve("cODEWArs", 1,5) = "cAWE... | algorithms | def solve(s, a, b):
return s[: a] + s[a: b + 1][:: - 1] + s[b + 1:]
| Simple string reversal II | 5a8d1c82373c2e099d0000ac | [
"Algorithms"
] | https://www.codewars.com/kata/5a8d1c82373c2e099d0000ac | 7 kyu |
We have to find the longest substring of identical characters in a very long string.
Let's see an example:
```
s1 = "1111aa994bbbb1111AAAAAFF?<mmMaaaaaaaaaaaaaaaaaaaaaaaaabf"
```
The longest substring in ```s1``` is ```"aaaaaaaaaaaaaaaaaaaaaaaaa"``` having a length of ```25```, made of character, "a", with its corres... | reference | import re
def find_longest_substr(s):
m = max(re . finditer(r'([A-Za-z0-9])\1*', s),
key=lambda m: m . end() - m . start())
return [str(ord(m . group(1))), m . end() - m . start(), [m . start(), m . end() - 1]]
| #1 Strings: Find The Longest Substring and Required Data. | 59167d51c63c18af32000055 | [
"Fundamentals",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/59167d51c63c18af32000055 | 6 kyu |
**Principal Diagonal** -- The principal diagonal in a matrix identifies those elements of the matrix running from North-West to South-East.
**Secondary Diagonal** -- the secondary diagonal of a matrix identifies those elements of the matrix running from North-East to South-West.
For example:
```
matrix: [... | reference | def diagonal(m):
P = sum(m[i][i] for i in range(len(m)))
S = sum(m[i][- i - 1] for i in range(len(m)))
if P > S:
return "Principal Diagonal win!"
elif S > P :
return "Secondary Diagonal win!"
else :
return 'Draw!' | Principal Diagonal | VS | Secondary Diagonal | 5a8c1b06fd5777d4c00000dd | [
"Fundamentals",
"Matrix",
"Algorithms"
] | https://www.codewars.com/kata/5a8c1b06fd5777d4c00000dd | 7 kyu |
# Definition
A **_Tidy number_** *is a number whose* **_digits are in non-decreasing order_**.
___
# Task
**_Given_** a number, **_Find if it is Tidy or not_** .
____
# Warm-up (Highly recommended)
# [Playing With Numbers Series](https://www.codewars.com/collections/playing-with-numbers)
___
# Notes
* **_Num... | reference | def tidyNumber(n):
s = list(str(n))
return s == sorted(s)
| Tidy Number (Special Numbers Series #9) | 5a87449ab1710171300000fd | [
"Fundamentals",
"Arrays",
"Strings"
] | https://www.codewars.com/kata/5a87449ab1710171300000fd | 7 kyu |
# Introduction and Warm-up (Highly recommended)
# [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)
___
# Definition
An **_element is leader_** *if it is greater than The Sum all the elements to its right side*.
____
# Task
**_Given_** an *array/list [] of int... | reference | def array_leaders(numbers):
return [n for (i, n) in enumerate(numbers) if n > sum(numbers[(i + 1):])]
| Array Leaders (Array Series #3) | 5a651865fd56cb55760000e0 | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/5a651865fd56cb55760000e0 | 7 kyu |
## Task
You're given two non-negative numbers `(0 <= x,y)`. The goal is to create a function named `simple_sum` which return their sum.
## Restrictions
The restrictions can be summurized as 'bit and logical operations are allowed'.
Here comphrensive description. You're code __mustn't__ contain:
```
1. `import`, `g... | reference | def simple_sum(x, y):
while x:
x, y = ((x & y) << 1), (x ^ y)
return y
| Simple Sum (with restrictions) | 584c692db32364474000000a | [
"Puzzles",
"Restricted"
] | https://www.codewars.com/kata/584c692db32364474000000a | 6 kyu |
Several officials, managers and even athletes of your national
football league have been charged with corruption allegations. The
upcoming season is at stake. With only a few days to go, the season's
pairings have not yet been established. In search for trustworthy
individuals you were assigned this important task.
... | algorithms | def schedule(teams):
if len(teams) % 2:
raise ValueError
season = []
for _ in range(len(teams) - 1):
season . append([(teams[i], teams[- 1 - i]) if i or len(season) % 2 else (teams[- 1 - i], teams[i]) for i in range(len(teams) / / 2)])
teams = [teams[0], teams[- 1]] + teams[1: - 1]
... | Football Season | 584d9a8fd2d637cccf00017a | [
"Combinatorics",
"Permutations",
"Algorithms"
] | https://www.codewars.com/kata/584d9a8fd2d637cccf00017a | 5 kyu |
This is a question from codingbat
Given an integer n greater than or equal to 0,
create and return an array with the following pattern:
squareUp(3) => [0, 0, 1, 0, 2, 1, 3, 2, 1]
squareUp(2) => [0, 1, 2, 1]
squareUp(4) => [0, 0, 0, 1, 0, 0, 2, 1, 0, 3, 2, 1, 4, 3, 2, 1]
~~~if-not:bf
0 <= `n` <= 1000.... | games | def square_up(n):
return [j if j <= i else 0 for i in range(1, n + 1) for j in range(n, 0, - 1)]
| Array - squareUp b! | 5a8bcd980025e99381000099 | [
"Mathematics",
"Arrays"
] | https://www.codewars.com/kata/5a8bcd980025e99381000099 | 7 kyu |
In this challenge, you will be creating a go board that users can play a game of go on. An understanding of the rules of go should be sufficient enough to complete this kata.
The main goals for this kata:
- Creating a go board to a specific size.
- Placing go stones on the board. (White and Black alternating).
- Captu... | algorithms | from copy import deepcopy
class Go:
MOVES = [(1, 0), (- 1, 0), (0, 1), (0, - 1)]
SYMBOLS = "xo"
HANDICAP = {(9, 9): ['7G', '3C', '3G', '7C', '5E'],
(13, 13): ['10K', '4D', '4K', '10D', '7G', '7D', '7K', '10G', '4G'],
(19, 19): ['16Q', '4D', '4Q', '16D', '10K', '10... | Game of Go | 59de9f8ff703c4891900005c | [
"Games",
"Performance",
"Algorithms"
] | https://www.codewars.com/kata/59de9f8ff703c4891900005c | 2 kyu |
Make the 2D list by the sequential integers started by the ```head``` number.
See the example test cases for the expected output.
```
Note:
-10**20 < the head number <10**20
1 <= the number of rows <= 1000
0 <= the number of columms <= 1000
``` | reference | def make_2d_list(head, row, col):
return [[head + c + r * col for c in range(col)] for r in range(row)]
| 2D list by the sequential integers | 5a8897d4ba1bb5f266000057 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a8897d4ba1bb5f266000057 | 7 kyu |
You will be given a list with the coefficients of a polynomial. Look the following order in both:
```
P(x) = 6x³ + 3x² + 5x -4
coefficients = [ 6, 3, 5, -4]
```
Your task is to express the polynomial like a string with its value for a certain determinate x:
```python
[6, 3, 5, -4], 4 returns "For 6*x^3 + 3*... | reference | import re
def calc_poly(coefs, x):
coefs = coefs[:: - 1]
res = sum(x * * i * c for i, c in enumerate(coefs))
poly = ' + ' . join(["{}*x^{}" . format(c, i)
for i, c in enumerate(coefs) if c][:: - 1])
poly = re . sub(r'\*x\^0|\^1\b|\b1\*(?!x\^0)',
'',... | Polynomials II: Coefficients In a List | 5694b4f9a01ae685c400002f | [
"Fundamentals",
"Mathematics",
"Strings",
"Logic"
] | https://www.codewars.com/kata/5694b4f9a01ae685c400002f | 6 kyu |
## Emotional Sort ( ︶︿︶)
You'll have a function called "**sortEmotions**" that will return an array of **emotions** sorted. It has two parameters, the first parameter called "**arr**" will expect an array of **emotions** where an **emotion** will be one of the following:
- **:D** -> Super Happy
- **:)** -> Happy
- **... | reference | def sort_emotions(arr, order):
return sorted(arr, key=[':D', ':)', ':|', ':(', 'T_T']. index, reverse=not order)
| Emotional Sort ( ︶︿︶) | 5a86073fb17101e453000258 | [
"Arrays",
"Fundamentals",
"Sorting"
] | https://www.codewars.com/kata/5a86073fb17101e453000258 | 6 kyu |
### Please also check out other katas in [Domino Tiling series](https://www.codewars.com/collections/5d19554d13dba80026a74ff5)!
---
# Task
A domino is a rectangular block with `2` units wide and `1` unit high. A domino can be placed on a grid in two ways: horizontal or vertical.
```
## or #
#
```
You have in... | games | import numpy as np
def five_by_2n(n):
x = np . array([[1, 1, 1, 1, 1, 1, 1, 1], [1, 2, 1, 1, 1, 2, 2, 1], [1, 1, 2, 1, 1, 1, 2, 1], [1, 1, 1, 2, 1, 1, 2, 1], [
1, 1, 1, 1, 2, 1, 2, 2], [1, 2, 1, 1, 2, 1, 6, 1], [1, 2, 1, 1, 2, 1, 6, 1], [1, 2, 1, 1, 2, 1, 6, 1]])
y = np . array([1, 1,... | Domino Tiling - 5 x 2N Board | 5a77f76bfd5777c6c300001c | [
"Puzzles",
"Mathematics",
"Logic",
"Dynamic Programming"
] | https://www.codewars.com/kata/5a77f76bfd5777c6c300001c | 4 kyu |
# Disclaimer
This kata is an insane step-up from [myjinxin's Four Warriors and a Lamp](https://www.codewars.com/kata/t-dot-t-t-dot-51-four-warriors-and-a-lamp), so I recommend to solve it first before trying this one. (You'll also get a better understanding of the story, though it doesn't matter very much in solving t... | games | def shortest_time(times):
times . sort()
cost = 0
while len(times) > 3:
t1 = times[0] + 2 * times[1] + times[- 1]
t2 = 2 * times[0] + times . pop() + times . pop()
cost += min(t1, t2)
cost += sum(times) - sum(times[: - 1]) * (len(times) < 3)
return cost
| (Insane) N Warriors and a Lamp | 5a77f725b17101edd5000020 | [
"Puzzles",
"Performance",
"Logic",
"Algorithms"
] | https://www.codewars.com/kata/5a77f725b17101edd5000020 | 5 kyu |
*NOTE: It is highly recommended that you complete the first 4 Kata in this Series before attempting this final Kata; otherwise, the description would make little sense.*
---
```if:java
<font color="orange"><b><i>For java users:</i></b></font> Each time you encounter an invalid case you 'll have to throw a `RuntimeExc... | algorithms | import re
class RSUProgram:
ID_PATT_BRA = r'[PpRFL)](?:0|[1-9]\d*)|[RFLq()]'
WHITE_COMMENTS = r'\s+|//.*?(?:\n|$)|/\*.*?\*/'
TOKENIZER = re . compile(r'|' . join(
[WHITE_COMMENTS, ID_PATT_BRA, r'.']), flags=re . DOTALL)
VALID_TOKEN = re . compile(ID_PATT_BRA)
IS_NOT_TOKEN = re .... | RoboScript #5 - The Final Obstacle (Implement RSU) | 5a12755832b8b956a9000133 | [
"Compilers",
"Interpreters",
"Algorithms"
] | https://www.codewars.com/kata/5a12755832b8b956a9000133 | 1 kyu |
A stick is balanced horizontally on a support. Will it topple over or stay balanced? (This is a physics problem: imagine a real wooden stick balanced horizontally on someone's finger or on a narrow table, for example).
The stick is represented as a list, where each entry shows the mass in that part of the stick.
The... | reference | from math import ceil
def will_it_balance(stick, gnd):
gravPt = sum(v * i for i, v in enumerate(stick)) / sum(stick)
return gnd[int(gravPt)] == gnd[ceil(gravPt)] == 1
| Will it balance? | 5a8328fefd57777fa3000072 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a8328fefd57777fa3000072 | 6 kyu |
In Spanish, the conjugated verb changes by adding suffixes and according to the person we're talking about. There's something similar in English when we talk about "She", "He"or "It" (3rd person singular):
With the verb "run":
**He / She / It runS**
As you can see, the rule (at least with regular verbs) is to add t... | reference | SUFFIXES = {'a': ['o', 'as', 'a', 'amos', 'ais', 'an'],
'e': ['o', 'es', 'e', 'emos', 'eis', 'en'],
'i': ['o', 'es', 'e', 'imos', 'is', 'en']}
def conjugate(verb):
return {verb: [verb[: - 2] + s for s in SUFFIXES[verb[- 2]]]}
| Spanish Conjugator | 5a81b78d4a6b344638000183 | [
"Strings",
"Arrays",
"Functional Programming",
"Fundamentals"
] | https://www.codewars.com/kata/5a81b78d4a6b344638000183 | 7 kyu |
In [American football](http://en.wikipedia.org/wiki/American_football#Scoring), scoring can occur in several ways. These scores have different values, which leads to scores that jump up based on the way the team has scored.
A team can score in one of the following ways:
* Scoring a *touchdown*, which gains **6 point... | algorithms | def score_breakdowns(score):
ways = []
for s in range(0, score + 1, 2):
for fg in range(0, score - s + 1, 3):
for td in range(0, score - s - fg + 1, 6):
for tdep in range(0, score - s - fg - td + 1, 7):
for tdtp in range(0, score - s - fg - td - tdep + 1, 8):
if s + fg + td + tdep + t... | Touchdown? | 52a401f1a65172ce8f00008d | [
"Algorithms"
] | https://www.codewars.com/kata/52a401f1a65172ce8f00008d | 4 kyu |
A binary tree is a data structure in which every node has at most two children (https://en.wikipedia.org/wiki/Binary_tree).
A possible implementation in python of a binary tree is:
```python
class Tree(object):
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.ri... | reference | def tree_amplitude(node, path=[]):
if not node:
return max(path) - min(path) if path else 0
left = tree_amplitude(node . left, path + [node . data])
right = tree_amplitude(node . right, path + [node . data])
return max(left, right)
| Find amplitude of a binary tree | 55eab8c5a15df752cc00002b | [
"Fundamentals"
] | https://www.codewars.com/kata/55eab8c5a15df752cc00002b | 6 kyu |
Given a string with friends to visit in different states:
```
ad3="John Daggett, 341 King Road, Plymouth MA
Alice Ford, 22 East Broadway, Richmond VA
Sal Carpenter, 73 6th Street, Boston MA"
```
we want to produce a result that sorts the names by state and lists the name of the state followed by the name of each person... | reference | from collections import defaultdict
import re
PATTERN = re . compile(r'(.+?), (.+?), (.+?(?= [A-Z]{2})) ([A-Z]{2})')
STATES = {"CA": "California",
"MA": "Massachusetts",
"OK": "Oklahoma",
"PA": "Pennsylvania",
"VA": "Virginia",
"AZ": "Arizona",
"ID": ... | Address Book by State | 59d0ee709f0cbcf65400003b | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/59d0ee709f0cbcf65400003b | 6 kyu |
Your task in this kata is to write a function which will take a square matrix and a non-negative integer `n` as inputs and return a matrix raised to the power `n`.
Be ready to handle big `n`s.
Example:
```python
A = [[1, 2], [1, 0]]
calc(A, 2) = [[3, 2], [1, 2]]
```
```haskell
calc [ [ 1, 2 ], [ 1, 0 ] ] 2 = [ [ 3, ... | algorithms | def calc(M, n):
def mulM(a, b, S=len(M)):
return [[sum(a[i][x] * b[x][j] for x in range(S))
for j in range(S)] for i in range(S)]
def quick(m, n):
if n < 2:
return m
out = quick(mulM(m, m), n >> 1)
if n & 1:
out = mulM(out, m)
return out
return... | Matrix Exponentiation | 5791bdba3467db61ff000040 | [
"Arrays",
"Matrix",
"Algorithms",
"Logic"
] | https://www.codewars.com/kata/5791bdba3467db61ff000040 | 6 kyu |
Find the longest substring in alphabetical order.
Example: the longest alphabetical substring in `"asdfaaaabbbbcttavvfffffdf"` is `"aaaabbbbctt"`.
There are tests with strings up to `10 000` characters long so your code will need to be efficient.
The input will only consist of lowercase characters and will be at lea... | reference | import re
reg = re . compile('a*b*c*d*e*f*g*h*i*j*k*l*m*n*o*p*q*r*s*t*u*v*w*x*y*z*')
def longest(s):
return max(reg . findall(s), key=len)
| Longest alphabetical substring | 5a7f58c00025e917f30000f1 | [
"Fundamentals",
"Strings"
] | https://www.codewars.com/kata/5a7f58c00025e917f30000f1 | 6 kyu |
Your task is very simple. Given an input string s, case\_sensitive(s), check whether all letters are lowercase or not. Return True/False and a list of all the entries that are not lowercase in order of their appearance in s.
For example, case\_sensitive('codewars') returns [True, []], but case\_sensitive('codeWaRs') r... | reference | def case_sensitive(s):
return [s . islower() or not s, [c for c in s if c . isupper()]]
| Case-sensitive! | 5a805631ba1bb55b0c0000b8 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5a805631ba1bb55b0c0000b8 | 7 kyu |
Your task is very simple. Just write a function that takes an input string of lowercase letters and returns `true`/`false` depending on whether the string is in alphabetical order or not.
### Examples (input -> output)
* "kata" -> false ('a' comes after 'k')
* "ant" -> true (all characters are in alphabetical order)... | reference | def alphabetic(s):
return sorted(s) == list(s)
| Alphabetically ordered | 5a8059b1fd577709860000f6 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5a8059b1fd577709860000f6 | 7 kyu |
This challenge is an extension of the kata of Codewars: **Missing and Duplicate Number"**, authored by the user **Uraza**. (You may search for it and complete it if you have not done it)
In this kata, we have an unsorted sequence of consecutive numbers from ```a``` to ```b```, such that ```a < b``` always (remember ... | reference | from collections import Counter
def find_dups_miss(arr):
mi, ma, c = min(arr), max(arr), Counter(arr)
duplicates = sorted(n for n in c if c[n] > 1)
return [ma * (ma + 1) / / 2 - mi * (mi - 1) / / 2 - sum(c), duplicates]
| Unknown amount of duplicates. One missing number. | 5a5cdb07fd56cbdd3c00005b | [
"Fundamentals",
"Mathematics",
"Arrays",
"Algorithms",
"Sorting",
"Performance"
] | https://www.codewars.com/kata/5a5cdb07fd56cbdd3c00005b | 6 kyu |
You are given a list of items (characters and/or integers). Find if an item reoccurs after a break of its sequence (see explanation below). In other words: are there any items that reoccur in the list, but separated by one or more different items?
A sequence is a continuous "repetition" (1 or more occurence) of the sa... | reference | from itertools import groupby
def is_reoccuring(xs):
cs = [k for k, _ in groupby(xs)]
return len(cs) != len(set(cs))
| Is there a sequence re-occuring in the list | 5a7e6bd576c0e2f27d00237a | [
"Arrays",
"Lists",
"Fundamentals",
"Performance"
] | https://www.codewars.com/kata/5a7e6bd576c0e2f27d00237a | 6 kyu |
# Definition
**_Extra perfect number_** *is the number that* **_first_** and **_last_** *bits* are **_set bits_**.
____
# Task
**_Given_** *a positive integer* `N` , **_Return_** the **_extra perfect numbers_** *in range from* `1` to `N` .
____
# Warm-up (Highly recommended)
# [Playing With Numbers Series]... | reference | def extra_perfect(n):
return list(range(1, n + 1, 2))
| Extra Perfect Numbers (Special Numbers Series #7) | 5a662a02e626c54e87000123 | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/5a662a02e626c54e87000123 | 7 kyu |
The goal of this kata is to write a function `tower(base, height, modulus)` that returns `base ** base ** ... ** base`, with `height` occurrences of `base`, modulo `modulus`. (`**` is the power operator in Python, in case this kata gets translated.) As input constraints, we have:
```
1 <= base < 1e20
0 <= height < 1e2... | refactoring | from math import log
def phi(n):
r, i = n, 2
while i * i <= n:
if n % i == 0:
r = r / / i * (i - 1)
while n % i == 0:
n / /= i
i += 1
if n > 1:
r = r / / n * (n - 1)
return r
def _tower(base, h, m):
if h < 2 or m == 1:
return pow(base, h,... | Power tower modulo m | 5a08b22b32b8b96f4700001c | [
"Refactoring"
] | https://www.codewars.com/kata/5a08b22b32b8b96f4700001c | 2 kyu |
# Story
Well, here I am stuck in another traffic jam.
*<span style='color:orange'>Damn all those courteous people!</span>*
Cars are trying to enter the main road from side-streets somewhere ahead of me and people keep letting them cut in.
Each time somebody is let in the effect ripples back down the road, so prett... | algorithms | def traffic_jam(road, sides):
X = road . index("X")
main = list(road[: X + 1])
for i in reversed(range(min(X, len(sides)))):
tmp = []
for j in range(1, min(len(main) - i - 1, len(sides[i])) + 1):
tmp . append(sides[i][- j])
tmp . append(main[i + j])
main[i + 1: i + len(tmp) / /... | Traffic Jam | 5a26073ce1ce0e3c01000023 | [
"Algorithms"
] | https://www.codewars.com/kata/5a26073ce1ce0e3c01000023 | 5 kyu |
In this kata the function returns an array/list like the one passed to it but with its nth element removed (with `0 <= n <= array/list.length - 1`). The function is already written for you and the basic tests pass, but random tests fail. Your task is to figure out why and fix it.
Good luck!
~~~if:javascript
Some good... | refactoring | def remove_nth_element(lst, n):
lst_copy = lst . copy()
del lst_copy[n]
return lst_copy
| Working with arrays II (and why your code fails in some katas) | 5a7b3d08fd5777bf6a000121 | [
"Refactoring",
"Arrays"
] | https://www.codewars.com/kata/5a7b3d08fd5777bf6a000121 | 7 kyu |
Convert Decimal Degrees to Degrees, Minutes, Seconds.
Remember: 1 degree = 60 minutes; 1 minute = 60 seconds.
Input: Positive number.
Output: Array [degrees, minutes, seconds]. E.g [30, 25, 25]
Trailing zeroes should be omitted in the output. E.g
```
convert (50)
//correct output -> [50]
//wrong output -> [50, ... | reference | def convert(i):
t = round(i * 3600)
d, m, s = t / / 3600, t % 3600 / / 60, t % 60
return [d, m, s] if s else [d, m] if m else [d]
| Convert Decimal Degrees to Degrees, Minutes, Seconds | 590ac6b9be4dff49b0000042 | [
"Fundamentals"
] | https://www.codewars.com/kata/590ac6b9be4dff49b0000042 | 7 kyu |
The description is rather long but it tries to explain what a financing plan is.
The fixed monthly payment for a fixed rate mortgage is the amount paid by the borrower every month that ensures
that the loan is paid off in full with interest at the end of its term.
The monthly payment formula is based on the annuit... | reference | def amort(rate, bal, term, num_payments):
monthlyRate = rate / (12 * 100)
c = bal * (monthlyRate * (1 + monthlyRate) * * term) / (((1 + monthlyRate) * * term) - 1)
newBalance = bal
for i in range(num_payments):
interest = newBalance * monthlyRate
princ = c - interest
newBalance = newB... | Financing a purchase | 59c68ea2aeb2843e18000109 | [
"Fundamentals",
"Mathematics"
] | https://www.codewars.com/kata/59c68ea2aeb2843e18000109 | 6 kyu |
Consider the following expansion:
```
solve("3(ab)") = "ababab" -- because "ab" repeats 3 times
solve("2(a3(b))") = "abbbabbb" -- because "a3(b)" == "abbb", which repeats twice.
```
Given a string, return the expansion of that string.
Input will consist of only lowercase letters and numbers (1 to 9) in valid par... | algorithms | def solve(s):
s1 = s[:: - 1]
s2 = ''
for i in s1:
if i . isalpha():
s2 += i
elif i . isdigit():
s2 = s2 * int(i)
return s2[:: - 1]
| Simple string expansion | 5a793fdbfd8c06d07f0000d5 | [
"Algorithms"
] | https://www.codewars.com/kata/5a793fdbfd8c06d07f0000d5 | 5 kyu |
# Introduction and Warm-up (Highly recommended)
# [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)
___
# Task
**_Given_** an *array/list [] of integers* , **_Find_** **_The maximum difference_** *between the successive elements in its sorted form*.
___
# Note... | reference | def max_gap(numbers):
lst = sorted(numbers)
return max(b - a for a, b in zip(lst, lst[1:]))
| Maximum Gap (Array Series #4) | 5a7893ef0025e9eb50000013 | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/5a7893ef0025e9eb50000013 | 7 kyu |
In graph theory, a graph is a collection of nodes with connections between them.
Any node can be connected to any other node exactly once, and can be connected to no nodes, to some nodes, or to every other node.
Nodes cannot be connected to themselves
A path through a graph is a sequence of nodes, with every node conne... | algorithms | def isTree(matrix):
visited_nodes = set([0])
crossed_edges = set()
agenda = [0]
while agenda:
node = agenda . pop()
for i in matrix[node]:
if (node, i) in crossed_edges:
continue
if i in visited_nodes:
return False
agenda . append(i)
crossed_edges . ... | Mistaking a forest for a tree | 5a752a0b0136a1266c0000b5 | [
"Algorithms"
] | https://www.codewars.com/kata/5a752a0b0136a1266c0000b5 | 5 kyu |
In this kata the function returns an array/list of numbers without its last element. The function is already written for you and the basic tests pass, but random tests fail. Your task is to figure out why and fix it.
Good luck!
Hint: watch out for side effects.
~~~if:javascript,coffeescript
Some good reading: [MDN ... | refactoring | def without_last(lst):
return lst[: - 1]
| Working with arrays I (and why your code fails in some katas) | 5a4ff3c5fd56cbaf9800003e | [
"Fundamentals",
"Arrays",
"Refactoring"
] | https://www.codewars.com/kata/5a4ff3c5fd56cbaf9800003e | 7 kyu |
This is harder version of [Square sums (simple)](/kata/square-sums-simple).
# Square sums
Write function that, given an integer number `N`, returns array of integers `1..N` arranged in a way, so sum of each 2 consecutive numbers is a square.
Solution is valid if and only if following two criterias are met:
1. Each nu... | bug_fixes | __import__('sys'). setrecursionlimit(10000)
def square_sums(n):
squares = [sq * sq for sq in range(2, int((n * 2 - 1) * * .5) + 1)]
Graph = {i: [j - i for j in squares if 0 < j - i <= n and j - i != i]
for i in range(1, n + 1)}
def get_result(G, res, ind):
if len(res) == n:
... | Square sums | 5a667236145c462103000091 | [
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/5a667236145c462103000091 | 1 kyu |
Given two arrays `a1` and `a2` of positive integers find the set of common elements between them and return the elements (a set) that have a sum or difference equal to *either* array length.
- All elements will be positive integers greater than 0
- If there are no results an empty set should be returned
- Each operati... | reference | def a1_thick_and_hearty(a1, a2):
s = set(a1) & set(a2)
return set(n for n in s if any(m != n and m in s for m in [len(a1) + n, abs(len(a1) - n), len(a2) + n, abs(len(a2) - n)]))
| A1 Thick and Hearty | 5a77e4af373c2edf72000085 | [
"Lists",
"Permutations",
"Fundamentals"
] | https://www.codewars.com/kata/5a77e4af373c2edf72000085 | 6 kyu |
The goal of this Kata is to reduce the passed integer to a single digit (if not already) by converting the number to binary, taking the sum of the binary digits, and if that sum is not a single digit then repeat the process.
- If the passed integer is already a single digit there is no need to reduce
```if:haskell,py... | reference | def single_digit(n):
while n > 9:
n = bin(n). count("1")
return n
| Single digit | 5a7778790136a132a00000c1 | [
"Binary",
"Fundamentals"
] | https://www.codewars.com/kata/5a7778790136a132a00000c1 | 7 kyu |
You are given a function `f` defined on the interval `[0, 1]` such that for some `x_max` in the interval `[0, 1]`, the function `f` is strictly increasing on the interval `[0, x_max]` and strictly decreasing on the interval `[x_max, 1]`. Your job is to determine `x_max` within an distance less than `1e-6` (i.e., `|x_ma... | reference | def max_x(f):
tau = (5 * * .5 - 1) / 2
a, b, c, d, coins = 0, 1, 1 - tau, tau, 0
fc, fd = f(c), f(d)
for _ in range(28):
if fc >= fd:
a, b, c, d = a, d, a + (d - a) * (1 - tau), c
fc, fd = f(c), fc
else:
a, b, c, d = c, b, d, c + (b - c) * (tau)
fc, fd = fd, f(d)
... | Golden Section Search | 5a7671e6373c2e8c3e00008d | [
"Fundamentals"
] | https://www.codewars.com/kata/5a7671e6373c2e8c3e00008d | 6 kyu |
There are two main ways to write out a quadratic function, standard form: `f(x) = a(x^2)+bx+c` and vertex form:<br /> `f(x) = a((x-h)^2) + k` (where (h,k) are the coordinates of the vertex of the parabola).
# Your Task
is to write a function `getVertex` that takes three parameters `a`, `b`, and `c` and returns an array... | algorithms | def getVertex(a, b, c):
h = b / (- 2 * a)
k = c - (a * h * * 2)
return [h, k]
| Parabolas: Standard to Vertex Form | 5a74d00c0025e979c9000145 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5a74d00c0025e979c9000145 | 7 kyu |
When developing a game, it's often useful to be able to control time. We could slow it down when a character dies, or speed it up to make things look flashy, or stop time altogether when the player pauses the game.
Let's write an object we can use to simulate time and mess with it as we wish!
## new SimTime()
Creates... | algorithms | class SimTime:
def __init__(self):
self . sim_time = 0
self . real_time = 0
self . speed = 1
def get(self):
return self . sim_time
def set_speed(self, new_speed):
self . speed = new_speed
def update(self, current_realtime):
assert current_realtime >= self . real_time
self . ... | Time Simulation | 5858326b994864753d0000d1 | [
"Algorithms"
] | https://www.codewars.com/kata/5858326b994864753d0000d1 | 6 kyu |
In recreational mathematics, a [Keith number](https://en.wikipedia.org/wiki/Keith_number) or repfigit number (short for repetitive Fibonacci-like digit) is a number in the following integer sequence:
`14, 19, 28, 47, 61, 75, 197, 742, 1104, 1537, 2208, 2580, 3684, 4788, 7385, 7647, 7909, ...` (sequence A007629 in the ... | algorithms | def is_keith_number(n):
numList = [int(i) for i in str(n)] # int array
if len(numList) > 1: # min 2 digits
itr = 0
while numList[0] <= n:
# replace array entries by its sum:
numList[itr % len(numList)] = sum(numList)
itr += 1
if n in numList: # keith-condition
return itr
r... | Keith Numbers | 590e4940defcf1751c000009 | [
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/590e4940defcf1751c000009 | 6 kyu |
##Tabs to spaces!
Suppose that in a developer team the agreed standard is to always use spaces for alignment. Somebody from another team with whom they cooperate uses another convention and regularly checks in code containing tabs. Now all the times he changes spaces to tabs or others change his tabs to spaces that wi... | reference | def tab_to_spaces(text):
return text . expandtabs(4)
| Tabs to spaces | 5779474882d7d0a10f000005 | [
"Fundamentals"
] | https://www.codewars.com/kata/5779474882d7d0a10f000005 | 7 kyu |
A pixmap shall be turned from black to white, turning all pixels to white in the process. But for optical reasons this shall *not* happen linearly, starting at the top and continuing line by line to the bottom:
```haskell
for_ [0..height-1] $ \ y ->
for_ [0..width-1] $ \ x ->
setBit x y
```
```lambdacalc
# pse... | algorithms | def dithering(width, height):
size = 1
while width > size or height > size:
size *= 2
if size == 1:
yield (0, 0)
else:
for (x, y) in dithering(size / 2, size / 2):
for t in ((x, y), (x + size / 2, y + size / 2), (x + size / 2, y), (x, y + size / 2)):
if t[0] < width and t[1]... | Dithering | 5426006a60d777c556001aad | [
"Algorithms"
] | https://www.codewars.com/kata/5426006a60d777c556001aad | 4 kyu |
Imagine that we have ATM with multiple currencies. The users can withdraw money of in any currency that the ATM has.
Our function must analyze the currency and value of what the users wants, and give money to the user starting from bigger values to smaller. The ATM gives the **least amount of notes** possible.
This k... | reference | import re
def atm(value):
match = re . fullmatch('([A-Z]+) ?(\d+)|(\d+) ?([A-Z]+)', value . upper())
currency = match . group(1) or match . group(4)
value = int(match . group(2) or match . group(3))
if currency not in VALUES:
return "Sorry, have no {}." . format(currency)
if value % V... | ATM money counter | 5665a6a07b5afe0aba00003a | [
"Regular Expressions",
"Mathematics",
"Fundamentals"
] | https://www.codewars.com/kata/5665a6a07b5afe0aba00003a | 6 kyu |
If you deposit $100 each year into a bank account with yearly 1% interest rate, how many years will it take you to accumulate minimum $5000? What if the interest is 3% instead?
This is the question you will answer in this kata for the interest rates 1, 2, 3, 4, 5 and 6% given a yearly deposit amount and target amount.... | algorithms | import math
def calculate_retirement(P, FV):
rates = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0}
for i in range(1, 7):
r = i / 100
rates[i] = math . ceil(math . log(
1 + (FV * r) / (P * r + P)) / math . log(1 + r))
return rates
| Save for retirement | 58177df1e7f457b89d000327 | [
"Mathematics",
"Algorithms",
"Logic"
] | https://www.codewars.com/kata/58177df1e7f457b89d000327 | 7 kyu |
# Password Check - Binary to String
A wealthy client has forgotten the password to his business website, but he has a list of possible passwords. His previous developer has left a file on the server with the name password.txt. You open the file and realize it's in binary format.
Write a script that takes an array of ... | reference | def decode_pass(pass_list, bits):
s = "" . join(chr(int(x, 2)) for x in bits . split())
return s if s in pass_list else False
| Password Check - Binary to String | 5a731b36e19d14400f000c19 | [
"Binary",
"Strings",
"Arrays",
"Fundamentals"
] | https://www.codewars.com/kata/5a731b36e19d14400f000c19 | 7 kyu |
Convert DD (decimal degrees) position to DMS (degrees, minutes, seconds).
##### Inputs:
`dd_lat` and `dd_lon` 2 floats representing the latitude and the longitude in degree -i.e. 2 floats included in [-90, 90] and [-180, 180]. Note that latitude 0 is north, longitude 0 is east.
##### Outputs:
A tuple of DMS latitudes... | reference | from math import modf
def dms(number: float, cardinal_dirs: str) - > str:
rem, D = modf(abs(number))
rem, M = modf(rem * 60)
S = rem * 60
return f' { D : 03.0 f } * { M : 02.0 f } \' { S : 06.3 f } " { cardinal_dirs [ number < 0 ]} '
def convert_to_dms(latitude: str, longitude: str) - > tu... | GPS coordinate conversions - DD to DMS | 5a72fd224a6b3463b00000a0 | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5a72fd224a6b3463b00000a0 | 7 kyu |
`This kata is the first of the ADFGX Ciphers, the harder version can be found `<a href='https://www.codewars.com/kata/adfgx-un-simplified/python' target='_blank'>here</a>.
The <a href='https://en.wikipedia.org/wiki/ADFGVX_cipher' target='_blank'>ADFGX Cipher</a> is a pretty well-known Cryptographic tool, and is essent... | reference | from itertools import product
import re
KEY = [a + b for a, b in product("ADFGX", repeat=2)]
def adfgx_encrypt(plaintext, square):
d = dict(zip(square, KEY))
oddity = d['i'] if 'i' in d else d['j']
return '' . join(d . get(c, oddity) for c in plaintext)
def adfgx_decrypt(ciphertext, square)... | ADFGX Simplified | 57f171f618e9fa58ef000083 | [
"Cryptography",
"Algorithms",
"Fundamentals"
] | https://www.codewars.com/kata/57f171f618e9fa58ef000083 | 6 kyu |
In this Kata, we are going to reverse a string while maintaining the spaces (if any) in their original place.
For example:
```
solve("our code") = "edo cruo"
-- Normal reversal without spaces is "edocruo".
-- However, there is a space at index 3, so the string becomes "edo cruo"
solve("your code rocks") = "skco redo... | algorithms | def solve(s):
it = reversed(s . replace(' ', ''))
return '' . join(c if c == ' ' else next(it) for c in s)
| Simple string reversal | 5a71939d373c2e634200008e | [
"Algorithms"
] | https://www.codewars.com/kata/5a71939d373c2e634200008e | 7 kyu |
This is a classic needing (almost) no further introduction.
Given a N x N chess board, place N queens on it so none can attack another: I.e. no other queens can be found horizontally, vertically or diagonally to the current.
On the board below, no further queens can be positioned.
<pre style="font-family:courier">+-... | algorithms | def nQueen(n):
if n == 2 or n == 3:
return []
r, odds, evens = n % 6, list(range(1, n, 2)), list(range(0, n, 2))
if r == 2:
evens[: 2] = evens[: 2][:: - 1]
evens . append(evens . pop(2))
if r == 3:
odds . append(odds . pop(0))
evens . extend(evens[: 2])
del evens[: ... | N queens problem (with no mandatory queen position) | 52cdc1b015db27c484000031 | [
"Performance",
"Algorithms"
] | https://www.codewars.com/kata/52cdc1b015db27c484000031 | 4 kyu |
Description:
Before smartphones and blackberry's without a qwerty keyboard, and prior to the development of T9 (predictive text entry) systems, the method to type words was called "multi-tap" and involved pressing a button repeatedly to cycle through the possible values.
------- ------- -------
| | | ABC... | reference | from itertools import groupby
from operator import itemgetter
_LAYOUT = (' 0', '1', 'ABC2', 'DEF3', 'GHI4',
'JKL5', 'MNO6', 'PQRS7', 'TUV8', 'WXYZ9')
_KEYMAP = {c: str(i) * j for i, key in enumerate(_LAYOUT)
for j, c in enumerate(key, 1)}
def sequence(phrase):
presses = (_KEYMAP . g... | Dumbphone Keypads | 5680e56f4797a55076000044 | [
"Fundamentals"
] | https://www.codewars.com/kata/5680e56f4797a55076000044 | 6 kyu |
We define the sequence ```SF``` in the following way in terms of four previous sequences: ```S1```, ```S2```, ```S3``` and ```ST```
<a href="http://imgur.com/kCiwfWT"><img src="http://i.imgur.com/kCiwfWT.jpg?1" title="source: imgur.com" /></a>
We are interested in collecting the terms of SF that are multiple of ten.
... | reference | def find_mult10_SF(n):
return 16 * * n * (81 * * n + 9) / / 24
| Multiples of Ten in a Sequence Which Values Climb Up | 561d54055e399e2f62000045 | [
"Fundamentals",
"Algorithms",
"Mathematics",
"Data Structures",
"Sorting",
"Memoization"
] | https://www.codewars.com/kata/561d54055e399e2f62000045 | 6 kyu |
Given a number N, can you fabricate the two numbers NE and NO such that NE is formed by even digits of N and NO is formed by odd digits of N?
Examples:
| input | NE | NO |
|:------:|:----:|:---:|
| 126453 | 264 | 153 |
| 3012 | 2 | 31 |
| 4628 | 4628 | 0 |
`0` is considered as an even number.
In C an... | reference | def even_and_odd(n):
ne = ""
no = ""
for x in str(n):
if int(x) % 2 == 0:
ne += x
else:
no += x
if len(ne) == 0:
ne = "0"
if len(no) == 0:
no = "0"
return (int(ne), int(no))
| Even and Odd ! | 594adadee075005308000122 | [
"Fundamentals"
] | https://www.codewars.com/kata/594adadee075005308000122 | 7 kyu |
# Background
<a href="https://en.wikipedia.org/wiki/There_Was_an_Old_Lady_Who_Swallowed_a_Fly">There was an Old Lady who Swallowed a Fly</a>
<pre style='color:orange'>
There was an old lady who swallowed a <span style="color:red;background:black">fly</span>;
I don't know why she swallowed a fly - perhaps she'll die... | algorithms | def old_lady_swallows(animals: list) - > list:
ord_an = [None, 'fly', 'spider', 'bird',
'cat', 'dog', 'goat', 'cow', 'horse', None]
res = []
for a in animals:
ind_a = ord_an . index(a)
res = [x for x in res if x != ord_an[ind_a - 1]]
if ord_an[ind_a + 1] not in res:
r... | There was an Old Lady who Swallowed a Fly | 5a68ffe3e626c5e85700002d | [
"Algorithms"
] | https://www.codewars.com/kata/5a68ffe3e626c5e85700002d | 6 kyu |
The task is simply stated. Given an integer <code>n</code> (<code>3 < n < 10<sup>9</sup></code>), find the length of the smallest list of [*perfect squares*](https://en.wikipedia.org/wiki/Square_number) which add up to <code>n</code>. Come up with the best algorithm you can; you'll need it!
<strong>Examples:</strong>
... | algorithms | def one_square(n):
return round(n * * .5) * * 2 == n
def two_squares(n):
while n % 2 == 0:
n / /= 2
p = 3
while p * p <= n:
while n % (p * p) == 0:
n / /= p * p
while n % p == 0:
if p % 4 == 3:
return False
n / /= p
p += 2
return n % 4 == 1
def three_s... | Sums of Perfect Squares | 5a3af5b1ee1aaeabfe000084 | [
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/5a3af5b1ee1aaeabfe000084 | 4 kyu |
### Introduction and Warm-up (Highly recommended)
### [Playing With Lists/Arrays Series](https://www.codewars.com/collections/playing-with-lists-slash-arrays)
___
## Task
**_Given_** an *array/list [] of integers* , **_Find the product of the k maximal_** numbers.
___
### Notes
* **_Array/list_** size is *at leas... | reference | from functools import reduce
from operator import mul
from heapq import nlargest
def maxProduct(lst, n):
return reduce(mul, nlargest(n, lst))
| Product Of Maximums Of Array (Array Series #2) | 5a63948acadebff56f000018 | [
"Fundamentals",
"Arrays"
] | https://www.codewars.com/kata/5a63948acadebff56f000018 | 7 kyu |
Additive number is a string whose digits can form an additive sequence.
Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.
For example:<br/>
```"112358"``` is an additive number because the digits can form an additive sequence: ```1, 1, 2, 3, 5, 8```
```1 +... | algorithms | def find_additive_numbers(num):
for k in range(2, len(num)):
for j in range(1, k):
if k - j > 1 and num[j] == '0':
continue
a, b = j, k
out = [num[: a], num[a: b]]
while b < len(num):
x = int(out[- 2]) + int(out[- 1])
a, b = b, b + len(str(x))
y = int(num[a: b])
... | Additive Numbers | 5693239fb761dc8670000001 | [
"Parsing",
"Algorithms"
] | https://www.codewars.com/kata/5693239fb761dc8670000001 | 5 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:
What's a reversible prime? That is: A prime, reverse all the digits, get a new number. If the new number is also a prime, then it is a reversible prime .
... | algorithms | from gmpy2 import is_prime, next_prime
def gen():
prime = 0
while True:
prime = next_prime(prime)
if is_prime(int(str(prime)[:: - 1])):
yield prime
primes, result = gen(), []
def reversible_prime(n):
while len(result) <= n:
result . append(next(primes))
return re... | n-th reversible prime | 5826c14622be6ef2a4000033 | [
"Puzzles",
"Algorithms"
] | https://www.codewars.com/kata/5826c14622be6ef2a4000033 | 6 kyu |
### Please also check out other katas in [Domino Tiling series](https://www.codewars.com/collections/5d19554d13dba80026a74ff5)!
---
# Task
A domino is a rectangular block with `2` units wide and `1` unit high. A domino can be placed on a grid in two ways: horizontal or vertical.
```
## or #
#
```
You have in... | games | def two_by_n(n, k):
s = [1, k, 2 * k * (k - 1)]
for _ in range(2, n):
s . append((k - 2) * s[- 1] + (k - 1) * (k - 1) * s[- 2])
return s[n] % 12345787
| Domino Tiling - 2 x N Board | 5a59e029145c46eaac000062 | [
"Mathematics",
"Algorithms",
"Dynamic Programming",
"Puzzles"
] | https://www.codewars.com/kata/5a59e029145c46eaac000062 | 4 kyu |
# Disclaimer
This Kata is an insane step-up from [GiacomoSorbi's Kata](https://www.codewars.com/kata/total-increasing-or-decreasing-numbers-up-to-a-power-of-10/python),
so I recommend to solve it first before trying this one.
# Problem Description
A positive integer `n` is called an *increasing number* if its digits... | games | from math import comb
def insane_inc_or_dec(max_digits):
'''
Derivation summerized:
Counting the number of increasing (or decreasing) numbers with d digits is equivalent
to counting the number of ways to put d "balls" in 9 (or 10) boxes representing each digit,
e.g. for decreasing numbers:
| |oo| |o... | Insane Increasing or Decreasing Numbers | 5993e6f701726f0998000030 | [
"Algorithms",
"Mathematics",
"Puzzles",
"Performance"
] | https://www.codewars.com/kata/5993e6f701726f0998000030 | 4 kyu |
Get the list of integers for 'totalAuthored' and 'totalCompleted' of the ```n```th ranker at Codewars Leaderboard.
```(1 <= n <= 500)```
See Example Test Cases for the expected data format.
(Note 1 : Mind the title of this kata as well as [https://dev.codewars.com/](https://dev.codewars.com/) )
(Note 2 : It is re... | reference | from bs4 import BeautifulSoup
import requests
req = requests . get("https://www.codewars.com/users/leaderboard"). content
bs = BeautifulSoup(req, "html.parser")
tr = [x . attrs["data-username"]
for x in bs . find_all(lambda x: "data-username" in x . attrs)]
def get_codeChallenges(n):
req = requests... | Codewars API | 5a6b80cb880385a8f7000089 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a6b80cb880385a8f7000089 | 5 kyu |
In this Kata you will rotate a binary tree. You need to implement two methods to rotate a binary tree: one to rotate it to the **left** and one to rotate it to the **right**.
If rotation is impossible, return the tree unchanged.
```if:javascript,
You need not always ( though you may ) return a _new_ tree ( or entirel... | algorithms | def rotate_right(tree):
if tree . left is not None:
new_right = tree
tree = tree . left
new_right . left = tree . right
tree . right = new_right
return tree
def rotate_left(tree):
if tree . right is not None:
new_left = tree
tree = tree . right
new_left . right = tree . left
... | The Binary Tree, or There and Back Again | 5a6de0ec0136a1761d000093 | [
"Algorithms",
"Data Structures",
"Trees"
] | https://www.codewars.com/kata/5a6de0ec0136a1761d000093 | 6 kyu |
This is related to <a href="https://www.codewars.com/kata/cat-years-dog-years">my other Kata</a> about cats and dogs.
# Kata Task
I have a cat and a dog which I got as kitten / puppy.
I forget when that was, but I do know their current ages as `catYears` and `dogYears`.
Find how long I have owned each of my pets an... | reference | def owned_cat_and_dog(cy, dy):
cat = 0 if cy < 15 else 1 if cy < 24 else 2 + (cy - 24) / / 4
dog = 0 if dy < 15 else 1 if dy < 24 else 2 + (dy - 24) / / 5
return [cat, dog]
| Cat Years, Dog Years (2) | 5a6d3bd238f80014a2000187 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a6d3bd238f80014a2000187 | 7 kyu |
We are introducing a new variant of the popular game [Codenames](https://czechgames.com/en/codenames/) for two players.
We are looking at a board of 5x5 words. Players try to guess the words of the other team but without guessing one of their own words.
Your job is to create a board for two players. Therefore, you as... | algorithms | from random import sample
def player_matrixes(R=7, B=7):
res = sample('R' * R + 'B' * B + '-' * (25 - R - B), k=25)
red_matrix = [[res[5 * x + y] if res[5 * x + y] !=
'B' else '-' for y in range(5)] for x in range(5)]
blue_matrix = [[res[5 * x + y] if res[5 * x + y] !=
... | Codenames - matrix conversions | 5a6ccef6b17101c74900004e | [
"Matrix",
"Algorithms"
] | https://www.codewars.com/kata/5a6ccef6b17101c74900004e | 6 kyu |
As you see in Example test cases, the os running this service is ```posix```.
Return the output by executing the command given as the string on posix os.
See the example test cases for the expected data format. | reference | import os
def get_output(s):
return os . popen(s). read()
| Posix command | 5a6986abe626c5d3e9000063 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a6986abe626c5d3e9000063 | 7 kyu |
This is simple version of harder [Square Sums](/kata/square-sums).
# Square sums
Write function `square_sums_row` ( or `squareSumsRow` or `SquareSumsRow` ) that, given integer number `N` (in range `2..43`), returns array of integers `1..N` arranged in a way, so sum of each 2 consecutive numbers is a square.
Solution... | algorithms | def square_sums_row(n):
def dfs():
if not inp:
yield res
for v in tuple(inp):
if not res or not ((res[- 1] + v) * * .5 % 1):
res . append(v)
inp . discard(v)
yield from dfs()
inp . add(res . pop())
inp, res = set(range(1, n + 1)), []
return next(dfs(), Fals... | Square sums (simple) | 5a6b24d4e626c59d5b000066 | [
"Algorithms",
"Mathematics"
] | https://www.codewars.com/kata/5a6b24d4e626c59d5b000066 | 5 kyu |
Your task is to define a function that understands basic mathematical expressions and solves them.
For example:
```python
calculate("1 + 1") # => 2
calculate("18 + 4*6") # => 42
calculate("245 - 826") # => -581
calculate("09 + 000482") # => 491
calculate("8 / 4 + 6") # => 8
calculate("5 + 1 / 5") ... | algorithms | import re
def calculate(input):
try:
return eval(re . sub(r'(\d+)', lambda m: str(int(m . group(1))), input))
except:
return False
| Calculate the expression | 582b3b085ad95285c4000013 | [
"Mathematics",
"Strings",
"Algorithms"
] | https://www.codewars.com/kata/582b3b085ad95285c4000013 | 5 kyu |
This function will take in a list of strings and put them into a hashmap. A hashmap is a quick way to store and lookup items you might need based on the 'hash' of the item (https://en.wikipedia.org/wiki/Hash_table). In this example, we're going to create hashes based on the sum of the characters. Each charater has a de... | reference | from functools import reduce
from collections import defaultdict
def my_hash_map(list_of_strings):
return reduce(lambda h, s: h[sum(map(ord, s))]. append(s) or h, list_of_strings, defaultdict(list))
| Make Your Own Hashmap | 5a6a02adcadebf618400002b | [
"Strings",
"Fundamentals"
] | https://www.codewars.com/kata/5a6a02adcadebf618400002b | 7 kyu |
Your job is to write a function that takes a string and a maximum number of characters per line and then inserts line breaks as necessary so that no line in the resulting string is longer than the specified limit.
If possible, line breaks should not split words. However, if a single word is longer than the limit, it o... | algorithms | def word_wrap(text, limit):
st = iter(text . split())
cur = next(st, None)
res = ['']
while cur:
if len(res[- 1]) + len(cur) + (res[- 1] != '') <= limit:
res[- 1] += ' ' * (res[- 1] != '') + cur
cur = next(st, None)
elif len(cur) > limit and limit - len(res[- 1]) - 1 > 0:
... | Word Wrap | 55fd8b5e61d47237810000d9 | [
"Algorithms"
] | https://www.codewars.com/kata/55fd8b5e61d47237810000d9 | 5 kyu |
Consider a sequence generation that follows the following steps. We will store removed values in variable `res`. Assume `n = 25`:
```Haskell
-> [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25] Let's remove the first number => res = [1]. We get..
-> [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21... | algorithms | def solve(n):
zoznam = [int(i) for i in range(2, n + 1)]
res = [1]
while zoznam != []:
res . append(zoznam[0])
del zoznam[0:: zoznam[0]]
return sum(res)
| Array reduction | 5a6761be145c4691ee000090 | [
"Algorithms"
] | https://www.codewars.com/kata/5a6761be145c4691ee000090 | 6 kyu |
In this Kata, you will check if it is possible to convert a string to a palindrome by changing one character.
For instance:
```Haskell
solve ("abbx") = True, because we can convert 'x' to 'a' and get a palindrome.
solve ("abba") = False, because we cannot get a palindrome by changing any character.
solve ("abcba") ... | algorithms | def solve(s):
v = sum(s[i] != s[- 1 - i] for i in range((len(s)) / / 2))
return v == 1 or not v and len(s) % 2
| Single character palindromes II | 5a66ea69e6be38219f000110 | [
"Algorithms"
] | https://www.codewars.com/kata/5a66ea69e6be38219f000110 | 7 kyu |
Following on from [Points of Reflection](https://www.codewars.com/kata/points-of-reflection), given a number of points and a single midpoint, a 2D shape can be inferred.
*Task:*
You will be given two inputs. The first will be a two-dimensional sequence in which the inner sequences contain two elements representing pa... | algorithms | def symmetric_shape(shape, q):
return shape + list(map(lambda x: (2 * q[0] - x[0], 2 * q[1] - x[1]), shape))
| Shape Symmetry | 57c13e724677bbc5fc000a0b | [
"Mathematics",
"Geometry",
"Algorithms"
] | https://www.codewars.com/kata/57c13e724677bbc5fc000a0b | 7 kyu |
Carpe Diem! Yolo! On Fleek? Crushing it. You've got some awesome phrases that you want to hang up on your wall. The problem is that you don't have any frames laying around. So instead, you decide to write a program to create your frame.
Write a function called `frame` that will take two parameters as input: a phras... | reference | def frame(phr='', ch='*'):
l = len(phr) + 4
line = ch * l
middle = ch + ' ' * (l - 2) + ch
return line + '\n' + middle + '\n' + ((ch + ' ' + phr + ' ' + ch + '\n') if phr else '') + middle + '\n' + line
| Rithm Series: Frame a Phrase Simple | 5867d76b36959fa4a400034e | [
"Fundamentals",
"ASCII Art"
] | https://www.codewars.com/kata/5867d76b36959fa4a400034e | 7 kyu |
Get n seconds before the target time. See Example Test Cases about the format. | reference | from datetime import *
def seconds_ago(s, n):
return str(datetime . strptime(s, '%Y-%m-%d %H:%M:%S') - timedelta(seconds=n))
| N seconds ago | 5a631508e626c5f127000055 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a631508e626c5f127000055 | 7 kyu |
<p>A rectangle can be split up into a grid of 1x1 squares, the amount of which being equal to the product of the two dimensions of the rectangle. Depending on the size of the rectangle, that grid of 1x1 squares can also be split up into larger squares, for example a 3x2 rectangle has a total of 8 squares, as there are ... | algorithms | def findSquares(x, y):
return sum((x - i) * (y - i) for i in range(y))
| Squares in a Rectangle | 5a62da60d39ec5d947000093 | [
"Mathematics",
"Algorithms"
] | https://www.codewars.com/kata/5a62da60d39ec5d947000093 | 6 kyu |
## Task:
* Complete the pattern using the following set of characters: `■`,` `, `◥`, `◤`, `◣`, `◢`
* In this kata, we need draw a Heart.
## Rules:
- parameter `n` The width of heart, an even number, n>=6, the heart's height increases with n, look at example.
- return a string, `■ ◥◤◣◢` represents th... | games | def draw(n):
shape = ['◢' + (n / / 2 - 2) * '■' + '◣◢' + (n / / 2 - 2) * '■' + '◣']
shape . extend(n / / 6 * ['■' * n])
shape . extend(['◥' + i * 2 * '■' + '◤' for i in range(n / / 2 - 1, - 1, - 1)])
return '\n' . join(row . center(n, ' ') for row in shape)
| ■□ Pattern □■ : Heart | 56e8d06029035a0c7c001d85 | [
"ASCII Art"
] | https://www.codewars.com/kata/56e8d06029035a0c7c001d85 | 6 kyu |
Given three arrays of integers, return the sum of elements that are common in all three arrays.
For example:
```
common([1,2,3],[5,3,2],[7,3,2]) = 5 because 2 & 3 are common in all 3 arrays
common([1,2,2,3],[5,3,2,2],[7,3,2,2]) = 7 because 2,2 & 3 are common in the 3 arrays
```
More examples in the test cases.
Go... | algorithms | from collections import Counter
def common(a, b, c):
return sum((Counter(a) & Counter(b) & Counter(c)). elements())
| Common array elements | 5a6225e5d8e145b540000127 | [
"Arrays",
"Performance",
"Algorithms"
] | https://www.codewars.com/kata/5a6225e5d8e145b540000127 | 6 kyu |
### Task
You will be given a string of English digits "stuck" together, like this:
`"zeronineoneoneeighttwoseventhreesixfourtwofive"`
Your task is to split the string into separate digits:
`"zero nine one one eight two seven three six four two five"`
### Examples
```
"three" --> "three"
"eightsix" ... | reference | import re
def uncollapse(digits):
return ' ' . join(re . findall('zero|one|two|three|four|five|six|seven|eight|nine', digits))
| Uncollapse Digits | 5a626fc7fd56cb63c300008c | [
"Regular Expressions",
"Fundamentals"
] | https://www.codewars.com/kata/5a626fc7fd56cb63c300008c | 6 kyu |
In this kata we are focusing on the Numpy python package. You must write a function called `looper` which takes three integers `start, stop and number` as input and returns a list from `start` to `stop` with `number` total values in the list. Five examples are shown below:
```
looper(1, 5, 1) = [1.0]
looper(1, 5, 2) ... | games | from numpy import linspace
def looper(start, stop, number):
return list(linspace(start, stop, number))
| Looper | 5a35f08b9e5f4923790010dc | [
"NumPy",
"Puzzles"
] | https://www.codewars.com/kata/5a35f08b9e5f4923790010dc | 7 kyu |
FizzBuzz is often one of the first programming puzzles people learn. Now undo it with reverse FizzBuzz!
Write a function that accepts a string, which will always be a valid section of FizzBuzz. Your function must return an array that contains the numbers in order to generate the given section of FizzBuzz.
Notes:
- If... | games | def reverse_fizzbuzz(s):
if s == 'Fizz':
return [3]
if s == 'Buzz':
return [5]
if s == 'Fizz Buzz':
return [9, 10]
if s == 'Buzz Fizz':
return [5, 6]
if s == 'FizzBuzz':
return [15]
s = s . split()
for i in range(len(s)):
if s[i]. isdi... | Reverse FizzBuzz | 5a622f5f85bef7a9e90009e2 | [
"Puzzles"
] | https://www.codewars.com/kata/5a622f5f85bef7a9e90009e2 | 6 kyu |
Given an array of ints, return the index such that the sum of the elements to the right of that index equals the sum of the elements to the left of that index. If there is no such index, return `-1`. If there is more than one such index, return the left-most index.
For example:
```
peak([1,2,3,5,3,2,1]) = 3, because ... | algorithms | def peak(arr):
for i, val in enumerate(arr):
if sum(arr[: i]) == sum(arr[i + 1:]):
return i
return - 1
| Peak array index | 5a61a846cadebf9738000076 | [
"Arrays",
"Algorithms"
] | https://www.codewars.com/kata/5a61a846cadebf9738000076 | 7 kyu |
You are trying to cross a river by jumping along stones. Every time you land on a stone, you hop forwards by the value of that stone. If you skip *over* a stone then its value doesn't affect you in any way. Eg:
```
x--x-----x-->
[1][2][5][1]
```
Of course, crossing from the other side might give you a different ans... | reference | def hop_across(lst):
def one_side(lst):
i = 0
steps = 0
while i < len(lst):
i += lst[i]
steps += 1
return steps
return one_side(lst) + one_side(lst[:: - 1])
| Hop Across | 5a60d519400f93fc450032e5 | [
"Fundamentals"
] | https://www.codewars.com/kata/5a60d519400f93fc450032e5 | 7 kyu |
Consider an array containing cats and dogs. Each dog can catch only one cat, but cannot catch a cat that is more than `n` elements away. Your task will be to return the maximum number of cats that can be caught.
For example:
```Haskell
solve(['D','C','C','D','C'], 2) = 2, because the dog at index 0 (D0) catches C1 and... | algorithms | def solve(arr, reach):
dogs, nCats = {i for i, x in enumerate(arr) if x == 'D'}, 0
for i, c in enumerate(arr):
if c == 'C':
catchingDog = next(
(i + id for id in range(- reach, reach + 1) if i + id in dogs), None)
if catchingDog is not None:
nCats += 1
dogs . remove(catchingD... | Arrays of cats and dogs | 5a5f48f2880385daac00006c | [
"Algorithms"
] | https://www.codewars.com/kata/5a5f48f2880385daac00006c | 6 kyu |
Write a function that returns an array with each element representing one bit of a 32 bit integer in such a way that if printed it would appear as the binary representation of the integer (Least Significant Bit on the right).
e.g. 1 = 00000000000000000000000000000001
Assign either a 1 or a 0 to the array element dep... | algorithms | def showBits(n):
return list(map(int, '{:032b}' . format(n if n >= 0 else 2 * * 32 + n)))
| Binary Representation of an Integer | 5a5f3034cadebf76db000023 | [
"Binary",
"Algorithms"
] | https://www.codewars.com/kata/5a5f3034cadebf76db000023 | 7 kyu |
Simple transposition is a basic and simple cryptography technique. We make 2 rows and put first a letter in the Row 1, the second in the Row 2, third in Row 1 and so on until the end. Then we put the text from Row 2 next to the Row 1 text and thats it.
Complete the function that receives a string and encrypt it with t... | reference | def simple_transposition(text):
return text[:: 2] + text[1:: 2]
| Simple transposition | 57a153e872292d7c030009d4 | [
"Algorithms",
"Cryptography",
"Fundamentals"
] | https://www.codewars.com/kata/57a153e872292d7c030009d4 | 6 kyu |
I often send "bit letter" to my colleagues to talk about our boss or what do we have for dinner.
A bit letter takes 1 char, just like ASCII, but there are some "parameters" in upper 3 bits to describe it.
```
0 0 0 0 0 0 0 0
[punctuation] [capital] [letter index]
```
###### [punctuation]... | reference | def bit_letter(n):
def code(n):
x, i = divmod(n, 32)
p, c = divmod(x, 2)
return ' ' * (p == 1) + chr(97 + i - c * 32) + ',.' [p - 2] * (p > 1)
return '' . join(code(i) for i in n)
| Bit Letters | 580f5818a88b4a5b2500061d | [
"Fundamentals"
] | https://www.codewars.com/kata/580f5818a88b4a5b2500061d | 6 kyu |
Every positive integer can be written as a sum of [Fibonacci numbers](https://en.wikipedia.org/wiki/Fibonacci_number). For example `10 = 8 + 2` _or_ `5 + 3 + 2` _or_ `3 + 3 + 2 + 2`. Apparently, this representation is not unique.
It becomes unique, if we rule out *consecutive* Fibonacci numbers: this is [Zeckendorf's ... | reference | def Zeckendorf_rep(n):
if n >= 0:
fibs, res = [1, 2], []
while fibs[- 1] < n:
fibs . append(sum(fibs[- 2:]))
while n > 0:
x = fibs . pop()
if x <= n:
res . append(x)
n -= x
return res
| Zeckendorf representation | 555b605a76962690ea0000c8 | [
"Fundamentals"
] | https://www.codewars.com/kata/555b605a76962690ea0000c8 | 6 kyu |
# Let's watch a parade!
## Brief
You're going to watch a parade, but you only care about one of the groups marching. The parade passes through the street where your house is. Your house is at number `location` of the street. Write a function `parade_time` that will tell you the times when you need to appear to see all ... | algorithms | def parade_time(groups, location, speed, pref):
return [c / / speed for c, p in enumerate(groups, 1 + location) if p == pref]
| Time to Watch a Parade! | 560d41fd7e0b946ac700011c | [
"Algorithms"
] | https://www.codewars.com/kata/560d41fd7e0b946ac700011c | 7 kyu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.