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
You will be given an array of objects representing data about developers who have signed up to attend the next web development meetup that you are organising. Three programming languages will be represented: Python, Ruby and JavaScript. Your task is to return either: - `true` if the number of meetup participants repr...
algorithms
from collections import Counter def is_language_diverse(lst): c = Counter(map(lambda x: x["language"], lst)). values() return max(c) <= 2 * min(c)
Coding Meetup #13 - Higher-Order Functions Series - Is the meetup language-diverse?
58381907f8ac48ae070000de
[ "Functional Programming", "Data Structures", "Arrays", "Fundamentals", "Algorithms", "Strings" ]
https://www.codewars.com/kata/58381907f8ac48ae070000de
6 kyu
Create a finite automaton that has three states. Finite automatons are the same as finite state machines for our purposes. Our simple automaton, accepts the language of `A`, defined as `{0, 1}` and should have three states: `q1`, `q2`, and `q3`. Here is the description of the states: * `q1` is our start state, we beg...
algorithms
class Automaton (object): def __init__(self): self . automata = {('q1', '1'): 'q2', ('q1', '0'): 'q1', ('q2', '0'): 'q3', ('q2', '1'): 'q2', ('q3', '0'): 'q2', ('q3', '1'): 'q2'} self . state = "q1" def read_commands(self, commands): for c in co...
Design a Simple Automaton (Finite State Machine)
5268acac0d3f019add000203
[ "State Machines", "Artificial Intelligence", "Algorithms", "Object-oriented Programming" ]
https://www.codewars.com/kata/5268acac0d3f019add000203
6 kyu
There is a house with 4 levels. In that house there is an elevator. You can program this elevator to go up or down, depending on what button the user touches inside the elevator. Valid levels must be only these numbers: `0,1,2,3` Valid buttons must be only these strings: `'0','1','2','3'` Possible return values are...
reference
levels = [0, 1, 2, 3] buttons = ['0', '1', '2', '3'] def goto(level, button): if level not in levels or button not in buttons: return 0 else: return int(button) - level
Simple elevator
52ed326b8df6540e06000029
[ "State Machines", "Fundamentals" ]
https://www.codewars.com/kata/52ed326b8df6540e06000029
7 kyu
In this Kata, you have to design a simple routing class for a web framework. The router should accept bindings for a given url, http method and an action. Then, when a request with a bound url and method comes in, it should return the result of the action. Example usage: ```python router = Router() router.bind('/h...
reference
class Router: def __init__(self): self . _routes = {} def bind(self, url, method, action): self . _routes[(url, method)] = action def runRequest(self, url, method): return self . _routes . get((url, method), lambda: "Error 404: Not Found")()
Simple Web Framework #1: Create a basic router
588a00ad70720f2cd9000005
[ "Object-oriented Programming", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/588a00ad70720f2cd9000005
6 kyu
The dragon's curve is a self-similar fractal which can be obtained by a recursive method. Starting with the string `D0 = 'Fa'`, at each step simultaneously perform the following operations: ``` replace 'a' with: 'aRbFR' replace 'b' with: 'LFaLb' ``` For example (spaces added for more visibility) : ``` 1st iterati...
algorithms
def Dragon(n): if type(n) != int or n < 0: return "" stg, a, b = "F{a}", "{a}R{b}FR", "LF{a}L{b}" for _ in range(n): stg = stg . format(a=a, b=b) return stg . replace("{a}", ""). replace("{b}", "")
Dragon's Curve
53ad7224454985e4e8000eaa
[ "Mathematics", "Recursion", "Algorithms" ]
https://www.codewars.com/kata/53ad7224454985e4e8000eaa
6 kyu
The Ackermann function is a famous function that played a big role in computability theory as the first example of a total computable function that is not primitive recursive. Since then the function has been a bit simplified but is still of good use. Due to its definition in terms of extremely deep recursion it can b...
algorithms
from numbers import Number def Ackermann(m, n): if isinstance(n, Number) and isinstance(m, Number): if m >= 0 and n >= 0: return Ackermann_Aux(m, n) return None def Ackermann_Aux(m, n): if m == 0: return n + 1 if m > 0: if n == 0: return Ackermann_Aux(m - 1, 1)...
Ackermann Function
53ad69892a27079b34000bd9
[ "Mathematics", "Algorithms", "Recursion" ]
https://www.codewars.com/kata/53ad69892a27079b34000bd9
6 kyu
Mutual Recursion allows us to take the fun of regular recursion (where a function calls itself until a terminating condition) and apply it to multiple functions calling each other! Let's use the Hofstadter Female and Male sequences to demonstrate this technique. You'll want to create two functions `F` and `M` such th...
algorithms
def f(n): return n - m(f(n - 1)) if n else 1 def m(n): return n - f(m(n - 1)) if n else 0
Mutual Recursion
53a1eac7e0afd3ad3300008b
[ "Mathematics", "Algorithms", "Recursion" ]
https://www.codewars.com/kata/53a1eac7e0afd3ad3300008b
6 kyu
You are given a string of `n` lines, each substring being `n` characters long: For example: `s = "abcd\nefgh\nijkl\nmnop"` We will study some transformations of this square of strings. - Symmetry with respect to the main cross diagonal: `diag_2_sym` (or `diag2Sym` or `diag-2-sym`) ``` diag_2_sym(s) => "plhd\nokg...
reference
def rot_90_counter(s): return list(zip(* s))[:: - 1] def diag_2_sym(s): return list(zip(* s[:: - 1]))[:: - 1] def selfie_diag2_counterclock(s): return (tuple(l) + ('|',) + m + ('|',) + r for l, m, r in zip(s, diag_2_sym(s), rot_90_counter(s))) def oper(func, s): ret...
Moves in squared strings (IV)
56dbf59b0a10feb08c000227
[ "Algorithms", "Strings" ]
https://www.codewars.com/kata/56dbf59b0a10feb08c000227
6 kyu
You are given a string of `n` lines, each substring being `n` characters long: For example: `s = "abcd\nefgh\nijkl\nmnop"` We will study some transformations of this square of strings. Let's now transform this string! - Symmetry with respect to the main diagonal: diag_1_sym (or diag1Sym or diag-1-sym) ``` diag_1_sy...
reference
def rot_90_clock(strng): return '\n' . join('' . join(x) for x in zip(* strng . split('\n')[:: - 1])) def diag_1_sym(strng): return '\n' . join('' . join(x) for x in zip(* strng . split('\n'))) def selfie_and_diag1(strng): return '\n' . join('|' . join(x) for x in zip(strng . split('\n'), diag_...
Moves in squared strings (III)
56dbeec613c2f63be4000be6
[ "Algorithms", "Strings" ]
https://www.codewars.com/kata/56dbeec613c2f63be4000be6
6 kyu
# Be Concise I - The Ternary Operator You are given a function ```describeAge``` / ```describe_age``` that takes a parameter ```age``` (which will always be a **positive integer**) and does the following: 1. If the age is ```12``` or lower, it ```return "You're a(n) kid"``` 2. If the age is anything between ```13``` ...
refactoring
def describe_age(a): return f"You're a(n) { a < 13 and 'kid' or a < 18 and 'teenager' or a < 65 and 'adult' or 'elderly' } "
Be Concise I - The Ternary Operator
56f3f6a82010832b02000f38
[ "Fundamentals", "Refactoring" ]
https://www.codewars.com/kata/56f3f6a82010832b02000f38
8 kyu
You are given a string of `n` lines, each substring being `n` characters long: For example: `s = "abcd\nefgh\nijkl\nmnop"` We will study some transformations of this square of strings. - Clock rotation 180 degrees: rot ``` rot(s) => "ponm\nlkji\nhgfe\ndcba" ``` - selfie_and_rot(s) (or selfieAndRot or selfie-and-rot)...
reference
def rot(string): return string[:: - 1] def selfie_and_rot(string): s_dot = '\n' . join([s + '.' * len(s) for s in string . split('\n')]) return s_dot + '\n' + rot(s_dot) def oper(fct, s): return fct(s)
Moves in squared strings (II)
56dbe7f113c2f63570000b86
[ "Algorithms", "Strings" ]
https://www.codewars.com/kata/56dbe7f113c2f63570000b86
6 kyu
There exists a sequence of numbers that follows the pattern ``` 1 11 21 1211 111221 312211 13112221 1113213211 . . . ``` Starting with "1" the following lines are produced by "saying what you see", so that line two is "one one"...
algorithms
from itertools import groupby def look_and_say(data='1', maxlen=5): L = [] for i in range(maxlen): data = "" . join(str(len(list(g))) + str(n) for n, g in groupby(data)) L . append(data) return L
Look and say numbers
53ea07c9247bc3fcaa00084d
[ "Recursion", "Algorithms" ]
https://www.codewars.com/kata/53ea07c9247bc3fcaa00084d
6 kyu
# The die is cast! Your task in this kata is to write a "dice roller" that interprets a subset of [dice notation](http://en.wikipedia.org/wiki/Dice_notation). # Description In most role-playing games, die rolls required by the system are given in the form `AdX`. `A` and `X` are variables, separated by the letter **...
algorithms
import re import random def roll(desc, verbose=False): if not isinstance(desc, str): return False ans = re . findall(r'^(\d*)d(\d+)(([+\-]\d+)*)$', desc . replace(' ', '')) if len(ans) == 0: return False dct = {i: eval(v) for i, v in enumerate(ans[0]) if v} dices = {'d...
RPG dice roller
549cb9c0c36a02ce2e000156
[ "Regular Expressions", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/549cb9c0c36a02ce2e000156
5 kyu
This time we want to write calculations using functions and get the results. Let's have a look at some examples: ```javascript seven(times(five())); // must return 35 four(plus(nine())); // must return 13 eight(minus(three())); // must return 5 six(dividedBy(two())); // must return 3 ``` ```haskell seven $ times $ fiv...
reference
def identity(a): return a def zero(f=identity): return f(0) def one(f=identity): return f(1) def two(f=identity): return f(2) def three(f=identity): return f(3) def four(f=identity): return f(4) def five(f=identity): return f(5) def six(f=identity): return f(6) def seven(f=identi...
Calculating with Functions
525f3eda17c7cd9f9e000b39
[ "Functional Programming" ]
https://www.codewars.com/kata/525f3eda17c7cd9f9e000b39
5 kyu
You need to create a function that will validate if given parameters are valid geographical coordinates. Valid coordinates look like the following: __"23.32353342, -32.543534534"__. The return value should be either __true__ or __false__. Latitude (which is first float) can be between 0 and 90, positive or negative. ...
algorithms
def is_valid_coordinates(coordinates): try: lat, lng = [abs(float(c)) for c in coordinates . split(',') if 'e' not in c] except ValueError: return False return lat <= 90 and lng <= 180
Coordinates Validator
5269452810342858ec000951
[ "Regular Expressions", "Algorithms" ]
https://www.codewars.com/kata/5269452810342858ec000951
6 kyu
I started this as a joke among friends, telling that converting numbers to other integer bases is for n00bs, while an actual coder at least converts numbers to more complex bases like [pi (or π or however you wish to spell it in your language)](http://en.wikipedia.org/wiki/Pi), so they dared me proving I was better. A...
algorithms
from math import pi, log char = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' def converter(n, decimals=0, base=pi): if n == 0: return "0" if not decimals else "0." + "0" * decimals res = "" if n > 0 else "-" n = abs(n) for q in xrange(int(log(n, base)), - decimals - 1, - 1): if q == - 1: ...
Decimal to any Rational or Irrational Base Converter
5509609d1dbf20a324000714
[ "Mathematics", "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/5509609d1dbf20a324000714
4 kyu
Write a function that will solve a 9x9 Sudoku puzzle. The function will take one argument consisting of the 2D puzzle array, with the value ```0``` representing an unknown square. The Sudokus tested against your function will be "easy" (i.e. determinable; there will be no need to assume and test possibilities on unkn...
algorithms
def sudoku(P): for row, col in [(r, c) for r in range(9) for c in range(9) if not P[r][c]]: rr, cc = (row / / 3) * 3, (col / / 3) * 3 use = {1, 2, 3, 4, 5, 6, 7, 8, 9} - ({P[row][c] for c in range(9)} | {P[r][col] for r in range(9)} | {P[rr + r][cc + c] for r...
Sudoku Solver
5296bc77afba8baa690002d7
[ "Games", "Game Solvers", "Algorithms" ]
https://www.codewars.com/kata/5296bc77afba8baa690002d7
3 kyu
# Task Consider the following ciphering algorithm: ``` For each character replace it with its code. Concatenate all of the obtained numbers. ``` Given a ciphered string, return the initial one if it is known that it consists only of lowercase letters. Note: here the character's code means its `decimal ASCII code`, t...
games
import re def decipher(cipher): return re . sub(r'1?\d\d', lambda m: chr(int(m . group())), cipher)
Simple Fun #49: Decipher
5888514674b58e929a000036
[ "Puzzles" ]
https://www.codewars.com/kata/5888514674b58e929a000036
7 kyu
# Kata Impossible I - The Impossible Lottery ## Overview and Background Story One day, someone tells you that there exists a lottery very close to your home in which every participant is only required to pay ```5 British pounds``` per round but the winner of the lottery receives ```1000 trillion``` British pounds! N...
games
class Ticket: def __eq__(self, _): return True lottery_ticket = Ticket()
Kata Impossible I - The Impossible Lottery
56caf4a1145912a5c4000b76
[ "Puzzles" ]
https://www.codewars.com/kata/56caf4a1145912a5c4000b76
6 kyu
There's a new security company in Paris, and they decided to give their employees an algorithm to make first name recognition faster. In the blink of an eye, they can now detect if a string is a first name, no matter if it is a one-word name or an hyphenated name. They're given this documentation with the algorithm: ...
reference
import re def show_me(name): return bool(re . match(r'(-[A-Z][a-z]+)+$', '-' + name))
Sir , showMe yourID
574c51aa3e4ea6de22001363
[ "Regular Expressions", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/574c51aa3e4ea6de22001363
7 kyu
Linked Lists - Merge Sort Write a MergeSort() function which recursively sorts a list in ascending order. Note that this problem requires recursion. Given FrontBackSplit() and SortedMerge(), you can write a classic recursive MergeSort(). Split the list into two smaller lists, recursively sort those lists, and finally ...
algorithms
class Node (object): def __init__(self, data=None): self . data = data self . next = None def merge_sort(list): if not list or not list . next: return list front, back = Node(), Node() front_back_split(list, front, back) return sorted_merge(merge_sort(front), merge_sort(...
Linked Lists - Merge Sort
55e5fa3501fd9c3f4d000050
[ "Linked Lists", "Data Structures", "Algorithms", "Sorting", "Recursion" ]
https://www.codewars.com/kata/55e5fa3501fd9c3f4d000050
6 kyu
Linked Lists - Shuffle Merge Write a ShuffleMerge() function that takes two lists and merges their nodes together to make one list, taking nodes alternately between the two lists. So ShuffleMerge() with `1 -> 2 -> 3 -> null` and `7 -> 13 -> 1 -> null` should yield `1 -> 7 -> 2 -> 13 -> 3 -> 1 -> null`. If either list ...
algorithms
class Node (object): def __init__(self, data=None): self . data = data self . next = None def shuffle_merge(first, second): if not first: return second head = first while second: first . next, first, second = second, second, first . next return head
Linked Lists - Shuffle Merge
55e5253dcd20f821c400008e
[ "Linked Lists", "Data Structures", "Algorithms" ]
https://www.codewars.com/kata/55e5253dcd20f821c400008e
6 kyu
# Generate user links Your task is to create userlinks for the url, you will be given a username and must return a valid link. ## Example ``` generate_link('matt c') http://www.codewars.com/users/matt%20c ``` ### reference use this as a reference [encoding](http://www.w3schools.com/tags/ref_urlencode.asp)
games
from urllib . parse import quote def generate_link(user: str) - > str: return f"http://www.codewars.com/users/ { quote ( user )} "
Generate user links
57037ed25a7263ac35000c80
[ "Puzzles" ]
https://www.codewars.com/kata/57037ed25a7263ac35000c80
8 kyu
For this exercise you will be strengthening your page-fu mastery. You will complete the PaginationHelper class, which is a utility class helpful for querying paging information related to an array. The class is designed to take in an array of values and an integer indicating how many items will be allowed per each p...
algorithms
class PaginationHelper: def __init__(self, collection, items_per_page): self . _item_count = len(collection) self . items_per_page = items_per_page def item_count(self): return self . _item_count def page_count(self): return - (self . _item_count / / - self . items_per_page) de...
PaginationHelper
515bb423de843ea99400000a
[ "Object-oriented Programming", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/515bb423de843ea99400000a
5 kyu
Linked Lists - Front Back Split Write a FrontBackSplit() function that takes one list and splits it into two sublists — one for the front half, and one for the back half. If the number of elements is odd, the extra element should go in the front list. For example, FrontBackSplit() on the list `2 -> 3 -> 5 -> 7 -> 11 -...
reference
class Node (object): def __init__(self, data=None): self . data = data self . next = None def front_back_split(source, front, back): if not source or not source . next: raise ValueError if not source . next . next: front . data, front . next = source . data, None back . data, back . ...
Linked Lists - Front Back Split
55e1d2ba1a3229674d000037
[ "Linked Lists", "Data Structures", "Fundamentals" ]
https://www.codewars.com/kata/55e1d2ba1a3229674d000037
5 kyu
Linked Lists - Recursive Reverse Write a **Recursive** Reverse() function that recursively reverses a linked list. You may want to use a nested function for the recursive calls. ```javascript var list = 2 -> 1 -> 3 -> 6 -> 5 -> null reverse(list) === 5 -> 6 -> 3 -> 1 -> 2 -> null ``` Related Kata in order of expecte...
algorithms
class Node: def __init__(self, data=None, next=None): self . data = data self . next = next def reverse(head, tail=None): return reverse(head . next, Node(head . data, tail)) if head else tail
Linked Lists - Recursive Reverse
55e725b930957a038a000042
[ "Linked Lists", "Data Structures", "Algorithms" ]
https://www.codewars.com/kata/55e725b930957a038a000042
6 kyu
Linked Lists - Iterative Reverse Write an **iterative** Reverse() function that reverses a linked list. Ideally, Reverse() should only need to make one pass of the list. ```javascript var list = 2 -> 1 -> 3 -> 6 -> 5 -> null reverse(list) list === 5 -> 6 -> 3 -> 1 -> 2 -> null ``` The push() and buildOneTwoThree() ...
algorithms
class Node (object): def __init__(self, data=None): self . data = data self . next = None def reverse(head): rev = None current = head while current: rev = push(rev, current . data) current = current . next if head: head . data = rev . data head . next = rev ....
Linked Lists - Iterative Reverse
55e72695870aae78c4000026
[ "Linked Lists", "Data Structures", "Algorithms" ]
https://www.codewars.com/kata/55e72695870aae78c4000026
6 kyu
Linked Lists - Remove Duplicates Write a RemoveDuplicates() function which takes a list sorted in increasing order and deletes any duplicate nodes from the list. Ideally, the list should only be traversed once. The head of the resulting list should be returned. ```javascript var list = 1 -> 2 -> 3 -> 3 -> 4 -> 4 -> 5...
reference
class Node (object): def __init__(self, data): self . data = data self . next = None def remove_duplicates(head): if head == None: return head current = head next = current . next while next: if current . data == next . data: current . next = current . next . next next = ...
Linked Lists - Remove Duplicates
55d9f257d60c5fd98d00001b
[ "Linked Lists", "Data Structures", "Fundamentals" ]
https://www.codewars.com/kata/55d9f257d60c5fd98d00001b
6 kyu
Linked Lists - Insert Sort Write an InsertSort() function which rearranges nodes in a linked list so they are sorted in increasing order. You can use the SortedInsert() function that you created in the "Linked Lists - Sorted Insert" kata below. The InsertSort() function takes the head of a linked list as an argument a...
reference
class Node (object): def __init__(self, data, next=None): self . data = data self . next = next def insert_sort(head): n, r = head, None while n: r = sorted_insert(r, n . data) n = n . next return r
Linked Lists - Insert Sort
55d0c7ee7c0d30a12b000045
[ "Linked Lists", "Data Structures", "Fundamentals", "Sorting" ]
https://www.codewars.com/kata/55d0c7ee7c0d30a12b000045
6 kyu
Linked Lists - Move Node Write a MoveNode() function which takes the node from the front of the source list and moves it to the front of the destintation list. You should throw an error when the source list is empty. For simplicity, we use a Context object to store and return the state of the two linked lists. A Conte...
reference
class Node (object): def __init__(self, data, nxt=None): self . data, self . next = data, nxt class Context (object): def __init__(self, source, dest): self . source, self . dest = source, dest def move_node(source, dest): if source is None: raise ValueError return Conte...
Linked Lists - Move Node
55da347204760ba494000038
[ "Linked Lists", "Data Structures", "Fundamentals" ]
https://www.codewars.com/kata/55da347204760ba494000038
7 kyu
Linked Lists - Alternating Split Write an AlternatingSplit() function that takes one list and divides up its nodes to make two smaller lists. The sublists should be made from alternating elements in the original list. So if the original list is `a -> b -> a -> b -> a -> null` then one sublist should be `a -> a -> a ->...
reference
class Node (object): def __init__(self, data=None): self . data = data self . next = None class Context (object): def __init__(self, first, second): self . first = first self . second = second def alternating_split(head): if head is None or head . next is None: raise Va...
Linked Lists - Alternating Split
55dd5386575839a74f0000a9
[ "Data Structures", "Linked Lists", "Fundamentals" ]
https://www.codewars.com/kata/55dd5386575839a74f0000a9
5 kyu
Linked Lists - Append Write an Append() function which appends one linked list to another. The head of the resulting list should be returned. ```javascript var listA = 1 -> 2 -> 3 -> null var listB = 4 -> 5 -> 6 -> null append(listA, listB) === 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null ``` ```coffeescript listA = 1 -> 2 -> ...
reference
class Node (object): def __init__(self, data): self . data = data self . next = None def last(head): n = head while n and n . next: n = n . next return n def append(listA, listB): if not listA: return listB last(listA). next = listB return listA
Linked Lists - Append
55d17ddd6d7868493e000074
[ "Linked Lists", "Data Structures", "Fundamentals" ]
https://www.codewars.com/kata/55d17ddd6d7868493e000074
7 kyu
Implement the method **length**, which accepts a linked list (head), and returns the length of the list. For example: Given the list: `1 -> 2 -> 3 -> 4`, **length** should return 4. The linked list is defined as follows: ```javascript function Node(data, next = null) { this.data = data; this.next = next; } ``` `...
reference
def length(head): count = 0 while head != None: count += 1 head = head . next return count
Fun with lists: length
581e476d5f59408553000a4b
[ "Lists", "Fundamentals" ]
https://www.codewars.com/kata/581e476d5f59408553000a4b
7 kyu
# Task Given a string `str`, reverse it and omit all non-alphabetic characters. # Example For `str = "krishan"`, the output should be `"nahsirk"`. For `str = "ultr53o?n"`, the output should be `"nortlu"`. # Input/Output - `[input]` string `str` A string consists of lowercase latin letters, digits and sym...
reference
def reverse_letter(s): return '' . join([i for i in s if i . isalpha()])[:: - 1]
Simple Fun #176: Reverse Letter
58b8c94b7df3f116eb00005b
[ "Fundamentals" ]
https://www.codewars.com/kata/58b8c94b7df3f116eb00005b
7 kyu
Linked Lists - Sorted Insert Write a SortedInsert() function which inserts a node into the correct location of a pre-sorted linked list which is sorted in ascending order. SortedInsert takes the head of a linked list and data used to create a node as arguments. SortedInsert() should also return the head of the list. ...
reference
class Node (object): def __init__(self, data, nxt=None): self . data = data self . next = nxt def sorted_insert(head, data): if not head or data < head . data: return Node(data, head) else: head . next = sorted_insert(head . next, data) return head
Linked Lists - Sorted Insert
55cc33e97259667a08000044
[ "Linked Lists", "Data Structures", "Fundamentals" ]
https://www.codewars.com/kata/55cc33e97259667a08000044
6 kyu
Linked Lists - Sorted Intersect Write a SortedIntersect() function which creates and returns a list representing the intersection of two lists that are sorted in increasing order. Ideally, each list should only be traversed once. The resulting list should not contain duplicates. ```javascript var first = 1 -> 2 -> 2 ...
algorithms
class Node (object): def __init__(self, data=None, nxt=None): self . data, self . next = data, nxt # For so little text, the cyclomatic complexity here is pretty staggering def sorted_intersect(first, second): if not first or not second: return None if first . next and first . dat...
Linked Lists - Sorted Intersect
55e67e44bf97fa66900000a0
[ "Linked Lists", "Data Structures", "Algorithms" ]
https://www.codewars.com/kata/55e67e44bf97fa66900000a0
6 kyu
Linked Lists - Sorted Merge Write a SortedMerge() function that takes two lists, each of which is sorted in increasing order, and merges the two together into one list which is in increasing order. SortedMerge() should return the new list. The new list should be made by splicing together the nodes of the first two lis...
algorithms
class Node (object): def __init__(self, data=None, nxt=None): self . data, self . next = data, nxt def sorted_merge(first, second): if not first: return second if not second: return first return Node(first . data, sorted_merge(first . next, second)) if first . data < seco...
Linked Lists - Sorted Merge
55e5d31bf7ca1e44980000a7
[ "Linked Lists", "Data Structures", "Algorithms" ]
https://www.codewars.com/kata/55e5d31bf7ca1e44980000a7
6 kyu
John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns. `ls = [50, 55, 57, 58, 60]`. John is tired of driving and he says to Mary that he doesn't want to drive more than `t = 174 miles` and he will visit only `3` towns. Which distances, hence w...
reference
import itertools def choose_best_sum(t, k, ls): try: return max(sum(i) for i in itertools . combinations(ls, k) if sum(i) <= t) except: return None
Best travel
55e7280b40e1c4a06d0000aa
[ "Fundamentals" ]
https://www.codewars.com/kata/55e7280b40e1c4a06d0000aa
5 kyu
## Introduction <pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;"> We all love to play games especially as children. I have fond memories playing Connect 4 with my brother so decided to create this Kata based on the classic game. Connec...
reference
class Connect4 (): def __init__(self): self . grid = [[0] * 7 for _ in range(6)] self . player = 1 self . finish = False # We only check the possibles moves from the last play, no need to check the whole board def check(self, row, col): # Horizontal for j in range(max(0, col - 3), ...
Connect 4
586c0909c1923fdb89002031
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/586c0909c1923fdb89002031
5 kyu
# Introduction <pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;"> Welcome Adventurer. Your aim is to navigate the maze and reach the finish point without touching any walls. Doing so will kill you instantly! </pre> # Task <pre style="...
reference
def maze_runner(maze, directions): n = len(maze) # find start point for i in range(n): if 2 in maze[i]: row = i col = maze[row]. index(2) break # follow directions for step in directions: if step == "N": row -= 1 elif step == "S": row += 1 elif step == "E...
Maze Runner
58663693b359c4a6560001d6
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/58663693b359c4a6560001d6
6 kyu
Your task, is to create a NxN spiral with a given `size`. For example, spiral with size 5 should look like this: ``` 00000 ....0 000.0 0...0 00000 ``` and with the size 10: ``` 0000000000 .........0 00000000.0 0......0.0 0.0000.0.0 0.0..0.0.0 0.0....0.0 0.000000.0 0........0 0000000000 ``` Return value should cont...
algorithms
def spiralize(size): def on_board(x, y): return 0 <= x < size and 0 <= y < size def is_one(x, y): return on_board(x, y) and spiral[y][x] == 1 def can_move(): return on_board(x + dx, y + dy) and not (is_one(x + 2 * dx, y + 2 * dy) or is_one(x + dx - dy, y + dy + dx) or is_one(x + dx + dy,...
Make a spiral
534e01fbbb17187c7e0000c6
[ "Algorithms", "Arrays", "Logic" ]
https://www.codewars.com/kata/534e01fbbb17187c7e0000c6
3 kyu
You need to write a password generator that meets the following criteria: * 6 - 20 characters long * contains at least one lowercase letter * contains at least one uppercase letter * contains at least one number * contains only alphanumeric characters (no special characters) Return the random password as a string. *...
reference
from string import ascii_lowercase as LOWER, ascii_uppercase as UPPER, digits as DIGITS from random import choice, shuffle, randint def password_gen(): pw = [choice(UPPER), choice(LOWER), choice(DIGITS)] + \ [choice(UPPER + LOWER + DIGITS) for i in range(randint(3, 17))] shuffle(pw) return...
Password generator
58ade2233c9736b01d0000b3
[ "Regular Expressions", "Security", "Fundamentals" ]
https://www.codewars.com/kata/58ade2233c9736b01d0000b3
6 kyu
Cara is applying for several different jobs. The online application forms ask her to respond within a specific character count. Cara needs to check that her answers fit into the character limit. Annoyingly, some application forms count spaces as a character, and some don't. Your challenge: Write Cara a function `ch...
reference
def charCheck(text, mx, spaces): text = text if spaces else text . replace(' ', '') return [len(text) <= mx, text[: mx]]
Character limits: How long is your piece of string?
58af4ed8673e88a719000116
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/58af4ed8673e88a719000116
6 kyu
Write function alternateCase which switch every letter in string from upper to lower and from lower to upper. E.g: Hello World -> hELLO wORLD
reference
def alternateCase(s): return s . swapcase()
Alternate case
57a62154cf1fa5b25200031e
[ "Fundamentals" ]
https://www.codewars.com/kata/57a62154cf1fa5b25200031e
7 kyu
Write function `replaceAll` (Python: `replace_all`) that will replace all occurrences of an item with another. __Python / JavaScript__: The function has to work for strings and lists. Example: replaceAll [1,2,2] 1 2 -> in list [1,2,2] we replace 1 with 2 to get new list [2,2,2] ```swift replaceAll(replaceAll(array: ...
reference
def replace_all(obj, find, replace): if isinstance(obj, str): return obj . replace(find, replace) elif isinstance(obj, list): return [x if x != find else replace for x in obj]
Replace all items
57ae18c6e298a7a6d5000c7a
[ "Fundamentals", "Arrays", "Lists", "Regular Expressions" ]
https://www.codewars.com/kata/57ae18c6e298a7a6d5000c7a
7 kyu
In this kata you parse RGB colors represented by strings. The formats are primarily used in HTML and CSS. Your task is to implement a function which takes a color as a string and returns the parsed color as a map (see Examples). ## Input: The input string represents one of the following: - **6-digit hexadecimal** - ...
reference
def parse_html_color(color): color = PRESET_COLORS . get(color . lower(), color) if len(color) == 7: r, g, b = (int(color[i: i + 2], 16) for i in range(1, 7, 2)) else: r, g, b = (int(color[i + 1] * 2, 16) for i in range(3)) return dict(zip("rgb", (r, g, b)))
Parse HTML/CSS Colors
58b57ae2724e3c63df000006
[ "Fundamentals", "Algorithms", "Strings", "Parsing" ]
https://www.codewars.com/kata/58b57ae2724e3c63df000006
6 kyu
You are writing an encoder/decoder to convert between javascript strings and a binary representation of Morse code. Each Morse code character is represented by a series of "dots" and "dashes". In binary, a dot is a single bit (`1`) and a dash is three bits (`111`). Between each dot or dash within a single character, w...
algorithms
import re class Morse: @ classmethod def encode(self, message): bits = "0000000" . join(["000" . join([Morse . alpha[char] for char in word]) for word in message . split(' ')]) return [int((int("{0:0<32s}" . format(bit32), base=2) + 0x80000000) % 0x100000000 - 0x80...
Morse Encoding
536602df5d0266e7b0000d31
[ "Bits", "Strings", "Binary", "Parsing", "Algorithms" ]
https://www.codewars.com/kata/536602df5d0266e7b0000d31
5 kyu
Write function `makeParts` or `make_parts` (depending on your language) that will take an array as argument and the size of the chunk. Example: if an array of size 123 is given and chunk size is 10 there will be 13 parts, 12 of size 10 and 1 of size 3.
reference
def makeParts(arr, csize): return [arr[i: i + csize] for i in range(0, len(arr), csize)]
Cut array into smaller parts
58ac59d21c9e1d7dc5000150
[ "Fundamentals" ]
https://www.codewars.com/kata/58ac59d21c9e1d7dc5000150
7 kyu
Batman & Robin have gotten into quite a pickle this time. The Joker has mixed up their iconic quotes and also replaced one of the characters in their names, with a number. They need help getting things back in order. Implement the getQuote method which takes in an array of quotes, and a string comprised of letters and...
reference
import re class BatmanQuotes (object): @ staticmethod def get_quote(quotes, hero): return {'B': 'Batman', 'R': 'Robin', 'J': 'Joker'}[hero[0]] + ": " + quotes[int(re . search('\d+', hero). group())]
Batman Quotes
551614eb77dd9ee37100003e
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/551614eb77dd9ee37100003e
7 kyu
# The problem ```if:javascript,coffeescript,haskell,rust In this kata, you're going write a function called `pointInPoly` to test if a point is inside a polygon. ``` ```if:python In this kata, you're going write a function called `point_in_polygon` to test if a point is inside a polygon. ``` ```if:javascript,coffee...
algorithms
from typing import List, Tuple # Input parameters for visualize_polygon are the same, as for point_in_polygon from preloaded import visualize_polygon from matplotlib . path import Path def point_in_polygon(polygon: List[Tuple[float, float]], point: Tuple[float, float]) - > bool: return Path(polygon). contains_poi...
Point in Polygon
530265044b7e23379d00076a
[ "Geometry", "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/530265044b7e23379d00076a
6 kyu
#Unflatten a list (Easy) There are several katas like "Flatten a list". These katas are done by so many warriors, that the count of available list to flattin goes down! So you have to build a method, that creates new arrays, that can be flattened! #Shorter: You have to unflatten a list/an array. You get an array of...
algorithms
def unflatten(flat_array): arr = flat_array[:] for i, v in enumerate(arr): if v > 2: arr[i], arr[i + 1: i + v] = arr[i: i + v], [] return arr
Unflatten a list (Easy)
57e2dd0bec7d247e5600013a
[ "Mathematics", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/57e2dd0bec7d247e5600013a
7 kyu
After yet another dispute on their game the Bingo Association decides to change course and automate the game. Can you help the association by writing a method to create a random Bingo card? ## Bingo Cards A Bingo card contains 24 unique and random numbers according to this scheme: * 5 numbers from the B column in t...
algorithms
import random def get_bingo_card(): b = ['B' + str(n) for n in random . sample(range(1, 16), 5)] i = ['I' + str(n) for n in random . sample(range(16, 31), 5)] n = ['N' + str(n) for n in random . sample(range(31, 46), 4)] g = ['G' + str(n) for n in random . sample(range(46, 61), 5)] o = ['O...
Bingo Card
566d5e2e57d8fae53c00000c
[ "Games", "Algorithms" ]
https://www.codewars.com/kata/566d5e2e57d8fae53c00000c
6 kyu
This is the advanced version of the [Vigenère Cipher Helper](https://www.codewars.com/kata/vigenere-cipher-helper) kata. The following assumes that you have already completed that kata -- if you haven't done it yet, you should start there. The basic concept is the same as in the previous kata (see the detailed explan...
algorithms
class VigenereAutokeyCipher: def __init__(self, key, abc): self . key = key self . abc = abc self . alle = len(abc) def cipher(self, s, m): output, keyarr = '', list(self . key) for char in s: try: output += self . abc[(self . abc . index(char) + ...
Vigenère Autokey Cipher Helper
52d2e2be94d26fc622000735
[ "Algorithms", "Ciphers", "Security", "Object-oriented Programming", "Strings" ]
https://www.codewars.com/kata/52d2e2be94d26fc622000735
5 kyu
Extend the String object (JS) or create a function (Python, C#) that converts the value of the String **to and from Base64** using the ASCII (UTF-8 for C#) character set. ### Example (input -> output): ``` 'this is a string!!' -> 'dGhpcyBpcyBhIHN0cmluZyEh' ``` You can learn more about Base64 encoding and decoding <a ...
algorithms
CODES = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" def to_base_64(string): padding = 3 - len(string) % 3 if len(string) % 3 else 0 binary = '' . join(format(ord(i), '08b') for i in string) + '00' * padding return '' . join(CODES[int(binary[i: i + 6], 2)] for i in range(0, len...
Base64 Encoding
5270f22f862516c686000161
[ "Binary", "Strings", "Algorithms" ]
https://www.codewars.com/kata/5270f22f862516c686000161
5 kyu
Esoteric languages are pretty hard to program, but it's fairly interesting to write interpreters for them! Your task is to write a method which will interpret Befunge-93 code! Befunge-93 is a language in which the code is presented not as a series of instructions, but as instructions scattered on a 2D plane; your poin...
algorithms
from random import choice def interpret(code): code = [list(l) for l in code . split('\n')] x, y = 0, 0 dx, dy = 1, 0 output = '' stack = [] string_mode = False while True: move = 1 i = code[y][x] if string_mode: if i == '"': string_mode = False el...
Befunge Interpreter
526c7b931666d07889000a3c
[ "Interpreters", "Algorithms" ]
https://www.codewars.com/kata/526c7b931666d07889000a3c
4 kyu
# Introduction <pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;"> In the United Kingdom, the driving licence is the official document which authorises its holder to operate various types of motor vehicle on highways and some other roads...
reference
from datetime import datetime def driver(data): first, middle, last, dob, gender = data try: d = datetime . strptime(dob, '%d-%b-%Y') except ValueError: d = datetime . strptime(dob, '%d-%B-%Y') return '{:9<5}{[2]}{:0>2}{:0>2}{[3]}{[0]}{[0]}9AA' . format( last[: 5]. upper(),...
Driving Licence
586a1af1c66d18ad81000134
[ "Strings", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/586a1af1c66d18ad81000134
7 kyu
# Introduction <pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;"> A vending machine is a machine that dispenses items such as snacks and beverages to customers automatically, after the customer inserts currency or credit into the machin...
reference
class Item (): def __init__(self, item): self . name = item["name"] self . quantity = item["quantity"] self . price = item["price"] class VendingMachine (): def __init__(self, items, money): self . items = {item["code"]: Item(item) for item in items} self . money = money d...
Vending Machine
586e6d4cb98de09e3800014f
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/586e6d4cb98de09e3800014f
6 kyu
# Introduction <pre style="white-space: pre-wrap;white-space: -moz-pre-wrap;white-space: -pre-wrap;white-space: -o-pre-wrap;word-wrap: break-word;"> Snakes and Ladders is an ancient Indian board game regarded today as a worldwide classic. It is played between two or more players on a gameboard having numbered, gridded...
reference
class SnakesLadders: snakes_and_ladders = { 2: 38, 7: 14, 8: 31, 15: 26, 21: 42, 28: 84, 36: 44, 51: 67, 71: 91, 78: 98, 87: 94, 16: 6, 46: 25, 49: 11, 62: 19, 64: 60, ...
Snakes and Ladders
587136ba2eefcb92a9000027
[ "Design Patterns", "Games", "Fundamentals" ]
https://www.codewars.com/kata/587136ba2eefcb92a9000027
5 kyu
You need to design a recursive function called ```replicate``` which will receive arguments ```times``` and ```number```. The function should return an array containing repetitions of the ```number``` argument. For instance, ```replicate(3, 5)``` should return ```[5,5,5]```. If the ```times``` argument is negative, r...
algorithms
@ countcalls def replicate(times, number): if times > 0: return [number] + replicate(times - 1, number) return []
Recursive Replication
57547f9182655569ab0008c4
[ "Recursion", "Algorithms" ]
https://www.codewars.com/kata/57547f9182655569ab0008c4
7 kyu
Write a function which reduces fractions to their simplest form! Fractions will be presented as an array/tuple (depending on the language) of strictly positive integers, and the reduced fraction must be returned as an array/tuple: ``` input: [numerator, denominator] output: [reduced numerator, reduced denominator] ...
reference
from fractions import Fraction def reduce_fraction(fraction): t = Fraction(* fraction) return (t . numerator, t . denominator)
Reduce My Fraction
576400f2f716ca816d001614
[ "Fundamentals", "Recursion", "Algorithms" ]
https://www.codewars.com/kata/576400f2f716ca816d001614
7 kyu
<h2>Write a function that sums squares of numbers in list that may contain more lists</h2> Example: ```javascript var l = [1,2,3] SumSquares(l) == 14 var l = [[1,2],3] SumSquares(l) == 14 var l = [[[[[[[[[1]]]]]]]]] SumSquares(l) == 1 var l = [10,[[10],10],[10]] SumSquares(l) == 400 ``` Note: your solution must NO...
reference
def sumsquares(l): return sum([i * * 2 if type(i) == int else sumsquares(i) for i in l])
Sum squares of numbers in list that may contain more lists
57882daf90b2f375280000ad
[ "Fundamentals", "Recursion" ]
https://www.codewars.com/kata/57882daf90b2f375280000ad
7 kyu
### self_converge `Goal`: Given a number (with a minimum of 3 digits), return the number of iterations it takes to arrive at a derived number that converges on to itself, as per the following [Kaprekar][Kaprekar] routine. As a learning exercise, come up with a solution that uses recursion. The following steps would be ...
algorithms
def self_converge(number): n, cycle = str(number), set() while n not in cycle: cycle . add(n) s = '' . join(sorted(n)) n = '%0*d' % (len(n), int(s[:: - 1]) - int(s)) return - 1 if not int(n) else len(cycle)
self_converge
54ab259e15613ce0c8001bab
[ "Recursion", "Algorithms" ]
https://www.codewars.com/kata/54ab259e15613ce0c8001bab
5 kyu
# Convert a linked list to a string ## Related Kata Although this Kata is not part of an official Series, you may also want to try out [Parse a linked list from a string](https://www.codewars.com/kata/582c5382f000e535100001a7) if you enjoyed this Kata. ## Preloaded Preloaded for you is a class, struct or derived da...
algorithms
def stringify(list): return 'None' if list == None else str(list . data) + ' -> ' + stringify(list . next)
Convert a linked list to a string
582c297e56373f0426000098
[ "Linked Lists", "Recursion", "Algorithms" ]
https://www.codewars.com/kata/582c297e56373f0426000098
7 kyu
Task ====== Make a custom esolang interpreter for the language [InfiniTick](https://esolangs.org/wiki/InfiniTick). InfiniTick is a descendant of [Tick](https://esolangs.org/wiki/tick) but also very different. Unlike Tick, InfiniTick has 8 commands instead of 4. It also runs infinitely, stopping the program only when a...
reference
def interpreter(tape): memory, ptr, output, iCmd = {}, 0, "", 0 while True: cmd = tape[iCmd] if cmd == ">": ptr += 1 elif cmd == "<": ptr -= 1 elif cmd == "+": memory[ptr] = (memory . get(ptr, 0) + 1) % 256 elif cmd == "-": memory[ptr] = (memory . get(ptr, 0) ...
Esolang: InfiniTick
58817056e7a31c2ceb000052
[ "Esoteric Languages", "Interpreters", "Strings", "Arrays" ]
https://www.codewars.com/kata/58817056e7a31c2ceb000052
5 kyu
Task ======= Make a custom esolang interpreter for the language Tick. Tick is a descendant of [Ticker](https://www.codewars.com/kata/esolang-ticker) but also very different data and command-wise. Syntax/Info ======== Commands are given in character format. Non-command characters should be ignored. Tick has an potent...
reference
def interpreter(tape): memory, ptr, output = {}, 0, "" for command in tape: if command == ">": ptr += 1 elif command == "<": ptr -= 1 elif command == "+": memory[ptr] = (memory . get(ptr, 0) + 1) % 256 elif command == "*": output += chr(memory[ptr]) ...
Esolang: Tick
587edac2bdf76ea23500011a
[ "Esoteric Languages", "Interpreters", "Strings", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/587edac2bdf76ea23500011a
6 kyu
## Task: Consider a sequence where the first two numbers are `0` and `1` and the next number of the sequence is the sum of the previous 2 modulo 3. Write a function that finds the nth number of the sequence. ## Constraints: * #### 1 ≤ N ≤ 10^19 ## Example: ``` sequence(1); 0 sequence(2); 1 sequence(3); 1 ```
reference
def sequence(n): # The sequence of numers repeat after the eighth number return [0, 1, 1, 2, 0, 2, 2, 1][(n - 1) % 8]
The Modulo-3 Sequence
589d33e4e0bbce5d6300061c
[ "Fundamentals" ]
https://www.codewars.com/kata/589d33e4e0bbce5d6300061c
6 kyu
### Task Your friend advised you to see a new performance in the most popular theater in the city. He knows a lot about art and his advice is usually good, but not this time: the performance turned out to be awfully dull. It's so bad you want to sneak out, which is quite simple, especially since the exit is located rig...
games
def seats_in_theater(tot_cols, tot_rows, col, row): return (tot_cols - col + 1) * (tot_rows - row)
Simple Fun #1: Seats in Theater
588417e576933b0ec9000045
[ "Puzzles", "Mathematics" ]
https://www.codewars.com/kata/588417e576933b0ec9000045
8 kyu
This kata is the first of a sequence of four about "Squared Strings". You are given a string of `n` lines, each substring being `n` characters long: For example: `s = "abcd\nefgh\nijkl\nmnop"` We will study some transformations of this square of strings. - Vertical mirror: vert_mirror (or vertMirror or vert-mirror)...
reference
def vert_mirror(s): return "\n" . join(line[:: - 1] for line in s . split("\n")) def hor_mirror(s): return "\n" . join(s . split("\n")[:: - 1]) def oper(fct, s): return fct(s)
Moves in squared strings (I)
56dbe0e313c2f63be4000b25
[ "Fundamentals", "Algorithms", "Strings" ]
https://www.codewars.com/kata/56dbe0e313c2f63be4000b25
7 kyu
Your goal is to implement the method **meanVsMedian** which accepts an *odd-length* array of integers and returns one of the following: * 'mean' - in case **mean** value is **larger than** median value * 'median' - in case **median** value is **larger than** mean value * 'same' - in case both mean and median share the...
reference
from numpy import mean, median def mean_vs_median(numbers): if mean(numbers) > median(numbers): return 'mean' elif mean(numbers) < median(numbers): return 'median' else: return 'same'
Mean vs. Median
5806445c3f1f9c2f72000031
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5806445c3f1f9c2f72000031
7 kyu
Compare two strings by comparing the sum of their values (ASCII character code). * For comparing treat all letters as UpperCase * `null/NULL/Nil/None` should be treated as empty strings * If the string contains other characters than letters, treat the whole string as it would be empty Your method should return `true`...
reference
def string_cnt(s): try: if s . isalpha(): return sum(ord(a) for a in s . upper()) except AttributeError: pass return 0 def compare(s1, s2): return string_cnt(s1) == string_cnt(s2)
Compare Strings by Sum of Chars
576bb3c4b1abc497ec000065
[ "Mathematics", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/576bb3c4b1abc497ec000065
7 kyu
My friend John likes to go to the cinema. He can choose between system A and system B. ``` System A : he buys a ticket (15 dollars) every time System B : he buys a card (500 dollars) and a first ticket for 0.90 times the ticket price, then for each additional ticket he pays 0.90 times the price paid for the previous t...
reference
import math def movie(card, ticket, perc): num = 0 priceA = 0 priceB = card while math . ceil(priceB) >= priceA: num += 1 priceA += ticket priceB += ticket * (perc * * num) return num
Going to the cinema
562f91ff6a8b77dfe900006e
[ "Fundamentals" ]
https://www.codewars.com/kata/562f91ff6a8b77dfe900006e
7 kyu
In this kata, your job is to create a class Dictionary which you can add words to and their entries. Example: ```python >>> d = Dictionary() >>> d.newentry('Apple', 'A fruit that grows on trees') >>> print(d.look('Apple')) A fruit that grows on trees >>> print(d.look('Banana')) Can't find entry for Banana ``` ```jav...
reference
class Dictionary (object): def __init__(self): self . my_dict = {} def look(self, key): return self . my_dict . get(key, "Can't find entry for {}" . format(key)) def newentry(self, key, value): """ new_entry == PEP8 (forced by Codewars) """ self . my_dict[key] = value
Interactive Dictionary
57a93f93bb9944516d0000c1
[ "Fundamentals" ]
https://www.codewars.com/kata/57a93f93bb9944516d0000c1
7 kyu
ASCII85 is a binary-to-ASCII encoding scheme that's used within PDF and Postscript, and which provides data-size savings over base 64. Your task is to extend the String object with two new methods, ```toAscii85``` (```to_ascii85``` in ruby) and ```fromAscii85``` (```from_ascii85``` in ruby), which handle encoding and d...
algorithms
PLAIN, PLAIN_FILLER = (4, 256, 0), chr(0) ASC85, ASC85_FILLER = (5, 85, 33), "u" ZIPPR = "!!!!!", "z" def toAscii85(data): return "<~%s~>" % "" . join(map(lambda x: x . replace(* ZIPPR), quantize(PLAIN_FILLER, data, PLAIN, ASC85))) def fromAscii85(data): return "" . join(quantize(ASC85_FILLER, '...
ASCII85 Encoding & Decoding
5277dc3ff4bfbd9a36000c1c
[ "Binary", "Strings", "Algorithms" ]
https://www.codewars.com/kata/5277dc3ff4bfbd9a36000c1c
5 kyu
Given an array of positive or negative integers <code> I= [i<sub>1</sub>,..,i<sub>n</sub>]</code> you have to produce a sorted array P of the form <code>[ [p, sum of all i<sub>j</sub> of I for which p is a prime factor (p positive) of i<sub>j</sub>] ...]</code> P will be sorted by increasing order of the prime nu...
algorithms
from collections import defaultdict def sum_for_list(lst): def factors(x): p_facs = [] i = 2 while x > 1 or x < - 1: if x % i == 0: p_facs . append(i) x / /= i else: i += 1 return list(set(p_facs)) fac_dict = defaultdict(int) for i in lst: for ...
Sum by Factors
54d496788776e49e6b00052f
[ "Arrays", "Algorithms", "Mathematics" ]
https://www.codewars.com/kata/54d496788776e49e6b00052f
4 kyu
# Task Given a rectangular `matrix` and integers `a` and `b`, consider the union of the ath row and the bth (both 0-based) column of the `matrix`. Return sum of all elements of that union. # Example For ``` matrix = [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]] a = 1 and b = 3 ``` the output shou...
games
def crossing_sum(matrix, row, col): return sum(matrix[row]) + sum(line[col] for line in matrix) - matrix[row][col]
Simple Fun #61: Crossing Sum
5889ab4928c08c08da00009b
[ "Puzzles" ]
https://www.codewars.com/kata/5889ab4928c08c08da00009b
7 kyu
# Area of an annulus When given the length of the arrow as `a`, where `a` is an `integer` and `≥ 1`, calculate the area of the annulus (the grey ring). ![annulus](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAIAAACx0UUtAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAACI5SURBVHhe7Z3Ri1zHl...
games
from math import pi def annulus_area(r): return round(r * r / 4 * pi, 2)
Area of an annulus
5896616336c4bad1c50000d7
[ "Mathematics", "Puzzles" ]
https://www.codewars.com/kata/5896616336c4bad1c50000d7
7 kyu
#Sort the columns of a csv-file You get a string with the content of a csv-file. The columns are separated by semicolons.<br> The first line contains the names of the columns.<br> Write a method that sorts the columns by the names of the columns alphabetically and incasesensitive. An example: ``` Before sorting: As ...
algorithms
def sort_csv_columns(csv_file_content, sep=';', end='\n'): '''Sort a CSV file by column name.''' csv_columns = zip(* (row . split(sep) for row in csv_file_content . split(end))) sorted_columns = sorted(csv_columns, key=lambda col: col[0]. lower()) return end . join(sep . join(...
Sort the columns of a csv-file
57f7f71a7b992e699400013f
[ "Strings", "Arrays", "Algorithms", "Sorting" ]
https://www.codewars.com/kata/57f7f71a7b992e699400013f
6 kyu
In her trip to Italy, Elizabeth Gilbert made it her duty to eat perfect pizza. One day she ordered one for dinner, and then some Italian friends appeared at her room. The problem is that there were many people who ask for a piece of pizza at that moment, and she had a knife that only cuts straight. Given the number of...
algorithms
def max_pizza(n): return n * (n + 1) / / 2 + 1 if n >= 0 else - 1
Pizza pieces
5551dc71101b2cf599000023
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/5551dc71101b2cf599000023
6 kyu
# # Task: * #### Complete the pattern, using the special character ```■ □``` * #### In this kata, we draw some histogram of the sound performance of ups and downs. # # Rules: - parameter ```waves``` The value of sound waves, an array of number, all number in array >=0. - return a string, ```■``` represent...
games
def draw(waves): m = max(waves) rotHist = [('■' * v). rjust(m, '□') for v in waves] return '\n' . join(map('' . join, zip(* rotHist)))
■□ Pattern □■ : Wave
56e67d6166d442121800074c
[ "ASCII Art", "Puzzles" ]
https://www.codewars.com/kata/56e67d6166d442121800074c
6 kyu
# Brainscrambler [Brainscrambler](https://esolangs.org/wiki/Brainscrambler) is an Esoteric programming language. A Brainscrambler program consists of a string containing * command characters * decimal numbers, which are the input of the program. Brainscrabler memory is made up of three stacks storing integers : `A`,...
reference
class Interpreter: def __init__(self): self . stacks = [[0], [0], [0]] self . stk = 0 def read(self, code): res, cur, ln, loop = [], 0, len(code), [] while cur < ln: if code[cur] in '+-': if not self . stacks[self . stk]: self . stacks[self . stk]. append(0) else: ...
Brainscrambler - Esoteric programming #3
56941f177c0a52aef50000a2
[ "Interpreters", "Esoteric Languages" ]
https://www.codewars.com/kata/56941f177c0a52aef50000a2
5 kyu
Write a function ```sort_cards()``` that sorts a shuffled list of cards, so that any given list of cards is sorted by rank, no matter the starting collection. All cards in the list are represented as strings, so that sorted list of cards looks like this: ```['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q',...
algorithms
def sort_cards(cards): return sorted(cards, key="A23456789TJQK" . index)
Sort deck of cards
56f399b59821793533000683
[ "Fundamentals", "Algorithms", "Lists", "Sorting" ]
https://www.codewars.com/kata/56f399b59821793533000683
7 kyu
Write a function `groupIn10s` which takes any number of arguments, groups them into tens, and sorts each group in ascending order. The return value should be an array of arrays, so that numbers between `0` and`9` inclusive are in position `0`, numbers between `10` and `19` are in position `1`, etc. Here's an example...
reference
from collections import defaultdict def group_in_10s(* args): if not args: return [] tens = defaultdict(list) for n in sorted(args): tens[n / / 10]. append(n) return [tens . get(d, None) for d in range(max(tens) + 1)]
Group in 10s
5694d22eb15d78fe8d00003a
[ "Arrays", "Lists", "Fundamentals" ]
https://www.codewars.com/kata/5694d22eb15d78fe8d00003a
6 kyu
A poor miner is trapped in a mine and you have to help him to get out ! Only, the mine is all dark so you have to tell him where to go. In this kata, you will have to implement a method `solve(map, miner, exit)` that has to return the path the miner must take to reach the exit as an array of moves, such as : `['up', ...
games
# name of direction, name of opposite, translation function dirs = [ ('left', 'right', lambda (x, y): (x - 1, y)), ('right', 'left', lambda (x, y): (x + 1, y)), ('up', 'down', lambda (x, y): (x, y - 1)), ('down', 'up', lambda (x, y): (x, y + 1)), ] def solve(map, miner, exit): # we turn ...
Escape the Mines !
5326ef17b7320ee2e00001df
[ "Data Structures", "Algorithms", "Puzzles", "Graph Theory" ]
https://www.codewars.com/kata/5326ef17b7320ee2e00001df
5 kyu
Linked Lists - Insert Nth Implement an InsertNth() function (`insert_nth()` in PHP) which can insert a new node at any index within a list. InsertNth() is a more general version of the Push() function that we implemented in the first kata listed below. Given a list, an index 'n' in the range 0..length, and a data el...
reference
class Node (object): def __init__(self, data, nxt=None): self . data = data self . next = nxt def insert_nth(head, index, data): if index == 0: return Node(data, head) if head and index > 0: head . next = insert_nth(head . next, index - 1, data) return head raise Va...
Linked Lists - Insert Nth Node
55cacc3039607536c6000081
[ "Linked Lists", "Data Structures", "Fundamentals" ]
https://www.codewars.com/kata/55cacc3039607536c6000081
6 kyu
# Linked Lists - Get Nth Implement a `GetNth()` function that takes a linked list and an integer index and returns the node stored at the `Nth` index position. `GetNth()` uses the C numbering convention that the first node is index 0, the second is index 1, ... and so on. So for the list `42 -> 13 -> 666`, `GetNth(1)...
reference
class Node (object): def __init__(self, data): self . data = data self . next = None def get_nth(node, index): v = - 1 n = node while n: v += 1 if v == index: return n n = n . next raise ValueError
Linked Lists - Get Nth Node
55befc42bfe4d13ab1000007
[ "Linked Lists", "Data Structures", "Fundamentals" ]
https://www.codewars.com/kata/55befc42bfe4d13ab1000007
7 kyu
Linked Lists - Length & Count Implement `length` to count the number of nodes in a linked list.<br> ```javascript length(null) => 0 length(1 -> 2 -> 3 -> null) => 3 ``` ```csharp Node.Length(nullptr) => 0 Node.Length(1 -> 2 -> 3 -> nullptr) => 3 ``` ```cpp Length(null) => 0 Length(1 -> 2 -> 3 -> null) => 3 ``` ```cobo...
reference
class Node (object): def __init__(self, data): self . data = data self . next = None def length(node): leng = 0 while node: leng += 1 node = node . next return leng def count(node, data): c = 0 while node: if node . data == data: c += 1 node = node . next ...
Linked Lists - Length & Count
55beec7dd347078289000021
[ "Linked Lists", "Data Structures", "Fundamentals" ]
https://www.codewars.com/kata/55beec7dd347078289000021
6 kyu
Linked Lists - Push & BuildOneTwoThree Write push() and buildOneTwoThree() functions to easily update and initialize linked lists. Try to use the push() function within your buildOneTwoThree() function. Here's an example of push() usage: ```javascript var chained = null chained = push(chained, 3) chained = push(chain...
reference
class Node (object): def __init__(self, data, next=None): self . data = data self . next = next def push(head, data): return Node(data, head) def build_one_two_three(): return Node(1, Node(2, Node(3)))
Linked Lists - Push & BuildOneTwoThree
55be95786abade3c71000079
[ "Linked Lists", "Fundamentals" ]
https://www.codewars.com/kata/55be95786abade3c71000079
7 kyu
You will be given an array of objects representing data about developers who have signed up to attend the next coding meetup that you are organising. Given the following input array: ```javascript var list1 = [ { firstName: 'Nikau', lastName: 'R.', country: 'New Zealand', continent: 'Oceania', age: 39, language: ...
reference
def sort_by_language(arr): return sorted(arr, key=lambda x: (x["language"], x["first_name"]))
Coding Meetup #17 - Higher-Order Functions Series - Sort by programming language
583ea278c68d96a5fd000abd
[ "Functional Programming", "Data Structures", "Arrays", "Fundamentals", "Algorithms", "Sorting" ]
https://www.codewars.com/kata/583ea278c68d96a5fd000abd
7 kyu
Oh No! The song sheets have been dropped in the snow and the lines of each verse have become all jumbled up. <h1>Task</h1> ```if-not:python You have to write a comparator function which can sort the lines back into their correct order, otherwise Christmas will be cancelled! ``` ```if:python You have to write a so...
reference
def song_sorter(lines): return sorted(lines, key=lambda x: ['On', '12', '11', '10', '9', '8', '7', '6', '5', '4', '3', '2', 'and', 'a']. index(x . split()[0]))
The 12 Days of Christmas
57dd3a06eb0537b899000a64
[ "Strings", "Sorting", "Fundamentals" ]
https://www.codewars.com/kata/57dd3a06eb0537b899000a64
7 kyu
## Task Some people are standing in a row in a park. There are trees between them which cannot be moved. Your task is to rearrange the people by their heights in a non-descending order without moving the trees. ## Example For `a = [-1, 150, 190, 170, -1, -1, 160, 180]`, the output should be `[-1, 150, 160, 17...
games
def sort_by_height(a): s = iter(sorted(x for x in a if x != - 1)) return [x if x == - 1 else next(s) for x in a]
Simple Fun #88: Sort By Height
589577f0d1b93ae32a000001
[ "Puzzles", "Sorting", "Algorithms" ]
https://www.codewars.com/kata/589577f0d1b93ae32a000001
7 kyu
You're continuing to enjoy your new piano, as described in <a href="https://www.codewars.com/kata/piano-kata-part-1">Piano Kata, Part 1</a>. You're also continuing the exercise where you start on the very first (leftmost, lowest in pitch) key on the 88-key keyboard, which (as shown below) is the note A, with the little...
reference
def which_note(count): return "A A# B C C# D D# E F F# G G#" . split()[(count - 1) % 88 % 12]
Piano Kata, Part 2
589631d24a7323d18d00016f
[ "Fundamentals" ]
https://www.codewars.com/kata/589631d24a7323d18d00016f
6 kyu
## Your Story "A *piano* in the home meant something." - *Fried Green Tomatoes at the Whistle Stop Cafe* You've just realized a childhood dream by getting a beautiful and beautiful-sounding upright piano from a friend who was leaving the country. You immediately started doing things like playing "<a href="https://en.w...
reference
def black_or_white_key(key_press_count): return "black" if (key_press_count - 1) % 88 % 12 in [1, 4, 6, 9, 11] else "white"
Piano Kata, Part 1
589273272fab865136000108
[ "Fundamentals" ]
https://www.codewars.com/kata/589273272fab865136000108
6 kyu
# Esolang Interpreters #3 - Custom Paintfuck Interpreter ## About this Kata Series "Esolang Interpreters" is a Kata Series that originally began as three separate, independent esolang interpreter Kata authored by [@donaldsebleung](http://codewars.com/users/donaldsebleung) which all shared a similar format and were al...
algorithms
def interpreter(code, iterations, width, height): code = "" . join(c for c in code if c in "[news]*") canvas = [[0] * width for _ in range(height)] row = col = step = count = loop = 0 while step < len(code) and count < iterations: command = code[step] if loop: if command == "[": loo...
Esolang Interpreters #3 - Custom Paintf**k Interpreter
5868a68ba44cfc763e00008d
[ "Esoteric Languages", "Interpreters", "Algorithms", "Tutorials" ]
https://www.codewars.com/kata/5868a68ba44cfc763e00008d
4 kyu
# Esolang Interpreters #2 - Custom Smallfuck Interpreter ## About this Kata Series "Esolang Interpreters" is a Kata Series that originally began as three separate, independent esolang interpreter Kata authored by [@donaldsebleung](http://codewars.com/users/donaldsebleung) which all shared a similar format and were al...
algorithms
def interpreter(code, tape): tape = list(map(int, tape)) ptr = step = loop = 0 while 0 <= ptr < len(tape) and step < len(code): command = code[step] if loop: if command == "[": loop += 1 elif command == "]": loop -= 1 elif command == ">": ptr += 1 ...
Esolang Interpreters #2 - Custom Smallfuck Interpreter
58678d29dbca9a68d80000d7
[ "Esoteric Languages", "Interpreters", "Algorithms", "Tutorials" ]
https://www.codewars.com/kata/58678d29dbca9a68d80000d7
5 kyu
*For the rest of this Kata, I would recommend considering "fuck" to be non-profane.* # Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck) ## About this Kata Series "Esolang Interpreters" is a Kata Series that originally began as three separate, independent esolang interprete...
algorithms
def my_first_interpreter(code): memory, output = 0, "" for command in code: if command == "+": memory += 1 elif command == ".": output += chr(memory % 256) return output
Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck)
586dd26a69b6fd46dd0000c0
[ "Interpreters", "Esoteric Languages", "Algorithms", "Tutorials" ]
https://www.codewars.com/kata/586dd26a69b6fd46dd0000c0
6 kyu
Given the root node of a binary tree (but not necessarily a binary search tree,) write three functions that will print the tree in pre-order, in-order, and post-order. A Node has the following properties: ```javascript var data; // A number or string. Node left; // Undefined if there is no left child. Node right; //...
algorithms
# Pre-order traversal def pre_order(node): return [node . data] + pre_order(node . left) + pre_order(node . right) if node else [] # In-order traversal def in_order(node): return in_order(node . left) + [node . data] + in_order(node . right) if node else [] # Post-order traversal def ...
Binary Tree Traversal
5268956c10342831a8000135
[ "Binary Trees", "Trees", "Recursion", "Data Structures", "Algorithms" ]
https://www.codewars.com/kata/5268956c10342831a8000135
5 kyu
Given the node object: ``` Node: val: <int>, left: <Node> or null, right: <Node> or null ``` write a function `compare(a, b)` which compares the two trees defined by Nodes a and b and returns `true` if they are equal in structure and in value and `false` otherwise. Examples: ``` 1 1 | \ | \ 2 3 ...
algorithms
def compare(a, b): return a . val == b . val and compare(a . left, b . left) and compare(a . right, b . right) if a and b else a == b
Binary Tree Compare
55847fcd3e7dadc9f800005f
[ "Binary Trees", "Algorithms" ]
https://www.codewars.com/kata/55847fcd3e7dadc9f800005f
6 kyu
# Story Hereinafter, `[space]` refers to `" "`, `[tab]` refers to `"\t"`, and `[LF]` refers to `"\n"` for illustrative purposes. This does not mean that you can use these placeholders in your solution. In esoteric language called [Whitespace](http://compsoc.dur.ac.uk/whitespace/), numbers are represented in the follow...
reference
from string import maketrans def whitespace_number(n): return (' \n' if n == 0 else '{:+b}\n' . format(n). translate(maketrans('+-01', ' \t \t')))
Convert integer to Whitespace format
55b350026cc02ac1a7000032
[ "Binary", "Fundamentals" ]
https://www.codewars.com/kata/55b350026cc02ac1a7000032
6 kyu
Oh no! Ghosts have reportedly swarmed the city. It's your job to get rid of them and save the day! In this kata, strings represent buildings while whitespaces within those strings represent ghosts. So what are you waiting for? Return the building(string) without any ghosts(whitespaces)! Example: ``` "Sky scra per" ...
reference
message = "You just wanted my autograph didn't you?" def ghostbusters(building): return building . replace(' ', '') if ' ' in building else message
Ghostbusters (whitespace removal)
5668e3800636a6cd6a000018
[ "Fundamentals", "Regular Expressions", "Strings" ]
https://www.codewars.com/kata/5668e3800636a6cd6a000018
7 kyu
Here is a new kata that Codewars asked me to do related to interviewing and working in a production setting. You might be familar with and have used Angular.js. Among other things, it lets you create your own filters that work as functions. You can then put these in a page to perform specific data changes, such as sho...
algorithms
def shorten_number(suffixes, base): def filter(num_string): try: num = int(num_string) except: return str(num_string) suf_index = 0 while num > base and suf_index < len(suffixes) - 1: num = num / / base suf_index += 1 return str(num) + suffixes[suf_index] return fi...
Number Shortening Filter
56b4af8ac6167012ec00006f
[ "Angular", "Algorithms" ]
https://www.codewars.com/kata/56b4af8ac6167012ec00006f
6 kyu