instance_id int64 0 132 | instance_name stringlengths 3 24 | instruction stringlengths 194 12.1k | signature stringlengths 24 10.6k | test stringlengths 515 24.4k |
|---|---|---|---|---|
0 | accumulate | # Instructions
Implement the `accumulate` operation, which, given a collection and an operation to perform on each element of the collection, returns a new collection containing the result of applying that operation to each element of the input collection.
Given the collection of numbers:
- 1, 2, 3, 4, 5
And the op... | def accumulate(collection, operation):
pass
| import unittest
from accumulate import accumulate
class AccumulateTest(unittest.TestCase):
def test_empty_sequence(self):
self.assertEqual(accumulate([], lambda x: x / 2), [])
def test_pow(self):
self.assertEqual(
accumulate([1, 2, 3, 4, 5], lambda x: x * x), [1, 4, 9, 16, 25])
... |
1 | acronym | # Instructions
Convert a phrase to its acronym.
Techies love their TLA (Three Letter Acronyms)!
Help generate some jargon by writing a program that converts a long name like Portable Network Graphics to its acronym (PNG).
Punctuation is handled as follows: hyphens are word separators (like whitespace); all other pu... | def abbreviate(words):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/acronym/canonical-data.json
# File last updated on 2023-07-20
import unittest
from acronym import (
abbreviate,
)
class AcronymTest(unittest.TestCase):
def test_basic(self):
... |
2 | affine_cipher | # Instructions
Create an implementation of the affine cipher, an ancient encryption system created in the Middle East.
The affine cipher is a type of monoalphabetic substitution cipher.
Each character is mapped to its numeric equivalent, encrypted with a mathematical function and then converted to the letter relating... | def encode(plain_text, a, b):
pass
def decode(ciphered_text, a, b):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/affine-cipher/canonical-data.json
# File last updated on 2023-07-20
import unittest
from affine_cipher import (
decode,
encode,
)
class AffineCipherTest(unittest.TestCase):
def ... |
3 | all_your_base | # Introduction
You've just been hired as professor of mathematics.
Your first week went well, but something is off in your second week.
The problem is that every answer given by your students is wrong!
Luckily, your math skills have allowed you to identify the problem: the student answers _are_ correct, but they're al... | def rebase(input_base, digits, output_base):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/all-your-base/canonical-data.json
# File last updated on 2023-07-20
import unittest
from all_your_base import (
rebase,
)
class AllYourBaseTest(unittest.TestCase):
def test_single_b... |
4 | allergies | # Instructions
Given a person's allergy score, determine whether or not they're allergic to a given item, and their full list of allergies.
An allergy test produces a single numeric score which contains the information about all the allergies the person has (that they were tested for).
The list of items (and their v... | class Allergies:
def __init__(self, score):
pass
def allergic_to(self, item):
pass
@property
def lst(self):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/allergies/canonical-data.json
# File last updated on 2023-07-20
import unittest
from allergies import (
Allergies,
)
class AllergiesTest(unittest.TestCase):
def test_eggs_not_allerg... |
5 | alphametics | # Instructions
Given an alphametics puzzle, find the correct solution.
[Alphametics][alphametics] is a puzzle where letters in words are replaced with numbers.
For example `SEND + MORE = MONEY`:
```text
S E N D
M O R E +
-----------
M O N E Y
```
Replacing these with valid numbers gives:
```text
9 5 6 7
1... | def solve(puzzle):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/alphametics/canonical-data.json
# File last updated on 2023-07-20
import unittest
from alphametics import (
solve,
)
class AlphameticsTest(unittest.TestCase):
def test_puzzle_with_t... |
6 | anagram | # Introduction
At a garage sale, you find a lovely vintage typewriter at a bargain price!
Excitedly, you rush home, insert a sheet of paper, and start typing away.
However, your excitement wanes when you examine the output: all words are garbled!
For example, it prints "stop" instead of "post" and "least" instead of "... | def find_anagrams(word, candidates):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/anagram/canonical-data.json
# File last updated on 2024-02-28
import unittest
from anagram import (
find_anagrams,
)
class AnagramTest(unittest.TestCase):
def test_no_matches(self):... |
7 | armstrong_numbers | # Instructions
An [Armstrong number][armstrong-number] is a number that is the sum of its own digits each raised to the power of the number of digits.
For example:
- 9 is an Armstrong number, because `9 = 9^1 = 9`
- 10 is _not_ an Armstrong number, because `10 != 1^2 + 0^2 = 1`
- 153 is an Armstrong number, because:... | def is_armstrong_number(number):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/armstrong-numbers/canonical-data.json
# File last updated on 2023-07-20
import unittest
from armstrong_numbers import (
is_armstrong_number,
)
class ArmstrongNumbersTest(unittest.TestCa... |
8 | atbash_cipher | # Instructions
Create an implementation of the atbash cipher, an ancient encryption system created in the Middle East.
The Atbash cipher is a simple substitution cipher that relies on transposing all the letters in the alphabet such that the resulting alphabet is backwards.
The first letter is replaced with the last ... | def encode(plain_text):
pass
def decode(ciphered_text):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/atbash-cipher/canonical-data.json
# File last updated on 2023-07-20
import unittest
from atbash_cipher import (
decode,
encode,
)
class AtbashCipherTest(unittest.TestCase):
def ... |
9 | bank_account | # Introduction
After years of filling out forms and waiting, you've finally acquired your banking license.
This means you are now officially eligible to open your own bank, hurray!
Your first priority is to get the IT systems up and running.
After a day of hard work, you can already open and close accounts, as well a... | class BankAccount:
def __init__(self):
pass
def get_balance(self):
pass
def open(self):
pass
def deposit(self, amount):
pass
def withdraw(self, amount):
pass
def close(self):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/bank-account/canonical-data.json
# File last updated on 2023-07-20
import unittest
from bank_account import (
BankAccount,
)
class BankAccountTest(unittest.TestCase):
def test_newly... |
10 | beer_song | # Instructions
Recite the lyrics to that beloved classic, that field-trip favorite: 99 Bottles of Beer on the Wall.
Note that not all verses are identical.
```text
99 bottles of beer on the wall, 99 bottles of beer.
Take one down and pass it around, 98 bottles of beer on the wall.
98 bottles of beer on the wall, 98... | def recite(start, take=1):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/beer-song/canonical-data.json
# File last updated on 2023-07-20
import unittest
from beer_song import (
recite,
)
class BeerSongTest(unittest.TestCase):
def test_first_generic_verse... |
11 | binary | # Instructions
Convert a binary number, represented as a string (e.g. '101010'), to its decimal equivalent using first principles.
Implement binary to decimal conversion.
Given a binary input string, your program should produce a decimal output.
The program should handle invalid inputs.
## Note
- Implement the conv... | def parse_binary(binary_string):
pass
| """Tests for the binary exercise
Implementation note:
If the argument to parse_binary isn't a valid binary number the
function should raise a ValueError with a meaningful error message.
"""
import unittest
from binary import parse_binary
class BinaryTest(unittest.TestCase):
def test_binary_1_is_decimal_1(self):... |
12 | binary_search | # Introduction
You have stumbled upon a group of mathematicians who are also singer-songwriters.
They have written a song for each of their favorite numbers, and, as you can imagine, they have a lot of favorite numbers (like [0][zero] or [73][seventy-three] or [6174][kaprekars-constant]).
You are curious to hear the ... | def find(search_list, value):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/binary-search/canonical-data.json
# File last updated on 2023-07-20
import unittest
from binary_search import (
find,
)
class BinarySearchTest(unittest.TestCase):
def test_finds_a_v... |
13 | binary_search_tree | # Instructions
Insert and search for numbers in a binary tree.
When we need to represent sorted data, an array does not make a good data structure.
Say we have the array `[1, 3, 4, 5]`, and we add 2 to it so it becomes `[1, 3, 4, 5, 2]`.
Now we must sort the entire array again!
We can improve on this by realizing th... | class TreeNode:
def __init__(self, data, left=None, right=None):
self.data = None
self.left = None
self.right = None
def __str__(self):
return f'TreeNode(data={self.data}, left={self.left}, right={self.right})'
class BinarySearchTree:
def __init__(self, tree_data):
... | # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/binary-search-tree/canonical-data.json
# File last updated on 2023-07-20
import unittest
from binary_search_tree import (
BinarySearchTree,
TreeNode,
)
class BinarySearchTreeTest(un... |
14 | bob | # Introduction
Bob is a [lackadaisical][] teenager.
He likes to think that he's very cool.
And he definitely doesn't get excited about things.
That wouldn't be cool.
When people talk to him, his responses are pretty limited.
[lackadaisical]: https://www.collinsdictionary.com/dictionary/english/lackadaisical
# Instru... | def response(hey_bob):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/bob/canonical-data.json
# File last updated on 2023-07-20
import unittest
from bob import (
response,
)
class BobTest(unittest.TestCase):
def test_stating_something(self):
s... |
15 | book_store | # Instructions
To try and encourage more sales of different books from a popular 5 book series, a bookshop has decided to offer discounts on multiple book purchases.
One copy of any of the five books costs $8.
If, however, you buy two different books, you get a 5% discount on those two books.
If you buy 3 different... | def total(basket):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/book-store/canonical-data.json
# File last updated on 2023-07-20
import unittest
from book_store import (
total,
)
class BookStoreTest(unittest.TestCase):
def test_only_a_single_boo... |
16 | bottle_song | # Instructions
Recite the lyrics to that popular children's repetitive song: Ten Green Bottles.
Note that not all verses are identical.
```text
Ten green bottles hanging on the wall,
Ten green bottles hanging on the wall,
And if one green bottle should accidentally fall,
There'll be nine green bottles hanging on the... | def recite(start, take=1):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/bottle-song/canonical-data.json
# File last updated on 2023-07-20
import unittest
from bottle_song import (
recite,
)
class BottleSongTest(unittest.TestCase):
def test_first_generic... |
17 | bowling | # Instructions
Score a bowling game.
Bowling is a game where players roll a heavy ball to knock down pins arranged in a triangle.
Write code to keep track of the score of a game of bowling.
## Scoring Bowling
The game consists of 10 frames.
A frame is composed of one or two ball throws with 10 pins standing at fram... | class BowlingGame:
def __init__(self):
pass
def roll(self, pins):
pass
def score(self):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/bowling/canonical-data.json
# File last updated on 2023-07-21
import unittest
from bowling import (
BowlingGame,
)
class BowlingTest(unittest.TestCase):
def roll_new_game(self, roll... |
18 | change | # Instructions
Correctly determine the fewest number of coins to be given to a customer such that the sum of the coins' value would equal the correct amount of change.
## For example
- An input of 15 with [1, 5, 10, 25, 100] should return one nickel (5) and one dime (10) or [5, 10]
- An input of 40 with [1, 5, 10, 2... | def find_fewest_coins(coins, target):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/change/canonical-data.json
# File last updated on 2024-03-05
import unittest
from change import (
find_fewest_coins,
)
class ChangeTest(unittest.TestCase):
def test_change_for_1_cen... |
19 | circular_buffer | # Instructions
A circular buffer, cyclic buffer or ring buffer is a data structure that uses a single, fixed-size buffer as if it were connected end-to-end.
A circular buffer first starts empty and of some predefined length.
For example, this is a 7-element buffer:
```text
[ ][ ][ ][ ][ ][ ][ ]
```
Assume that a 1 ... | class BufferFullException(BufferError):
"""Exception raised when CircularBuffer is full.
message: explanation of the error.
"""
def __init__(self, message):
pass
class BufferEmptyException(BufferError):
"""Exception raised when CircularBuffer is empty.
message: explanation of the er... | # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/circular-buffer/canonical-data.json
# File last updated on 2023-07-20
import unittest
from circular_buffer import (
CircularBuffer,
BufferEmptyException,
BufferFullException,
)
... |
20 | clock | # Instructions
Implement a clock that handles times without dates.
You should be able to add and subtract minutes to it.
Two clocks that represent the same time should be equal to each other.
# Instructions append
The tests for this exercise expect your clock will be implemented via a Clock `class` in Python.
If yo... | class Clock:
def __init__(self, hour, minute):
pass
def __repr__(self):
pass
def __str__(self):
pass
def __eq__(self, other):
pass
def __add__(self, minutes):
pass
def __sub__(self, minutes):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/clock/canonical-data.json
# File last updated on 2023-07-20
import unittest
from clock import (
Clock,
)
class ClockTest(unittest.TestCase):
# Create A String Representation
def... |
21 | collatz_conjecture | # Instructions
The Collatz Conjecture or 3x+1 problem can be summarized as follows:
Take any positive integer n.
If n is even, divide n by 2 to get n / 2.
If n is odd, multiply n by 3 and add 1 to get 3n + 1.
Repeat the process indefinitely.
The conjecture states that no matter which number you start with, you will a... | def steps(number):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/collatz-conjecture/canonical-data.json
# File last updated on 2023-07-20
import unittest
from collatz_conjecture import (
steps,
)
class CollatzConjectureTest(unittest.TestCase):
de... |
22 | complex_numbers | # Instructions
A complex number is a number in the form `a + b * i` where `a` and `b` are real and `i` satisfies `i^2 = -1`.
`a` is called the real part and `b` is called the imaginary part of `z`.
The conjugate of the number `a + b * i` is the number `a - b * i`.
The absolute value of a complex number `z = a + b * i... | class ComplexNumber:
def __init__(self, real, imaginary):
pass
def __eq__(self, other):
pass
def __add__(self, other):
pass
def __mul__(self, other):
pass
def __sub__(self, other):
pass
def __truediv__(self, other):
pass
def __abs__(self)... | # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/complex-numbers/canonical-data.json
# File last updated on 2023-07-19
import math
import unittest
from complex_numbers import (
ComplexNumber,
)
class ComplexNumbersTest(unittest.TestCa... |
23 | connect | # Instructions
Compute the result for a game of Hex / Polygon.
The abstract boardgame known as [Hex][hex] / Polygon / CON-TAC-TIX is quite simple in rules, though complex in practice.
Two players place stones on a parallelogram with hexagonal fields.
The player to connect his/her stones to the opposite side first win... |
class ConnectGame:
def __init__(self, board):
pass
def get_winner(self):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/connect/canonical-data.json
# File last updated on 2023-07-19
import unittest
from connect import (
ConnectGame,
)
class ConnectTest(unittest.TestCase):
def test_an_empty_board_has_... |
24 | crypto_square | # Instructions
Implement the classic method for composing secret messages called a square code.
Given an English text, output the encoded version of that text.
First, the input is normalized: the spaces and punctuation are removed from the English text and the message is down-cased.
Then, the normalized characters ... | def cipher_text(plain_text):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/crypto-square/canonical-data.json
# File last updated on 2023-07-19
import unittest
from crypto_square import (
cipher_text,
)
class CryptoSquareTest(unittest.TestCase):
def test_em... |
25 | custom_set | # Instructions
Create a custom set type.
Sometimes it is necessary to define a custom data structure of some type, like a set.
In this exercise you will define your own set.
How it works internally doesn't matter, as long as it behaves like a set of unique elements.
| class CustomSet:
def __init__(self, elements=[]):
pass
def isempty(self):
pass
def __contains__(self, element):
pass
def issubset(self, other):
pass
def isdisjoint(self, other):
pass
def __eq__(self, other):
pass
def add(self, element):
... | # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/custom-set/canonical-data.json
# File last updated on 2024-07-08
import unittest
from custom_set import (
CustomSet,
)
class CustomSetTest(unittest.TestCase):
def test_sets_with_no_... |
26 | darts | # Instructions
Calculate the points scored in a single toss of a Darts game.
[Darts][darts] is a game where players throw darts at a [target][darts-target].
In our particular instance of the game, the target rewards 4 different amounts of points, depending on where the dart lands:
![Our dart scoreboard with values ... | def score(x, y):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/darts/canonical-data.json
# File last updated on 2023-07-19
import unittest
from darts import (
score,
)
class DartsTest(unittest.TestCase):
def test_missed_target(self):
se... |
27 | diamond | # Instructions
The diamond kata takes as its input a letter, and outputs it in a diamond shape.
Given a letter, it prints a diamond starting with 'A', with the supplied letter at the widest point.
## Requirements
- The first row contains one 'A'.
- The last row contains one 'A'.
- All rows, except the first and last... | def rows(letter):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/diamond/canonical-data.json
# File last updated on 2023-07-19
import unittest
from diamond import (
rows,
)
class DiamondTest(unittest.TestCase):
def test_degenerate_case_with_a_sin... |
28 | difference_of_squares | # Instructions
Find the difference between the square of the sum and the sum of the squares of the first N natural numbers.
The square of the sum of the first ten natural numbers is
(1 + 2 + ... + 10)² = 55² = 3025.
The sum of the squares of the first ten natural numbers is
1² + 2² + ... + 10² = 385.
Hence the diff... | def square_of_sum(number):
pass
def sum_of_squares(number):
pass
def difference_of_squares(number):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/difference-of-squares/canonical-data.json
# File last updated on 2023-07-19
import unittest
from difference_of_squares import (
difference_of_squares,
square_of_sum,
sum_of_square... |
29 | diffie_hellman | # Instructions
Diffie-Hellman key exchange.
Alice and Bob use Diffie-Hellman key exchange to share secrets.
They start with prime numbers, pick private keys, generate and share public keys, and then generate a shared secret key.
## Step 0
The test program supplies prime numbers p and g.
## Step 1
Alice picks a pr... | def private_key(p):
pass
def public_key(p, g, private):
pass
def secret(p, public, private):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/diffie-hellman/canonical-data.json
# File last updated on 2023-07-19
import unittest
from diffie_hellman import (
private_key,
public_key,
secret,
)
class DiffieHellmanTest(unit... |
30 | dnd_character | # Introduction
After weeks of anticipation, you and your friends get together for your very first game of [Dungeons & Dragons][dnd] (D&D).
Since this is the first session of the game, each player has to generate a character to play with.
The character's abilities are determined by rolling 6-sided dice, but where _are_... | class Character:
def __init__(self):
pass
def modifier(value):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/dnd-character/canonical-data.json
# File last updated on 2023-12-27
import unittest
from dnd_character import (
Character,
modifier,
)
class DndCharacterTest(unittest.TestCase):
... |
31 | dominoes | # Instructions
Make a chain of dominoes.
Compute a way to order a given set of dominoes in such a way that they form a correct domino chain (the dots on one half of a stone match the dots on the neighboring half of an adjacent stone) and that dots on the halves of the stones which don't have a neighbor (the first and... | def can_chain(dominoes):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/dominoes/canonical-data.json
# File last updated on 2023-07-19
import unittest
from dominoes import (
can_chain,
)
class DominoesTest(unittest.TestCase):
def test_empty_input_empty_... |
32 | dot_dsl | # Instructions
A [Domain Specific Language (DSL)][dsl] is a small language optimized for a specific domain.
Since a DSL is targeted, it can greatly impact productivity/understanding by allowing the writer to declare _what_ they want rather than _how_.
One problem area where they are applied are complex customizations... | NODE, EDGE, ATTR = range(3)
class Node:
def __init__(self, name, attrs):
self.name = name
self.attrs = attrs
def __eq__(self, other):
return self.name == other.name and self.attrs == other.attrs
class Edge:
def __init__(self, src, dst, attrs):
self.src = src
self... | import unittest
from dot_dsl import Graph, Node, Edge, NODE, EDGE, ATTR
class DotDslTest(unittest.TestCase):
def test_empty_graph(self):
g = Graph()
self.assertEqual(g.nodes, [])
self.assertEqual(g.edges, [])
self.assertEqual(g.attrs, {})
def test_graph_with_one_node(self):
... |
33 | eliuds_eggs | # Introduction
Your friend Eliud inherited a farm from her grandma Tigist.
Her granny was an inventor and had a tendency to build things in an overly complicated manner.
The chicken coop has a digital display showing an encoded number representing the positions of all eggs that could be picked up.
Eliud is asking you... | def egg_count(display_value):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/eliuds-eggs/canonical-data.json
# File last updated on 2024-02-02
import unittest
from eliuds_eggs import (
egg_count,
)
class EliudsEggsTest(unittest.TestCase):
def test_0_eggs(sel... |
34 | error_handling | # Instructions
Implement various kinds of error handling and resource management.
An important point of programming is how to handle errors and close resources even if errors occur.
This exercise requires you to handle various errors.
Because error handling is rather programming language specific you'll have to refe... | def handle_error_by_throwing_exception():
pass
def handle_error_by_returning_none(input_data):
pass
def handle_error_by_returning_tuple(input_data):
pass
def filelike_objects_are_closed_on_exception(filelike_object):
pass
| import unittest
import error_handling as er
class FileLike:
def __init__(self, fail_something=True):
self.is_open = False
self.was_open = False
self.did_something = False
self.fail_something = fail_something
def open(self):
self.was_open = False
self.is_open = ... |
35 | etl | # Introduction
You work for a company that makes an online multiplayer game called Lexiconia.
To play the game, each player is given 13 letters, which they must rearrange to create words.
Different letters have different point values, since it's easier to create words with some letters than others.
The game was orig... | def transform(legacy_data):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/etl/canonical-data.json
# File last updated on 2023-07-19
import unittest
from etl import (
transform,
)
class EtlTest(unittest.TestCase):
def test_single_letter(self):
lega... |
36 | flatten_array | # Instructions
Take a nested list and return a single flattened list with all values except nil/null.
The challenge is to take an arbitrarily-deep nested list-like structure and produce a flattened structure without any nil/null values.
For example:
input: [1,[2,3,null,4],[null],5]
output: [1,2,3,4,5]
| def flatten(iterable):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/flatten-array/canonical-data.json
# File last updated on 2023-07-19
import unittest
from flatten_array import (
flatten,
)
class FlattenArrayTest(unittest.TestCase):
def test_empty(... |
37 | food_chain | # Instructions
Generate the lyrics of the song 'I Know an Old Lady Who Swallowed a Fly'.
While you could copy/paste the lyrics, or read them from a file, this problem is much more interesting if you approach it algorithmically.
This is a [cumulative song][cumulative-song] of unknown origin.
This is one of many comm... | def recite(start_verse, end_verse):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/food-chain/canonical-data.json
# File last updated on 2023-07-19
import unittest
from food_chain import (
recite,
)
class FoodChainTest(unittest.TestCase):
def test_fly(self):
... |
38 | forth | # Instructions
Implement an evaluator for a very simple subset of Forth.
[Forth][forth]
is a stack-based programming language.
Implement a very basic evaluator for a small subset of Forth.
Your evaluator has to support the following words:
- `+`, `-`, `*`, `/` (integer arithmetic)
- `DUP`, `DROP`, `SWAP`, `OVER` (s... | class StackUnderflowError(Exception):
pass
def evaluate(input_data):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/forth/canonical-data.json
# File last updated on 2023-07-19
import unittest
from forth import (
evaluate,
StackUnderflowError,
)
class ForthTest(unittest.TestCase):
def test_par... |
39 | gigasecond | # Introduction
The way we measure time is kind of messy.
We have 60 seconds in a minute, and 60 minutes in an hour.
This comes from ancient Babylon, where they used 60 as the basis for their number system.
We have 24 hours in a day, 7 days in a week, and how many days in a month?
Well, for days in a month it depends n... | def add(moment):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/gigasecond/canonical-data.json
# File last updated on 2023-07-19
from datetime import datetime
import unittest
from gigasecond import (
add,
)
class GigasecondTest(unittest.TestCase):
... |
40 | go_counting | # Instructions
Count the scored points on a Go board.
In the game of go (also known as baduk, igo, cờ vây and wéiqí) points are gained by completely encircling empty intersections with your stones.
The encircled intersections of a player are known as its territory.
Calculate the territory of each player.
You may ass... |
class Board:
"""Count territories of each player in a Go game
Args:
board (list[str]): A two-dimensional Go board
"""
def __init__(self, board):
pass
def territory(self, x, y):
"""Find the owner and the territories given a coordinate on
the board
Args:... | # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/go-counting/canonical-data.json
# File last updated on 2023-07-19
import unittest
from go_counting import (
Board,
WHITE,
BLACK,
NONE,
)
class GoCountingTest(unittest.TestCa... |
41 | grade_school | # Instructions
Given students' names along with the grade that they are in, create a roster for the school.
In the end, you should be able to:
- Add a student's name to the roster for a grade
- "Add Jim to grade 2."
- "OK."
- Get a list of all students enrolled in a grade
- "Which students are in grade 2?"
-... | class School:
def __init__(self):
pass
def add_student(self, name, grade):
pass
def roster(self):
pass
def grade(self, grade_number):
pass
def added(self):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/grade-school/canonical-data.json
# File last updated on 2023-07-19
import unittest
from grade_school import (
School,
)
class GradeSchoolTest(unittest.TestCase):
def test_roster_is_... |
42 | grains | # Instructions
Calculate the number of grains of wheat on a chessboard given that the number on each square doubles.
There once was a wise servant who saved the life of a prince.
The king promised to pay whatever the servant could dream up.
Knowing that the king loved chess, the servant told the king he would like to... | def square(number):
pass
def total():
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/grains/canonical-data.json
# File last updated on 2023-09-27
import unittest
from grains import (
square,
total,
)
class GrainsTest(unittest.TestCase):
def test_grains_on_square... |
43 | grep | # Instructions
Search files for lines matching a search string and return all matching lines.
The Unix [`grep`][grep] command searches files for lines that match a regular expression.
Your task is to implement a simplified `grep` command, which supports searching for fixed strings.
The `grep` command takes three arg... | def grep(pattern, flags, files):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/grep/canonical-data.json
# File last updated on 2023-07-19
import io
import unittest
from grep import (
grep,
)
from unittest import mock
FILE_TEXT = {
"iliad.txt": """Achilles sing,... |
44 | hamming | # Instructions
Calculate the Hamming Distance between two DNA strands.
Your body is made up of cells that contain DNA.
Those cells regularly wear out and need replacing, which they achieve by dividing into daughter cells.
In fact, the average human body experiences about 10 quadrillion cell divisions in a lifetime!
... | def distance(strand_a, strand_b):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/hamming/canonical-data.json
# File last updated on 2023-07-19
import unittest
from hamming import (
distance,
)
class HammingTest(unittest.TestCase):
def test_empty_strands(self):
... |
45 | hangman | # Instructions
Implement the logic of the hangman game using functional reactive programming.
[Hangman][hangman] is a simple word guessing game.
[Functional Reactive Programming][frp] is a way to write interactive programs.
It differs from the usual perspective in that instead of saying "when the button is pressed i... | # Game status categories
# Change the values as you see fit
STATUS_WIN = 'win'
STATUS_LOSE = 'lose'
STATUS_ONGOING = 'ongoing'
class Hangman:
def __init__(self, word):
self.remaining_guesses = 9
self.status = STATUS_ONGOING
def guess(self, char):
pass
def get_masked_word(self):
... | import unittest
import hangman
from hangman import Hangman
# Tests adapted from csharp//hangman/HangmanTest.cs
class HangmanTests(unittest.TestCase):
def test_initially_9_failures_are_allowed(self):
game = Hangman('foo')
self.assertEqual(game.get_status(), hangman.STATUS_ONGOING)
self.as... |
46 | hello_world | # Instructions
The classical introductory exercise.
Just say "Hello, World!".
["Hello, World!"][hello-world] is the traditional first program for beginning programming in a new language or environment.
The objectives are simple:
- Modify the provided code so that it produces the string "Hello, World!".
- Run the te... | def hello():
return 'Goodbye, Mars!'
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/hello-world/canonical-data.json
# File last updated on 2023-07-19
import unittest
try:
from hello_world import (
hello,
)
except ImportError as import_fail:
message = imp... |
47 | hexadecimal | # Instructions
Convert a hexadecimal number, represented as a string (e.g. "10af8c"), to its decimal equivalent using first principles (i.e. no, you may not use built-in or external libraries to accomplish the conversion).
On the web we use hexadecimal to represent colors, e.g. green: 008000, teal: 008080, navy: 0000... | def hexa(hex_string):
pass
| # To avoid trivial solutions, try to solve this problem without the
# function int(s, base=16)
import unittest
from hexadecimal import hexa
class HexadecimalTest(unittest.TestCase):
def test_valid_hexa1(self):
self.assertEqual(hexa('1'), 1)
def test_valid_hexa2(self):
self.assertEqual(hexa(... |
48 | high_scores | # Instructions
Manage a game player's High Score list.
Your task is to build a high-score component of the classic Frogger game, one of the highest selling and most addictive games of all time, and a classic of the arcade era.
Your task is to write methods that return the highest score from the list, the last added s... | class HighScores:
def __init__(self, scores):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/high-scores/canonical-data.json
# File last updated on 2023-07-19
import unittest
from high_scores import (
HighScores,
)
class HighScoresTest(unittest.TestCase):
def test_list_of_s... |
49 | house | # Instructions
Recite the nursery rhyme 'This is the House that Jack Built'.
> [The] process of placing a phrase of clause within another phrase of clause is called embedding.
> It is through the processes of recursion and embedding that we are able to take a finite number of forms (words and phrases) and construct a... | def recite(start_verse, end_verse):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/house/canonical-data.json
# File last updated on 2023-07-19
import unittest
from house import (
recite,
)
class HouseTest(unittest.TestCase):
def test_verse_one_the_house_that_jack_... |
50 | isbn_verifier | # Instructions
The [ISBN-10 verification process][isbn-verification] is used to validate book identification numbers.
These normally contain dashes and look like: `3-598-21508-8`
## ISBN
The ISBN-10 format is 9 digits (0 to 9) plus one check character (either a digit or an X only).
In the case the check character is... | def is_valid(isbn):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/isbn-verifier/canonical-data.json
# File last updated on 2023-07-19
import unittest
from isbn_verifier import (
is_valid,
)
class IsbnVerifierTest(unittest.TestCase):
def test_valid... |
51 | isogram | # Instructions
Determine if a word or phrase is an isogram.
An isogram (also known as a "non-pattern word") is a word or phrase without a repeating letter, however spaces and hyphens are allowed to appear multiple times.
Examples of isograms:
- lumberjacks
- background
- downstream
- six-year-old
The word _isogram... | def is_isogram(string):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/isogram/canonical-data.json
# File last updated on 2023-07-19
import unittest
from isogram import (
is_isogram,
)
class IsogramTest(unittest.TestCase):
def test_empty_string(self):
... |
52 | killer_sudoku_helper | # Instructions
A friend of yours is learning how to solve Killer Sudokus (rules below) but struggling to figure out which digits can go in a cage.
They ask you to help them out by writing a small program that lists all valid combinations for a given cage, and any constraints that affect the cage.
To make the output o... | def combinations(target, size, exclude):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/killer-sudoku-helper/canonical-data.json
# File last updated on 2023-07-19
import unittest
from killer_sudoku_helper import (
combinations,
)
class KillerSudokuHelperTest(unittest.TestC... |
53 | kindergarten_garden | # Introduction
The kindergarten class is learning about growing plants.
The teacher thought it would be a good idea to give the class seeds to plant and grow in the dirt.
To this end, the children have put little cups along the window sills and planted one type of plant in each cup.
The children got to pick their favo... | class Garden:
def __init__(self, diagram, students):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/kindergarten-garden/canonical-data.json
# File last updated on 2023-07-19
import unittest
from kindergarten_garden import (
Garden,
)
class KindergartenGardenTest(unittest.TestCase):
... |
54 | knapsack | # Introduction
Bob is a thief.
After months of careful planning, he finally manages to crack the security systems of a fancy store.
In front of him are many items, each with a value and weight.
Bob would gladly take all of the items, but his knapsack can only hold so much weight.
Bob has to carefully consider which i... | def maximum_value(maximum_weight, items):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/knapsack/canonical-data.json
# File last updated on 2023-12-27
import unittest
from knapsack import (
maximum_value,
)
class KnapsackTest(unittest.TestCase):
def test_no_items(self)... |
55 | largest_series_product | # Introduction
You work for a government agency that has intercepted a series of encrypted communication signals from a group of bank robbers.
The signals contain a long sequence of digits.
Your team needs to use various digital signal processing techniques to analyze the signals and identify any patterns that may ind... | def largest_product(series, size):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/largest-series-product/canonical-data.json
# File last updated on 2023-07-19
import unittest
from largest_series_product import (
largest_product,
)
class LargestSeriesProductTest(unitt... |
56 | leap | # Introduction
A leap year (in the Gregorian calendar) occurs:
- In every year that is evenly divisible by 4.
- Unless the year is evenly divisible by 100, in which case it's only a leap year if the year is also evenly divisible by 400.
Some examples:
- 1997 was not a leap year as it's not divisible by 4.
- 1900 wa... | def leap_year(year):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/leap/canonical-data.json
# File last updated on 2023-07-19
import unittest
from leap import (
leap_year,
)
class LeapTest(unittest.TestCase):
def test_year_not_divisible_by_4_in_com... |
57 | ledger | # Instructions
Refactor a ledger printer.
The ledger exercise is a refactoring exercise.
There is code that prints a nicely formatted ledger, given a locale (American or Dutch) and a currency (US dollar or euro).
The code however is rather badly written, though (somewhat surprisingly) it consistently passes the test ... | # -*- coding: utf-8 -*-
from datetime import datetime
class LedgerEntry:
def __init__(self):
self.date = None
self.description = None
self.change = None
def create_entry(date, description, change):
entry = LedgerEntry()
entry.date = datetime.strptime(date, '%Y-%m-%d')
entry.d... | # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/ledger/canonical-data.json
# File last updated on 2023-12-27
import unittest
from ledger import (
format_entries,
create_entry,
)
class LedgerTest(unittest.TestCase):
maxDiff = ... |
58 | linked_list | # Introduction
You are working on a project to develop a train scheduling system for a busy railway network.
You've been asked to develop a prototype for the train routes in the scheduling system.
Each route consists of a sequence of train stations that a given train stops at.
# Instructions
Your team has decided to... | class Node:
def __init__(self, value, succeeding=None, previous=None):
pass
class LinkedList:
def __init__(self):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/linked-list/canonical-data.json
# File last updated on 2023-07-19
import unittest
from linked_list import (
LinkedList,
)
class LinkedListTest(unittest.TestCase):
def test_pop_gets_... |
59 | list_ops | # Instructions
Implement basic list operations.
In functional languages list operations like `length`, `map`, and `reduce` are very common.
Implement a series of basic list operations, without using existing functions.
The precise number and names of the operations to be implemented will be track dependent to avoid ... | def append(list1, list2):
pass
def concat(lists):
pass
def filter(function, list):
pass
def length(list):
pass
def map(function, list):
pass
def foldl(function, list, initial):
pass
def foldr(function, list, initial):
pass
def reverse(list):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/list-ops/canonical-data.json
# File last updated on 2023-07-19
import unittest
from list_ops import (
append,
concat,
foldl,
foldr,
length,
reverse,
filter as list... |
60 | luhn | # Instructions
Given a number determine whether or not it is valid per the Luhn formula.
The [Luhn algorithm][luhn] is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers and Canadian Social Insurance Numbers.
The task is to check if a given string is valid.
#... | class Luhn:
def __init__(self, card_num):
pass
def valid(self):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/luhn/canonical-data.json
# File last updated on 2023-07-19
import unittest
from luhn import (
Luhn,
)
class LuhnTest(unittest.TestCase):
def test_single_digit_strings_can_not_be_val... |
61 | markdown | # Instructions
Refactor a Markdown parser.
The markdown exercise is a refactoring exercise.
There is code that parses a given string with [Markdown syntax][markdown] and returns the associated HTML for that string.
Even though this code is confusingly written and hard to follow, somehow it works and all the tests are... | import re
def parse(markdown):
lines = markdown.split('\n')
res = ''
in_list = False
in_list_append = False
for i in lines:
if re.match('###### (.*)', i) is not None:
i = '<h6>' + i[7:] + '</h6>'
elif re.match('##### (.*)', i) is not None:
i = '<h5>' + i[6:]... | # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/markdown/canonical-data.json
# File last updated on 2023-07-19
import unittest
from markdown import (
parse,
)
class MarkdownTest(unittest.TestCase):
def test_parses_normal_text_as_... |
62 | matching_brackets | # Introduction
You're given the opportunity to write software for the Bracketeer™, an ancient but powerful mainframe.
The software that runs on it is written in a proprietary language.
Much of its syntax is familiar, but you notice _lots_ of brackets, braces and parentheses.
Despite the Bracketeer™ being powerful, it ... | def is_paired(input_string):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/matching-brackets/canonical-data.json
# File last updated on 2023-07-19
import unittest
from matching_brackets import (
is_paired,
)
class MatchingBracketsTest(unittest.TestCase):
d... |
63 | matrix | # Instructions
Given a string representing a matrix of numbers, return the rows and columns of that matrix.
So given a string with embedded newlines like:
```text
9 8 7
5 3 2
6 6 7
```
representing this matrix:
```text
1 2 3
|---------
1 | 9 8 7
2 | 5 3 2
3 | 6 6 7
```
your code should be able to sp... | class Matrix:
def __init__(self, matrix_string):
pass
def row(self, index):
pass
def column(self, index):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/matrix/canonical-data.json
# File last updated on 2023-07-19
import unittest
from matrix import (
Matrix,
)
class MatrixTest(unittest.TestCase):
def test_extract_row_from_one_number... |
64 | meetup | # Introduction
Every month, your partner meets up with their best friend.
Both of them have very busy schedules, making it challenging to find a suitable date!
Given your own busy schedule, your partner always double-checks potential meetup dates with you:
- "Can I meet up on the first Friday of next month?"
- "What ... | # subclassing the built-in ValueError to create MeetupDayException
class MeetupDayException(ValueError):
"""Exception raised when the Meetup weekday and count do not result in a valid date.
message: explanation of the error.
"""
def __init__(self):
pass
def meetup(year, month, week, day_of_w... | # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/meetup/canonical-data.json
# File last updated on 2023-07-19
from datetime import date
import unittest
from meetup import (
meetup,
MeetupDayException,
)
class MeetupTest(unittest.T... |
65 | minesweeper | # Introduction
[Minesweeper][wikipedia] is a popular game where the user has to find the mines using numeric hints that indicate how many mines are directly adjacent (horizontally, vertically, diagonally) to a square.
[wikipedia]: https://en.wikipedia.org/wiki/Minesweeper_(video_game)
# Instructions
Your task is to ... | def annotate(minefield):
# Function body starts here
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/minesweeper/canonical-data.json
# File last updated on 2023-07-19
import unittest
from minesweeper import (
annotate,
)
class MinesweeperTest(unittest.TestCase):
def test_no_rows(se... |
66 | nth_prime | # Instructions
Given a number n, determine what the nth prime is.
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
If your language provides methods in the standard library to deal with prime numbers, pretend they don't exist and implement them yourself.
# Instruct... | def prime(number):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/nth-prime/canonical-data.json
# File last updated on 2023-07-19
import unittest
from nth_prime import (
prime,
)
def prime_range(n):
"""Returns a list of the first n primes"""
r... |
67 | ocr_numbers | # Instructions
Given a 3 x 4 grid of pipes, underscores, and spaces, determine which number is represented, or whether it is garbled.
## Step One
To begin with, convert a simple binary font to a string containing 0 or 1.
The binary font uses pipes and underscores, four rows high and three columns wide.
```text
... | def convert(input_grid):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/ocr-numbers/canonical-data.json
# File last updated on 2023-07-19
import unittest
from ocr_numbers import (
convert,
)
class OcrNumbersTest(unittest.TestCase):
def test_recognizes_0... |
68 | octal | # Instructions
Convert an octal number, represented as a string (e.g. '1735263'), to its decimal equivalent using first principles (i.e. no, you may not use built-in or external libraries to accomplish the conversion).
Implement octal to decimal conversion.
Given an octal input string, your program should produce a d... | def parse_octal(digits):
pass
| """Tests for the octal exercise
Implementation note:
If the string supplied to parse_octal cannot be parsed as an octal number
your program should raise a ValueError with a meaningful error message.
"""
import unittest
from octal import parse_octal
class OctalTest(unittest.TestCase):
def test_octal_1_is_decimal... |
69 | paasio | # Instructions
Report network IO statistics.
You are writing a [PaaS][paas], and you need a way to bill customers based on network and filesystem usage.
Create a wrapper for network connections and files that can report IO statistics.
The wrapper must report:
- The total number of bytes read/written.
- The total nu... | import io
class MeteredFile(io.BufferedRandom):
"""Implement using a subclassing model."""
def __init__(self, *args, **kwargs):
pass
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def __iter__(self):
pass
def __next__(self):
... | import errno
import os
import unittest
from unittest.mock import ANY, call, NonCallableMagicMock, patch
from paasio import MeteredFile, MeteredSocket
import errno
import inspect
import io
import os
ZEN = b"""Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is b... |
70 | palindrome_products | # Instructions
Detect palindrome products in a given range.
A palindromic number is a number that remains the same when its digits are reversed.
For example, `121` is a palindromic number but `112` is not.
Given a range of numbers, find the largest and smallest palindromes which
are products of two numbers within th... | def largest(min_factor, max_factor):
"""Given a range of numbers, find the largest palindromes which
are products of two numbers within that range.
:param min_factor: int with a default value of 0
:param max_factor: int
:return: tuple of (palindrome, iterable).
Iterable should conta... | # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/palindrome-products/canonical-data.json
# File last updated on 2023-07-19
import unittest
from palindrome_products import (
largest,
smallest,
)
class PalindromeProductsTest(unittes... |
71 | pangram | # Introduction
You work for a company that sells fonts through their website.
They'd like to show a different sentence each time someone views a font on their website.
To give a comprehensive sense of the font, the random sentences should use **all** the letters in the English alphabet.
They're running a competition ... | def is_pangram(sentence):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/pangram/canonical-data.json
# File last updated on 2023-07-19
import unittest
from pangram import (
is_pangram,
)
class PangramTest(unittest.TestCase):
def test_empty_sentence(self)... |
72 | pascals_triangle | # Introduction
With the weather being great, you're not looking forward to spending an hour in a classroom.
Annoyed, you enter the class room, where you notice a strangely satisfying triangle shape on the blackboard.
Whilst waiting for your math teacher to arrive, you can't help but notice some patterns in the triangl... | def rows(row_count):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/pascals-triangle/canonical-data.json
# File last updated on 2023-07-19
import sys
import unittest
from pascals_triangle import (
rows,
)
TRIANGLE = [
[1],
[1, 1],
[1, 2, 1],
... |
73 | perfect_numbers | # Instructions
Determine if a number is perfect, abundant, or deficient based on Nicomachus' (60 - 120 CE) classification scheme for positive integers.
The Greek mathematician [Nicomachus][nicomachus] devised a classification scheme for positive integers, identifying each as belonging uniquely to the categories of [p... | def classify(number):
""" A perfect number equals the sum of its positive divisors.
:param number: int a positive integer
:return: str the classification of the input integer
"""
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/perfect-numbers/canonical-data.json
# File last updated on 2023-07-19
import unittest
from perfect_numbers import (
classify,
)
class PerfectNumbersTest(unittest.TestCase):
def test... |
74 | phone_number | # Instructions
Clean up user-entered phone numbers so that they can be sent SMS messages.
The **North American Numbering Plan (NANP)** is a telephone numbering system used by many countries in North America like the United States, Canada or Bermuda.
All NANP-countries share the same international country code: `1`.
... | class PhoneNumber:
def __init__(self, number):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/phone-number/canonical-data.json
# File last updated on 2023-07-19
import unittest
from phone_number import (
PhoneNumber,
)
class PhoneNumberTest(unittest.TestCase):
def test_clean... |
75 | pig_latin | # Introduction
Your parents have challenged you and your sibling to a game of two-on-two basketball.
Confident they'll win, they let you score the first couple of points, but then start taking over the game.
Needing a little boost, you start speaking in [Pig Latin][pig-latin], which is a made-up children's language th... | def translate(text):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/pig-latin/canonical-data.json
# File last updated on 2023-07-19
import unittest
from pig_latin import (
translate,
)
class PigLatinTest(unittest.TestCase):
def test_word_beginning_w... |
76 | point_mutations | # Instructions
Calculate the Hamming difference between two DNA strands.
A mutation is simply a mistake that occurs during the creation or
copying of a nucleic acid, in particular DNA. Because nucleic acids are
vital to cellular functions, mutations tend to cause a ripple effect
throughout the cell. Although mutation... | def hamming_distance(dna_strand_1, dna_strand_2):
pass
| import unittest
from point_mutations import hamming_distance
class PointMutationsTest(unittest.TestCase):
def test_no_difference_between_empty_strands(self):
self.assertEqual(hamming_distance('', ''), 0)
def test_no_difference_between_identical_strands(self):
self.assertEqual(hamming_distanc... |
77 | poker | # Instructions
Pick the best hand(s) from a list of poker hands.
See [Wikipedia][poker-hands] for an overview of poker hands.
[poker-hands]: https://en.wikipedia.org/wiki/List_of_poker_hands
| def best_hands(hands):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/poker/canonical-data.json
# File last updated on 2023-12-27
import unittest
from poker import (
best_hands,
)
class PokerTest(unittest.TestCase):
def test_single_hand_always_wins(se... |
78 | pov | # Instructions
Reparent a tree on a selected node.
A [tree][wiki-tree] is a special type of [graph][wiki-graph] where all nodes are connected but there are no cycles.
That means, there is exactly one path to get from one node to another for any pair of nodes.
This exercise is all about re-orientating a tree to see t... | from json import dumps
class Tree:
def __init__(self, label, children=None):
self.label = label
self.children = children if children is not None else []
def __dict__(self):
return {self.label: [c.__dict__() for c in sorted(self.children)]}
def __str__(self, indent=None):
... | # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/pov/canonical-data.json
# File last updated on 2023-07-19
import unittest
from pov import (
Tree,
)
class PovTest(unittest.TestCase):
def test_results_in_the_same_tree_if_the_input_... |
79 | prime_factors | # Instructions
Compute the prime factors of a given natural number.
A prime number is only evenly divisible by itself and 1.
Note that 1 is not a prime number.
## Example
What are the prime factors of 60?
- Our first divisor is 2.
2 goes into 60, leaving 30.
- 2 goes into 30, leaving 15.
- 2 doesn't go cleanl... | def factors(value):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/prime-factors/canonical-data.json
# File last updated on 2023-07-19
import unittest
from prime_factors import (
factors,
)
class PrimeFactorsTest(unittest.TestCase):
def test_no_fac... |
80 | protein_translation | # Instructions
Translate RNA sequences into proteins.
RNA can be broken into three nucleotide sequences called codons, and then translated to a polypeptide like so:
RNA: `"AUGUUUUCU"` => translates to
Codons: `"AUG", "UUU", "UCU"`
=> which become a polypeptide with the following sequence =>
Protein: `"Methionine",... | def proteins(strand):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/protein-translation/canonical-data.json
# File last updated on 2024-07-08
import unittest
from protein_translation import (
proteins,
)
class ProteinTranslationTest(unittest.TestCase):
... |
81 | proverb | # Instructions
For want of a horseshoe nail, a kingdom was lost, or so the saying goes.
Given a list of inputs, generate the relevant proverb.
For example, given the list `["nail", "shoe", "horse", "rider", "message", "battle", "kingdom"]`, you will output the full text of this proverbial rhyme:
```text
For want of ... | def proverb():
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/proverb/canonical-data.json
# File last updated on 2023-07-19
import unittest
from proverb import (
proverb,
)
# PLEASE TAKE NOTE: Expected result lists for these test cases use **implic... |
82 | pythagorean_triplet | # Instructions
A Pythagorean triplet is a set of three natural numbers, {a, b, c}, for which,
```text
a² + b² = c²
```
and such that,
```text
a < b < c
```
For example,
```text
3² + 4² = 5².
```
Given an input integer N, find all Pythagorean triplets for which `a + b + c = N`.
For example, with N = 1000, there ... | def triplets_with_sum(number):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/pythagorean-triplet/canonical-data.json
# File last updated on 2023-07-19
import unittest
from pythagorean_triplet import (
triplets_with_sum,
)
class PythagoreanTripletTest(unittest.Te... |
83 | queen_attack | # Instructions
Given the position of two queens on a chess board, indicate whether or not they are positioned so that they can attack each other.
In the game of chess, a queen can attack pieces which are on the same row, column, or diagonal.
A chessboard can be represented by an 8 by 8 array.
So if you are told the... | class Queen:
def __init__(self, row, column):
pass
def can_attack(self, another_queen):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/queen-attack/canonical-data.json
# File last updated on 2023-07-19
import unittest
from queen_attack import (
Queen,
)
class QueenAttackTest(unittest.TestCase):
# Test creation of Q... |
84 | rail_fence_cipher | # Instructions
Implement encoding and decoding for the rail fence cipher.
The Rail Fence cipher is a form of transposition cipher that gets its name from the way in which it's encoded.
It was already used by the ancient Greeks.
In the Rail Fence cipher, the message is written downwards on successive "rails" of an im... | def encode(message, rails):
pass
def decode(encoded_message, rails):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/rail-fence-cipher/canonical-data.json
# File last updated on 2023-07-19
import unittest
from rail_fence_cipher import (
decode,
encode,
)
class RailFenceCipherTest(unittest.TestCase... |
85 | raindrops | # Introduction
Raindrops is a slightly more complex version of the FizzBuzz challenge, a classic interview question.
# Instructions
Your task is to convert a number into its corresponding raindrop sounds.
If a given number:
- is divisible by 3, add "Pling" to the result.
- is divisible by 5, add "Plang" to the resu... | def convert(number):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/raindrops/canonical-data.json
# File last updated on 2023-07-19
import unittest
from raindrops import (
convert,
)
class RaindropsTest(unittest.TestCase):
def test_the_sound_for_1_i... |
86 | rational_numbers | # Instructions
A rational number is defined as the quotient of two integers `a` and `b`, called the numerator and denominator, respectively, where `b != 0`.
~~~~exercism/note
Note that mathematically, the denominator can't be zero.
However in many implementations of rational numbers, you will find that the denominato... | class Rational:
def __init__(self, numer, denom):
self.numer = None
self.denom = None
def __eq__(self, other):
return self.numer == other.numer and self.denom == other.denom
def __repr__(self):
return f'{self.numer}/{self.denom}'
def __add__(self, other):
pass
... | # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/rational-numbers/canonical-data.json
# File last updated on 2023-07-19
import unittest
from rational_numbers import (
Rational,
)
class RationalNumbersTest(unittest.TestCase):
# Te... |
87 | react | # Instructions
Implement a basic reactive system.
Reactive programming is a programming paradigm that focuses on how values are computed in terms of each other to allow a change to one value to automatically propagate to other values, like in a spreadsheet.
Implement a basic reactive system with cells with settable ... | class InputCell:
def __init__(self, initial_value):
self.value = None
class ComputeCell:
def __init__(self, inputs, compute_function):
self.value = None
def add_callback(self, callback):
pass
def remove_callback(self, callback):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/react/canonical-data.json
# File last updated on 2023-07-19
from functools import partial
import unittest
from react import (
InputCell,
ComputeCell,
)
class ReactTest(unittest.Test... |
88 | rectangles | # Instructions
Count the rectangles in an ASCII diagram like the one below.
```text
+--+
++ |
+-++--+
| | |
+--+--+
```
The above diagram contains these 6 rectangles:
```text
+-----+
| |
+-----+
```
```text
+--+
| |
| |
| |
+--+
```
```text
+--+
| |
+--+
```
```text
... | def rectangles(strings):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/rectangles/canonical-data.json
# File last updated on 2023-07-19
import unittest
from rectangles import (
rectangles,
)
class RectanglesTest(unittest.TestCase):
def test_no_rows(sel... |
89 | resistor_color | # Instructions
If you want to build something using a Raspberry Pi, you'll probably use _resistors_.
For this exercise, you need to know two things about them:
- Each resistor has a resistance value.
- Resistors are small - so small in fact that if you printed the resistance value on them, it would be hard to read.
... | def color_code(color):
pass
def colors():
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/resistor-color/canonical-data.json
# File last updated on 2023-07-19
import unittest
from resistor_color import (
color_code,
colors,
)
class ResistorColorTest(unittest.TestCase):
... |
90 | resistor_color_duo | # Instructions
If you want to build something using a Raspberry Pi, you'll probably use _resistors_.
For this exercise, you need to know two things about them:
- Each resistor has a resistance value.
- Resistors are small - so small in fact that if you printed the resistance value on them, it would be hard to read.
... | def value(colors):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/resistor-color-duo/canonical-data.json
# File last updated on 2023-07-19
import unittest
from resistor_color_duo import (
value,
)
class ResistorColorDuoTest(unittest.TestCase):
def... |
91 | resistor_color_expert | # Introduction
If you want to build something using a Raspberry Pi, you'll probably use _resistors_.
Like the previous `Resistor Color Duo` and `Resistor Color Trio` exercises, you will be translating resistor color bands to human-readable labels.
- Each resistor has a resistance value.
- Resistors are small - so sma... | def resistor_label(colors):
pass
| import unittest
from resistor_color_expert import (
resistor_label,
)
# Tests adapted from `problem-specifications//canonical-data.json`
class ResistorColorExpertTest(unittest.TestCase):
def test_orange_orange_black_and_red(self):
self.assertEqual(resistor_label(["orange", "orange", "black", "red"])... |
92 | resistor_color_trio | # Instructions
If you want to build something using a Raspberry Pi, you'll probably use _resistors_.
For this exercise, you need to know only three things about them:
- Each resistor has a resistance value.
- Resistors are small - so small in fact that if you printed the resistance value on them, it would be hard to ... | def label(colors):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/resistor-color-trio/canonical-data.json
# File last updated on 2023-07-19
import unittest
from resistor_color_trio import (
label,
)
class ResistorColorTrioTest(unittest.TestCase):
... |
93 | rest_api | # Instructions
Implement a RESTful API for tracking IOUs.
Four roommates have a habit of borrowing money from each other frequently, and have trouble remembering who owes whom, and how much.
Your task is to implement a simple [RESTful API][restful-wikipedia] that receives [IOU][iou]s as POST requests, and can delive... | class RestAPI:
def __init__(self, database=None):
pass
def get(self, url, payload=None):
pass
def post(self, url, payload=None):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/rest-api/canonical-data.json
# File last updated on 2023-07-19
import json
import unittest
from rest_api import (
RestAPI,
)
class RestApiTest(unittest.TestCase):
def test_no_users(... |
94 | reverse_string | # Introduction
Reversing strings (reading them from right to left, rather than from left to right) is a surprisingly common task in programming.
For example, in bioinformatics, reversing the sequence of DNA or RNA strings is often important for various analyses, such as finding complementary strands or identifying pa... | def reverse(text):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/reverse-string/canonical-data.json
# File last updated on 2024-02-28
import unittest
from reverse_string import (
reverse,
)
class ReverseStringTest(unittest.TestCase):
def test_an_... |
95 | rna_transcription | # Introduction
You work for a bioengineering company that specializes in developing therapeutic solutions.
Your team has just been given a new project to develop a targeted therapy for a rare type of cancer.
~~~~exercism/note
It's all very complicated, but the basic idea is that sometimes people's bodies produce too... | def to_rna(dna_strand):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/rna-transcription/canonical-data.json
# File last updated on 2023-07-19
import unittest
from rna_transcription import (
to_rna,
)
class RnaTranscriptionTest(unittest.TestCase):
def ... |
96 | robot_name | # Instructions
Manage robot factory settings.
When a robot comes off the factory floor, it has no name.
The first time you turn on a robot, a random name is generated in the format of two uppercase letters followed by three digits, such as RX837 or BC811.
Every once in a while we need to reset a robot to its factor... | class Robot:
def __init__(self):
pass
| import unittest
import random
from robot_name import Robot
class RobotNameTest(unittest.TestCase):
# assertRegex() alias to address DeprecationWarning
# assertRegexpMatches got renamed in version 3.2
if not hasattr(unittest.TestCase, "assertRegex"):
assertRegex = unittest.TestCase.assertRegexpMat... |
97 | robot_simulator | # Instructions
Write a robot simulator.
A robot factory's test facility needs a program to verify robot movements.
The robots have three possible movements:
- turn right
- turn left
- advance
Robots are placed on a hypothetical infinite grid, facing a particular direction (north, east, south, or west) at a set of ... | # Globals for the directions
# Change the values as you see fit
EAST = None
NORTH = None
WEST = None
SOUTH = None
class Robot:
def __init__(self, direction=NORTH, x_pos=0, y_pos=0):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/robot-simulator/canonical-data.json
# File last updated on 2023-07-19
import unittest
from robot_simulator import (
Robot,
NORTH,
EAST,
SOUTH,
WEST,
)
class RobotSimulat... |
98 | roman_numerals | # Description
Today, most people in the world use Arabic numerals (0–9).
But if you travelled back two thousand years, you'd find that most Europeans were using Roman numerals instead.
To write a Roman numeral we use the following Latin letters, each of which has a value:
| M | D | C | L | X | V | I |... | def roman(number):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/roman-numerals/canonical-data.json
# File last updated on 2024-07-08
import unittest
from roman_numerals import (
roman,
)
class RomanNumeralsTest(unittest.TestCase):
def test_1_is_... |
99 | rotational_cipher | # Instructions
Create an implementation of the rotational cipher, also sometimes called the Caesar cipher.
The Caesar cipher is a simple shift cipher that relies on transposing all the letters in the alphabet using an integer key between `0` and `26`.
Using a key of `0` or `26` will always yield the same output due t... | def rotate(text, key):
pass
| # These tests are auto-generated with test data from:
# https://github.com/exercism/problem-specifications/tree/main/exercises/rotational-cipher/canonical-data.json
# File last updated on 2023-07-19
import unittest
from rotational_cipher import (
rotate,
)
class RotationalCipherTest(unittest.TestCase):
def ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.