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
Mothers arranged a dance party for the children in school. At that party, there are only mothers and their children. All are having great fun on the dance floor when suddenly all the lights went out. It's a dark night and no one can see each other. But you were flying nearby and you can see in the dark and have ability...
reference
def find_children(dancing_brigade): return '' . join(sorted(dancing_brigade, key=lambda c: (c . upper(), c . islower())))
Where is my parent!?(cry)
58539230879867a8cd00011c
[ "Fundamentals" ]
https://www.codewars.com/kata/58539230879867a8cd00011c
6 kyu
Your task is simple enough. You will write a function which takes a tree as its input. Your function should output one string with the values of the nodes in an order corresponding to a breadth first search. This string also should be broken into levels corresponding to the depth of the nodes tree, and there should be...
algorithms
# preloaded TreeNode class: """ class TreeNode: def __init__(self, value, children = None): self.value = value self.children = [] if children is None else children """ from preloaded import TreeNode def tree_printer(tree: TreeNode) - > str: q = [tree] res = [] while q: res . a...
Tree-D Printer
57a22f50bb99445c5e000171
[ "Algorithms" ]
https://www.codewars.com/kata/57a22f50bb99445c5e000171
6 kyu
Your task is to calculate the maximum possible height of a perfectly square pyramid (the number of complete layers) that we can build, given `n` number of cubes as the argument. * The top layer is always only 1 cube and is always present. * There are no hollow areas, meaning each layer must be fully populated with cub...
reference
def pyramid_height(n): i = 0 while n > 0: i += 1 n -= i * * 2 return i - (n < 0)
Calculate Pyramid Height
56968ce7753513604b000055
[ "Logic", "Mathematics", "Puzzles", "Fundamentals" ]
https://www.codewars.com/kata/56968ce7753513604b000055
6 kyu
# Task CodeBots decided to make a gift for CodeMaster's birthday. They got a pack of candies of various sizes from the store, but instead of giving the whole pack they are trying to make the biggest possible candy from them. On each turn it is possible: ``` to pick any two candies of the same size and merge them ...
games
from heapq import heapify, heappop, heappushpop def obtain_max_number(lst): heapify(lst) while lst: m = heappop(lst) if lst and lst[0] == m: heappushpop(lst, 2 * m) return m
Simple Fun #66: Obtain Max Number
5893f03c779ce5faab0000f6
[ "Puzzles" ]
https://www.codewars.com/kata/5893f03c779ce5faab0000f6
6 kyu
Write a function that returns all of the *sublists* of a list/array. Example: ```math power([1,2,3]); => [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] ``` For more details regarding this, see the [power set][power set] entry in wikipedia. [pure]: http://en.wikipedia.org/wiki/Pure_function [power set]: http...
algorithms
def power(s): """Computes all of the sublists of s""" set = [[]] for num in s: set += [x + [num] for x in set] return set
By the Power Set of Castle Grayskull
53d3173cf4eb7605c10001a8
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/53d3173cf4eb7605c10001a8
5 kyu
A zero-indexed array ```arr``` consisting of n integers is given. The dominator of array ```arr``` is the value that occurs in <b>more</b> than half of the elements of ```arr```.<br/> For example, consider array ```arr``` such that ```arr = [3,4,3,2,3,1,3,3]```<br/> The dominator of ```arr``` is 3 because it occurs in ...
reference
def dominator(arr): for x in set(arr): if arr . count(x) > len(arr) / 2.0: return x return - 1
What dominates your array?
559e10e2e162b69f750000b4
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/559e10e2e162b69f750000b4
7 kyu
John is a worker, his job is to remove screws from a machine. There are 2 types of screws: slotted (`-`) and cross (`+`). John has two screwdrivers, one for each type of screw. The input will be a (non-empty) string of screws, e.g. : `"---+++"` When John begins to work, he stands at the first screw, with the correct ...
games
def sc(s): return 2 * len(s) - 1 + 5 * (s . count('+-') + s . count('-+'))
Coding 3min : Remove screws I
5710a50d336aed828100055a
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/5710a50d336aed828100055a
7 kyu
You have a collection of lovely poems. Unfortunately, they aren't formatted very well. They're all on one line, like this: ``` Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. ``` What you want is to present each sentence on a new line,...
reference
def format_poem(poem): return ".\n" . join(poem . split(". "))
Thinkful - String Drills: Poem formatter
585af8f645376cda59000200
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/585af8f645376cda59000200
7 kyu
You're writing an excruciatingly detailed alternate history novel set in a world where [Daniel Gabriel Fahrenheit](https://en.wikipedia.org/wiki/Daniel_Gabriel_Fahrenheit) was never born. Since Fahrenheit never lived the world kept on using the [Rømer scale](https://en.wikipedia.org/wiki/R%C3%B8mer_scale), invented by...
reference
def celsius_to_romer(temp): # Converts temperature in degrees Celsius to degrees Romer return (temp * 21 / 40) + 7.5
Thinkful - Number Drills: Rømer temperature
5862eeeae20244d5eb000005
[ "Fundamentals" ]
https://www.codewars.com/kata/5862eeeae20244d5eb000005
7 kyu
You've got a bunch of textual data with embedded phone numbers. Write a function `area_code()` that finds and returns just the area code portion of the phone number. ```python >>> message = "The supplier's phone number is (555) 867-5309" >>> area_code(message) '555' ``` The returned area code should be a string, not a ...
reference
def area_code(text): return text[text . find("(") + 1: text . find(")")]
Thinkful - String Drills: Areacode extractor
585a36b445376cbc22000072
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/585a36b445376cbc22000072
7 kyu
This challenge extends the previous [repeater()](https://www.codewars.com/kata/thinkful-string-drills-repeater) challenge. Just like last time, your job is to write a function that accepts a string and a number as arguments. This time, however, you should format the string you return like this: ```python >>> repeater('...
reference
def repeater(string, n): return '"{}" repeated {} times is: "{}"' . format(string, n, string * n)
Thinkful - String Drills: Repeater level 2
585a1f0945376c112a00019a
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/585a1f0945376c112a00019a
7 kyu
Write a program that outputs the top `n` elements from a list. Example: ```python largest(2, [7,6,5,4,3,2,1]) # => [6,7] ``` ```javascript largest(2, [7,6,5,4,3,2,1]) // => [6,7] ``` ```java largest(2, new int[]{7, 6, 5, 4, 3, 2, 1}) // => new int[]{6, 7} ``` ```haskell largest 2 [7,6,5,4,3,2,1] -- => [6,7] ``` ```c...
reference
def largest(n, xs): import heapq return heapq . nlargest(n, xs)[:: - 1]
Largest Elements
53d32bea2f2a21f666000256
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/53d32bea2f2a21f666000256
7 kyu
### Description: Remove all exclamation marks from sentence except at the end. ### Examples ``` "Hi!" ---> "Hi!" "Hi!!!" ---> "Hi!!!" "!Hi" ---> "Hi" "!Hi!" ---> "Hi!" "Hi! Hi!" ---> "Hi Hi!" "Hi" ---> "Hi" ```
reference
def remove(s): return s . replace('!', '') + '!' * (len(s) - len(s . rstrip('!')))
Exclamation marks series #3: Remove all exclamation marks from sentence except at the end
57faefc42b531482d5000123
[ "Fundamentals" ]
https://www.codewars.com/kata/57faefc42b531482d5000123
7 kyu
In this kata, you must create a function `powers`/`Powers` that takes an array, and returns the number of subsets possible to create from that list. In other words, counts the power sets. For instance ```coffeescript powers([1,2,3]) => 8 ``` ...due to... ```coffeescript powers([1,2,3]) => [[], [1], [2], [3], [1,2...
algorithms
def powers(list): return 2 * * len(list)
Counting power sets
54381f0b6f032f933c000108
[ "Sets", "Permutations", "Arrays", "Algorithms" ]
https://www.codewars.com/kata/54381f0b6f032f933c000108
7 kyu
In democracy we have a lot of elections. For example, we have to vote for a class representative in school, for a new parliament or a new government. Usually, we vote for a candidate, i.e. a set of eligible candidates is given. This is done by casting a ballot into a ballot-box. After that, it must be counted how many...
algorithms
from collections import Counter def getWinner(ballots): winner, n_votes = Counter(ballots). most_common(1)[0] return winner if n_votes > len(ballots) / 2 else None
Who won the election?
554910d77a3582bbe300009c
[ "Algorithms", "Lists", "Fundamentals" ]
https://www.codewars.com/kata/554910d77a3582bbe300009c
6 kyu
You have to search all numbers from inclusive 1 to inclusive a given number x, that have the given digit d in it.<br> The value of d will always be 0 - 9.<br> The value of x will always be greater than 0. You have to return as an array<br> - the count of these numbers,<br> - their sum <br> - and their product.<br> ...
algorithms
from functools import reduce import operator def numbers_with_digit_inside(x, d): l = [x for x in range(1, x + 1) if str(d) in str(x)] return [len(l), sum(l), reduce(operator . mul, l, 1) if l else 0]
Numbers with this digit inside
57ad85bb7cb1f3ae7c000039
[ "Mathematics", "Algorithms" ]
https://www.codewars.com/kata/57ad85bb7cb1f3ae7c000039
7 kyu
You are going to be given a word. Your job will be to make sure that each character in that word has the exact same number of occurrences. You will return `true` if it is valid, or `false` if it is not. For this kata, capitals are considered the same as lowercase letters. Therefore: `"A" == "a"` The input is a strin...
algorithms
from collections import Counter def validate_word(word): return len(set(Counter(word . lower()). values())) == 1
Character Counter
56786a687e9a88d1cf00005d
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/56786a687e9a88d1cf00005d
7 kyu
The aim of this kata is to split a given string into different strings of equal size (note size of strings is passed to the method) Example: Split the below string into other strings of size #3 'supercalifragilisticexpialidocious' Will return a new string 'sup erc ali fra gil ist ice xpi ali doc iou...
reference
def split_in_parts(s, n): return ' ' . join([s[i: i + n] for i in range(0, len(s), n)])
Split In Parts
5650ab06d11d675371000003
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/5650ab06d11d675371000003
7 kyu
Given 2 strings, `a` and `b`, return a string of the form: `shorter+reverse(longer)+shorter.` In other words, the shortest string has to be put as prefix and as suffix of the reverse of the longest. Strings `a` and `b` may be empty, but not null (In C# strings may also be null. Treat them as if they are empty.). I...
reference
def shorter_reverse_longer(a, b): if len(a) < len(b): a, b = b, a return b + a[:: - 1] + b
shorter concat [reverse longer]
54557d61126a00423b000a45
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/54557d61126a00423b000a45
7 kyu
Note: This kata has been inspired by [GCJ 2010's "Store credit"](https://code.google.com/codejam/contest/351101/dashboard#s=p0), where one also has to parse the actual input. If you solved this kata, try that one too. Note that GCJ's version always has a solution, whereas this kata might not. ### Story You got a gift ...
algorithms
def buy(x, arr): for i, y in enumerate(arr[: - 1]): for j, z in enumerate(arr[i + 1:]): if y + z == x: return [i, i + j + 1]
A Gift Well Spent
54554846126a002d5b000854
[ "Lists", "Algorithms" ]
https://www.codewars.com/kata/54554846126a002d5b000854
7 kyu
Write a function, `factory`, that takes a number as its parameter and returns another function. The returned function should take an array of numbers as its parameter, and return an array of those numbers *multiplied by the number that was passed into the first function*. In the example below, 5 is the number passed ...
reference
def factory(x): return lambda ar: [x * el for el in ar]
First-Class Function Factory
563f879ecbb8fcab31000041
[ "Fundamentals", "Functional Programming", "Arrays" ]
https://www.codewars.com/kata/563f879ecbb8fcab31000041
7 kyu
We’ve all seen katas that ask for conversion from snake-case to camel-case, from camel-case to snake-case, or from camel-case to kebab-case — the possibilities are endless. But if we don’t know the case our inputs are in, these are not very helpful. ### Task: So the task here is to implement a function (called `id` ...
reference
import re CASES = [ ('snake', re . compile(r'\A[a-z]+(_[a-z]+)+\Z')), ('kebab', re . compile(r'\A[a-z]+(-[a-z]+)+\Z')), ('camel', re . compile(r'\A[a-z]+([A-Z][a-z]*)+\Z')), ('none', re . compile(r'')), ] def case_id(c_str): for case, pattern in CASES: if pattern . match(c_str): ...
Identify Case
5819a6fdc929bae4f5000a33
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/5819a6fdc929bae4f5000a33
7 kyu
<h1>Tube strike options calculator</h1> <h3>The sweaty bus ride</h3> There is a tube strike today so instead of getting the London Underground home you have decided to take the bus. It's a hot day and you have been sitting on the bus for over an hour, but the bus is hardly moving. Your arm is sticking to the window and...
algorithms
def calculator(distance, bus_drive, bus_walk): hr = distance / walk return ( 'Bus' if hr > 2 else 'Walk' if hr < 1 / 6 else 'Walk' if hr <= bus_drive / bus + bus_walk / walk else 'Bus' )
Tube strike options calculator
568ade64cfd7a55d9300003e
[ "Fundamentals", "Algorithms" ]
https://www.codewars.com/kata/568ade64cfd7a55d9300003e
7 kyu
<strong>*SCHEDULE YOUR DA(RRA)Y*</strong> The best way to have a productive day is to plan out your work schedule. Given the following three inputs, please create an array of time alloted to work, broken up with time alloted with breaks: <strong>Input 1</strong>: Hours - Number of hours available to you to get your...
algorithms
def day_plan(hours, tasks, duration): td, hm, tmo = tasks * duration, hours * 60, tasks - 1 if td > hm: return "You're not sleeping tonight!" arr = [0] * (tasks + tmo) arr[:: 2], arr[1:: 2] = [duration] * \ tasks, [round((hm - td) / (tmo or 1))] * tmo return arr
SCHEDULE YOUR DA(RRA)Y
581de9a5b7bad5d369000150
[ "Arrays", "Algorithms", "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/581de9a5b7bad5d369000150
7 kyu
You will be given an array that contains two strings. Your job is to create a function that will take those two strings and transpose them, so that the strings go from top to bottom instead of left to right. ```javascript e.g. transposeTwoStrings(['Hello','World']); should return H W e o l r l l o d ``` A few...
games
from itertools import zip_longest def transpose_two_strings(lst): return "\n" . join(f" { a } { b } " for a, b in zip_longest(* lst, fillvalue=" "))
Transpose two strings in an array
581f4ac139dc423f04000b99
[ "Arrays", "Strings", "Fundamentals" ]
https://www.codewars.com/kata/581f4ac139dc423f04000b99
7 kyu
Haskell has some useful functions for dealing with lists: ```haskell $ ghci GHCi, version 7.6.3: http://www.haskell.org/ghc/ :? for help λ head [1,2,3,4,5] 1 λ tail [1,2,3,4,5] [2,3,4,5] λ init [1,2,3,4,5] [1,2,3,4] λ last [1,2,3,4,5] 5 ``` Your job is to implement these functions in your given language. Make sure i...
reference
def head(arr): return arr[0] def tail(arr): return arr[1:] def init(arr): return arr[: - 1] def last(arr): return arr[- 1]
Head, Tail, Init and Last
54592a5052756d5c5d0009c3
[ "Arrays", "Lists", "Fundamentals" ]
https://www.codewars.com/kata/54592a5052756d5c5d0009c3
7 kyu
In this kata, you will write an arithmetic list which is basically a list that contains consecutive terms in the sequence. <br /> You will be given three parameters : + `first` the first term in the sequence + `c` the constant that you are going to <strong>ADD</strong> ( since it is an arithmetic sequence...) + `l` th...
reference
def seqlist(first, skipBy, count): last = (skipBy * count) + first return list(range(first, last, skipBy))
Arithmetic List!
541da001259d9ca85d000688
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/541da001259d9ca85d000688
7 kyu
You will be given a string (x) featuring a cat 'C' and a mouse 'm'. The rest of the string will be made up of '.'. You need to find out if the cat can catch the mouse from it's current position. The cat can jump over three characters. So: C.....m returns 'Escaped!' <-- more than three characters between C...m retu...
reference
def cat_mouse(x): return 'Escaped!' if x . count('.') > 3 else 'Caught!'
Cat and Mouse - Easy Version
57ee24e17b45eff6d6000164
[ "Fundamentals", "Strings" ]
https://www.codewars.com/kata/57ee24e17b45eff6d6000164
7 kyu
A comfortable word is a word which you can type always alternating the hand you type with (assuming you type using a QWERTY keyboard and use fingers as shown in the image below). That being said, complete the function which receives a word and returns `true` if it's a comfortable word and `false` otherwise. The word ...
algorithms
def comfortable_word(word): left, right = "qwertasdfgzxcvb", "yuiophjklnm" l = True if word[0] in left else False for letter in word[1:]: if letter in left and l: return False if letter in right and not l: return False l = not l return True
Comfortable words
56684677dc75e3de2500002b
[ "Strings", "Algorithms" ]
https://www.codewars.com/kata/56684677dc75e3de2500002b
7 kyu
## Task Write a method, that replaces every nth char _oldValue_ with char _newValue_. ## Inputs * `text`: the string to modify * `n`: change the target letter every `n`<sup>th</sup> occurrencies * `old_value` (or similar): the targetted character * `new_value` (or similar): the character to use as replacement Note ...
algorithms
def replace_nth(text, n, old, new): count = 0 res = "" for c in text: if c == old: count += 1 if count == n: res += new count = 0 continue res += c return res
Replace every nth
57fcaed83206fb15fd00027a
[ "Algorithms", "Strings" ]
https://www.codewars.com/kata/57fcaed83206fb15fd00027a
7 kyu
Your task is to return how many times a string contains a given character. The function takes a string(inputS) as a parameter and a char(charS) which is the character that you will have to find and count. For example, if you get an input string "Hello world" and the character to find is "o", return 2.
algorithms
def string_counter(string, char): return string . count(char)
How many times does it contain?
584466950d3bedb9b300001f
[ "Fundamentals", "Strings", "Algorithms" ]
https://www.codewars.com/kata/584466950d3bedb9b300001f
7 kyu
John wants to decorate the walls of a room with wallpaper. He wants a fool-proof method for getting it right. John knows that the rectangular room has a length of `l` meters, a width of `w` meters, a height of `h` meters. The standard width of the rolls he wants to buy is `52` centimeters. The length of a roll is `10...
reference
from math import ceil numbers = {0: "zero", 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine", 10: "ten", 11: "eleven", 12: "twelve", 13: "thirteen", 14: "fourteen", 15: "fifteen", 16: "sixteen", 17: "seventeen", 18: "eighteen", 19: "nineteen", 20...
Easy wallpaper
567501aec64b81e252000003
[ "Fundamentals" ]
https://www.codewars.com/kata/567501aec64b81e252000003
7 kyu
Given a square matrix (i.e. an array of subarrays), find the sum of values from the first value of the first array, the second value of the second array, the third value of the third array, and so on... ## Examples ``` array = [[1, 2], [3, 4]] diagonal sum: 1 + 4 = 5 ``` ``` array = [[5, 9,...
reference
def diagonal_sum(array): return sum(row[i] for i, row in enumerate(array))
Find sum of top-left to bottom-right diagonals
5497a3c181dd7291ce000700
[ "Matrix", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5497a3c181dd7291ce000700
7 kyu
Create a function that takes a number and finds the factors of it, listing them in **descending** order in an **array**. If the parameter is not an integer or less than 1, return `-1`. In C# return an empty array. For Example: `factors(54)` should return `[54, 27, 18, 9, 6, 3, 2, 1]`
reference
def factors(x): return - 1 if type(x) != int or x < 1 else [i for i in range(1, x + 1) if x % i == 0][:: - 1]
Find factors of a number
564fa92d1639fbefae00009d
[ "Sorting", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/564fa92d1639fbefae00009d
7 kyu
To complete this Kata you need to make a function `multiplyAll`/`multiply_all` which takes an array of integers as an argument. This function must return another function, which takes a single integer as an argument and returns a new array. The returned array should consist of each of the elements from the first arra...
reference
def multiply_all(arr): def m(n): return [i * n for i in arr] return m
Currying functions: multiply all elements in an array
586909e4c66d18dd1800009b
[ "Functional Programming", "Fundamentals" ]
https://www.codewars.com/kata/586909e4c66d18dd1800009b
7 kyu
Python dictionaries are inherently unsorted. So what do you do if you need to sort the contents of a dictionary? Create a function that returns a sorted list of `(key, value)` tuples (Javascript: arrays of 2 items). The list must be sorted by the `value` and be sorted **largest to smallest**. ## Examples ```python...
reference
def sort_dict(d): return sorted(d . items(), key=lambda x: x[1], reverse=True)
Sorting Dictionaries
53da6a7e112bd15cbc000012
[ "Sorting", "Lists", "Fundamentals" ]
https://www.codewars.com/kata/53da6a7e112bd15cbc000012
7 kyu
Move every letter in the provided string forward 10 letters through the alphabet. If it goes past 'z', start again at 'a'. Input will be a string with length > 0.
reference
from string import ascii_lowercase as al tbl = str . maketrans(al, al[10:] + al[: 10]) def move_ten(st): return st . translate(tbl)
Move 10
57cf50a7eca2603de0000090
[ "Fundamentals", "Strings", "Arrays" ]
https://www.codewars.com/kata/57cf50a7eca2603de0000090
7 kyu
<h1>Easy; Make a box</h1> Given a number as a parameter (between 2 and 30), return an array containing strings which form a box. Like this: n = `5` ``` [ '-----', '- -', '- -', '- -', '-----' ] ``` n = `3` ``` [ '---', '- -', '---' ] ```
algorithms
def box(n): return ['-' * n] + ['-' + ' ' * (n - 2) + '-'] * (n - 2) + ['-' * n]
Make a square box!
58644e8ddf95f81a38001d8d
[ "Strings", "Arrays", "ASCII Art", "Algorithms" ]
https://www.codewars.com/kata/58644e8ddf95f81a38001d8d
7 kyu
Given an array of positive integers, replace every element with the least greater element to its right. If there is no greater element to its right, replace it with -1. For instance, given the array `[8, 58, 71, 18, 31, 32, 63, 92, 43, 3, 91, 93, 25, 80, 28]`, the desired output is `[18, 63, 80, 25, 32, 43...
algorithms
def array_manip(array): return [min([a for a in array[i + 1:] if a > array[i]], default=- 1) for i in range(len(array))]
Array Manipulation
58d5e6c114286c8594000027
[ "Arrays", "Binary Search Trees", "Algorithms" ]
https://www.codewars.com/kata/58d5e6c114286c8594000027
7 kyu
The accounts of the "Fat to Fit Club (FFC)" association are supervised by John as a volunteered accountant. The association is funded through financial donations from generous benefactors. John has a list of the first `n` donations: `[14, 30, 5, 7, 9, 11, 15]` He wants to know how much the next benefactor should give t...
reference
from math import ceil def new_avg(arr, newavg): value = int(ceil((len(arr) + 1) * newavg - sum(arr))) if value < 0: raise ValueError return value
Looking for a benefactor
569b5cec755dd3534d00000f
[ "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/569b5cec755dd3534d00000f
7 kyu
The __Hamming weight__ of a string is the number of symbols that are different from the zero-symbol of the alphabet used. There are several algorithms for efficient computing of the Hamming weight for numbers. In this Kata, speaking technically, you have to find out the number of '1' bits in a binary representation of ...
algorithms
def hamming_weight(x): return bin(x). count('1')
Count the Ones
5519e930cd82ff8a9a000216
[ "Binary", "Algorithms" ]
https://www.codewars.com/kata/5519e930cd82ff8a9a000216
7 kyu
Fellow code warrior, we need your help! We seem to have lost one of our sequence elements, and we need your help to retrieve it! Our sequence given was supposed to contain all of the integers from 0 to 9 (in no particular order), but one of them seems to be missing. Write a function that accepts a sequence of unique...
reference
def get_missing_element(seq): return 45 - sum(seq)
Return the Missing Element
5299413901337c637e000004
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/5299413901337c637e000004
7 kyu
Write a method that returns true if a given parameter is a power of 4, and false if it's not. If parameter is not an Integer (eg String, Array) method should return false as well. (In C# Integer means all integer Types like Int16,Int32,.....) ### Examples ```ruby power_of_4(1024) => true power_of_4(55) => false po...
reference
from math import log def powerof4(n): if type(n) in (float, int) and n > 0: return log(n, 4). is_integer() return False
Power of 4
544d114f84e41094a9000439
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/544d114f84e41094a9000439
7 kyu
You must implement a function that returns the difference between the largest and the smallest value in a given `list / array` (`lst`) received as the parameter. * `lst` contains integers, that means it may contain some negative numbers * if `lst` is empty or contains a single element, return `0` * `lst` is not sorted...
reference
def max_diff(list): return max(list) - min(list) if list else 0
max diff - easy
588a3c3ef0fbc9c8e1000095
[ "Mathematics", "Lists", "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/588a3c3ef0fbc9c8e1000095
7 kyu
Complete the function so that it returns the number of seconds that have elapsed between the start and end times given. ##### Tips: - The start/end times are given as Date (JS/CoffeeScript), DateTime (C#), Time (Nim), datetime(Python) and Time (Ruby) instances. - The start time will always be before the end time.
reference
def elapsed_seconds(start, end): return (end - start). total_seconds()
Elapsed Seconds
517b25a48557c200b800000c
[ "Date Time", "Fundamentals" ]
https://www.codewars.com/kata/517b25a48557c200b800000c
7 kyu
Create a function that returns a villain name based on the user's birthday. The birthday will be passed to the function as a valid Date object, so for simplicity, there's no need to worry about converting strings to dates. The first name will come from the month, and the last name will come from the last digit of the ...
reference
def get_villain_name(birthdate): first = ["The Evil", "The Vile", "The Cruel", "The Trashy", "The Despicable", "The Embarrassing", "The Disreputable", "The Atrocious", "The Twirling", "The Orange", "The Terrifying", "The Awkward"] last = ["Mustache", "Pickle", "Hood Ornament", "Raisin", "Recycli...
Find Your Villain Name
536c00e21da4dc0a0700128b
[ "Arrays", "Date Time", "Fundamentals" ]
https://www.codewars.com/kata/536c00e21da4dc0a0700128b
7 kyu
You have to create a method "compoundArray" which should take as input two int arrays of different length and return one int array with numbers of both arrays shuffled one by one. ```Example: Input - {1,2,3,4,5,6} and {9,8,7,6} Output - {1,9,2,8,3,7,4,6,5,6} ```
reference
def compound_array(a, b): x = [] while a or b: if a: x . append(a . pop(0)) if b: x . append(b . pop(0)) return x
CompoundArray
56044de2aa75e28875000017
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/56044de2aa75e28875000017
7 kyu
Complete the function `power_of_two`/`powerOfTwo` (or equivalent, depending on your language) that determines if a given non-negative integer is a [power of two](https://en.wikipedia.org/wiki/Power_of_two). From the corresponding Wikipedia entry: > *a power of two is a number of the form 2<sup>n</sup> where **n** is ...
reference
def power_of_two(num): return bin(num). count('1') == 1
Power of two
534d0a229345375d520006a0
[ "Mathematics", "Algorithms", "Fundamentals" ]
https://www.codewars.com/kata/534d0a229345375d520006a0
7 kyu
# RegExp Fun #1 - When I miss few days of gym ## Disclaimer The background story of this Kata is 100% fiction. Any resemblance to real people or real events is **nothing more than a coincidence** and should be regarded as such. ## Background Story You are a person who loves to go to the gym everyday with the squad...
reference
import re def gym_slang(phrase): phrase = re . sub(r'([pP])robably', r'\1rolly', phrase) phrase = re . sub(r'([iI]) am', r"\1'm", phrase) phrase = re . sub(r'([iI])nstagram', r'\1nsta', phrase) phrase = re . sub(r'([dD])o not', r"\1on't", phrase) phrase = re . sub(r'([gG])oing to', r'\1onn...
RegExp Fun #1 - When I miss few days of gym
5720a81309e1f9b232001c5b
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/5720a81309e1f9b232001c5b
7 kyu
A sequence is usually a set or an array of numbers that has a strict way for moving from the nth term to the (n+1)th term.<br /> If ``f(n) = f(n-1) + c`` where ``c`` is a constant value, then ``f`` is an arithmetic sequence.<br /> An example would be (where the first term is 0 and the constant is 1) is [0, 1, 2, 3, 4, ...
reference
def nthterm(first, n, c): return first + n * c
Arithmetic Sequence!
540f8a19a7d43d24ac001018
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/540f8a19a7d43d24ac001018
7 kyu
Your task is to write function which takes string and list of delimiters as an input and returns list of strings/characters after splitting given string. Example: ```python multiple_split('Hi, how are you?', [' ']) => ['Hi,', 'how', 'are', 'you?'] multiple_split('1+2-3', ['+', '-']) => ['1', '2', '3'] ``` ```javascrip...
algorithms
from re import split, escape def multiple_split(string, delimiters=[]): return filter(None, split('|' . join(map(escape, delimiters)), string))
Split string by multiple delimiters
575690ee34a34efb37001796
[ "Fundamentals", "Algorithms", "Arrays", "Strings", "Logic" ]
https://www.codewars.com/kata/575690ee34a34efb37001796
7 kyu
# Filter the number Oh, no! The number has been mixed up with the text. Your goal is to retrieve the number from the text, can you return the number back to its original state? ## Task Your task is to return a number from a string. ## Details You will be given a string of numbers and letters mixed up, you have to ret...
reference
def filter_string(string): return int('' . join(filter(str . isdigit, string)))
Filter the number
55b051fac50a3292a9000025
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/55b051fac50a3292a9000025
7 kyu
Given a string made of digits `[0-9]`, return a string where each digit is repeated a number of times equals to its value. ## Examples ```haskell "312" should return "333122" ``` ```haskell "102269" should return "12222666666999999999" ```
reference
def explode(s): return '' . join(c * int(c) for c in s)
Digits explosion
585b1fafe08bae9988000314
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/585b1fafe08bae9988000314
7 kyu
Write 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 charact...
reference
def calculate(num1, operation, num2): # your code here try: return eval("{} {} {}" . format(num1, operation, num2)) except (ZeroDivisionError, SyntaxError): return None
Basic Calculator
5296455e4fe0cdf2e000059f
[ "Fundamentals" ]
https://www.codewars.com/kata/5296455e4fe0cdf2e000059f
7 kyu
Implement `String#to_cents`, which should parse prices expressed as `$1.23` and return number of cents, or in case of bad format return `nil`.
reference
import re def to_cents(amount): m = re . match(r'\$(\d+)\.(\d\d)\Z', amount) return int(m . expand(r'\1\2')) if m else None
Regexp basics - parsing prices
56833b76371e86f8b6000015
[ "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/56833b76371e86f8b6000015
7 kyu
## Description You are a *Fruit Ninja*, your skill is cutting fruit. All the fruit will be cut in half by your knife. For example: ``` [ "apple", "pear", "banana" ] --> ["app", "le", "pe", "ar", "ban", "ana"] ``` As you see, all fruits are cut in half. You should pay attention to `"apple"`: if you cannot ...
games
def cut(x): if x in FRUIT_NAMES: m = (len(x) + 1) / / 2 return [x[: m], x[m:]] return [x] def cut_fruits(fruits): return [x for xs in map(cut, fruits) for x in xs]
I guess this is a 7kyu kata #6: Fruit Ninja I
57d60363a65454701d000e11
[ "Puzzles" ]
https://www.codewars.com/kata/57d60363a65454701d000e11
7 kyu
No Story No Description Only by Thinking and Testing Look at result of testcase, guess the code! # #Series:<br> <a href="http://www.codewars.com/kata/56d904db9963e9cf5000037d">01:A and B?</a><br> <a href="http://www.codewars.com/kata/56d9292cc11bcc3629000533">02:Incomplete string</a><br> <a href="http://www.c...
games
import re def testit(s): return len(re . findall(r'w.*?o.*?r.*?d', s, re . I))
Thinking & Testing : How many "word"?
56eff1e64794404a720002d2
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/56eff1e64794404a720002d2
7 kyu
No Story No Description Only by Thinking and Testing Look at result of testcase, guess the code! # #Series:<br> <a href="http://www.codewars.com/kata/56d904db9963e9cf5000037d">01:A and B?</a><br> <a href="http://www.codewars.com/kata/56d9292cc11bcc3629000533">02:Incomplete string</a><br> <a href="http://www.c...
games
def testit(n): return bin(n). count('1')
Thinking & Testing : True or False
56d931ecc443d475d5000003
[ "Puzzles" ]
https://www.codewars.com/kata/56d931ecc443d475d5000003
7 kyu
No Story No Description Only by Thinking and Testing Look at result of testcase, guess the code! # Series: <a href="http://www.codewars.com/kata/56d904db9963e9cf5000037d">01:A and B?</a><br> <a href="http://www.codewars.com/kata/56d9292cc11bcc3629000533">02:Incomplete string</a><br> <a href="http://www.codewars.co...
games
def testit(s): return s[:: - 1]. title()[:: - 1]
Thinking & Testing : Something capitalized
56d93f249c844788bc000002
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/56d93f249c844788bc000002
7 kyu
No Story No Description Only by Thinking and Testing Look at result of testcase, guess the code! ## Series * <a href="http://www.codewars.com/kata/56d904db9963e9cf5000037d">01:A and B?</a> * <a href="http://www.codewars.com/kata/56d9292cc11bcc3629000533">02:Incomplete string</a> * <a href="http://www.codewars.com...
games
import re def testit(s): return re . sub("(.)(.)", lambda m: chr((ord(m[1]) + ord(m[2])) / / 2), s)
Thinking & Testing : Incomplete string
56d9292cc11bcc3629000533
[ "Puzzles" ]
https://www.codewars.com/kata/56d9292cc11bcc3629000533
7 kyu
No Story No Description Only by Thinking and Testing Look at the results of the testcases, and guess the code! --- ## Series: 01. [A and B?](http://www.codewars.com/kata/56d904db9963e9cf5000037d) 02. [Incomplete string](http://www.codewars.com/kata/56d9292cc11bcc3629000533) 03. [True or False](http://www.codewars...
games
def mystery(a): return a[0] * a[3] + a[1] * a[2]
Thinking & Testing : Math of Primary School
56d9b46113f38864b8000c5a
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/56d9b46113f38864b8000c5a
7 kyu
<p align="center"><b>Shortest Code : Jumping Dutch act<br>(Code length limit: 90 chars)</b></p> This is the challenge version of coding 3min series. If you feel difficult, please complete the [simple version](http://www.codewars.com/kata/570bcd9715944a2c8e000009) ## Task: Mr. despair wants to jump off Dutch act, So...
games
def sc(f): return "Aa~ " * (f - 1) + 'Pa!' * (f > 1) + ' Aa!' * \ (1 < f < 7) # 51 characters without this comment
Shortest Code : Jumping Dutch act
570bbf7b6731d44b36001fde
[ "Puzzles", "Games", "Restricted" ]
https://www.codewars.com/kata/570bbf7b6731d44b36001fde
7 kyu
This is the simple version of Shortest Code series. If you need some challenges, please try the [challenge version](http://www.codewars.com/kata/570f45fab29c705d330004e3) ## Task: There is a rectangular land and we need to plant trees on the edges of that land. I will give you three parameters: ```width``` and ```l...
games
def sc(width, length, gaps): # your code here a, b = divmod(2 * width + 2 * length - 4, gaps + 1) return 0 if b else a
Coding 3min : Planting Trees
5710443187a36a9cee0005a1
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/5710443187a36a9cee0005a1
7 kyu
### Task Yes, your eyes are no problem, this is toLoverCase (), not toLowerCase (), we want to make the world full of love. ### What do we need to do? You need to add a prototype function to the String, the name is toLoverCase. Function can convert the letters in the string, converted to "L", "O", "V", "E", ...
games
def to_lover_case(string): return "" . join("LOVE" [(ord(c) - 97) % 4] if c . isalpha() else c for c in string)
Coding 3min : toLoverCase()
5713b0253b510cd97f001148
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/5713b0253b510cd97f001148
7 kyu
# Description: Move all exclamation marks to the end of the sentence # Examples ``` "Hi!" ---> "Hi!" "Hi! Hi!" ---> "Hi Hi!!" "Hi! Hi! Hi!" ---> "Hi Hi Hi!!!" "Hi! !Hi Hi!" ---> "Hi Hi Hi!!!" "Hi! Hi!! Hi!" ---> "Hi Hi Hi!!!!" ```
reference
def remove(s): return s . replace('!', '') + s . count('!') * '!'
Exclamation marks series #8: Move all exclamation marks to the end of the sentence
57fafd0ed80daac48800019f
[ "Fundamentals" ]
https://www.codewars.com/kata/57fafd0ed80daac48800019f
7 kyu
## Task To charge your mobile phone battery, do you know how much time it takes from 0% to 100%? It depends on your cell phone battery capacity and the power of the charger. A rough calculation method is: ``` 0% --> 85% (fast charge) (battery capacity(mAh) * 85%) / power of the charger(mA) 85% --> 95% (decreasing ch...
games
def calculate_time(b, c): return round(b / float(c) * 1.3 + 0.0001, 2)
So Easy: Charge time calculation
57ea0ee4491a151fc5000acf
[ "Puzzles" ]
https://www.codewars.com/kata/57ea0ee4491a151fc5000acf
7 kyu
# Description: Remove words from the sentence if they contain exactly one exclamation mark. Words are separated by a single space, without leading/trailing spaces. # Examples ``` remove("Hi!") === "" remove("Hi! Hi!") === "" remove("Hi! Hi! Hi!") === "" remove("Hi Hi! Hi!") === "Hi" remove("Hi! !Hi Hi!") === "" remo...
reference
def remove(s): return ' ' . join(w for w in s . split(' ') if w . count('!') != 1)
Exclamation marks series #7: Remove words from the sentence if it contains one exclamation mark
57fafb6d2b5314c839000195
[ "Fundamentals", "Strings", "Algorithms" ]
https://www.codewars.com/kata/57fafb6d2b5314c839000195
7 kyu
You will be given a string (`map`) featuring a cat `"C"` and a mouse `"m"`. The rest of the string will be made up of dots (`"."`) The cat can move the given number of `moves` up, down, left or right, but **not diagonally**. You need to find out if the cat can catch the mouse from it's current position and return `"Ca...
games
def cat_mouse(map_, moves): if 'C' not in map_ or 'm' not in map_: return 'boring without two animals' for row, line in enumerate(map_ . splitlines()): if 'C' in line: cat = row, line . index('C') if 'm' in line: mouse = row, line . index('m') distance = abs(cat[0] - mouse[0]) ...
Cat and Mouse - 2D Version
57f8842367c96a89dc00018e
[ "Graph Theory", "Algorithms" ]
https://www.codewars.com/kata/57f8842367c96a89dc00018e
7 kyu
## Story John runs a shop, bought some goods, and then sells them. He used a special accounting method, like this: ``` [[60,20],[60,-20]] ``` Each sub array records the commodity price and profit/loss to sell (percentage). Positive mean profit and negative means loss. In the example above, John's first commodity sold...
games
def profitLoss(records): return round(sum(price - price / (1 + profit / 100) for (price, profit) in records), 2)
T.T.T. #7: Profit or loss
5768b775b8ed4a360f000b20
[ "Puzzles", "Games" ]
https://www.codewars.com/kata/5768b775b8ed4a360f000b20
7 kyu
Write a regex to validate a 24 hours time string. See examples to figure out what you should check for: Accepted: 01:00 - 1:00 Not accepted: 24:00 You should check for correct length and no spaces.
reference
import re _24H = re . compile(r'^([01]?\d|2[0-3]):[0-5]\d$') def validate_time(time): return bool(_24H . match(time))
regex validation of 24 hours time.
56a4a3d4043c316002000042
[ "Regular Expressions", "Date Time", "Fundamentals" ]
https://www.codewars.com/kata/56a4a3d4043c316002000042
7 kyu
Challenge: Given a two-dimensional array of integers, return the flattened version of the array with all the integers in the sorted (ascending) order. Example: Given [[3, 2, 1], [4, 6, 5], [], [9, 7, 8]], your function should return [1, 2, 3, 4, 5, 6, 7, 8, 9]. ```if:javascript Addendum: Please, keep in mind, that...
reference
def flatten_and_sort(array): return sorted([j for i in array for j in i])
Flatten and sort an array
57ee99a16c8df7b02d00045f
[ "Arrays", "Sorting", "Fundamentals" ]
https://www.codewars.com/kata/57ee99a16c8df7b02d00045f
7 kyu
Given 2 string parameters, show a concatenation of: - the reverse of the 2nd string with inverted case; e.g `Fish` -> `HSIf` - a separator in between both strings: `@@@` - the 1st string reversed with inverted case and then mirrored; e.g `Water` -> `RETAwwATER ` ** Keep in mind that this kata was initially designed ...
reference
def reverse_and_mirror(s1, s2): swap = s1 . swapcase() return '{}@@@{}{}' . format(s2[:: - 1]. swapcase(), swap[:: - 1], swap) # PEP8: function name should use snake_case reverseAndMirror = reverse_and_mirror
String Reversing, Changing case, etc.
58305403aeb69a460b00019a
[ "Fundamentals" ]
https://www.codewars.com/kata/58305403aeb69a460b00019a
7 kyu
In Russia, there is an army-purposed station named UVB-76 or "Buzzer" (see also https://en.wikipedia.org/wiki/UVB-76). Most of time specific "buzz" noise is being broadcasted, but on very rare occasions, the buzzer signal is interrupted and a voice transmission in Russian takes place. Transmitted messages have always t...
algorithms
import re def validate(msg): return bool(re . match( '^MDZHB \d\d \d\d\d [A-Z]+ \d\d \d\d \d\d \d\d$', msg))
UVB-76 Message Validator
56445cc2e5747d513c000033
[ "Algorithms", "Strings", "Regular Expressions" ]
https://www.codewars.com/kata/56445cc2e5747d513c000033
7 kyu
Mr. E Ven only likes even length words. Please create a translator so that he doesn't have to hear those pesky odd length words. For some reason he also hates punctuation, he likes his sentences to flow. Your translator should take in a string and output it with all odd length words having an extra letter (the last le...
reference
def evenator(s): return ' ' . join(w + w[- 1] if len(w) % 2 else w for w in s . translate(None, '.,?!_'). split())
Help Mr. E
56ce2f90aa4ac7a4770019fa
[ "Strings", "Fundamentals", "Regular Expressions" ]
https://www.codewars.com/kata/56ce2f90aa4ac7a4770019fa
7 kyu
Complete the function that returns the color of the given square on a normal, 8x8 chess board: ![chessboard](https://i.imgur.com/aM0oVWW.png) ## Examples ``` "a", 8 ==> "white" "b", 2 ==> "black" "f", 5 ==> "white" ``` ~~~if:c For C language: Do not allocate memory for the return value, simply return a strin...
algorithms
def square_color(file, rank): return 'white' if (ord(file) + rank) % 2 else 'black'
White or Black?
563319974612f4fa3f0000e0
[ "Algorithms" ]
https://www.codewars.com/kata/563319974612f4fa3f0000e0
7 kyu
Your friend Cody has to sell a lot of jam, so he applied a good 25% discount to all his merchandise. Trouble is that he mixed all the prices (initial and discounted), so now he needs your cool coding skills to filter out only the discounted prices. For example, consider this inputs: ``` "15 20 60 75 80 100" "9 9 12 1...
algorithms
def find_discounted(prices): prices = [int(n) for n in prices . split()] return " " . join(prices . remove(round(p * 4 / 3)) or str(p) for p in prices)
Find the discounted prices
56f3ed90de254a2ca7000e20
[ "Arrays", "Lists", "Algorithms" ]
https://www.codewars.com/kata/56f3ed90de254a2ca7000e20
6 kyu
Given an array of numbers (in string format), you must return a string. The numbers correspond to the letters of the alphabet in reverse order: a=26, z=1 etc. You should also account for `'!'`, `'?'` and `' '` that are represented by '27', '28' and '29' respectively. All inputs will be valid.
reference
chars = "_zyxwvutsrqponmlkjihgfedcba!? " def switcher(arr): return "" . join(chars[int(i)] for i in arr if i != "0")
Numbers to Letters
57ebaa8f7b45ef590c00000c
[ "Fundamentals", "Strings", "Arrays" ]
https://www.codewars.com/kata/57ebaa8f7b45ef590c00000c
7 kyu
We need to write some code to return the original price of a product, the return type must be of type decimal and the number must be rounded to two decimal places. We will be given the sale price (discounted price), and the sale percentage, our job is to figure out the original price. ### For example: Given an item...
reference
def discover_original_price(discounted_price, sale_percentage): return round(discounted_price / ((100 - sale_percentage) * 0.01), 2)
Discover The Original Price
552564a82142d701f5001228
[ "Fundamentals", "Mathematics" ]
https://www.codewars.com/kata/552564a82142d701f5001228
7 kyu
Another rewarding day in the fast-paced world of WebDev. Man, you love your job! But as with any job, somtimes things can get a little tedious. Part of the website you're working on has a very repetitive structure, and writing all the HTML by hand is a bore. Time to automate! You want to write some functions that will ...
games
class HTMLGen: def __init__(self): self . a = lambda t: self . tag("a", t) self . b = lambda t: self . tag("b", t) self . p = lambda t: self . tag("p", t) self . body = lambda t: self . tag("body", t) self . div = lambda t: self . tag("div", t) self . span = lambda t: self . tag("span...
HTML Generator
54eecc187f9142cc4600119e
[ "Functional Programming", "Puzzles" ]
https://www.codewars.com/kata/54eecc187f9142cc4600119e
7 kyu
<h2>#~For Kids Challenges~#</h2> <h4>Your task is easy, write a function that takes an date in format d/m/Y(String) and return what day of the week it was(String).</h4> <h5 style="background-color:#ccc;color:#333">Example: "21/01/2017" -> "Saturday", "31/03/2017" -> "Friday"</h5> <p>Have fun!</p>
reference
from dateutil . parser import parse def day_of_week(date): return parse(date, dayfirst=True). strftime("%A")
#~For Kids~# d/m/Y -> Day of the week.
5885b5d2b632089dc30000cc
[ "Fundamentals", "Date Time" ]
https://www.codewars.com/kata/5885b5d2b632089dc30000cc
7 kyu
You have just boarded a train when your friend texts you to ask how long it will take your train to reach the stop where they're waiting for you. Assuming that you know the distance in km and the train's average speed in km/h, let your friend know how long it will take the train to reach their stop, rounding the time ...
reference
def reach_destination(distance, speed): time = round(2 * distance / speed) / 2 return 'The train will be there in %g hour%s.' % (time, 's' * (time != 1))
How long will it take the train to reach its final destination?
58342f14fa17ad4285000307
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/58342f14fa17ad4285000307
7 kyu
In this exercise, a string is passed to a method and a new string has to be returned with the first character of each word in the string. For example: ``` "This Is A Test" ==> "TIAT" ``` Strings will only contain letters and spaces, with exactly 1 space between words, and no leading/trailing spaces.
reference
def make_string(s): return '' . join(a[0] for a in s . split())
Return String of First Characters
5639bdcef2f9b06ce800005b
[ "Strings", "Regular Expressions", "Fundamentals" ]
https://www.codewars.com/kata/5639bdcef2f9b06ce800005b
7 kyu
Given two arrays of integers `m` and `n`, test if they contain *at least* one identical element. Return `true` if they do; `false` if not. Your code must handle any value within the range of a 32-bit integer, and must be capable of handling either array being empty (which is a `false` result, as there are no duplicate...
reference
def duplicate_elements(m, n): return not set(m). isdisjoint(n)
Identical Elements
583ebb9328a0c034490001ba
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/583ebb9328a0c034490001ba
7 kyu
You will be given an array of numbers. For each number in the array you will need to create an object. The object key will be the number, as a string. The value will be the corresponding character code, as a string. Return an array of the resulting objects. All inputs will be arrays of numbers. All character codes...
reference
def num_obj(s): return [{str(i): chr(i)} for i in s]
Numbers to Objects
57ced2c1c6fdc22123000316
[ "Fundamentals", "Strings", "Arrays" ]
https://www.codewars.com/kata/57ced2c1c6fdc22123000316
7 kyu
**This Kata is intended as a small challenge for my students** All Star Code Challenge #1 Write a function, called `sumPPG`, that takes two NBA player objects/struct/Hash/Dict/Class and sums their PPG ### Examples: ```haskell -- Player is defined as: data Player = Player { team :: String, ppg :: Double } deriving (...
reference
def sum_ppg(player_one, player_two): return player_one['ppg'] + player_two['ppg']
All Star Code Challenge #1
5863f97fb3a675d9a700003f
[ "Fundamentals" ]
https://www.codewars.com/kata/5863f97fb3a675d9a700003f
7 kyu
## Task Write a method `remainder` which takes two integer arguments, `dividend` and `divisor`, and returns the remainder when dividend is divided by divisor. Do <b>NOT</b> use the modulus operator (%) to calculate the remainder! #### Assumption Dividend will always be `greater than or equal to` divisor. #### Notes...
algorithms
def remainder(dividend, divisor): return dividend - (dividend / / divisor) * divisor
Finding Remainder Without Using '%' Operator
564f458b4d75e24fc9000041
[ "Mathematics", "Restricted", "Algorithms" ]
https://www.codewars.com/kata/564f458b4d75e24fc9000041
7 kyu
Write a function that returns the number of '2's in the factorization of a number. For example, ```python two_count(24) ``` ```ruby two_count(24) ``` ```javascript twoCount(24) ``` ```coffeescript twoCount 24 ``` ```haskell twoCount 24 ``` ```csharp TwoCount(24) ``` ```clojure two-count 24 ``` should return 3, since ...
algorithms
def two_count(n): res = 0 while not n & 1: res += 1 n >>= 1 return res
How many twos?
56aed5db9d5cb55de000001c
[ "Algorithms" ]
https://www.codewars.com/kata/56aed5db9d5cb55de000001c
7 kyu
Create a function that takes a string and returns that string with the first half lowercased and the last half uppercased. eg: foobar == fooBAR If it is an odd number then 'round' it up to find which letters to uppercase. See example below. sillycase("brian") // --^-- midpoint // bri ...
reference
def sillycase(silly): half = (len(silly) + 1) / / 2 return silly[: half]. lower() + silly[half:]. upper()
SillyCASE
552ab0a4db0236ff1a00017a
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/552ab0a4db0236ff1a00017a
7 kyu
~~~if-not:scala Return an array containing the numbers from 1 to N, where N is the parametered value. ~~~ ~~~if:scala Return a list containing the numbers from 1 to N, where N is the parametered value. ~~~ Replace certain values however if any of the following conditions are met: * If the value is a multiple of 3: us...
algorithms
def fizzbuzz(n): li = [] for i in range(1, n + 1): if i % 3 == 0 and i % 5 == 0: li . append("FizzBuzz") elif i % 3 == 0: li . append("Fizz") elif i % 5 == 0: li . append("Buzz") else: li . append(i) return li
Fizz Buzz
5300901726d12b80e8000498
[ "Algorithms", "Fundamentals", "Arrays" ]
https://www.codewars.com/kata/5300901726d12b80e8000498
7 kyu
# Description "It's the end of trick-or-treating and we have a list/array representing how much candy each child in our group has made out with. We don't want the kids to start arguing, and using our parental intuition we know trouble is brewing as many of the children in the group have received different amounts of ca...
algorithms
def candies(s): if not s or len(s) == 1: return - 1 return len(s) * max(s) - sum(s)
Candy problem
55466644b5d240d1d70000ba
[ "Lists", "Algorithms" ]
https://www.codewars.com/kata/55466644b5d240d1d70000ba
7 kyu
Write a function `last` that accepts a list and returns the last element in the list. If the list is empty: In languages that have a built-in `option` or `result` type (like OCaml or Haskell), return an empty `option` ~~~if-not:python In languages that do not have an empty option, just return `null` ~~~ ~~~if:python...
reference
def last(lst): return lst[- 1] if lst else None
99 Problems, #1: last in list
57d86d3d3c3f961278000005
[ "Lists", "Fundamentals" ]
https://www.codewars.com/kata/57d86d3d3c3f961278000005
7 kyu
Step through my `green glass door`. You can take the `moon`, but not the `sun`. You can take your `slippers`, but not your `sandals`. You can go through `yelling`, but not `shouting`. You can't run through `fast`, but you can run with `speed`. You can take a `sheet`, but not your `blanket`. You can wear your `gla...
reference
def step_through_with(s): return any(m == n for m, n in zip(s, s[1:]))
Green Glass Door
5642bf07a586135a6f000004
[ "Strings", "Fundamentals", "Puzzles" ]
https://www.codewars.com/kata/5642bf07a586135a6f000004
7 kyu
Given a number return the closest number to it that is divisible by 10. Example input: ``` 22 25 37 ``` Expected output: ``` 20 30 40 ```
algorithms
def closest_multiple_10(i): return round(i, - 1)
Return the closest number multiple of 10
58249d08b81f70a2fc0001a4
[ "Mathematics", "Fundamentals" ]
https://www.codewars.com/kata/58249d08b81f70a2fc0001a4
7 kyu
# Introduction You are the developer working on a website which features a large counter on its homepage, proudly displaying the number of happy customers who have downloaded your companies software. You have been tasked with adding an effect to this counter to make it more interesting. Instead of just displaying ...
reference
def counter_effect(n): return [list(range(int(x) + 1)) for x in n]
Hit Count
57b6f850a6fdc76523001162
[ "Arrays", "Fundamentals" ]
https://www.codewars.com/kata/57b6f850a6fdc76523001162
7 kyu
You have to create a function named reverseIt. Write your function so that in the case a string or a number is passed in as the data , you will return the data in reverse order. If the data is any other type, return it as it is. Examples of inputs and subsequent outputs: ``` "Hello" -> "olleH" "314159" -> "951413" ...
reference
def reverse_it(data): if type(data) in [int, str, float]: return type(data)(str(data)[:: - 1]) return data
reverseIt
557a2c136b19113912000010
[ "Fundamentals" ]
https://www.codewars.com/kata/557a2c136b19113912000010
7 kyu
In this kata you need to create a function that takes a 2D array/list of non-negative integer pairs and returns the sum of all the "saving" that you can have getting the [LCM](https://en.wikipedia.org/wiki/Least_common_multiple) of each couple of number compared to their simple product. For example, if you are given: ...
reference
import math def sum_differences_between_products_and_LCMs(pairs): prod1 = [math . prod(x) for x in pairs] lcm1 = [math . lcm(x[0], x[- 1]) for x in pairs] return sum([x - y for x, y in zip(prod1, lcm1)])
Sum of differences between products and LCMs
56e56756404bb1c950000992
[ "Arrays", "Lists", "Fundamentals" ]
https://www.codewars.com/kata/56e56756404bb1c950000992
7 kyu
[Vowel harmony](https://en.wikipedia.org/wiki/Vowel_harmony) is a phenomenon in some languages. It means that "A vowel or vowels in a word are changed to sound the same (thus "in harmony.")" ([wikipedia](https://en.wikipedia.org/wiki/Vowel_harmony#Hungarian)). This kata is based on [vowel harmony in Hungarian](https://...
reference
def dative(word): for c in word[:: - 1]: if c in u'eéiíöőüű': return word + 'nek' elif c in u'aáoóuú': return word + 'nak'
Hungarian Vowel Harmony (easy)
57fd696e26b06857eb0011e7
[ "Strings", "Fundamentals" ]
https://www.codewars.com/kata/57fd696e26b06857eb0011e7
7 kyu
Given a string, you progressively need to concatenate the first character from the left and the first character from the right and "1", then the second character from the left and the second character from the right and "2", and so on. If the string's length is odd drop the central element. For example: ```python cha...
reference
def char_concat(word): return '' . join([(word[i] + word[- 1 - i] + str(i + 1)) for i in range(len(word) / / 2)])
Character Concatenation
55147ff29cd40b43c600058b
[ "Fundamentals" ]
https://www.codewars.com/kata/55147ff29cd40b43c600058b
7 kyu
As the title suggests, this is the hard-core version of <a href="https://www.codewars.com/kata/sum-of-a-sequence/" target="_blank"> another neat kata</a>. The task is simple to explain: simply sum all the numbers from the first parameter being the beginning to the second parameter being the upper limit (possibly inclu...
algorithms
# from math import copysign def sequence_sum(a, b, step): n = (b - a) / / step return 0 if n < 0 else (n + 1) * (n * step + a + a) / / 2
Sum of a Sequence [Hard-Core Version]
587a88a208236efe8500008b
[ "Algorithms" ]
https://www.codewars.com/kata/587a88a208236efe8500008b
6 kyu
You've come to visit your grandma and she immediately found you a job - her Christmas tree needs decorating! She first shows you a tree with a given number of branches, and then hands you some baubles (or loads of them!). You know your grandma is a very particular person and that she'd like the baubles distributed in...
algorithms
def baubles_on_tree(baubles, branches): if not branches: return "Grandma, we will have to buy a Christmas tree first!" d, r = divmod(baubles, branches) return [d + 1] * r + [d] * (branches - r)
Christmas baubles on the tree
5856c5f7f37aeceaa100008e
[ "Arrays", "Algorithms" ]
https://www.codewars.com/kata/5856c5f7f37aeceaa100008e
7 kyu