description
stringlengths
38
154k
category
stringclasses
5 values
solutions
stringlengths
13
289k
name
stringlengths
3
179
id
stringlengths
24
24
tags
listlengths
0
13
url
stringlengths
54
54
rank_name
stringclasses
8 values
The function must return the sequence of titles that match the string passed as an argument. ```if:javascript TITLES is a preloaded sequence of strings. ``` ```javascript TITLES = ['Rocky 1', 'Rocky 2', 'My Little Poney'] search('ock') --> ['Rocky 1', 'Rocky 2'] ``` ```python titles = ['Rocky 1', 'Rocky 2', 'My Li...
bug_fixes
def search(titles, term): return list(filter(lambda title: term in title . lower(), titles))
Breaking search bad
52cd53948d673a6e66000576
[ "Regular Expressions", "Debugging" ]
https://www.codewars.com/kata/52cd53948d673a6e66000576
6 kyu
Dear Coder, We at [SomeLargeCompany] have decided to expand on the functionality of our online text editor. We have written a new function that accepts a phrase, a word and an array of indexes. We want this function to return the phrase, with the word inserted at each of the indexes given by the array. However, our ...
bug_fixes
def insert_at_indexes(phrase, word, indexes): for i in indexes[:: - 1]: phrase = phrase[: i] + word + phrase[i:] return phrase
Inserting multiple strings into another string
52f3eeb274c7e693a600288e
[ "Strings", "Debugging" ]
https://www.codewars.com/kata/52f3eeb274c7e693a600288e
6 kyu
<h1 id="heading">Debug the functions</h1> <i>Should be easy, begin by looking at the code. Debug the code and the functions should work.</i> <i>There are three functions: ```Multiplication (x)``` ```Addition (+)``` and ```Reverse (!esreveR)```</i> <style> i { font-size:16px; } #heading { padding: 2em; text-al...
bug_fixes
from functools import reduce from operator import mul def multi(l_st): return reduce(mul, l_st) def add(l_st): return sum(l_st) def reverse(s): return s[:: - 1]
Debug the functions EASY
5844a422cbd2279a0c000281
[ "Debugging" ]
https://www.codewars.com/kata/5844a422cbd2279a0c000281
7 kyu
<h1>Reducing Problems - Bug Fixing #8</h1> <p> Oh no! Timmy's reduce is causing problems, Timmy's goal is to calculate the two teams scores and return the winner but timmy has gotten confused and sometimes teams don't enter their scores, total the scores out of 3! Help timmy fix his program! Return true if team 1 wins...
bug_fixes
def calculate_total(team1, team2): return sum(team1) > sum(team2)
Reducing Problems - Bug Fixing #8
55d2603d506a40e162000056
[ "Debugging", "Arrays" ]
https://www.codewars.com/kata/55d2603d506a40e162000056
7 kyu
Here we have a function that help us spam our hearty laughter. But is not working! I need you to find out why... Expected results: ```javascript spam(1); // hue spam(6); // huehuehuehuehuehue spam(14); // huehuehuehuehuehuehuehuehuehuehuehuehuehue ``` ```php spam(1); // 'hue' spam(6); // 'huehuehuehuehuehue' spam...
bug_fixes
# fix this code! def spam(number): return 'hue' * number
Multiply characters
52e9aa89b5acdd26d3000127
[ "Strings", "Fundamentals", "Debugging" ]
https://www.codewars.com/kata/52e9aa89b5acdd26d3000127
7 kyu
**Debug** a function called calculate that takes 3 values. The first and third values are numbers. The second value is a character. If the character is "+" , "-", "\*", or "/", the function will return the result of the corresponding mathematical function on the two numbers. If the string is not one of the specified ch...
bug_fixes
def calculate(a, o, b): if o == "+": return a + b if o == "-": return a - b if o == "*": return a * b if o == "/" and b != 0: return a / b # one-liner # return [a+b, a-b, a*b, a/b if b else None, None]["+-*/".find(o)]
Debug Basic Calculator
56368f37d464c0a43c00007f
[ "Fundamentals", "Debugging" ]
https://www.codewars.com/kata/56368f37d464c0a43c00007f
7 kyu
<h1>Failed Sort - Bug Fixing #4</h1> Oh no, Timmy's Sort doesn't seem to be working? Your task is to fix the sortArray function to sort all numbers in ascending order
bug_fixes
def sort_array(value): return "" . join(sorted(value))
Failed Sort - Bug Fixing #4
55c7f90ac8025ebee1000062
[ "Debugging", "Sorting" ]
https://www.codewars.com/kata/55c7f90ac8025ebee1000062
7 kyu
# Class conundrum - Bug Fixing #7 Oh no! Timmy's `List` class has broken! Can you help Timmy and fix his class? Timmy has a `List` class he has created, this is used for type strict arrays (which Timmy calls Lists). When Timmy calls the `count` property of the list it still remains at `0` when adding items. Also it...
bug_fixes
class List: def __init__(self, list_type): self . type = list_type self . items = [] self . count = 0 def add(self, item): if type(item) != self . type: return "This item is not of type: {}" . format(self . type . __name__) self . items += [item] self . count += 1 retur...
Class conundrum - Bug Fixing #7
55cd4ce59382498cbd000080
[ "Debugging" ]
https://www.codewars.com/kata/55cd4ce59382498cbd000080
7 kyu
You have an award-winning garden and every day the plants need exactly 40mm of water. You created a great piece of JavaScript to calculate the amount of water your plants will need when you have taken into consideration the amount of rain water that is forecast for the day. Your jealous neighbour hacked your computer a...
reference
def rain_amount(mm): if mm < 40: return "You need to give your plant " + str(40 - mm) + "mm of water" else: return "Your plant has had more than enough water for today!"
Fix your code before the garden dies!
57158fb92ad763bb180004e7
[ "Fundamentals", "Debugging" ]
https://www.codewars.com/kata/57158fb92ad763bb180004e7
8 kyu
Here is a piece of code: ```javascript function getStatus(isBusy) { var msg = (isBusy ? "busy" : "available"); return { status: msg } } ``` ```python def get_status(is_busy): status = "busy" if is_busy else "available" return status ``` ```ruby def get_status(is_busy) status = is_busy ? "busy...
bug_fixes
def get_status(is_busy): status = "busy" if is_busy else "available" return {"status": status}
Unexpected parsing
54fdaa4a50f167b5c000005f
[ "Debugging" ]
https://www.codewars.com/kata/54fdaa4a50f167b5c000005f
8 kyu
Jack really likes his number five: the trick here is that you have to multiply each number by 5 raised to the number of digits of each numbers, so, for example: ``` 3 --> 15 ( 3 * 5¹) 10 --> 250 ( 10 * 5²) 200 --> 25000 (200 * 5³) 0 --> 0 ( 0 * 5¹) -3 --> -15 ( -3 * 5¹) ```
reference
def multiply(n): return n * 5 * * len(str(abs(n)))
Multiply the number
5708f682c69b48047b000e07
[ "Fundamentals" ]
https://www.codewars.com/kata/5708f682c69b48047b000e07
8 kyu
# Fix the Bugs (Syntax) - My First Kata ## Overview Hello, this is my first Kata so forgive me if it is of poor quality. In this Kata you should fix/create a program that ```return```s the following values: - ```false/False``` if either a or b (or both) are not numbers - ```a % b``` plus ```b % a``` if both argum...
bug_fixes
def my_first_kata(a, b): # your code here if type(a) == int and type(b) == int: return a % b + b % a else: return False
Fix the Bugs (Syntax) - My First Kata
56aed32a154d33a1f3000018
[ "Debugging" ]
https://www.codewars.com/kata/56aed32a154d33a1f3000018
8 kyu
Some new animals have arrived at the zoo. The zoo keeper is concerned that perhaps the animals do not have the right tails. To help her, you must correct the broken function to make sure that the second argument (tail), is the same as the last letter of the first argument (body) - otherwise the tail wouldn't fit! If t...
bug_fixes
def correct_tail(body, tail): return body . endswith(tail)
Is this my tail?
56f695399400f5d9ef000af5
[ "Debugging" ]
https://www.codewars.com/kata/56f695399400f5d9ef000af5
8 kyu
We want an array, but not just any old array, an array with contents! Write a function that produces an array with the numbers `0` to `N-1` in it. For example, the following code will result in an array containing the numbers `0` to `4`: ``` arr(5) // => [0,1,2,3,4] ``` Note: The parameter is optional. So you have t...
reference
def arr(n=0): return list(range(n))
Filling an array (part 1)
571d42206414b103dc0006a1
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/571d42206414b103dc0006a1
8 kyu
Your boss decided to save money by purchasing some cut-rate optical character recognition software for scanning in the text of old novels to your database. At first it seems to capture words okay, but you quickly notice that it throws in a lot of numbers at random places in the text. ### Examples (input -> output) ``...
reference
def string_clean(s): return '' . join(x for x in s if not x . isdigit())
String cleaning
57e1e61ba396b3727c000251
[ "Regular Expressions", "Fundamentals", "Strings" ]
https://www.codewars.com/kata/57e1e61ba396b3727c000251
8 kyu
The number ```$89$``` is the first integer with more than one digit that fulfills the property partially introduced in the title of this kata. What's the use of saying "Eureka"? Because this sum gives the same number: ```$89 = 8^1 + 9^2$``` The next number in having this property is ```$135$```: See this property ag...
reference
def dig_pow(n): return sum(int(x) * * y for y, x in enumerate(str(n), 1)) def sum_dig_pow(a, b): return [x for x in range(a, b + 1) if x == dig_pow(x)]
Take a Number And Sum Its Digits Raised To The Consecutive Powers And ....¡Eureka!!
5626b561280a42ecc50000d1
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/5626b561280a42ecc50000d1
6 kyu
You are given an *odd-length* array of integers, in which all of them are the same, except for one single number. Complete the method which accepts such an array, and returns that single different number. **The input array will always be valid!** (odd-length >= 3) ## Examples ``` [1, 1, 2] ==> 2 [17, 17, 3, 17, 17,...
reference
def stray(arr): for x in arr: if arr . count(x) == 1: return x
Find the stray number
57f609022f4d534f05000024
[ "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/57f609022f4d534f05000024
7 kyu
```if-not:javascript,python Write function `parseFloat` which takes an input and returns a number or `Nothing` if conversion is not possible. ``` ```if:python Write function `parse_float` which takes a string/list and returns a number or 'none' if conversion is not possible. ``` ```if:javascript Write function `parse...
reference
def parse_float(string): try: return float(string) except: return None
Parse float
57a386117cb1f31890000039
[ "Fundamentals" ]
https://www.codewars.com/kata/57a386117cb1f31890000039
8 kyu
There are 32 letters in the Polish alphabet: 9 vowels and 23 consonants. Your task is to change the letters with diacritics: ``` ą -> a, ć -> c, ę -> e, ł -> l, ń -> n, ó -> o, ś -> s, ź -> z, ż -> z ``` and print out the string without the use of the Polish letters. For example: ``` "Jędrzej Błądziński" --> "J...
reference
def correct_polish_letters(s): return s . translate(str . maketrans("ąćęłńóśźż", "acelnoszz"))
Polish alphabet
57ab2d6072292dbf7c000039
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/57ab2d6072292dbf7c000039
8 kyu
Write a simple function that takes a `Date` as a parameter and returns a `Boolean` representing whether the date is today or not. Make sure that your function does not return a false positive by only checking the day.
games
from datetime import datetime def is_today(date): return date . date() == datetime . today(). date()
Is the date today
563c13853b07a8f17c000022
[ "Date Time", "Puzzles" ]
https://www.codewars.com/kata/563c13853b07a8f17c000022
8 kyu
Ahoy matey! You are a leader of a small pirate crew. And you have a plan. With the help of OOP you wish to make a pretty efficient system to identify ships with heavy booty on board! Unfortunately for you, people weigh a lot these days, so how do you know if a ship is full of gold and not people? You begin with writ...
reference
class Ship: def __init__(self, draft, crew): self . draft = draft self . crew = crew # Your code here def is_worth_it(self): return self . draft - self . crew * 1.5 > 20
OOP: Object Oriented Piracy
54fe05c4762e2e3047000add
[ "Object-oriented Programming", "Fundamentals" ]
https://www.codewars.com/kata/54fe05c4762e2e3047000add
8 kyu
## Task Description You're re-designing a blog, and the blog's posts have the `Weekday Month Day, time` format for showing the date and time when a post was made, e.g., `Friday May 2, 7pm`. You're running out of screen real estate, and on some pages you want to display a shorter format, `Weekday Month Day` that omits...
reference
def shorten_to_date(long_date): return long_date . split(',')[0]
Remove the time
56b0ff16d4aa33e5bb00008e
[ "Date Time", "Parsing", "Fundamentals" ]
https://www.codewars.com/kata/56b0ff16d4aa33e5bb00008e
8 kyu
In this kata, we will make a function to test whether a period is late. Our function will take three parameters: last - The Date object with the date of the last period today - The Date object with the date of the check cycleLength - Integer representing the length of the cycle in days Return true if the number o...
reference
def period_is_late(last, today, cycle_length): return (today - last). days > cycle_length
Is your period late?
578a8a01e9fd1549e50001f1
[ "Fundamentals", "Date Time" ]
https://www.codewars.com/kata/578a8a01e9fd1549e50001f1
8 kyu
# Classy Classes Basic Classes, this kata is mainly aimed at the new JS ES6 Update introducing classes ### Task Your task is to complete this Class, the Person class has been created. You must fill in the Constructor method to accept a name as string and an age as number, complete the get Info property and getInfo...
reference
class Person: def __init__(self, name, age): self . name = name self . age = age @ property def info(self): return '{}s age is {}' . format(self . name, self . age)
Classy Classes
55a144eff5124e546400005a
[ "Fundamentals", "Object-oriented Programming" ]
https://www.codewars.com/kata/55a144eff5124e546400005a
8 kyu
# Invalid Login - Bug Fixing #11 Oh NO! Timmy has moved divisions... but now he's in the field of security. Timmy, being the top coder he is, has allowed some bad code through. You must help Timmy and filter out any injected code! ## Task Your task is simple, search the password string for any injected code (Injecte...
bug_fixes
def validate(username, password): database = Database() return database . login(username, password)
Invalid Login - Bug Fixing #11
55e4c52ad58df7509c00007e
[ "Security", "Debugging" ]
https://www.codewars.com/kata/55e4c52ad58df7509c00007e
8 kyu
## Terminal game turn function You are creating a text-based terminal version of your favorite board game. In the board game, each turn has six steps that must happen in this order: roll the dice, move, combat, get coins, buy more health, and print status. --- You are using a library (`Game.Logic` in C#) that alread...
reference
def do_turn(): roll_dice() move() combat() get_coins() buy_health() print_status()
Grasshopper - Terminal Game Turn Function
56019d3b2c39ccde76000086
[ "Fundamentals" ]
https://www.codewars.com/kata/56019d3b2c39ccde76000086
8 kyu
A variation of determining leap years, assuming only integers are used and years can be negative and positive. Write a function which will return the days in the year and the year entered in a string. For example: ````if:javascript ```javascript yearDays(2000) returns "2000 has 366 days" ``` ```` ````if-not:javascri...
reference
def year_days(year): days = 365 if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: days += 1 return "%d has %d days" % (year, days)
Days in the year
56d6c333c9ae3fc32800070f
[ "Date Time", "Fundamentals" ]
https://www.codewars.com/kata/56d6c333c9ae3fc32800070f
8 kyu
You should get and parse the html of the [codewars leaderboard page](https://www.codewars.com/users/leaderboard). You can use `Nokogiri`(Ruby) or `BeautifulSoup`(Python) or `CheerioJS`(Javascript). For Javascript: Return a Promise resolved with your 'Leaderboard' Object! ---- ### Note: Use the Overall leaderboar...
reference
from bs4 import BeautifulSoup import requests URL = 'https://www.codewars.com/users/leaderboard' class solution: class user: def __init__(self, name, clan, honor): self . name = name self . clan = clan self . honor = honor class FuckYourIndex (list): def __init__(self, L): ...
Scraping: Codewars Top 500 Users
581c06b95cfa838603000435
[ "Fundamentals" ]
https://www.codewars.com/kata/581c06b95cfa838603000435
5 kyu
A [pernicious number](https://en.wikipedia.org/wiki/Pernicious_number) is a positive integer whose binary digit sum (or [Hamming weight](https://en.wikipedia.org/wiki/Hamming_weight)) is a prime number. ``` 25 = 11001 --> digit sum = 3 --> 3 is prime --> therefore 25 is a pernicious number 75 = 1001011 --> digit...
algorithms
def pernicious(n): return [x for x in range(int(n) + 1) if bin(x). count("1") in [2, 3, 5, 7, 11, 13]] or "No pernicious numbers"
Pernicious Numbers
56e195d02bb22479e50016af
[ "Arrays", "Binary", "Algorithms" ]
https://www.codewars.com/kata/56e195d02bb22479e50016af
7 kyu
Who knows the nursery rhyme <a href="https://www.youtube.com/watch?v=Ak7kedzR8bg">Ten Green Bottles</a>? Lyrics: ``` 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 wall. Nine green bottles ha...
algorithms
def ten_green_bottles(n): numbers = {10: 'ten', 9: 'nine', 8: 'eight', 7: 'seven', 6: 'six', 5: 'five', 4: 'four', 3: 'three', 2: 'two', 1: 'one', 0: 'no'} res = [] for x in range(n, 0, - 1): s = f""" { numbers [ x ]. capitalize ()} green bottle { 's' if x > 1 else '' } hanging on th...
Ten Green Bottles
5838e2978bbc04b7cd000008
[ "Algorithms" ]
https://www.codewars.com/kata/5838e2978bbc04b7cd000008
7 kyu
Imagine you are in a universe where you can just perform the following arithematic operations. Addition(+), Subtraction(-), Multiplication(\*), Division(/). You are given given a postfix expression. Postfix expression is where operands come after operator. Each operator and operand are seperated by a space. You need to...
algorithms
def postfix_evaluator(expr): stack = [] operators = "- + * //" . split() for i in expr . replace("/", "//"). split(): if i in operators: y, x = stack . pop(), stack . pop() i = str(eval(x + i + y)) stack . append(i) return int(stack[0])
Evaluate a postfix expression
577e9095d648a15b800000d4
[ "Algorithms" ]
https://www.codewars.com/kata/577e9095d648a15b800000d4
5 kyu
We define a special score for a word (ssw) as follows. We multiply the corresponding 10 - base ascii code for each letter of the word by its respective frequency of this letter in the word, we collect these addens and we sum them up. For example for the word, ```investigation``` we have the respective ascci codes and ...
reference
import itertools as it def score(word): return sum(ord(c) for c in word) WORDS = sorted(sorted(WORD_LIST, key=score), key=len) WORDS = {l: [(s, list(ws)) for s, ws in it . groupby(g, key=score)] for l, g in it . groupby(WORDS, key=len)} def find_word(length, max_ssw): t...
Special Scores For Words
563c9f8073ccb1464d0000ae
[ "Fundamentals", "Data Structures", "Algorithms", "Memoization" ]
https://www.codewars.com/kata/563c9f8073ccb1464d0000ae
6 kyu
The central dogma of molecular biology is that DNA is transcribed into RNA, which is then tranlsated into protein. RNA, like DNA, is a long strand of nucleic acids held together by a sugar backbone (ribose in this case). Each segment of three bases is called a <i>codon</i>. Molecular machines called ribosomes translate...
reference
from itertools import takewhile AMINO_ACID = { # Phenylalanine 'UUC': 'F', 'UUU': 'F', # Leucine 'UUA': 'L', 'UUG': 'L', 'CUU': 'L', 'CUC': 'L', 'CUA': 'L', 'CUG': 'L', # Isoleucine 'AUU': 'I', 'AUC': 'I', 'AUA': 'I', # Methionine 'AUG': 'M', # Valine 'GUU': 'V', 'GUC'...
RNA to Protein Sequence Translation
555a03f259e2d1788c000077
[ "Fundamentals" ]
https://www.codewars.com/kata/555a03f259e2d1788c000077
6 kyu
Base on the fairy tale [Diamonds and Toads](https://en.wikipedia.org/wiki/Diamonds_and_Toads) from Charles Perrault. In this kata you will have to complete a function that take 2 arguments: - A string, that correspond to what the daugther says. - A string, that tell you wich fairy the girl have met, this one can be `...
reference
from collections import Counter def diamonds_and_toads(sentence, fairy): c = Counter(sentence) d = {'good': ['ruby', 'crystal'], 'evil': ['python', 'squirrel']} return {s: c[s[0]] + 2 * c[s[0]. upper()] for s in d[fairy]}
Diamonds and Toads
57fa537f8b0760c7da000407
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/57fa537f8b0760c7da000407
6 kyu
In genetics a reading frame is a way to divide a sequence of nucleotides (DNA bases) into a set of consecutive non-overlapping triplets (also called codon). Each of this triplets is translated into an amino-acid during a translation process to create proteins. In a single strand of DNA you find 3 Reading frames, for e...
algorithms
from preloaded import codons def translate_with_frame(dna, frames=[1, 2, 3, - 1, - 2, - 3]): rdna = dna . translate(str . maketrans('AGTC', 'TCAG'))[:: - 1] return ['' . join(codons . get([rdna, dna][fr > 0][k: k + 3], '') for k in range(abs(fr) - 1, len(dna), 3)) for fr in frames]
Translate DNA in 6 frames
5708ef48fe2d018413000776
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/5708ef48fe2d018413000776
5 kyu
## Task Give you two strings: ```s1``` and ```s2```. If they are opposite, return `true`; otherwise, return `false`. Note: The result should be a boolean value, instead of a string. The ```opposite``` means: All letters of the two strings are the same, but the case is opposite. you can assume that the string only con...
games
def is_opposite(s1, s2): return False if not (s1 or s2) else s1 . swapcase() == s2
They say that only the name is long enough to attract attention. They also said that only a simple Kata will have someone to solve it. This is a sadly story #1: Are they opposite?
574b1916a3ebd6e4fa0012e7
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/574b1916a3ebd6e4fa0012e7
8 kyu
# Task You are given an array of integers that you want distribute between several groups. The first group should contain numbers from 1 to 10<sup>4</sup>, the second should contain those from 10<sup>4</sup> + 1 to 2 x 10<sup>4</sup>, ..., the 100<sup>th</sup> one should contain numbers from 99 x 10<sup>4</sup> + 1 to...
games
def numbers_grouping(a): return len(set((n - 1) / / 10000 for n in a)) + len(a)
Simple Fun #34: Numbers Grouping
588711735ea0b4649e000001
[ "Puzzles" ]
https://www.codewars.com/kata/588711735ea0b4649e000001
7 kyu
# Task `N` candles are placed in a row, some of them are initially lit. For each candle from the 1st to the Nth the following algorithm is applied: if the observed candle is lit then states of this candle and all candles before it are changed to the opposite. Which candles will remain lit after applying the algorithm ...
games
def switch_lights(initial_states): states = list(initial_states) parity = 0 for i in reversed(range(len(states))): parity ^= initial_states[i] states[i] ^= parity return states
Simple Fun #39: Switch Lights
5888145122fe8620950000f0
[ "Puzzles" ]
https://www.codewars.com/kata/5888145122fe8620950000f0
7 kyu
The pair of integer numbers `(m, n)`, such that `10 > m > n > 0`, (below 10), that its sum, `(m + n)`, and rest, `(m - n)`, are perfect squares, is (5, 4). Let's see what we have explained with numbers. ``` 5 + 4 = 9 = 3² 5 - 4 = 1 = 1² (10 > 5 > 4 > 0) ``` The pair of numbers `(m, n)`, closest to and below 50, havi...
reference
def closest_pair_tonum(uLim): return next((a, b) for a in reversed(range(1, uLim)) for b in reversed(range(1, a)) if not (a + b) * * .5 % 1 and not (a - b) * * .5 % 1)
The Sum and The Rest of Certain Pairs of Numbers have to be Perfect Squares
561e1e2e6b2e78407d000011
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/561e1e2e6b2e78407d000011
7 kyu
Santa is coming to town and he needs your help finding out who's been naughty or nice. You will be given an entire year of JSON data following this format: ```javascript { January: { '1': 'Naughty','2': 'Naughty', ..., '31': 'Nice' }, February: { '1': 'Nice','2': 'Naughty', ..., '28': 'Nice...
reference
def naughty_or_nice(data): nice = 0 for month in data: for day in data[month]: nice += 1 if data[month][day] == "Nice" else - 1 return "Nice!" if nice >= 0 else "Naughty!"
Naughty or Nice
5662b14e0a1fb8320a00005c
[ "JSON", "Fundamentals" ]
https://www.codewars.com/kata/5662b14e0a1fb8320a00005c
7 kyu
There are many word games that can help to make our minds more agile. Many TV programs, in different countries, use them as entertainment for the audience. Lorraine had tried to win one of them many times but she was not successful in her attempts. The TV contest is as follows: - The TV show host gives a random calle...
reference
def unscramble(scramble): return [i for i in word_list if sorted(i) == sorted(scramble)]
Lorraine Wants to Win the TV Contest
562dbaf65d4ab6685c0000ed
[ "Fundamentals", "Algorithms", "Data Structures" ]
https://www.codewars.com/kata/562dbaf65d4ab6685c0000ed
7 kyu
Your task is to write a function that takes two or more objects and returns a new object which combines all the input objects. All input object properties will have only numeric values. Objects are combined together so that the values of matching keys are added together. An example: ```javascript const objA = { a: ...
reference
def combine(* bs): c = {} for b in bs: for k, v in b . items(): c[k] = v + c . get(k, 0) return c
Combine objects
56bd9e4b0d0b64eaf5000819
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/56bd9e4b0d0b64eaf5000819
7 kyu
Colour plays an important role in our lifes. Most of us like this colour better then another. User experience specialists believe that certain colours have certain psychological meanings for us. You are given a 2D array, composed of a colour and its 'common' association in each array element. The function you will wri...
reference
def colour_association(arr): return [{k: v} for k, v in arr]
Colour Association
56d6b7e43e8186c228000637
[ "Fundamentals" ]
https://www.codewars.com/kata/56d6b7e43e8186c228000637
7 kyu
In genetics 2 differents DNAs sequences can code for the same protein. This is due to the redundancy of the genetic code, in fact 2 different tri-nucleotide can code for the same amino-acid. For example the tri-nucleotide 'TTT' and the tri-nucleotide 'TTC' both code for the amino-acid 'F'. For more information you ca...
algorithms
def code_for_same_protein(seq1, seq2): return all(codons[seq1[c: c + 3]] == codons[seq2[c: c + 3]] for c in range(0, len(seq1), 3))
2 DNAs sequences, coding for same protein?
57cbb9e240e3024aae000b26
[ "Strings", "Algorithms", "Arrays" ]
https://www.codewars.com/kata/57cbb9e240e3024aae000b26
7 kyu
Complete the method that takes a sequence of objects with two keys each: country or state, and capital. Keys may be symbols or strings. The method should return an array of sentences declaring the state or country and its capital. ## Examples ```ruby state_capitals = [{state: 'Maine', capital: 'Augusta'}] capital(s...
reference
def capital(capitals): return [f"The capital of { c . get ( 'state' ) or c [ 'country' ]} is { c [ 'capital' ]} " for c in capitals]
Find the Capitals
53573877d5493b4d6e00050c
[ "Fundamentals" ]
https://www.codewars.com/kata/53573877d5493b4d6e00050c
7 kyu
<p>In this finite version of <a href="http://en.wikipedia.org/wiki/Conway's_Game_of_Life">Conway's Game of Life</a> (here is an excerpt of the rules) ... </p> <p> <i> The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, alive o...
games
def next_gen(cells): ng = Life(cells) return ng . process(1) class Life: def __init__(self, cells): self . cells = cells self . neighbor = [(- 1, - 1), (- 1, 1), (1, 1), (1, - 1), (0, 1), (0, - 1), (1, 0), (- 1, 0)] self . _forLife = lambda x, y: self . _...
Conway's Game of Life
525fbff0594da0665c0003a3
[ "Games", "Graphics", "Puzzles", "Cellular Automata" ]
https://www.codewars.com/kata/525fbff0594da0665c0003a3
5 kyu
Your task is to implement a function that calculates an election winner from a list of voter selections using an [Instant Runoff Voting](http://en.wikipedia.org/wiki/Instant-runoff_voting) algorithm. If you haven't heard of IRV, here's a basic overview (slightly altered for this kata): - Each voter selects several can...
algorithms
from collections import Counter def runoff(voters): while voters[0]: poll = Counter(ballot[0] for ballot in voters) winner, maxscore = max(poll . items(), key=lambda x: x[1]) minscore = min(poll . values()) if maxscore * 2 > len(voters): return winner voters = [[c for c in voter ...
Instant Runoff Voting
52996b5c99fdcb5f20000004
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/52996b5c99fdcb5f20000004
4 kyu
<img src=http://upload.wikimedia.org/wikipedia/commons/thumb/f/f0/Chickpea_Cakes_-_Kolkata_2011-03-24_2015.JPG/320px-Chickpea_Cakes_-_Kolkata_2011-03-24_2015.JPG> Welcome Warrior! Let's play a game! You've gotten challenged by a lot of kata, now it's time for you to challenge the kata! In a room is a table with a pi...
games
from heapq import heapify, heappop, heappush class Player: def __init__(self, cakes): # We will compute and store all possible states for the game # The boolean value indicates if a victory is possible self . states = {(1, 1): True, (1, 2): False, (1, 3): False, (2, 1): False} # ...
Don't Eat the Last Cake!
5384df88aa6fc164bb000e7d
[ "Puzzles" ]
https://www.codewars.com/kata/5384df88aa6fc164bb000e7d
5 kyu
Steve and Josh are bored and want to play something. They don't want to think too much, so they come up with a really simple game. Write a function called winner and figure out who is going to win. They are dealt the same number of cards. They both flip the card on the top of their deck. Whoever has a card with higher...
algorithms
def winner(deck_Steve, deck_Josh): deck = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'] Steve = 0 Josh = 0 for i in range(len(deck_Steve)): if deck . index(deck_Steve[i]) > deck . index(deck_Josh[i]): Steve += 1 elif deck . index(deck_Steve[i]) < deck . index(deck_...
Simple card game
53417de006654f4171000587
[ "Arrays", "Games", "Algorithms" ]
https://www.codewars.com/kata/53417de006654f4171000587
6 kyu
Complete the function that determines the score of a hand in the card game [Blackjack](https://en.wikipedia.org/wiki/Blackjack) (aka 21). The function receives an array of strings that represent each card in the hand (`"2"`, `"3",` ..., `"10"`, `"J"`, `"Q"`, `"K"` or `"A"`) and should return the score of the hand (int...
algorithms
def score_hand(a): n = sum(11 if x == "A" else 10 if x in "JQK" else int(x) for x in a) for _ in range(a . count("A")): if n > 21: n -= 10 return n
Blackjack Scorer
534ffb35edb1241eda0015fe
[ "Games", "Algorithms" ]
https://www.codewars.com/kata/534ffb35edb1241eda0015fe
5 kyu
Your task is to create a function that will take an integer and return the result of the look-and-say function on that integer. This should be a general function that takes as input any positive integer, and returns an integer; inputs are not limited to the sequence which starts with "1". Conway's Look-and-say sequen...
algorithms
from itertools import groupby def look_say(n): return int("" . join(f' { len ( list ( v ))}{ k } ' for k, v in groupby(str(n))))
Conway's Look and Say - Generalized
530045e3c7c0f4d3420001af
[ "Algorithms" ]
https://www.codewars.com/kata/530045e3c7c0f4d3420001af
5 kyu
The Western Suburbs Croquet Club has two categories of membership, Senior and Open. They would like your help with an application form that will tell prospective members which category they will be placed. To be a senior, a member must be at least 55 years old and have a handicap greater than 7. In this croquet club, ...
reference
def openOrSenior(data): return ["Senior" if age >= 55 and handicap >= 8 else "Open" for (age, handicap) in data]
Categorize New Member
5502c9e7b3216ec63c0001aa
[ "Fundamentals" ]
https://www.codewars.com/kata/5502c9e7b3216ec63c0001aa
7 kyu
## An identifier is simply a name... Can you amend this object so that its properties comprise only vaild identifiers?
bug_fixes
Person = { '1stname': "John", 'second-name': "Doe", 'email@ddress': "john.doe@email.com", 'male.female': "M" }
What's wrong with these identifiers?
56bb01de0e8b29de50000b19
[ "Bugs", "Fundamentals", "Rules", "Language Syntax" ]
https://www.codewars.com/kata/56bb01de0e8b29de50000b19
8 kyu
In Haskell, _Monads_ are simple containers, or even 'box-like' datastructures, of which lists are included, which can respond to certain functions, which are defined in the Monad typeclass. (To put it simply!) In this kata, you must implement the __Bind__ function for lists, or arrays. In haskell, the function is repr...
algorithms
def bind(lst, func): return [y for x in lst for y in func(x)]
Binding within the List Monad
546e416c8e3b6bf82f0002f2
[ "Monads", "Lists", "Algorithms" ]
https://www.codewars.com/kata/546e416c8e3b6bf82f0002f2
6 kyu
## Prologue You're part of a team porting MS Paint into the browser and currently working on a new UI component that allows user to control the canvas zoom level. According to the wireframes delivered to you in PowerPoint format the user should be able to *cycle* through specified zoom levels by clicking a button in ...
algorithms
from typing import List, Optional def cycle(d: int, v: List[int], c: int) - > Optional[int]: try: return v[v . index(c) + d] except ValueError: return except IndexError: return v[0]
Cycle a list of values
5456812629ccbf311b000078
[ "Algorithms" ]
https://www.codewars.com/kata/5456812629ccbf311b000078
6 kyu
This is a hard version of <a href = 'http://www.codewars.com/kata/56a1c074f87bc2201200002e'>How many are smaller than me?</a>. If you have troubles solving this one, have a look at the easier kata first. Write ```javascript function smaller(arr) ``` ```rust fn smaller(arr: &[i32]) -> Vec<usize> ``` that given an array...
algorithms
class Tree: ''' v,r,l: value, left, right, n: number of occurrences of v lt: number of numbers lower than v (in the left subtree only) ''' def __init__(self, v): self . v, self . l, self . r, self . n, self . lt = v, None, None, 1, 0 def insert(tree, v): if not tree: re...
How many are smaller than me II?
56a1c63f3bc6827e13000006
[ "Algorithms", "Performance" ]
https://www.codewars.com/kata/56a1c63f3bc6827e13000006
3 kyu
Write a function that given, an array ```arr```, returns an array containing at each index ```i``` the amount of numbers that are smaller than ```arr[i]``` to the right. For example: ``` * Input [5, 4, 3, 2, 1] => Output [4, 3, 2, 1, 0] * Input [1, 2, 0] => Output [1, 1, 0] ``` If you've completed this one and you f...
algorithms
def smaller(arr): # Good Luck! return [len([a for a in arr[i:] if a < arr[i]]) for i in range(0, len(arr))]
How many are smaller than me?
56a1c074f87bc2201200002e
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/56a1c074f87bc2201200002e
7 kyu
General Patron is faced with a problem , his intelligence has intercepted some secret messages from the enemy but they are all encrypted. Those messages are crucial to getting the jump on the enemy and winning the war. Luckily intelligence also captured an encoding device as well. However even the smartest programmer...
games
def decode(s): decrypted_message = '' i = 0 key = "bdhpF,82QsLirJejtNmzZKgnB3SwTyXG ?.6YIcflxVC5WE94UA1OoD70MkvRuPqHa" for char in s: i += 1 if char not in key: decrypted_message += char continue idx = (key . index(char) - i) % 66 decrypted_message += key[idx] return decrypt...
Help the general decode secret enemy messages.
52cf02cd825aef67070008fa
[ "Puzzles" ]
https://www.codewars.com/kata/52cf02cd825aef67070008fa
3 kyu
For encrypting strings this region of chars is given (in this order!): * all letters (ascending, first all UpperCase, then all LowerCase) * all digits (ascending) * the following chars: `.,:;-?! '()$%&"` These are 77 chars! (This region is zero-based.)<br/> Write two methods: <br/> ```csharp string Encrypt(string t...
algorithms
region = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;-?! '()$%&" + '"' def decrypt(encrypted_text): if not encrypted_text: return encrypted_text letters = list(encrypted_text) letters[0] = region[- (region . index(letters[0]) + 1)] for i in range(1, len(letters))...
Simple Encryption #2 - Index-Difference
5782b5ad202c0ef42f0012cb
[ "Fundamentals", "Cryptography", "Security", "Strings", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5782b5ad202c0ef42f0012cb
5 kyu
The Vigenère cipher is a classic cipher originally developed by Italian cryptographer Giovan Battista Bellaso and published in 1553. It is named after a later French cryptographer Blaise de Vigenère, who had developed a stronger autokey cipher (a cipher that incorporates the message of the text into the key). The cip...
algorithms
class VigenereCipher (object): def __init__(self, key: str, alphabet: str): self . alphabet = list(alphabet) self . key = [alphabet . index(i) for i in key] def encode(self, text): return "" . join([self . alphabet[(self . alphabet . index(text[i]) + self . key[i % len(self . key)]) % len(sel...
Vigenère Cipher Helper
52d1bd3694d26f8d6e0000d3
[ "Algorithms", "Ciphers", "Security", "Object-oriented Programming", "Strings" ]
https://www.codewars.com/kata/52d1bd3694d26f8d6e0000d3
4 kyu
You have to write two methods to *encrypt* and *decrypt* strings. Both methods have two parameters: ``` 1. The string to encrypt/decrypt 2. The Qwerty-Encryption-Key (000-999) ``` The rules are very easy: ``` The crypting-regions are these 3 lines from your keyboard: 1. "qwertyuiop" 2. "asdfghjkl" 3. "zxcvbnm,." If ...
algorithms
from collections import deque KEYBOARD = ['zxcvbnm,.', 'ZXCVBNM<>', 'asdfghjkl', 'ASDFGHJKL', 'qwertyuiop', 'QWERTYUIOP'] def encrypt(text, encryptKey): return converter(text, encryptKey, 1) def decrypt(text, encryptKey): return converter(text, encryptKey, - 1) def converter(text, encryptKe...
Simple Encryption #4 - Qwerty
57f14afa5f2f226d7d0000f4
[ "Cryptography", "Security", "Strings", "Algorithms" ]
https://www.codewars.com/kata/57f14afa5f2f226d7d0000f4
5 kyu
[Rotation ciphers](http://en.wikipedia.org/wiki/Caesar_cipher) are very vulnerable to brute force attacks. There are only 25 possible ways to decrypt the message. Example Encoded Message:````ymjxvznwwjqnxhzyj```` Possible Decoded Messages: ``` znkywaoxxkroyiazk, aolzxbpyylspzjbal, bpmaycqzzmtqakcbm, cqnbzdraanurbldc...
games
def rotation(string, n): return '' . join(chr(ord(c) + n - 26 * (ord(c) + n > 122)) for c in string) def decode(message, contents): return [rotation(message, n) for n in range(26) if contents ...
Rotation Cipher Cracker
54729e48e1d2a369e00000d3
[ "Ciphers", "Cryptography", "Algorithms", "Security", "Puzzles" ]
https://www.codewars.com/kata/54729e48e1d2a369e00000d3
6 kyu
Implement the [Polybius square cipher](http://en.wikipedia.org/wiki/Polybius_square). Replace every letter with a two digit number. The first digit is the row number, and the second digit is the column number of following square. Letters `'I'` and `'J'` are both 24 in this cipher: <style> table#polybius-square {width...
algorithms
def polybius(text): letmap = {"A": "11", "B": "12", "C": "13", "D": "14", "E": "15", "F": "21", "G": "22", "H": "23", "I": "24", "J": "24", "K": "25", "L": "31", "M": "32", "N": "33", "O": "34", "P": "35", "Q": "41", "R": "42", "S": "43", "T": "44", "U": "45", "V": "51", "W": "52", "X": "53", "Y": "54", "...
Polybius square cipher - encode
542a823c909c97da4500055e
[ "Cryptography", "Ciphers", "Algorithms" ]
https://www.codewars.com/kata/542a823c909c97da4500055e
6 kyu
A simple substitution cipher replaces one character from an alphabet with a character from an alternate alphabet, where each character's position in an alphabet is mapped to the alternate alphabet for encoding or decoding. E.g. ```javascript var abc1 = "abcdefghijklmnopqrstuvwxyz"; var abc2 = "etaoinshrdlucmfwypvbgkjq...
algorithms
class Cipher (object): def __init__(self, map1, map2): self . enc_key = str . maketrans(map1, map2) self . dec_key = str . maketrans(map2, map1) def encode(self, stg): return stg . translate(self . enc_key) def decode(self, stg): return stg . translate(self . dec_key)
Simple Substitution Cipher Helper
52eb114b2d55f0e69800078d
[ "Ciphers", "Security", "Object-oriented Programming", "Strings", "Algorithms" ]
https://www.codewars.com/kata/52eb114b2d55f0e69800078d
6 kyu
You are given a secret message you need to decipher. Here are the things you need to know to decipher it: For each word: - the second and the last letter is switched (e.g. `Hello` becomes `Holle`) - the first letter is replaced by its character code (e.g. `H` becomes `72`) * there are no special characters used, only...
reference
def decipher_word(word): i = sum(map(str . isdigit, word)) decoded = chr(int(word[: i])) if len(word) > i + 1: decoded += word[- 1] if len(word) > i: decoded += word[i + 1: - 1] + word[i: i + 1] return decoded def decipher_this(string): return ' ' . join(map(decipher_word, s...
Decipher this!
581e014b55f2c52bb00000f8
[ "Strings", "Arrays", "Ciphers", "Fundamentals" ]
https://www.codewars.com/kata/581e014b55f2c52bb00000f8
6 kyu
You have been recruited by an unknown organization for your cipher encrypting/decrypting skills. Being new to the organization they decide to test your skills. Your first test is to write an algorithm that encrypts the given string in the following steps. 1. The first step of the encryption is a standard ROT13 cip...
algorithms
def encrypter(strng): return '' . join(c if c == ' ' else chr(122 - ((ord(c) - 97) + 13) % 26) for c in strng)
ROT13 variant cipher
56fb3cde26cc99c2fd000009
[ "Cryptography", "Security", "Strings", "Algorithms" ]
https://www.codewars.com/kata/56fb3cde26cc99c2fd000009
6 kyu
Let’s get to know our hero: Agent #134 - Mr. Slayer. He was sent by his CSV agency to Ancient Rome in order to resolve some important national issues. However, something incredible has happened - the enemies have taken Julius Caesar as a prisoner!!! Caesar, not a simple man as you know, managed to send cryptic messag...
algorithms
from string import ascii_letters as az def caesar_crypto_encode(text, shift): if not text: return '' sh = shift % 52 return str . translate(text, str . maketrans(az, az[sh:] + az[: sh])). strip()
Cryptography #1 - Viva Cesare
576fac714bc84c312c0000b7
[ "Fundamentals", "Cryptography", "Algorithms" ]
https://www.codewars.com/kata/576fac714bc84c312c0000b7
6 kyu
A keyword cipher is a monoalphabetic cipher which uses a "keyword" to provide encryption. It is somewhat similar to a Caesar cipher. In a keyword cipher, repeats of letters in the keyword are removed and the alphabet is reordered such that the letters in the keyword appear first, followed by the rest of the letters in...
refactoring
from string import maketrans class keyword_cipher (object): def __init__(self, abc, keyword): key_abc = '' . join(sorted(set(keyword), key=keyword . index)) + \ '' . join(c for c in abc if c not in keyword) self . e_tab = maketrans(abc, key_abc) self . d_tab = maketrans(key_abc, abc) ...
Keyword Cipher Helper
535c1c80cdbf5011e600030f
[ "Cryptography", "Ciphers", "Security", "Object-oriented Programming", "Strings" ]
https://www.codewars.com/kata/535c1c80cdbf5011e600030f
6 kyu
# Number encrypting: cypher ## Part I of Number encrypting Katas *** ## Introduction Back then when the internet was coming up, most search functionalities simply looked for keywords in text to show relevant documents. Hackers weren't very keen on having their information displayed on websites, bulletin boards, newsgr...
reference
def cypher(s): return s . translate(str . maketrans('IREASGTBlzeasbtgoO', '123456781234567900'))
Number encrypting: cypher
57aa3927e298a757820000a8
[ "Fundamentals", "Strings", "Ciphers", "Cryptography" ]
https://www.codewars.com/kata/57aa3927e298a757820000a8
7 kyu
When you sign up for an account somewhere, some websites do not actually store your password in their databases. Instead, they will transform your password into something else using a cryptographic hashing algorithm. After the password is transformed, it is then called a *password hash*. Whenever you try to login, t...
reference
from hashlib import md5 def pass_hash(str): return md5(str . encode()). hexdigest()
Password Hashes
54207f9677730acd490000d1
[ "Security", "Fundamentals" ]
https://www.codewars.com/kata/54207f9677730acd490000d1
7 kyu
You have managed to intercept an important message and you are trying to read it. You realise that the message has been encoded and can be decoded by switching each letter with a corresponding letter. You also notice that each letter is paired with the letter that it coincides with when the alphabet is reversed. For...
games
from string import ascii_lowercase as alphabet def decode(message): return message . translate(str . maketrans(alphabet, alphabet[:: - 1]))
Decoding a message
565b9d6f8139573819000056
[ "Puzzles", "Algorithms", "Cryptography", "Security", "Games" ]
https://www.codewars.com/kata/565b9d6f8139573819000056
7 kyu
Fans of The Wire will appreciate this one. For those that haven't seen the show, the Barksdale Organization has a simple method for encoding telephone numbers exchanged via pagers: "Jump to the other side of the 5 on the keypad, and swap 5's and 0's." Here's a keypad for visualization. ``` ┌───┬───┬───┐ │ 1 │ 2 │ 3 │...
games
def decode(s): return s . translate(str . maketrans("1234567890", "9876043215"))
The Barksdale Code
573d498eb90ccf20a000002a
[ "Cryptography", "Puzzles" ]
https://www.codewars.com/kata/573d498eb90ccf20a000002a
7 kyu
The most basic encryption method is to map a char to another char by a certain math rule. Because every char has an ASCII value, we can manipulate this value with a simple math expression. For example 'a' + 1 would give us 'b', because 'a' value is 97 and 'b' value is 98. You will need to write a method which does ex...
games
def encrypt(text, rule): return "" . join(chr((ord(i) + rule) % 256) for i in text)
Basic Encryption
5862fb364f7ab46270000078
[ "Mathematics", "Strings", "Ciphers" ]
https://www.codewars.com/kata/5862fb364f7ab46270000078
6 kyu
Third day at your new cryptoanalyst job and you come across your toughest assignment yet. Your job is to implement a simple keyword cipher. A keyword cipher is a type of monoalphabetic substitution where two parameters are provided as such (string, keyword). The string is encrypted by taking the keyword, dropping any l...
algorithms
abc = "abcdefghijklmnopqrstuvwxyz" def keyword_cipher(s, keyword, key=""): for c in keyword + abc: if c not in key: key += c return s . lower(). translate(str . maketrans(abc, key))
Keyword Cipher
57241cafef90082e270012d8
[ "Cryptography", "Strings", "Algorithms" ]
https://www.codewars.com/kata/57241cafef90082e270012d8
6 kyu
Help Suzuki count his vegetables.... Suzuki is the master monk of his monastery so it is up to him to ensure the kitchen is operating at full capacity to feed his students and the villagers that come for lunch on a daily basis. This week there was a problem with his deliveries and all the vegetables became mixed up....
reference
def count_vegetables(s): items = s . split() veggies = ['cabbage', 'carrot', 'celery', 'cucumber', 'mushroom', 'onion', 'pepper', 'potato', 'tofu', 'turnip'] return sorted([(items . count(v), v) for v in veggies], reverse=True)
Help Suzuki count his vegetables....
56ff1667cc08cacf4b00171b
[ "Fundamentals" ]
https://www.codewars.com/kata/56ff1667cc08cacf4b00171b
7 kyu
Suzuki is a monk who climbs a large staircase to the monastery as part of a ritual. Some days he climbs more stairs than others depending on the number of students he must train in the morning. He is curious how many stairs might be climbed over the next 20 years and has spent a year marking down his daily progress. ...
reference
def stairs_in_20(stairs): return sum(sum(day) for day in stairs) * 20
How many stairs will Suzuki climb in 20 years?
56fc55cd1f5a93d68a001d4e
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/56fc55cd1f5a93d68a001d4e
8 kyu
Suzuki needs help lining up his students! Today Suzuki will be interviewing his students to ensure they are progressing in their training. He decided to schedule the interviews based on the length of the students name in descending order. The students will line up and wait for their turn. You will be given a string o...
reference
def lineup_students(s): return sorted(s . split(), key=lambda i: (len(i), i), reverse=True)
Suzuki needs help lining up his students!
5701800886306a876a001031
[ "Strings", "Sorting", "Fundamentals" ]
https://www.codewars.com/kata/5701800886306a876a001031
7 kyu
Help Suzuki rake his garden! The monastery has a magnificent Zen garden made of white gravel and rocks and it is raked diligently everyday by the monks. Suzuki having a keen eye is always on the lookout for anything creeping into the garden that must be removed during the daily raking such as insects or moss. You wi...
reference
VALID = {'gravel', 'rock'} def rake_garden(garden): return ' ' . join(a if a in VALID else 'gravel' for a in garden . split())
Help Suzuki rake his garden!
571c1e847beb0a8f8900153d
[ "Fundamentals" ]
https://www.codewars.com/kata/571c1e847beb0a8f8900153d
7 kyu
Help Suzuki purchase his Tofu! Suzuki has sent a lay steward to market who will purchase some items not produced in the monastary gardens for the monks. The stewart has with him a large box full of change from donations earlier in the day mixed in with some personal items. You will be given a string of items represent...
reference
def buy_tofu(cost, box): box = box . split() M, m = box . count('monme'), box . count('mon') total = 60 * M + m C, c = divmod(cost, 60) change = min(C, M) if 60 * change + m < cost: return 'leaving the market' return [m, M, total, change + (C - change) * 60 + c]
Help Suzuki purchase his Tofu!
57d4ecb8164a67b97c00003c
[ "Algorithms", "Data Structures", "Fundamentals" ]
https://www.codewars.com/kata/57d4ecb8164a67b97c00003c
6 kyu
__Function composition__ is a mathematical operation that mainly presents itself in lambda calculus and computability. It is explained well [here](http://www.mathsisfun.com/sets/functions-composition.html), but this is my explanation, in simple mathematical notation: ``` f3 = compose( f1 f2 ) Is equivalent to... f3...
reference
def compose(f, g): return lambda * x: f(g(* x))
Function Composition
5421c6a2dda52688f6000af8
[ "Functional Programming", "Fundamentals" ]
https://www.codewars.com/kata/5421c6a2dda52688f6000af8
6 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. Your task is to return an **object which includes the count of food options selected by the developers on the meetup sign-up form.**. For example, given the following i...
reference
from collections import Counter def order_food(lst): return Counter(dev['meal'] for dev in lst)
Coding Meetup #14 - Higher-Order Functions Series - Order the food
583952fbc23341c7180002fd
[ "Functional Programming", "Data Structures", "Arrays", "Fundamentals", "Algorithms", "Strings" ]
https://www.codewars.com/kata/583952fbc23341c7180002fd
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: 'Aba', lastName: 'N.', country: 'Ghana', continent: 'Africa', age: 21, language: 'Python' },...
reference
def find_odd_names(lst): return [x for x in lst if sum(map(ord, x["firstName"])) % 2]
Coding Meetup #15 - Higher-Order Functions Series - Find the odd names
583a8bde28019d615a000035
[ "Functional Programming", "Data Structures", "Arrays", "Fundamentals", "Algorithms", "Strings" ]
https://www.codewars.com/kata/583a8bde28019d615a000035
6 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: 'Harry', lastName: 'K.', country: 'Brazil', continent: 'Americas', age: 22, language: 'JavaS...
reference
def find_admin(lst, lang): return [i for i in lst if i['language'] == lang and i['githubAdmin'] == 'yes']
Coding Meetup #12 - Higher-Order Functions Series - Find GitHub admins
582dace555a1f4d859000058
[ "Functional Programming", "Data Structures", "Arrays", "Fundamentals", "Algorithms", "Strings" ]
https://www.codewars.com/kata/582dace555a1f4d859000058
7 kyu
You will be given a sequence 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: 'Maria', lastName: 'Y.', country: 'Cyprus', continent: 'Europe', age: 30, language: 'Java'...
algorithms
def get_average(lst): return round(sum(x["age"] for x in lst) / len(lst))
Coding Meetup #11 - Higher-Order Functions Series - Find the average age
582ba36cc1901399a70005fc
[ "Functional Programming", "Data Structures", "Arrays", "Fundamentals", "Algorithms", "Strings" ]
https://www.codewars.com/kata/582ba36cc1901399a70005fc
7 kyu
You will be given an array of objects (associative arrays in PHP) representing data about developers who have signed up to attend the next coding meetup that you are organising. Your task is to return: - `true` if developers from all of the following age groups have signed up: teens, twenties, thirties, forties, fift...
algorithms
def is_age_diverse(lst): arr = list(map(lambda x: x["age"] / / 10, lst)) return any(x >= 10 for x in arr) and all(i in arr for i in range(1, 10))
Coding Meetup #9 - Higher-Order Functions Series - Is the meetup age-diverse?
5829ca646d02cd1a65000284
[ "Functional Programming", "Data Structures", "Arrays", "Fundamentals", "Algorithms", "Strings" ]
https://www.codewars.com/kata/5829ca646d02cd1a65000284
6 kyu
You will be given a sequence of objects (associative arrays in PHP) representing data about developers who have signed up to attend the next coding meetup that you are organising. Your task is to return: - `true` if all of the following continents / geographic zones will be represented by at least one developer: 'Afr...
algorithms
def all_continents(lst): return len(set(x["continent"] for x in lst)) == 5
Coding Meetup #8 - Higher-Order Functions Series - Will all continents be represented?
58291fea7ff3f640980000f9
[ "Functional Programming", "Data Structures", "Arrays", "Fundamentals", "Algorithms", "Strings" ]
https://www.codewars.com/kata/58291fea7ff3f640980000f9
6 kyu
You will be given a sequence of objects representing data about developers who have signed up to attend the next coding meetup that you are organising. Your task is to return a sequence which includes the developer who is the oldest. In case of a tie, include all same-age senior developers listed in the same order as ...
algorithms
def find_senior(lst): mage = max(a['age'] for a in lst) return [a for a in lst if a['age'] == mage]
Coding Meetup #7 - Higher-Order Functions Series - Find the most senior developer
582887f7d04efdaae3000090
[ "Functional Programming", "Data Structures", "Arrays", "Fundamentals", "Algorithms", "Strings" ]
https://www.codewars.com/kata/582887f7d04efdaae3000090
6 kyu
You will be given an array of objects (associative arrays in PHP, tables in COBOL) representing data about developers who have signed up to attend the next coding meetup that you are organising. Your task is to return either: - `true` if all developers in the list code in the same language; or - `false` otherwise. F...
algorithms
def is_same_language(lst): return len(set(i["language"] for i in lst)) == 1
Coding Meetup #6 - Higher-Order Functions Series - Can they code in the same language?
58287977ef8d4451f90001a0
[ "Functional Programming", "Data Structures", "Arrays", "Fundamentals", "Algorithms", "Strings" ]
https://www.codewars.com/kata/58287977ef8d4451f90001a0
7 kyu
You will be given an array of objects (associative arrays in PHP, table in COBOL) representing data about developers who have signed up to attend the next coding meetup that you are organising. Your task is to return an **object (associative array in PHP, table in COBOL) which includes the count of each coding languag...
algorithms
from collections import Counter def count_languages(lst): return Counter([d['language'] for d in lst])
Coding Meetup #5 - Higher-Order Functions Series - Prepare the count of languages
5828713ed04efde70e000346
[ "Functional Programming", "Data Structures", "Arrays", "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/5828713ed04efde70e000346
7 kyu
You will be given an array of objects (associative arrays in PHP, tables in COBOL) representing data about developers who have signed up to attend the next coding meetup that you are organising. Your task is to **return an array where each object will have a new property 'greeting' with the following string value:** ...
algorithms
def greet_developers(lst): for x in lst: x["greeting"] = f"Hi { x [ 'firstName' ]} , what do you like the most about { x [ 'language' ]} ?" return lst
Coding Meetup #2 - Higher-Order Functions Series - Greet developers
58279e13c983ca4a2a00002a
[ "Data Structures", "Fundamentals", "Algorithms", "Strings", "Regular Expressions", "Arrays", "Functional Programming" ]
https://www.codewars.com/kata/58279e13c983ca4a2a00002a
7 kyu
You will be given an array of objects (associative arrays in PHP) representing data about developers who have signed up to attend the next coding meetup that you are organising. The list is ordered according to who signed up first. Your task is to return one of the following strings: - `< firstName here >, < country ...
algorithms
def get_first_python(users): for data in users: if data['language'] == 'Python': return f' { data [ "first_name" ]} , { data [ "country" ]} ' return 'There will be no Python developers'
Coding Meetup #4 - Higher-Order Functions Series - Find the first Python developer
5827bc50f524dd029d0005f2
[ "Functional Programming", "Data Structures", "Arrays", "Fundamentals", "Algorithms", "Strings", "Regular Expressions" ]
https://www.codewars.com/kata/5827bc50f524dd029d0005f2
7 kyu
You will be given an array of objects (associative arrays in PHP) representing data about developers who have signed up to attend the next coding meetup that you are organising. Your task is to return: - `true` if at least one Ruby developer has signed up; or - `false` if there will be no Ruby developers. For examp...
algorithms
def is_ruby_coming(lst): return any(x["language"] == "Ruby" for x in lst)
Coding Meetup #3 - Higher-Order Functions Series - Is Ruby coming?
5827acd5f524dd029d0005a4
[ "Data Structures", "Fundamentals", "Algorithms", "Strings", "Regular Expressions", "Arrays", "Functional Programming" ]
https://www.codewars.com/kata/5827acd5f524dd029d0005a4
7 kyu
You will be given an array of objects (hashes in ruby) representing data about developers who have signed up to attend the coding meetup that you are organising for the first time. Your task is to **return the number of JavaScript developers coming from Europe**. For example, given the following list: ```javascript ...
algorithms
def count_developers(lst): return sum(x["language"] == "JavaScript" and x["continent"] == "Europe" for x in lst)
Coding Meetup #1 - Higher-Order Functions Series - Count the number of JavaScript developers coming from Europe
582746fa14b3892727000c4f
[ "Data Structures", "Fundamentals", "Algorithms", "Strings", "Regular Expressions", "Arrays", "Functional Programming" ]
https://www.codewars.com/kata/582746fa14b3892727000c4f
7 kyu
You must create a function, `spread`, that takes a function and a list of arguments to be applied to that function. You must make this function return the result of calling the given function/lambda with the given arguments. eg: ```javascript spread(someFunction, [1, true, "Foo", "bar"] ) // is the same as... someFun...
reference
def spread(func, args): return func(* args)
Unpacking Arguments
540de1f0716ab384b4000828
[ "Functional Programming", "Fundamentals" ]
https://www.codewars.com/kata/540de1f0716ab384b4000828
7 kyu
Write a function `reverse` which reverses a list (or in clojure's case, any list-like data structure) (the dedicated builtin(s) functionalities are deactivated)
reference
def reverse(lst): out = list() for i in range(len(lst) - 1, - 1, - 1): out . append(lst[i]) return out
esreveR
5413759479ba273f8100003d
[ "Functional Programming", "Fundamentals" ]
https://www.codewars.com/kata/5413759479ba273f8100003d
7 kyu
Implement two methods `anyMatch` and `allMatch` which take the head of a linked list and a predicate function, and return: * anyMatch: whether the predicate is true for *any* of the list's elements. * allMatch: whether the predicate is true for *all* of the list's elements. For example: Given the list: `1 -> 2 -> 3`,...
reference
from typing import Callable def any_match(head: Node, pred: Callable[[any], bool]) - > bool: while head: if pred(head . data): return True head = head . next return False def all_match(head: Node, pred: Callable[[all], bool]) - > bool: while head: if not pred(head . data): return F...
Fun with lists: anyMatch + allMatch
581e50555f59405743001813
[ "Lists", "Functional Programming", "Fundamentals" ]
https://www.codewars.com/kata/581e50555f59405743001813
7 kyu
Implement the method **countIf** (`count_if` in PHP and Python), which accepts a linked list (head) and a predicate function, and returns the number of elements which apply to the given predicate. For example: Given the list: `1 -> 2 -> 3`, and the predicate `x => x >= 2`, **countIf** / `count_if` should return 2, sin...
reference
def count_if(head, func): counter = 0 while head: counter += func(head . data) head = head . next return counter
Fun with lists: countIf
5819081d056d4bdd410004f8
[ "Lists", "Functional Programming", "Fundamentals" ]
https://www.codewars.com/kata/5819081d056d4bdd410004f8
6 kyu
Implement the method **lastIndexOf** (`last_index_of` in PHP and Python), which accepts a linked list (head) and a value, and returns the index (zero based) of the *last* occurrence of that value if exists, or -1 otherwise. For example: Given the list: `1 -> 2 -> 3 -> 3`, and the value 3, **lastIndexOf** / `last_index...
reference
def last_index_of(head, search_val): i = 0 last = - 1 while head: value = head . data if value == search_val: last = i head = head . next i += 1 return last
Fun with lists: lastIndexOf
581c867a33b9fe732e000076
[ "Lists", "Fundamentals" ]
https://www.codewars.com/kata/581c867a33b9fe732e000076
7 kyu
Implement the method **indexOf** (`index_of` in PHP), which accepts a linked list (head) and a value, and returns the index (zero based) of the *first* occurrence of that value if exists, or -1 otherwise. For example: Given the list: `1 -> 2 -> 3 -> 3`, and the value 3, **indexOf** / `index_of` should return 2. The l...
reference
def index_of(head, value, idx=0): if head is None: return - 1 if head . data == value: return idx return index_of(head . next, value, idx + 1)
Fun with lists: indexOf
581c6b075cfa83852700021f
[ "Lists", "Fundamentals" ]
https://www.codewars.com/kata/581c6b075cfa83852700021f
7 kyu
### Context and Definitions You are in charge of developing a new cool JavaScript library that provides functionality similar to that of [Underscore.js](http://underscorejs.org/). You have started by adding a new **list data type** to your library. You came up with a design of a data structure that represents an [al...
algorithms
class Cons: def __init__(self, value, tail): self . value = value self . tail = tail def to_array(self, lst=None): if lst is None: lst = [] lst . append(self . value) if self . tail is not None: self . tail . to_array(lst) return lst @ classmethod def ...
Algebraic Lists
529a92d9aba78c356b000353
[ "Lists", "Algebra", "Algorithms" ]
https://www.codewars.com/kata/529a92d9aba78c356b000353
4 kyu