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 to teleport people anywhere you want. <h4 style="color:brown">Legend:</h4> -Uppercase letters stands for mothers, lowercase stand for their children, i.e. "A" mother's children are "aaaa".<br> -Function input: String contains only letters, uppercase letters are unique. <h4 style="color:brown">Task:</h4> Place all people in alphabetical order where Mothers are followed by their children, i.e. "aAbaBb" => "AaaBbb".
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 a space between each value. For example if the following tree were input to our function : ![alt text](https://upload.wikimedia.org/wikipedia/commons/thumb/f/f7/Binary_tree.svg/220px-Binary_tree.svg.png) the output would be a string and look something like this: ```javascript 2 7 5 2 6 9 5 11 4 ``` All nodes in the tree will have two properties, ```.value``` and ```.children```. You may assume the ```.value``` property will always be either a string or a number. The ```.children``` property will be an array containing all of the node's children. The tree is NOT necessarily a binary tree, each node may have many children nodes You may implement whatever method you see fit to search the tree. There are both breadth first and depth first approaches.
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 . append(" " . join(str(x . value) for x in q)) q = sum((x . children for x in q), []) return "\n" . join(res)
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 cubes. * The layers are thus so built that the corner cube always covers the inner 25% of the corner cube below it and so each row has one more cube than the one below it. If you were given only 5 cubes, the lower layer would have 4 cubes and the top 1 cube would sit right in the middle of them, where the lower 4 cubes meet. If you were given 14 cubes, you could build a pyramid of 3 layers, but 13 wouldn't be enough as you would be missing one cube, so only 2 layers would be complete and some cubes left over! What is the tallest pyramid possible we can build from the given number of cubes? Simply return the number of **complete** layers. ## Examples ```ruby 4 --> 1 5 --> 2 13 --> 2 14 --> 3 ```
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 into a candy which will be two times bigger; to pick a single candy of an even size and split it into two equal candies half of this size each.``` What is the size of the biggest candy they can make as a gift? # Example For `arr = [2, 4, 8, 1, 1, 15]`, the output should be 16. ``` [2, 4, 8, 1, 1, 15] --> [2, 4, 8, 2, 15] -->[4, 4, 8, 15] --> [8, 8, 15] --> [16, 15] -->choose 16 ``` # Input/Output - [input] integer array `arr` Array of positive integers. Constraints: `5 ≤ inputArray.length ≤ 50,` `1 ≤ inputArray[i] ≤ 100.` - `[output]` an integer
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]: https://en.wikipedia.org/wiki/Power_set
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 5 out of 8 elements of ```arr``` and 5 is more than a half of 8.<br/> Write a function ```dominator(arr)``` that, given a zero-indexed array ```arr``` consisting of n integers, returns the dominator of ```arr```. The function should return −1 if array does not have a dominator. All values in ```arr``` will be >=0.
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 screwdriver in his hand, and another in his tool kit. He works from left to right, removing every screw. When necessary, he switches between the screwdriver in his hand and the one in his tool kit. Each action takes a set amount of time: * remove one screw : 1 second * move to the next screw: 1 second * switch screwdrivers: 5 seconds Your task is to return the total time taken to remove all the screws, in seconds. ## Examples In order to be more clear, we use `ABCDEF` to represent the screws. The number in brackets is the time in seconds: ``` screws: "---+++" ABCDEF remove A (1) + move to B (1) + remove B (1) + move to C (1) + remove C (1) + move to D (1) + switch screwdriver (5) + remove D (1) + move to E (1) + remove E (1) + move to F (1) + remove F (1) total time = 16 seconds ``` Another example: ``` screws: "-+-+-+" ABCDEF remove A (1) + move to B (1) + switch screwdriver (5) + remove B (1) + move to C (1) + switch screwdriver (5) + remove C (1) + move to D (1) + switch screwdriver (5) + remove D (1) + move to E (1) + switch screwdriver (5) + remove E (1) + move to F (1) + switch screwdriver (5) + remove F (1) total time = 36 seconds ``` ## Variations * [Golf version](http://www.codewars.com/kata/57109bf197b4b3853a000274) * This work method may not be the fastest. For a better method, see [Remove screws II](http://www.codewars.com/kata/5710a8fd336aed00d9000594) ### Series: - [Bug in Apple](http://www.codewars.com/kata/56fe97b3cc08ca00e4000dc9) - [Father and Son](http://www.codewars.com/kata/56fe9a0c11086cd842000008) - [Jumping Dutch act](http://www.codewars.com/kata/570bcd9715944a2c8e000009) - [Planting Trees](http://www.codewars.com/kata/5710443187a36a9cee0005a1) - [Give me the equation](http://www.codewars.com/kata/56fe9b65cc08cafbc5000de3) - [Find the murderer](http://www.codewars.com/kata/570f3fc5b29c702c5500043e) - [Reading a Book](http://www.codewars.com/kata/570ca6a520c69f39dd0016d4) - [Eat watermelon](http://www.codewars.com/kata/570df12ce6e9282a7d000947) - [Special factor](http://www.codewars.com/kata/570e5d0b93214b1a950015b1) - [Guess the Hat](http://www.codewars.com/kata/570ef7a834e61306da00035b) - [Symmetric Sort](http://www.codewars.com/kata/5705aeb041e5befba20010ba) - [Are they symmetrical?](http://www.codewars.com/kata/5705cc3161944b10fd0004ba) - [Max Value](http://www.codewars.com/kata/570771871df89cf59b000742) - [Trypophobia](http://www.codewars.com/kata/56fe9ffbc25bf33fff000f7c) - [Virus in Apple](http://www.codewars.com/kata/5700af83d1acef83fd000048) - [Balance Attraction](http://www.codewars.com/kata/57033601e55d30d3e0000633) - [Remove screws I](http://www.codewars.com/kata/5710a50d336aed828100055a) - [Remove screws II](http://www.codewars.com/kata/5710a8fd336aed00d9000594) - [Regular expression compression](http://www.codewars.com/kata/570bae4b0237999e940016e9) - [Collatz Array(Split or merge)](http://www.codewars.com/kata/56fe9d579b7bb6b027000001) - [Tidy up the room](http://www.codewars.com/kata/5703ace6e55d30d3e0001029) - [Waiting for a Bus](http://www.codewars.com/kata/57070eff924f343280000015)
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, so that it looks like this: ``` Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. ``` Write a function, `format_poem()` that takes a string like the one line example as an argument and returns a new string that is formatted across multiple lines with each new sentence starting on a new line when you print it out. Try to solve this challenge with the [str.split()](https://docs.python.org/3/library/stdtypes.html#str.split) and the [str.join()](https://docs.python.org/3/library/stdtypes.html#str.join) string methods. Every sentence will end with a period, and every new sentence will have one space before the previous period. Be careful about trailing whitespace in your solution.
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 fellow Dane [Ole Rømer](https://en.wikipedia.org/wiki/Ole_R%C3%B8mer) to this very day, skipping over the Fahrenheit and Celsius scales entirely. Your magnum opus contains several thousand references to temperature, but those temperatures are all currently in degrees Celsius. You don't want to convert everything by hand, so you've decided to write a function, `celsius_to_romer()` that takes a temperature in degrees Celsius and returns the equivalent temperature in degrees Rømer. For example: `celsius_to_romer(24)` should return `20.1`.
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 number. Every phone number is formatted like in the example, and the only non-alphanumeric characters in the string are apostrophes `'` or the punctuation used in the phone number.
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('yo', 3) '"yo" repeated 3 times is: "yoyoyo"' >>> repeater('WuB', 6) '"WuB" repeated 6 times is: "WuBWuBWuBWuBWuBWuB"' ```
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] ``` ```csharp Kata.Largest(2, new List<int> {7, 6, 5, 4, 3, 2, 1}) => new List<int> {6, 7} ```
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], [2,3], [1,3], [1,2,3]] ``` Your function should be able to count sets up to the size of 500, so watch out; pretty big numbers occur there! For comparison, my Haskell solution can compute the number of sets for an array of length 90 000 in less than a second, so be quick! You should treat each array passed as a set of unique values for this kata. ----- ###Examples: ```coffeescript powers([]) => 1 powers([1]) => 2 powers([1,2]) => 4 powers([1,2,3,4]) => 16 ``` ```java Powers.powers(new int[]{}); // 1 Powers.powers(new int[]{1}); // 2 Powers.powers(new int[]{1,2}); // 4 Powers.powers(new int[]{1,2,3,4}); // 16 ``` ```csharp Kata.Powers(new int[] {}) => 1 Kata.Powers(new int[] {1}) => 2 Kata.Powers(new int[] {1,2}) => 4 Kata.Powers(new int[] {1,2,3,4}) => 16 ``` ----- Inspired by [this kata](http://www.codewars.com/kata/by-the-power-set-of-castle-grayskull) by [xcuthulu](http://www.codewars.com/users/xcthulhu) - refer to it if you're stuck!
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 ballots (= votes) a candidate got. A candidate will win this election if he has the <a href="https://en.wikipedia.org/wiki/Supermajority#Majority_of_the_entire_membership">absolute majority</a>. ## Your Task Return the name of the winner. If there is no winner, return `null / nil / None` depending on the language. ## Task Description There are no given candidates. An elector can vote for anyone. Each ballot contains only one name and represents one vote for this name. A name is an arbitrary string, e.g. `"A"`, `"B"`, or `"XJDHD"`. There are no spoiled ballots. The ballot-box is represented by an unsorted list of names. Each entry in the list corresponds to one vote for this name. You do not know the names in advance (because there are no candidates). A name wins the election if it gets more than `n / 2` votes (`n` = number of all votes, i.e. the size of the given list). ## Examples ```python # 3 votes for "A", 2 votes for "B" --> "A" wins the election ["A", "A", "A", "B", "B"] --> "A" # 2 votes for "A", 2 votes for "B" --> no winner ["A", "A", "B", "B"] --> None / nil / null # 1 vote for each name --> no winner ["A", "B", "C", "D"] --> None / nil / null # 3 votes for "A", 2 votes for "B", 1 vote for "C" --> no winner, as "A" does not have more than n / 2 = 3 votes ["A", "A", "A", "B", "B", "C"] --> None / nil / null ``` ## Note Please keep in mind the list of votes can be large (`n <= 1 200 000`). The given list is immutable, i.e. you cannot modify the list (otherwise this could lead to vote rigging). Good luck and have fun.
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> <br> For example:<br> ``` x = 11 d = 1 -> Numbers: 1, 10, 11 Return: [3, 22, 110] ``` <br> If there are no numbers, which include the digit, return [0,0,0]. <br> <br> Have fun coding it and please don't forget to vote and rank this kata! :-) <br> <br> I have created other katas. Have a look if you like coding and challenges.<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 string (with no spaces) containing `[a-z],[A-Z],[0-9]` and common symbols. The length will be `0 < length < 100`. ## Examples * `"abcabc"` is a valid word because `"a"` appears twice, `"b"` appears twice, and`"c"` appears twice. * `"abcabcd"` is **NOT** a valid word because `"a"` appears twice, `"b"` appears twice, `"c"` appears twice, but `"d"` only appears once! * `"123abc!"` is a valid word because all of the characters only appear once in the word.
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 s' Assumptions: String length is always greater than 0 String has no spaces Size is always positive
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.). If `a` and `b` have the same length treat `a` as the longer producing `b+reverse(a)+b`
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 card for your local store. It has some credit you can use to buy things, but it may be used only for up to two items, and any credit you don't use is lost. You want something for a friend and yourself. Therefore, you want to buy two items which add up the entire gift card value. ### Task You will get the value of the gift card `c` and a finite list of item values. You should return a pair of indices that correspond to values that add up to `c`: ```haskell buy 2 [1,1] = Just (0,1) buy 3 [1,1] = Nothing buy 5 [5,2,3,4,5] = Just (1,2) ``` ```javascript buy(2,[1,1]) = [0,1] buy(3,[1,1]) = null buy(5,[5,2,3,4,5]) = [1,2] ``` ```python buy(2,[1,1]) = [0,1] buy(3,[1,1]) = None buy(5,[5,2,3,4,5]) = [1,2] ``` ```coffeescript buy 2, [1,1] = [0,1] buy 3, [1,1] = null buy 5, [5,2,3,4,5] = [1,2] ``` ```cobol buy 2, [1,1] = [1, 2] buy 3, [1,1] = [0, 0] buy 5, [5,2,3,4,5] = [2, 3] ``` The indices start at `0` (`1` in COBOL). The first index should always be smaller than the second index. If there are multiple solutions, return the minimum (lexicographically): ```haskell buy 5 [1,2,3,4,5] = Just (0,3) -- the values at (1,2) also adds up to five, but (0,3) < (1,2) ``` ```javascript buy(5,[1,2,3,4,5]) = [0,3] // the values at [1,2] also adds up to five, but [0,3] < [1,2] ``` ```python buy(5,[1,2,3,4,5]) = [0,3] # the values at [1,2] also adds up to five, but [0,3] < [1,2] ``` ```coffeescript buy 5, [1,2,3,4,5] = [0,3] # the values at [1,2] also adds up to five, but [0,3] < [1,2] ``` ```cobol buy 5, [1, 2, 3, 4, 5] = [1, 4] * the values at [2, 3] also adds up to five, but [1, 4] < [2, 3] ```
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 into the first function. So it returns a function that takes an array and multiplies all elements in it by five. Translations and comments (and upvotes) welcome! ## Example ```javascript var fives = factory(5); // returns a function - fives var myArray = [1, 2, 3]; fives(myArray); //returns [5, 10, 15]; ``` ```python fives = factory(5) # returns a function - fives my_array = [1, 2, 3] fives(my_array) # returns [5, 10, 15] ``` ```coffeescript fives = factory(5) # returns a function - fives myArray = [1, 2, 3] fives(myArray) # returns [5, 10, 15] ``` ```haskell let fives = factory 5 -- returns a function - fives fives [1, 2, 3] -- returns [5, 10, 15] ``` ```csharp Func<int[],int[]> fives = FunctionFactory.factory(5); // returns a function - fives int[] myArray = new int[]{1, 2, 3}; fives(myArray); //returns [5, 10, 15]; ``` ```clojure (let [fives (factory 5)] ; returns a function - fives (fives [1 2 3])) ; returns [5 10 15] ``` ```factor { 1 2 3 } 5 factory ! returns a quotation call( seq -- newseq ) ! returns { 5 10 15 } ```
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` in Ruby/Crystal/JavaScript/CoffeeScript and `case_id` in Python/C) that takes a string, `c_str`, and returns a string with the case the input is in. The possible case types are “kebab”, “camel”, and ”snake”. If none of the cases match with the input, or if there are no 'spaces' in the input (for example in snake case, spaces would be '_'s), return “none”. Inputs will only have letters (no numbers or special characters). ### Some definitions Kebab case: `lowercase-words-separated-by-hyphens` Camel case: `lowercaseFirstWordFollowedByCapitalizedWords` Snake case: `lowercase_words_separated_by_underscores` ### Examples: ```ruby id(“hello-world”) #=> “kebab” id(“hello-to-the-world”) #=> “kebab” id(“helloWorld”) #=> “camel” id(“helloToTheWorld”) #=> “camel” id(“hello_world”) #=> “snake” id(“hello_to_the_world”) #=> “snake” id(“hello__world”) #=> “none” id(“hello_World”) #=> “none” id(“helloworld”) #=> “none” id(“hello-World”) #=> “none” ``` ```crystal id(“hello-world”) #=> “kebab” id(“hello-to-the-world”) #=> “kebab” id(“helloWorld”) #=> “camel” id(“helloToTheWorld”) #=> “camel” id(“hello_world”) #=> “snake” id(“hello_to_the_world”) #=> “snake” id(“hello__world”) #=> “none” id(“hello_World”) #=> “none” id(“helloworld”) #=> “none” id(“hello-World”) #=> “none” ``` ```javascript id(“hello-world”) #=> “kebab” id(“hello-to-the-world”) #=> “kebab” id(“helloWorld”) #=> “camel” id(“helloToTheWorld”) #=> “camel” id(“hello_world”) #=> “snake” id(“hello_to_the_world”) #=> “snake” id(“hello__world”) #=> “none” id(“hello_World”) #=> “none” id(“helloworld”) #=> “none” id(“hello-World”) #=> “none” ``` ```coffeescript id(“hello-world”) #=> “kebab” id(“hello-to-the-world”) #=> “kebab” id(“helloWorld”) #=> “camel” id(“helloToTheWorld”) #=> “camel” id(“hello_world”) #=> “snake” id(“hello_to_the_world”) #=> “snake” id(“hello__world”) #=> “none” id(“hello_World”) #=> “none” id(“helloworld”) #=> “none” id(“hello-World”) #=> “none” ``` ```python case_id(“hello-world”) #=> “kebab” case_id(“hello-to-the-world”) #=> “kebab” case_id(“helloWorld”) #=> “camel” case_id(“helloToTheWorld”) #=> “camel” case_id(“hello_world”) #=> “snake” case_id(“hello_to_the_world”) #=> “snake” case_id(“hello__world”) #=> “none” case_id(“hello_World”) #=> “none” case_id(“helloworld”) #=> “none” case_id(“hello-World”) #=> “none” ``` ```c case_id(“hello-world”) #=> “kebab” case_id(“hello-to-the-world”) #=> “kebab” case_id(“helloWorld”) #=> “camel” case_id(“helloToTheWorld”) #=> “camel” case_id(“hello_world”) #=> “snake” case_id(“hello_to_the_world”) #=> “snake” case_id(“hello__world”) #=> “none” case_id(“hello_World”) #=> “none” case_id(“helloworld”) #=> “none” case_id(“hello-World”) #=> “none” ``` Also check out my other creations — [Split Without Loss](https://www.codewars.com/kata/split-without-loss), [Adding Fractions](https://www.codewars.com/kata/adding-fractions), [Random Integers](https://www.codewars.com/kata/random-integers), [Implement String#transpose](https://www.codewars.com/kata/implement-string-number-transpose), [Implement Array#transpose!](https://www.codewars.com/kata/implement-array-number-transpose), [Arrays and Procs #1](https://www.codewars.com/kata/arrays-and-procs-number-1), and [Arrays and Procs #2](https://www.codewars.com/kata/arrays-and-procs-number-2)
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): return case
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 sweat drips off your nose as you try to read your neighbour's book when you say to yourself, "This is ridiculous. I could have walked faster than this!" Suddenly you have an idea for an app that helps people decide whether to walk or take the bus home when the London Underground is on strike. You rush home (relatively speaking) and begin to define the function that will underpin your app. <h3>Function specification</h3> You must create a function which takes three parameters; walking distance home, distance the bus must travel, and the combined distance of walking from the office to the bus stop and from the bus stop to your house. All distances are in kilometres. So for example, if your home is 5km away by foot, and the bus that takes you home travels 6km, but you have to walk 500 metres to the bus stop to catch it and 500 metres to your house once the bus arrives (i.e. 1km in total), which is faster, walking or taking the bus? Example - Which of these is faster?: <ul> <li>Start---Walk 5km--->End</li> <li>Start---Walk 500m---Bus 6km---Walk 500m--->End</li> </ul> Walking speed and bus driving speed have been given to you as two pre-loaded variables (```$global_variables``` in Ruby). ```walk``` = 5 (km/hr) ```bus``` = 8 (km/hr) The function must return the fastest option, either "Walk" or "Bus". If the walk is going to be over 2 hours, the function should recommend that you take the bus. If the walk is going to be under 10 minutes, the function should recommend that you walk. If both options are going to take the same amount of time, the function should recommend that you walk
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 work done! </br> <strong>Input 2</strong>: Tasks - How many tasks you have to do througout the day</br> <strong>Input 3</strong>: Duration (minutes)- How long each of your tasks will take to complete</br> <strong>Criteria to bear in mind:</strong></br> - Your schedule should start with work and end with work.</br> - It should also be in minutes, rounded to the nearest whole minute.</br> - If your work is going to take more time than you have, return "You're not sleeping tonight!"</br> <strong>Example:</strong> ```javascript dayPlan(8, 5, 30) == [ 30, 83, 30, 83, 30, 83, 30, 83, 30 ] dayPlan(3, 5, 60) == "You're not sleeping tonight!" ``` ```ruby day_plan(8, 5, 30) == [ 30, 83, 30, 83, 30, 83, 30, 83, 30 ] day_plan(3, 5, 60) == "You're not sleeping tonight!" ``` ```crystal day_plan(8, 5, 30) == [ 30, 83, 30, 83, 30, 83, 30, 83, 30 ] day_plan(3, 5, 60) == "You're not sleeping tonight!" ``` ```python day_plan(8, 5, 30) == [ 30, 82, 30, 82, 30, 82, 30, 82, 30 ] day_plan(3, 5, 60) == "You're not sleeping tonight!" ```
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 things to note: 1. There should be one space in between the two characters 2. You don't have to modify the case (i.e. no need to change to upper or lower) 3. If one string is longer than the other, there should be a space where the character would be
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 it doesn't edit the array; that would cause problems! Here's a cheat sheet: ```haskell | HEAD | <----------- TAIL ------------> | [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | <----------- INIT ------------> | LAST | head [x] = x tail [x] = [] init [x] = [] last [x] = x ``` Here's how I expect the functions to be called in your language: ```coffeescript head [1,2,3,4,5] => 1 tail [1,2,3,4,5] => [2,3,4,5] ``` ```javascript head([1,2,3,4,5]); => 1 tail([1,2,3,4,5]); => [2,3,4,5] ``` ```typescript head([1,2,3,4,5]); => 1 tail([1,2,3,4,5]); => [2,3,4,5] ``` ```python head([1,2,3,4,5]) => 1 tail([1,2,3,4,5]) => [2,3,4,5] ``` ```ruby head [1,2,3,4,5] => 1 tail [1,2,3,4,5] => [2,3,4,5] ``` ```clojure (head [1,2,3,4,5]) => 1 (tail [1,2,3,4,5]) => [2,3,4,5] ``` ```haskell head [1,2,3,4,5] => 1 tail [1,2,3,4,5] => [2,3,4,5] ``` ```csharp new List<int> {1, 2, 3, 4, 5}.Head() => 1 new List<int> {1, 2, 3, 4, 5}.Tail() => new List<int> {2, 3, 4, 5} ``` ```ocaml head [1; 2; 3; 4; 5] -> 1 tail [1; 2; 3; 4; 5] -> [2; 3; 4; 5] ``` --- _Most tests consist of 100 randomly generated arrays, each with four tests, one for each operation. There are 400 tests overall. No empty arrays will be given. Haskell has QuickCheck tests_ ```if:clojure __PLEASE NOTE:__ Clojure's `last` function shall be called `last_` to prevent name clashes. ``` ```if:csharp __PLEASE NOTE:__ C#'s `Last` function shall be called `Last_` to prevent name clashes. ```
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` the number of terms that should be `return`ed Useful link: <a href = "http://en.wikipedia.org/wiki/Sequence">Sequence</a> Be sure to check out my <a href = "http://www.codewars.com/kata/540f8a19a7d43d24ac001018">Arithmetic sequence</a> Kata first ;)<br /> Don't forget about the indexing pitfall ;)
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 returns 'Caught!' <-- as there are three characters between the two, the cat can jump.
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 will always be a string consisting of only ascii letters from `a` to `z`. ![](https://i.imgur.com/1I7Uuc5.jpg) To avoid problems with image availability, here's the lists of letters for each hand: * Left: `q, w, e, r, t, a, s, d, f, g, z, x, c, v, b` * Right: `y, u, i, o, p, h, j, k, l, n, m` ## Examples ``` "yams" --> true "test" --> false ```
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 for untyped languages: all inputs are always valid and of their expected type. ## Rules * Your method has to be case sensitive! * If n is 0 or negative or if it is larger than the count of the oldValue, return the original text without a change. ## Example: ``` n: 2 old_value: 'a' new_value: 'o' "Vader said: No, I am your father!" 1 2 3 4 -> 2nd and 4th occurence are replaced "Vader soid: No, I am your fother!" ``` As you can see in the example: The first changed is the 2nd 'a'. So the start is always at the nth suitable char and not at the first!
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` meters. He bears in mind however, that it’s best to have an extra length of wallpaper handy in case of mistakes or miscalculations so he wants to buy a length `15%` greater than the one he needs. Last time he did these calculations he got a headache, so could you help John? #### Task Your function `wallpaper(l, w, h)` should return as a plain English word in lower case the number of rolls he must buy. #### Example: `wallpaper(4.0, 3.5, 3.0) should return "ten"` `wallpaper(0.0, 3.5, 3.0) should return "zero"` #### Notes: - all rolls (even with incomplete width) are put edge to edge - 0 <= l, w, h (floating numbers); it can happens that `w * h * l` is zero - the integer `r` (number of rolls) will always be less or equal to 20 - FORTH: the number of rolls will be a *positive or null integer* (not a plain English word; this number can be greater than 20) - In Coffeescript, Javascript, Python, Ruby and Scala the English numbers are preloaded and can be accessed as: ``` numbers = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve","thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty"] ``` - For other languages it is not preloaded and you can instead copy the above list if you desire.
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: "twenty"} def wallpaper(l, w, h): return "zero" if w * l == 0 else numbers[ceil((2 * l + 2 * w) * h * 1.15 / 5.2)]
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, 1, 0], [8, 7, 2, 3], [1, 4, 1, 9], [2, 3, 8, 2]] diagonal sum: 5 + 7 + 1 + 2 = 15 ```
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 array multiplied by the integer. Example: ```javascript multiplyAll([1, 2, 3])(2) = [2, 4, 6]; ``` ```php multiply_all([1, 2, 3])(2); // => [2, 4, 6] ``` ```python multiply_all([1, 2, 3])(2); // => [2, 4, 6] ``` ```scala CurryingFunctions.multiplyAll(Array(1, 2, 3))(2); // => Array(2, 4, 6) ``` ```ocaml (multiply_all [1; 2; 3]) 2 (* [2; 4; 6] *) ``` You must not mutate the original array. Here's a [nice Youtube video about currying](https://www.youtube.com/watch?v=iZLP4qOwY8I), which might help you if this is new to you.
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 sort_dict({3:1, 2:2, 1:3}) == [(1,3), (2,2), (3,1)] sort_dict({1:2, 2:4, 3:6}) == [(3,6), (2,4), (1,2)] ``` ```javascript sortDict({3:1, 2:2, 1:3}) == [[1,3], [2,2], [3,1]] sortDict({1:2, 2:4, 3:6}) == [[3,6], [2,4], [1,2]] ``` ```haskell sortDict [(3,1), (2,2), (1,3)] `shouldBe` [(1,3), (2,2), (3,1)] sortDict [(1,2), (2,4), (3,6)] `shouldBe` [(3,6), (2,4), (1,2)] ```
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, 80, 93, 80, 25, 93, -1, 28, -1, -1]`. Your task is to create a function "arrayManip()" that takes in an array as its argument, manipulates the array as described above, then return the resulting array. Note: Return a new array, rather than modifying the passed array.
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 to the association so that the average of the first `n + 1` donations should reach an average of `30`. After doing the math he found `149`. He thinks that he could have made a mistake. if `dons = [14, 30, 5, 7, 9, 11, 15]` then `new_avg(dons, 30) --> 149` Could you help him? ## Task The function `new_avg(arr, navg)` should return the expected donation (rounded up to the next integer) that will permit to reach the average `navg`. Should the last donation be a non positive number `(<= 0)` John wants us: - to return: - Nothing in Haskell, Elm - None in F#, Ocaml, Rust, Scala - `-1` in C, D, Fortran, Nim, PowerShell, Go, Pascal, Prolog, Lua, Perl, Erlang - or to throw an error (some **examples** for such a case): - IllegalArgumentException() in Clojure, Java, Kotlin - ArgumentException() in C# - echo `ERROR` in Shell - argument-error in Racket - std::invalid_argument in C++ - ValueError in Python So, he will clearly see that his expectations are not great enough. *In "Sample Tests" you can see what to return.* ### Notes: - all donations and `navg` are numbers (integers or floats), `arr` can be empty. - See examples below and "Sample Tests" to see which return is to be done. ``` new_avg([14, 30, 5, 7, 9, 11, 15], 92) should return 645 new_avg([14, 30, 5, 7, 9, 11, 15], 2) should raise an error (ValueError or invalid_argument or argument-error or DomainError or ... ) or return `-1` or ERROR or Nothing or None depending on the language. ```
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 a number. Thus, ```ruby hamming_weight(10) # 1010 => 2 hamming_weight(21) # 10101 => 3 ``` ```javascript hammingWeight(10) // 1010 => 2 hammingWeight(21) // 10101 => 3 ``` The interesting part of this task is that you have to do it *without* string operation (hey, it's not really interesting otherwise) ;)
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 integers between 0 and 9 (inclusive), and returns the missing element. ### Examples: ``` [0, 5, 1, 3, 2, 9, 7, 6, 4] --> 8 [9, 2, 4, 5, 7, 0, 8, 6, 1] --> 3 ```
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 power_of_4("Four") => false ``` ```haskell isPowerOf4 1024 `shouldBe` True isPowerOf4 102 `shouldBe` False isPowerOf4 64 `shouldBe` True ``` ```python isPowerOf4 1024 #should return True isPowerOf4 102 #should return False isPowerOf4 64 #should return True ``` ```javascript powerOf4(1024) // returns true powerOf4(44) // returns false powerOf4("not a positive integer") // returns false ``` ```clojure (power-of-four? 3) ; returns false (power-of-four? 4) ; returns true ``` ```csharp Power.PowerOf4(1024); // returns true Power.PowerOf4(44); // returns false Power.PowerOf4("not a positive integer"); // returns false ```
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 ```c [1, 2, 3, 4] // returns 3 because 4 - 1 == 3 [1, 2, 3, -4] // returns 7 because 3 - (-4) == 7 ``` Have fun!
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 date: Month -> first name * January -> "The Evil" * February -> "The Vile" * March -> "The Cruel" * April -> "The Trashy" * May -> "The Despicable" * June -> "The Embarrassing" * July -> "The Disreputable" * August -> "The Atrocious" * September -> "The Twirling" * October -> "The Orange" * November -> "The Terrifying" * December -> "The Awkward" Last digit of date -> last name * 0 -> "Mustache" * 1 -> "Pickle" * 2 -> "Hood Ornament" * 3 -> "Raisin" * 4 -> "Recycling Bin" * 5 -> "Potato" * 6 -> "Tomato" * 7 -> "House Cat" * 8 -> "Teaspoon" * 9 -> "Laundry Basket" The returned value should be a string in the form of `"First Name Last Name"`. For example, a birthday of November 18 would return `"The Terrifying Teaspoon"`
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", "Recycling Bin", "Potato", "Tomato", "House Cat", "Teaspoon", "Laundry Basket"] # your code here return first[birthdate . month - 1] + ' ' + last[int(str(birthdate . day)[- 1])]
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 an integer, i.e. the result of exponentiation with number two as the base and integer **n** as the exponent.* You may assume the input is always valid. ## Examples ~~~if-not:nasm ```ruby power_of_two?(1024) # true power_of_two?(4096) # true power_of_two?(333) # false ``` ```python power_of_two(1024) ==> True power_of_two(4096) ==> True power_of_two(333) ==> False ``` ```java PowerOfTwo.isPowerOfTwo(1024) // -> true PowerOfTwo.isPowerOfTwo(4096) // -> true PowerOfTwo.isPowerOfTwo(333) // -> false ``` ```javascript isPowerOfTwo(1024) // -> true isPowerOfTwo(4096) // -> true isPowerOfTwo(333) // -> false ``` ```julia poweroftwo(1024) # true poweroftwo(4096) # true poweroftwo(333) # false ``` ```haskell isPowerOfTwo 1 `shouldBe` True isPowerOfTwo 2 `shouldBe` True isPowerOfTwo 6 `shouldBe` False isPowerOfTwo 8 `shouldBe` True isPowerOfTwo 1024 `shouldBe` True isPowerOfTwo 1026 `shouldBe` False ``` ```purescript powerOfTwo 1 `shouldEqual` true powerOfTwo 2 `shouldEqual` true powerOfTwo 6 `shouldEqual` false powerOfTwo 8 `shouldEqual` true powerOfTwo 1024 `shouldEqual` true powerOfTwo 1026 `shouldEqual` false ``` ```c power_of_two(0); // returns false power_of_two(16); // returns true power_of_two(100); // returns false power_of_two(1024); // returns true power_of_two(20000); // returns false ``` ```rust power_of_two(0); // false power_of_two(1); // true power_of_two(2); // true power_of_two(37); // false power_of_two(64); // true ``` ~~~ ~~~if:nasm ``` mov edi, 0 call power_of_two ; returns false (zero) mov edi, 16 call power_of_two ; returns true (non-zero) mov edi, 100 call power_of_two ; returns false mov edi, 1024 call power_of_two ; returns true mov edi, 20000 call power_of_two ; returns false ``` ~~~ Beware of certain edge cases - for example, `1` is a power of `2` since `2^0 = 1` and `0` is not a power of `2`.
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 of people that you've known since early childhood. However, you recently contracted a sickness that forced you to stay at home for over a week. As you see your body getting weaker and weaker every day and as you see your biceps and triceps disappearing, you can't help but lay in bed and cry. You're usually an optimistic person but this time negative thoughts come to your head ... ![When I miss few days of gym](https://pics.onsizzle.com/Instagram-faf8c9.png) ## Task As can be seen from the funny image above (or am I the only person to find the picture above hilarious?) there is lots of slang. Your task is to define a function ```gymSlang``` which accepts a string argument and does the following: 1. Replace *all* instances of ```"probably"``` to ```"prolly"``` 2. Replace *all* instances of ```"i am"``` to ```"i'm"``` 3. Replace *all* instances of ```"instagram"``` to ```"insta"``` 4. Replace *all* instances of ```"do not"``` to ```"don't"``` 5. Replace *all* instances of ```"going to"``` to ```"gonna"``` 6. Replace *all* instances of ```"combination"``` to ```"combo"``` Your replacement regexes **should be case-sensitive**, only replacing the words above with slang if the detected pattern is in **lowercase**. However, please note that apart from 100% lowercase matches, you will **also have to replace matches that are correctly capitalized** (e.g. ```"Probably" => "Prolly"``` or ```"Instagram" => "Insta"```). Finally, your code will be tested to make sure that you have used **RegExp** replace in your code. Enjoy :D
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'\1onna', phrase) phrase = re . sub(r'([cC])ombination', r'\1ombo', phrase) return phrase
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, 5, ... and so on] )<br /> Else if (pun) ``f(n) = f(n-1) * c`` where ``c`` is a constant value, then ``f`` is a geometric sequence.<br /> Example where the first term is 2 and the constant is 2 will be [2, 4, 8, 16, 32, 64, ... to infinity ... ]<br /> There are some sequences that aren't arithmetic nor are they geometric.<br /> Here is a link to feed your brain : <a href=http://en.wikipedia.org/wiki/Sequence>Sequence</a> ! You're going to write a function that's going to return the value in the nth index of an arithmetic sequence.(That is, adding a constant to move to the next element in the "set"). The function's name is `nthterm`/`Nthterm`, it takes three inputs `first`,`n`,`c` where: - ``first`` is the first value in the 0 INDEX.<br /> - ``n`` is the index of the value we want.<br /> - ``c`` is the constant added between the terms. Remember that `first` is in the index ``0`` .. just saying ...
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'] ``` ```javascript multipleSplit('Hi, how are you?', [' ']) => ['Hi,', 'how', 'are', 'you?'] multipleSplit('1+2-3', ['+', '-']) => ['1', '2', '3'] ``` List of delimiters is optional and can be empty, so take that into account. Important note: Result cannot contain empty string.
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 return all the numbers in that string in the order they occur.
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 characters, the function should return null (throw an `ArgumentException` in C#). ```javascript calculate(2,"+", 4); //Should return 6 calculate(6,"-", 1.5); //Should return 4.5 calculate(-4,"*", 8); //Should return -32 calculate(49,"/", -7); //Should return -7 calculate(8,"m", 2); //Should return null calculate(4,"/",0) //should return null ``` Keep in mind, you cannot divide by zero. If an attempt to divide by zero is made, return null (throw an `ArgumentException` in C#)/(None in Python).
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 cut a fruit into equal parts, then the first part will has a extra character. You should only cut the fruit, other things **should not be cut**, such as the `"bomb"`: ``` [ "apple", "pear", "banana", "bomb"] --> ["app", "le", "pe", "ar", "ban", "ana", "bomb"] ``` The valid fruit names are preloded for you as: ```javascript fruitsName ``` ```ruby $fruits_name ``` ```python FRUIT_NAMES ``` ```haskell fruits ``` ## Task ```if:javascript Complete function `cutFruits` that accepts argument `fruits`. Returns the result in accordance with the rules above. ``` ```if:ruby,python Complete function `cut_fruits` that accepts argument `fruits`. Returns the result in accordance with the rules above. ``` ```if:haskell Complete function cutFruits that accepts a String array/list. Returns the result in accordance with the rules above. ``` OK, that's all. I guess this is a 7kyu kata. If you agree, please rank it as 7kyu and vote `very`;-) If you think this kata is too easy or too hard, please shame me by rank it as you want and vote `somewhat` or `none` :[ --- ##### *[Click here](https://www.codewars.com/kata/search/?q=i+guess+this+is+a+kyu+kata) for more more "I guess this is ...kyu" katas!*
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.codewars.com/kata/56d931ecc443d475d5000003">03:True or False</a><br> <a href="http://www.codewars.com/kata/56d93f249c844788bc000002">04:Something capitalized</a><br> <a href="http://www.codewars.com/kata/56d949281b5fdc7666000004">05:Uniq or not Uniq</a> <br> <a href="http://www.codewars.com/kata/56d98b555492513acf00077d">06:Spatiotemporal index</a><br> <a href="http://www.codewars.com/kata/56d9b46113f38864b8000c5a">07:Math of Primary School</a><br> <a href="http://www.codewars.com/kata/56d9c274c550b4a5c2000d92">08:Math of Middle school</a><br> <a href="http://www.codewars.com/kata/56d9cfd3f3928b4edd000021">09:From nothingness To nothingness</a><br> <a href="http://www.codewars.com/kata/56dae2913cb6f5d428000f77">10:Not perfect? Throw away!</a> <br> <a href="http://www.codewars.com/kata/56db19703cb6f5ec3e001393">11:Welcome to take the bus</a><br> <a href="http://www.codewars.com/kata/56dc41173e5dd65179001167">12:A happy day will come</a><br> <a href="http://www.codewars.com/kata/56dc5a773e5dd6dcf7001356">13:Sum of 15(Hetu Luosliu)</a><br> <a href="http://www.codewars.com/kata/56dd3dd94c9055a413000b22">14:Nebula or Vortex</a><br> <a href="http://www.codewars.com/kata/56dd927e4c9055f8470013a5">15:Sport Star</a><br> <a href="http://www.codewars.com/kata/56de38c1c54a9248dd0006e4">16:Falsetto Rap Concert</a><br> <a href="http://www.codewars.com/kata/56de4d58301c1156170008ff">17:Wind whispers</a><br> <a href="http://www.codewars.com/kata/56de82fb9905a1c3e6000b52">18:Mobile phone simulator</a><br> <a href="http://www.codewars.com/kata/56dfce76b832927775000027">19:Join but not join</a><br> <a href="http://www.codewars.com/kata/56dfd5dfd28ffd52c6000bb7">20:I hate big and small</a><br> <a href="http://www.codewars.com/kata/56e0e065ef93568edb000731">21:I want to become diabetic ;-)</a><br> <a href="http://www.codewars.com/kata/56e0f1dc09eb083b07000028">22:How many blocks?</a><br> <a href="http://www.codewars.com/kata/56e1161fef93568228000aad">23:Operator hidden in a string</a><br> <a href="http://www.codewars.com/kata/56e127d4ef93568228000be2">24:Substring Magic</a><br> <a href="http://www.codewars.com/kata/56eccc08b9d9274c300019b9">25:Report about something</a><br> <a href="http://www.codewars.com/kata/56ee0448588cbb60740013b9">26:Retention and discard I</a><br> <a href="http://www.codewars.com/kata/56eee006ff32e1b5b0000c32">27:Retention and discard II</a><br> <a href="http://www.codewars.com/kata/56eff1e64794404a720002d2">28:How many "word"?</a><br> <a href="http://www.codewars.com/kata/56f167455b913928a8000c49">29:Hail and Waterfall</a><br> <a href="http://www.codewars.com/kata/56f214580cd8bc66a5001a0f">30:Love Forever</a><br> <a href="http://www.codewars.com/kata/56f25b17e40b7014170002bd">31:Digital swimming pool</a><br> <a href="http://www.codewars.com/kata/56f4202199b3861b880013e0">32:Archery contest</a><br> <a href="http://www.codewars.com/kata/56f606236b88de2103000267">33:The repair of parchment</a><br> <a href="http://www.codewars.com/kata/56f6b4369400f51c8e000d64">34:Who are you?</a><br> <a href="http://www.codewars.com/kata/56f7eb14f749ba513b0009c3">35:Safe position</a><br> <br> # #Special recommendation Another series, innovative and interesting, medium difficulty. People who like to challenge, can try these kata: <a href="http://www.codewars.com/kata/56c85eebfd8fc02551000281">Play Tetris : Shape anastomosis</a><br> <a href="http://www.codewars.com/kata/56cd5d09aa4ac772e3000323">Play FlappyBird : Advance Bravely</a><br>
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.codewars.com/kata/56d931ecc443d475d5000003">03:True or False</a><br> <a href="http://www.codewars.com/kata/56d93f249c844788bc000002">04:Something capitalized</a><br> <a href="http://www.codewars.com/kata/56d949281b5fdc7666000004">05:Uniq or not Uniq</a> <br> <a href="http://www.codewars.com/kata/56d98b555492513acf00077d">06:Spatiotemporal index</a><br> <a href="http://www.codewars.com/kata/56d9b46113f38864b8000c5a">07:Math of Primary School</a><br> <a href="http://www.codewars.com/kata/56d9c274c550b4a5c2000d92">08:Math of Middle school</a><br> <a href="http://www.codewars.com/kata/56d9cfd3f3928b4edd000021">09:From nothingness To nothingness</a><br> <a href="http://www.codewars.com/kata/56dae2913cb6f5d428000f77">10:Not perfect? Throw away!</a> <br> <a href="http://www.codewars.com/kata/56db19703cb6f5ec3e001393">11:Welcome to take the bus</a><br> <a href="http://www.codewars.com/kata/56dc41173e5dd65179001167">12:A happy day will come</a><br> <a href="http://www.codewars.com/kata/56dc5a773e5dd6dcf7001356">13:Sum of 15(Hetu Luosliu)</a><br> <a href="http://www.codewars.com/kata/56dd3dd94c9055a413000b22">14:Nebula or Vortex</a><br> <a href="http://www.codewars.com/kata/56dd927e4c9055f8470013a5">15:Sport Star</a><br> <a href="http://www.codewars.com/kata/56de38c1c54a9248dd0006e4">16:Falsetto Rap Concert</a><br> <a href="http://www.codewars.com/kata/56de4d58301c1156170008ff">17:Wind whispers</a><br> <a href="http://www.codewars.com/kata/56de82fb9905a1c3e6000b52">18:Mobile phone simulator</a><br> <a href="http://www.codewars.com/kata/56dfce76b832927775000027">19:Join but not join</a><br> <a href="http://www.codewars.com/kata/56dfd5dfd28ffd52c6000bb7">20:I hate big and small</a><br> <a href="http://www.codewars.com/kata/56e0e065ef93568edb000731">21:I want to become diabetic ;-)</a><br> <a href="http://www.codewars.com/kata/56e0f1dc09eb083b07000028">22:How many blocks?</a><br> <a href="http://www.codewars.com/kata/56e1161fef93568228000aad">23:Operator hidden in a string</a><br> <a href="http://www.codewars.com/kata/56e127d4ef93568228000be2">24:Substring Magic</a><br> <a href="http://www.codewars.com/kata/56eccc08b9d9274c300019b9">25:Report about something</a><br> <a href="http://www.codewars.com/kata/56ee0448588cbb60740013b9">26:Retention and discard I</a><br> <a href="http://www.codewars.com/kata/56eee006ff32e1b5b0000c32">27:Retention and discard II</a><br> <a href="http://www.codewars.com/kata/56eff1e64794404a720002d2">28:How many "word"?</a><br> <a href="http://www.codewars.com/kata/56f167455b913928a8000c49">29:Hail and Waterfall</a><br> <a href="http://www.codewars.com/kata/56f214580cd8bc66a5001a0f">30:Love Forever</a><br> <a href="http://www.codewars.com/kata/56f25b17e40b7014170002bd">31:Digital swimming pool</a><br> <a href="http://www.codewars.com/kata/56f4202199b3861b880013e0">32:Archery contest</a><br> <a href="http://www.codewars.com/kata/56f606236b88de2103000267">33:The repair of parchment</a><br> <a href="http://www.codewars.com/kata/56f6b4369400f51c8e000d64">34:Who are you?</a><br> <a href="http://www.codewars.com/kata/56f7eb14f749ba513b0009c3">35:Safe position</a><br> <br> # #Special recommendation Another series, innovative and interesting, medium difficulty. People who like to challenge, can try these kata: <a href="http://www.codewars.com/kata/56c85eebfd8fc02551000281">Play Tetris : Shape anastomosis</a><br> <a href="http://www.codewars.com/kata/56cd5d09aa4ac772e3000323">Play FlappyBird : Advance Bravely</a><br>
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.com/kata/56d931ecc443d475d5000003">03:True or False</a><br> <a href="http://www.codewars.com/kata/56d93f249c844788bc000002">04:Something capitalized</a><br> <a href="http://www.codewars.com/kata/56d949281b5fdc7666000004">05:Uniq or not Uniq</a> <br> <a href="http://www.codewars.com/kata/56d98b555492513acf00077d">06:Spatiotemporal index</a><br> <a href="http://www.codewars.com/kata/56d9b46113f38864b8000c5a">07:Math of Primary School</a><br> <a href="http://www.codewars.com/kata/56d9c274c550b4a5c2000d92">08:Math of Middle school</a><br> <a href="http://www.codewars.com/kata/56d9cfd3f3928b4edd000021">09:From nothingness To nothingness</a><br> <a href="http://www.codewars.com/kata/56dae2913cb6f5d428000f77">10:Not perfect? Throw away!</a> <br> <a href="http://www.codewars.com/kata/56db19703cb6f5ec3e001393">11:Welcome to take the bus</a><br> <a href="http://www.codewars.com/kata/56dc41173e5dd65179001167">12:A happy day will come</a><br> <a href="http://www.codewars.com/kata/56dc5a773e5dd6dcf7001356">13:Sum of 15(Hetu Luosliu)</a><br> <a href="http://www.codewars.com/kata/56dd3dd94c9055a413000b22">14:Nebula or Vortex</a><br> <a href="http://www.codewars.com/kata/56dd927e4c9055f8470013a5">15:Sport Star</a><br> <a href="http://www.codewars.com/kata/56de38c1c54a9248dd0006e4">16:Falsetto Rap Concert</a><br> <a href="http://www.codewars.com/kata/56de4d58301c1156170008ff">17:Wind whispers</a><br> <a href="http://www.codewars.com/kata/56de82fb9905a1c3e6000b52">18:Mobile phone simulator</a><br> <a href="http://www.codewars.com/kata/56dfce76b832927775000027">19:Join but not join</a><br> <a href="http://www.codewars.com/kata/56dfd5dfd28ffd52c6000bb7">20:I hate big and small</a><br> <a href="http://www.codewars.com/kata/56e0e065ef93568edb000731">21:I want to become diabetic ;-)</a><br> <a href="http://www.codewars.com/kata/56e0f1dc09eb083b07000028">22:How many blocks?</a><br> <a href="http://www.codewars.com/kata/56e1161fef93568228000aad">23:Operator hidden in a string</a><br> <a href="http://www.codewars.com/kata/56e127d4ef93568228000be2">24:Substring Magic</a><br> <a href="http://www.codewars.com/kata/56eccc08b9d9274c300019b9">25:Report about something</a><br> <a href="http://www.codewars.com/kata/56ee0448588cbb60740013b9">26:Retention and discard I</a><br> <a href="http://www.codewars.com/kata/56eee006ff32e1b5b0000c32">27:Retention and discard II</a><br> <a href="http://www.codewars.com/kata/56eff1e64794404a720002d2">28:How many "word"?</a><br> <a href="http://www.codewars.com/kata/56f167455b913928a8000c49">29:Hail and Waterfall</a><br> <a href="http://www.codewars.com/kata/56f214580cd8bc66a5001a0f">30:Love Forever</a><br> <a href="http://www.codewars.com/kata/56f25b17e40b7014170002bd">31:Digital swimming pool</a><br> <a href="http://www.codewars.com/kata/56f4202199b3861b880013e0">32:Archery contest</a><br> <a href="http://www.codewars.com/kata/56f606236b88de2103000267">33:The repair of parchment</a><br> <a href="http://www.codewars.com/kata/56f6b4369400f51c8e000d64">34:Who are you?</a><br> <a href="http://www.codewars.com/kata/56f7eb14f749ba513b0009c3">35:Safe position</a><br> # Special recommendation Another series, innovative and interesting, medium difficulty. People who like to challenge, can try these kata: <a href="http://www.codewars.com/kata/56c85eebfd8fc02551000281">Play Tetris : Shape anastomosis</a><br> <a href="http://www.codewars.com/kata/56cd5d09aa4ac772e3000323">Play FlappyBird : Advance Bravely</a><br>
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/kata/56d931ecc443d475d5000003">03:True or False</a> * <a href="http://www.codewars.com/kata/56d93f249c844788bc000002">04:Something capitalized</a> * <a href="http://www.codewars.com/kata/56d949281b5fdc7666000004">05:Uniq or not Uniq</a> * <a href="http://www.codewars.com/kata/56d98b555492513acf00077d">06:Spatiotemporal index</a> * <a href="http://www.codewars.com/kata/56d9b46113f38864b8000c5a">07:Math of Primary School</a> * <a href="http://www.codewars.com/kata/56d9c274c550b4a5c2000d92">08:Math of Middle school</a> * <a href="http://www.codewars.com/kata/56d9cfd3f3928b4edd000021">09:From nothingness To nothingness</a> * <a href="http://www.codewars.com/kata/56dae2913cb6f5d428000f77">10:Not perfect? Throw away!</a> * <a href="http://www.codewars.com/kata/56db19703cb6f5ec3e001393">11:Welcome to take the bus</a> * <a href="http://www.codewars.com/kata/56dc41173e5dd65179001167">12:A happy day will come</a> * <a href="http://www.codewars.com/kata/56dc5a773e5dd6dcf7001356">13:Sum of 15(Hetu Luosliu)</a> * <a href="http://www.codewars.com/kata/56dd3dd94c9055a413000b22">14:Nebula or Vortex</a> * <a href="http://www.codewars.com/kata/56dd927e4c9055f8470013a5">15:Sport Star</a> * <a href="http://www.codewars.com/kata/56de38c1c54a9248dd0006e4">16:Falsetto Rap Concert</a> * <a href="http://www.codewars.com/kata/56de4d58301c1156170008ff">17:Wind whispers</a> * <a href="http://www.codewars.com/kata/56de82fb9905a1c3e6000b52">18:Mobile phone simulator</a> * <a href="http://www.codewars.com/kata/56dfce76b832927775000027">19:Join but not join</a> * <a href="http://www.codewars.com/kata/56dfd5dfd28ffd52c6000bb7">20:I hate big and small</a> * <a href="http://www.codewars.com/kata/56e0e065ef93568edb000731">21:I want to become diabetic ;-)</a> * <a href="http://www.codewars.com/kata/56e0f1dc09eb083b07000028">22:How many blocks?</a> * <a href="http://www.codewars.com/kata/56e1161fef93568228000aad">23:Operator hidden in a string</a> * <a href="http://www.codewars.com/kata/56e127d4ef93568228000be2">24:Substring Magic</a> * <a href="http://www.codewars.com/kata/56eccc08b9d9274c300019b9">25:Report about something</a> * <a href="http://www.codewars.com/kata/56ee0448588cbb60740013b9">26:Retention and discard I</a> * <a href="http://www.codewars.com/kata/56eee006ff32e1b5b0000c32">27:Retention and discard II</a> * <a href="http://www.codewars.com/kata/56eff1e64794404a720002d2">28:How many "word"?</a> * <a href="http://www.codewars.com/kata/56f167455b913928a8000c49">29:Hail and Waterfall</a> * <a href="http://www.codewars.com/kata/56f214580cd8bc66a5001a0f">30:Love Forever</a> * <a href="http://www.codewars.com/kata/56f25b17e40b7014170002bd">31:Digital swimming pool</a> * <a href="http://www.codewars.com/kata/56f4202199b3861b880013e0">32:Archery contest</a> * <a href="http://www.codewars.com/kata/56f606236b88de2103000267">33:The repair of parchment</a> * <a href="http://www.codewars.com/kata/56f6b4369400f51c8e000d64">34:Who are you?</a> * <a href="http://www.codewars.com/kata/56f7eb14f749ba513b0009c3">35:Safe position</a> ## Special recommendation Another series, innovative and interesting, medium difficulty. People who like to challenge, can try these kata: * <a href="http://www.codewars.com/kata/56c85eebfd8fc02551000281">Play Tetris : Shape anastomosis * <a href="http://www.codewars.com/kata/56cd5d09aa4ac772e3000323">Play FlappyBird : Advance Bravely
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.com/kata/56d931ecc443d475d5000003) 04. [Something capitalized](http://www.codewars.com/kata/56d93f249c844788bc000002) 05. [Uniq or not Uniq](http://www.codewars.com/kata/56d949281b5fdc7666000004) 06. [Spatiotemporal index](http://www.codewars.com/kata/56d98b555492513acf00077d) 07. [Math of Primary School](http://www.codewars.com/kata/56d9b46113f38864b8000c5a) 08. [Math of Middle school](http://www.codewars.com/kata/56d9c274c550b4a5c2000d92) 09. [From nothingness To nothingness](http://www.codewars.com/kata/56d9cfd3f3928b4edd000021) 10. [Not perfect? Throw away!](http://www.codewars.com/kata/56dae2913cb6f5d428000f77) 11. [Welcome to take the bus](http://www.codewars.com/kata/56db19703cb6f5ec3e001393) 12. [A happy day will come](http://www.codewars.com/kata/56dc41173e5dd65179001167) 13. [Sum of 15(Hetu Luosliu)](http://www.codewars.com/kata/56dc5a773e5dd6dcf7001356) 14. [Nebula or Vortex](http://www.codewars.com/kata/56dd3dd94c9055a413000b22) 15. [Sport Star](http://www.codewars.com/kata/56dd927e4c9055f8470013a5) 16. [Falsetto Rap Concert](http://www.codewars.com/kata/56de38c1c54a9248dd0006e4) 17. [Wind whispers](http://www.codewars.com/kata/56de4d58301c1156170008ff) 18. [Mobile phone simulator](http://www.codewars.com/kata/56de82fb9905a1c3e6000b52) 19. [Join but not join](http://www.codewars.com/kata/56dfce76b832927775000027) 20. [I hate big and small](http://www.codewars.com/kata/56dfd5dfd28ffd52c6000bb7) 21. [I want to become diabetic ;-)](http://www.codewars.com/kata/56e0e065ef93568edb000731) 22. [How many blocks?](http://www.codewars.com/kata/56e0f1dc09eb083b07000028) 23. [Operator hidden in a string](http://www.codewars.com/kata/56e1161fef93568228000aad) 24. [Substring Magic](http://www.codewars.com/kata/56e127d4ef93568228000be2) 25. [Report about something](http://www.codewars.com/kata/56eccc08b9d9274c300019b9) 26. [Retention and discard I](http://www.codewars.com/kata/56ee0448588cbb60740013b9) 27. [Retention and discard II](http://www.codewars.com/kata/56eee006ff32e1b5b0000c32) 28. [How many "word"?](http://www.codewars.com/kata/56eff1e64794404a720002d2) 29. [Hail and Waterfall](http://www.codewars.com/kata/56f167455b913928a8000c49) 30. [Love Forever](http://www.codewars.com/kata/56f214580cd8bc66a5001a0f) 31. [Digital swimming pool](http://www.codewars.com/kata/56f25b17e40b7014170002bd) 32. [Archery contest](http://www.codewars.com/kata/56f4202199b3861b880013e0) 33. [The repair of parchment](http://www.codewars.com/kata/56f606236b88de2103000267) 34. [Who are you?](http://www.codewars.com/kata/56f6b4369400f51c8e000d64) 35. [Safe position](http://www.codewars.com/kata/56f7eb14f749ba513b0009c3) --- ## Special recommendation Another series, innovative and interesting, medium difficulty. People who like challenges, can try these kata: * [Play Tetris : Shape anastomosis](http://www.codewars.com/kata/56c85eebfd8fc02551000281) * [Play FlappyBird : Advance Bravely](http://www.codewars.com/kata/56cd5d09aa4ac772e3000323)
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 he came to the top of a building. Scientific research shows that a man jumped from the top of the roof, when the floor more than 6, the person will often die in an instant; When the floor is less than or equal to 6, the person will not immediately die, he would scream. (without proof) Input: ```floor```, The height of the building (floor) Output: a string, The voice of despair(When jumping Dutch act) ## Example: sc(2) should return ```"Aa~ Pa! Aa!"``` It means: ``` Mr. despair jumped from the 2 floor, the voice is "Aa~" He fell on the ground, the voice is "Pa!" He did not die immediately, and the final voice was "Aa!" ``` sc(6) should return ```"Aa~ Aa~ Aa~ Aa~ Aa~ Pa! Aa!"``` sc(7) should return ```"Aa~ Aa~ Aa~ Aa~ Aa~ Aa~ Pa!"``` sc(10) should return ```"Aa~ Aa~ Aa~ Aa~ Aa~ Aa~ Aa~ Aa~ Aa~ Pa!"``` if ```floor```<=1, Mr. despair is safe, return ```""``` ## Code length calculation In javascript, we can't get the user's real code, we can only get the system compiled code. Code length calculation is based the compiled code. For example: If you typed ```sc=x=>x+1``` after compile, it will be:```sc=function(x){return x+1;}``` ## The final advice Just play in this kata, Don't experiment in real life ;-) ## Series - [Bug in Apple](http://www.codewars.com/kata/56f8a648ba792a778a0000b9) - [Father and Son](http://www.codewars.com/kata/56f928b19982cc7a14000c9d) - [Jumping Dutch act](http://www.codewars.com/kata/570bbf7b6731d44b36001fde) - [Planting Trees](http://www.codewars.com/kata/570f45fab29c705d330004e3) - [Reading a Book](http://www.codewars.com/kata/570c560c15944a98e9000fd2) - [Eat watermelon](http://www.codewars.com/kata/570db6dade4dc8966600051c) - [Special factor](http://www.codewars.com/kata/570dff30e6e9284ba3000a8f) - [Symmetric Sort](http://www.codewars.com/kata/57049a1946edc26dbc00074a) - [Are they symmetrical?](http://www.codewars.com/kata/5705b59f5eef1f04f1000f84) - [Guess the Hat](http://www.codewars.com/kata/570e6d8576f0cde131000129) - [Find the murderer](http://www.codewars.com/kata/570e8d5693214b0095001b08) - [Give me the equation](http://www.codewars.com/kata/56fa24b10ba33be7d4000315) - [Balance Attraction](http://www.codewars.com/kata/5700c79dc155575b31000265) - [Max Value](http://www.codewars.com/kata/57075f6d4f2c293f0c0014be) - [Regular expression compression](http://www.codewars.com/kata/5707c6e74f2c29a750001f8b) - [Remove screws I](http://www.codewars.com/kata/57109bf197b4b3853a000274) - [Remove screws II](http://www.codewars.com/kata/57104927d860a31eab000b5d) - [Collatz Array(Split or merge)](http://www.codewars.com/kata/56fc7a29fca8b900eb001fac) - [Trypophobia](http://www.codewars.com/kata/56fe107569510b1b1b0002a5) - [Virus in Apple](http://www.codewars.com/kata/56ffd817140fcc0c3900099b) - [Waiting for a Bus](http://www.codewars.com/kata/5705da6ccb7293991300055f) - [Tidy up the room](http://www.codewars.com/kata/57035af2d80ec6cdb40008ed)
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 ```length```, two integers > 1 that represents the land's width and length; ```gaps```, an integer >= 0, that is the distance between two trees. Return how many trees have to be planted, if you can't achieve a symmetrical layout(see Example 3) then return 0. ### Example: ``` Example1: width=3, length=3, gaps=1 o - o we can plant 4 trees - - sc(3,3,1)=4 o - o Example2: width=3, length=3, gaps=3 o - - we can plant 2 trees - - sc(3,3,3)=2 - - o Example3: width=3, length=3, gaps=2 o - - if we plant 2 trees, some x o gaps of two trees will >2 x x x if we plant 3 trees, some o - - gaps of two trees will <2 x o so we can not finish it o - - sc(3,3,2)=0 Example4: width=7, length=7, gaps=3 o - - - o - - we can plant 6 trees - - sc(3,3,3)=6 - o - - o - - - - - o - - - o some corner case: Example5: width=3, length=3, gaps=0 o o o we can plant 8 trees o o sc(3,3,0)=8 o o o Example6: width=3, length=3, gaps=10 o 1 2 in this case, the max gaps 1 3 of two trees is 3 2 3 o gaps=10 can not finished so sc(3,3,10)=0 ``` ### Series: - [Bug in Apple](http://www.codewars.com/kata/56fe97b3cc08ca00e4000dc9) - [Father and Son](http://www.codewars.com/kata/56fe9a0c11086cd842000008) - [Jumping Dutch act](http://www.codewars.com/kata/570bcd9715944a2c8e000009) - [Planting Trees](http://www.codewars.com/kata/5710443187a36a9cee0005a1) - [Give me the equation](http://www.codewars.com/kata/56fe9b65cc08cafbc5000de3) - [Find the murderer](http://www.codewars.com/kata/570f3fc5b29c702c5500043e) - [Reading a Book](http://www.codewars.com/kata/570ca6a520c69f39dd0016d4) - [Eat watermelon](http://www.codewars.com/kata/570df12ce6e9282a7d000947) - [Special factor](http://www.codewars.com/kata/570e5d0b93214b1a950015b1) - [Guess the Hat](http://www.codewars.com/kata/570ef7a834e61306da00035b) - [Symmetric Sort](http://www.codewars.com/kata/5705aeb041e5befba20010ba) - [Are they symmetrical?](http://www.codewars.com/kata/5705cc3161944b10fd0004ba) - [Max Value](http://www.codewars.com/kata/570771871df89cf59b000742) - [Trypophobia](http://www.codewars.com/kata/56fe9ffbc25bf33fff000f7c) - [Virus in Apple](http://www.codewars.com/kata/5700af83d1acef83fd000048) - [Balance Attraction](http://www.codewars.com/kata/57033601e55d30d3e0000633) - [Remove screws I](http://www.codewars.com/kata/5710a50d336aed828100055a) - [Remove screws II](http://www.codewars.com/kata/5710a8fd336aed00d9000594) - [Regular expression compression](http://www.codewars.com/kata/570bae4b0237999e940016e9) - [Collatz Array(Split or merge)](http://www.codewars.com/kata/56fe9d579b7bb6b027000001) - [Tidy up the room](http://www.codewars.com/kata/5703ace6e55d30d3e0001029) - [Waiting for a Bus](http://www.codewars.com/kata/57070eff924f343280000015)
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", if not the letter, don't change it. ### How to convert? : ``` "love!".toLoverCase()="EVOL!" ``` ```javascript "l" is 11th(start with 0) in lower case letters abcdefghijklmnopqrstuvwxyz | 0... 11----------------->11th letter We use this number mod 4------> 11 % 4 = 3 the 3rd(also start with 0) letter of "LOVE" is "E" LOVE | 3--------->3rd letter so convert "l" to "E". and so on.. "o" convert to "V", "v" convert to "O", "e" convert to "L" last "!" remain unchanged, because it's not a letter. ``` more example see the testcases. ### Series: - [Bug in Apple](http://www.codewars.com/kata/56fe97b3cc08ca00e4000dc9) - [Father and Son](http://www.codewars.com/kata/56fe9a0c11086cd842000008) - [Jumping Dutch act](http://www.codewars.com/kata/570bcd9715944a2c8e000009) - [Planting Trees](http://www.codewars.com/kata/5710443187a36a9cee0005a1) - [Give me the equation](http://www.codewars.com/kata/56fe9b65cc08cafbc5000de3) - [Find the murderer](http://www.codewars.com/kata/570f3fc5b29c702c5500043e) - [Reading a Book](http://www.codewars.com/kata/570ca6a520c69f39dd0016d4) - [Eat watermelon](http://www.codewars.com/kata/570df12ce6e9282a7d000947) - [Special factor](http://www.codewars.com/kata/570e5d0b93214b1a950015b1) - [Guess the Hat](http://www.codewars.com/kata/570ef7a834e61306da00035b) - [Symmetric Sort](http://www.codewars.com/kata/5705aeb041e5befba20010ba) - [Are they symmetrical?](http://www.codewars.com/kata/5705cc3161944b10fd0004ba) - [Max Value](http://www.codewars.com/kata/570771871df89cf59b000742) - [Trypophobia](http://www.codewars.com/kata/56fe9ffbc25bf33fff000f7c) - [Virus in Apple](http://www.codewars.com/kata/5700af83d1acef83fd000048) - [Balance Attraction](http://www.codewars.com/kata/57033601e55d30d3e0000633) - [Remove screws I](http://www.codewars.com/kata/5710a50d336aed828100055a) - [Remove screws II](http://www.codewars.com/kata/5710a8fd336aed00d9000594) - [Regular expression compression](http://www.codewars.com/kata/570bae4b0237999e940016e9) - [Collatz Array(Split or merge)](http://www.codewars.com/kata/56fe9d579b7bb6b027000001) - [Tidy up the room](http://www.codewars.com/kata/5703ace6e55d30d3e0001029) - [Waiting for a Bus](http://www.codewars.com/kata/57070eff924f343280000015)
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 charge) (battery capacity(mAh) * 10%) / (power of the charger(mA) * 50%) 95% --> 100% (trickle charge) (battery capacity(mAh) * 5%) / (power of the charger(mA) * 20%) ``` For example: Your battery capacity is 1000 mAh and you use a charger 500 mA, to charge your mobile phone battery from 0% to 100% needs time: ``` 0% --> 85% (fast charge) 1.7 (hour) 85% --> 95% (decreasing charge) 0.4 (hour) 95% --> 100% (trickle charge) 0.5 (hour) total times = 1.7 + 0.4 + 0.5 = 2.6 (hour) ``` Complete function `calculateTime` that accepts two arguments `battery` and `charger`, return how many hours can charge the battery from 0% to 100%. The result should be a number, round to 2 decimal places (In Haskell, no need to round it).
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!") === "" remove("Hi! Hi!! Hi!") === "Hi!!" remove("Hi! !Hi! Hi!") === "!Hi!" ```
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 `"Caught!"` or `"Escaped!"` respectively. Finally, if one of two animals are not present, return `"boring without two animals"`. ## Examples ``` moves = 5 map = ..C...... ......... ....m.... returns "Caught!" because the cat can catch the mouse in 4 moves ``` ``` moves = 5 map = .C....... ......... ......m.. returns "Escaped!" because the cat cannot catch the mouse in 5 moves ```
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]) + abs(cat[1] - mouse[1]) return 'Caught!' if distance <= moves else 'Escaped!'
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 at a price of $60, he made a profit of 20%; Second commodities are sold at a price of $60 too, but he lost 20%. Please calculate, whether his account is profit or loss in the end? ## Rules Write a function ```profitLoss```, argument ```records``` is the list of sales. return a number(positive or negative), round to two decimal places. ## Examples ```javascript In the example above: profitLoss([[60,20],[60,-20]]) should return -5 Because the cost of the first commodity is 50, the cost of the second commodity is 75, the total cost is: 50+75=125 Selling price is: 60+60=120 So the end result is 120-125=-5. He made a loss of $5. profitLoss([[100,20],[80,-20]]) should return -3.33 profitLoss([[60,100],[60,-50]]) should return -30 profitLoss([[60,0],[60,0]]) should return 0 ```
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 JavaScript is by default sorting objects alphabetically. For more information, please consult: http://stackoverflow.com/questions/6093874/why-doesnt-the-sort-function-of-javascript-work-well ```
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 for Shell, I'm aware it may be easier in other languages.**
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 the same format like this: <b> MDZHB 01 213 SKIF 38 87 23 95 </b> or: <b> MDZHB 80 516 GANOMATIT 21 23 86 25 </b> Message format consists of following parts: <ul> <li> Initial keyword "MDZHB"; </li> <li> Two groups of digits, 2 digits in first and 3 in second ones; </li> <li> Some keyword of arbitrary length consisting only of uppercase letters; </li> <li> Final 4 groups of digits with 2 digits in each group. </li> </ul> Your task is to write a function that can validate the correct UVB-76 message. Function should return "True" if message is in correct format and "False" otherwise.
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 letter in the word). It should also remove all punctuation (.,?!) as well as any underscores (_). "How did we end up here? We go?" translated becomes-> "Howw didd we endd up here We go"
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 string literal `"black"` or `"white"` ~~~
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 12 12 15 16 20" ``` They should output: ``` "15 60 75" "9 9 12 15" ``` Every input will always have all the prices in pairs (initial and discounted) sorted from smaller to bigger. You might have noticed that the second sample input can be tricky already; also, try to have an eye for performances, as huge inputs could be tested too. ***Final Note:*** kata blatantly taken from [this problem](https://code.google.com/codejam/contest/8274486/dashboard) (and still not getting why they created a separated Code Jam for ladies, as I find it rather discriminating...).
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 at $75 sale price after applying a 25% discount, the function should return the original price of that item before applying the sale percentage, which is ($100.00) of course, rounded to two decimal places. DiscoverOriginalPrice(75, 25) => 100.00M where 75 is the sale price (discounted price), 25 is the sale percentage and 100 is the original price
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 generate the HTML for you. To organize your code, make of all your functions methods of a class called HTMLGen. Tag functions should be named after the tag of the element they create. Each function will take one argument, a string, which is the inner HTML of the element to be created. The functions will return the string for the appropriate HTML element. For example, JavaScript: ```javascript var g = new HTMLGen(); var paragraph = g.p('Hello, World!'); var block = g.div(paragraph); // The following are now true paragraph === '<p>Hello, World!</p>' block === '<div><p>Hello, World!</p></div>' ``` Python: ```python g = HTMLGen(); paragraph = g.p('Hello, World!') block = g.div(paragraph) # The following are now true paragraph == '<p>Hello, World!</p>' block == '<div><p>Hello, World!</p></div>' ``` Your HTMLGen class should have methods to create the following elements: * a * b * p * body * div * span * title * comment Note: The comment method should wrap its argument with an HTML comment. It is the only method whose name does not match an HTML tag. So, ```g.comment('i am a comment')``` must produce ```<!--i am a comment-->```.
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", t) self . title = lambda t: self . tag("title", t) def tag(self, tag_str, content): return "<{}>{}</{}>" . format(tag_str, content, tag_str) def comment(self, content): return "<!--{}-->" . format(content)
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 to the nearest half hour. As you are sending your reply via text, you should specify the time using numbers rather than words. For example, given a distance of 80 km and an average speed of 20 km/h: ```reachDestination(80, 20);``` Your function should return: ```'The train will be there in 4 hours.'``` Hint: Keep in mind that the returned sentence needs to follow basic grammatical rules.
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 duplicated elements).
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 are valid lower case letters. The input array will not be empty.
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 (Show) iverson = Player { team = "76ers", ppg = 11.2 } jordan = Player { team = "bulls", ppg = 20.2 } sumPpg iverson jordan == 31.4 ``` ```javascript function NBAplayer(name, team, ppg){ this.name=name; this.team=team; this.ppg=ppg; } var iverson = new NBAplayer("Iverson", "76ers", 11.2); var jordan = new NBAplaer("Jordan", "bulls", 20.2); sumPPG(iverson, jordan); // => 31.4 ``` ```python iverson = { 'team': '76ers', 'ppg': 11.2 } jordan = { 'team': 'bulls', 'ppg': 20.2 } sum_ppg(iverson, jordan) # => 31.4 ``` ```ruby iverson = { "team"=>"76ers", "ppg"=> 11.2 } jordan = { "team"=>"bulls", "ppg"=> 20.2 } sum_ppg(iverson, jordan) # => 31.4 ``` ```crystal iverson = { "team"=>"76ers", "ppg"=> 11.2 } jordan = { "team"=>"bulls", "ppg"=> 20.2 } sum_ppg(iverson, jordan) # => 31.4 ``` ```csharp Player iverson = new Player(team: "76ers", ppg: 11.2); Player jordan = new Player(team: "bulls", ppg: 20.2); AllStars.SumPPG(iverson, jordan) // => 31.4 ``` ```go iverson := NBAPlayer{ Team: "76ers", Ppg: 11.2 } jordan := NBAPlayer{ Team: "bulls", Ppg: 20.2 } SumPpg(iverson,jordan) // => 31.4 ``` ```php $iverson = [ 'team' => '76ers', 'ppg' => 11.2 ]; $jordan = [ 'team' => 'bulls', 'ppg' => 20.2 ]; sumPPG($iverson, $jordan); # => 31.4 ```
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 Make sure that the implemented `remainder` function works exactly the same as the `Modulus operator (%)`. ```if:c Note for C: `div()`, `fmod()`, `ldiv()`, `lldiv()`, `fmodf()`, and `fmodl()` have all been disabled. ``` ```if:java `SimpleInteger` is a tiny and immutable implementation of an integer number. Its interface is a very small subset of the `java.math.BigInteger` API: * `#add(SimpleInteger val)` * `#subtract(SimpleInteger val)` * `#multiply(SimpleInteger val)` * `#divide(SimpleInteger val)` * `#compareTo(SimpleInteger val)` ``` ~~~if:python `divmod` has also been disabled. ~~~
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 the factorization of 24 is 2^3 x 3 ```python two_count(17280) ``` ```ruby two_count(17280) ``` ```javascript twoCount(17280) ``` ```coffeescript twoCount 17280 ``` ```haskell twoCount 17280 ``` ```csharp TwoCount(17280) ``` ```clojure two-count 17280 ``` should return 7, since the factorization of 17280 is 2^7 x 5 x 3^3 The number passed to two_count (twoCount) will always be a positive integer greater than or equal to 1.
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 first half (lower-cased) // AN second half (upper-cased)
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: use the value "Fizz" instead * If the value is a multiple of 5: use the value "Buzz" instead * If the value is a multiple of 3 & 5: use the value "FizzBuzz" instead N will never be less than 1. Method calling example: ```python fizzbuzz(3) --> [1, 2, "Fizz"] ``` ```haskell fizzbuzz(3) --> ["1", "2", "Fizz"] ``` ```kotlin fizzBuzz(3) --> ["1", "2", "Fizz"] ``` ```csharp string[] result = FizzBuzz.GetFizzBuzzArray(3); // => [ "1", "2", "Fizz" ] ``` ```prolog fizzify(3, [1, 2, "Fizz"]). ``` ```scala FizzBuzz.fizzify(3) // List("1", "2", "Fizz") ```
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 candy from each home. So we want each child to have the same amount of candies, only we can't exactly take any candy away from the kids, that would be even worse. Instead we decide to give each child extra candy until they all have the same amount. # Task Your job is to find out how much candy each child has, and give them each additional candy until they too have as much as the child(ren) with the most candy. You also want to keep a total of how much candy you've handed out because reasons." Your job is to give all the kids the same amount of candies as the kid with the most candies and then return the total number candies that have been given out. If there are no kids, or only one, return -1. In the first case (look below) the most candies are given to second kid (i.e second place in list/array), 8. Because of that we will give the first kid 3 so he can have 8 and the third kid 2 and the fourth kid 4, so all kids will have 8 candies.So we end up handing out 3 + 2 + 4 = 9. ```python (5, 8, 6, 4) => 9 (1, 2, 4, 6) => 11 (1, 6) => 5 ( ) => -1 (6) => -1 (because only one kid) ```
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 In languages that do not have an empty option, just return `None` ~~~
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 `glasses`, but not your `contacts`. Have you figured it out? Good! Then write a program that can figure it out as well.
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 the count value immediatley when the page loads, we want to create the effect of each digit cycling through its preceding numbers before stopping on the actual value. <img src="http://www.customerexperienceinsight.com/wp-content/uploads/2013/05/96102264.jpg" style="width: 350px;height: 100px"></img> # Task As a step towards achieving this; you have decided to create a function that will produce a multi-dimensional array out of the hit count value. Each inner dimension of the array represents an individual digit in the hit count, and will include all numbers that come before it, going back to 0. ## Rules * The function will take one argument which will be a four character `string` representing hit count * The function must return a multi-dimensional array containing four inner arrays * The final value in each inner array must be the actual value to be displayed * Values returned in the array must be of the type `number` **Examples** ```javascript counterEffect("1250") // [[0,1],[0,1,2],[0,1,2,3,4,5],[0]] counterEffect("0050") // [[0],[0],[0,1,2,3,4,5],[0]] counterEffect("0000") // [[0],[0],[0],[0]] ``` ```php counter_effect("1250") // [[0,1],[0,1,2],[0,1,2,3,4,5],[0]] counter_effect("0050") // [[0],[0],[0,1,2,3,4,5],[0]] counter_effect("0000") // [[0],[0],[0],[0]] ```
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" [1,2,3] -> [1,2,3] ```
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: ``` [[15,18], [4,5], [12,60]] ``` Their product would be: ``` [270, 20, 720] ``` While their respective LCM would be: ``` [90, 20, 60] ``` Thus the result should be: ``` (270-90)+(20-20)+(720-60)==840 ``` This is a kata that I made, among other things, to let some of my trainees familiarize with the [euclidean algorithm](https://en.wikipedia.org/wiki/Euclidean_algorithm), a really neat tool to have on your belt ;)
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://en.wikipedia.org/wiki/Vowel_harmony#Hungarian). ### Task: Your goal is to create a function `dative()` (`Dative()` in C#) which returns the valid form of a valid Hungarian word `w` in [dative case](http://www.hungarianreference.com/Nouns/nak-nek-dative.aspx) i. e. append the correct suffix `nek` or `nak` to the word `w` based on vowel harmony rules. ### Vowel Harmony Rules (simplified) When the last vowel in the word is 1. a _front vowel_ (`e, é, i, í, ö, ő, ü, ű`) the suffix is `-nek` 2. a _back vowel_ (`a, á, o, ó, u, ú`) the suffix is `-nak` ### Examples: ```javascript dative("ablak") == "ablaknak" dative("szék") == "széknek" dative("otthon") == "otthonnak" ``` ```python dative("ablak") == "ablaknak" dative("szék") == "széknek" dative("otthon") == "otthonnak" ``` ```php dative("ablak"); // "ablaknak" dative("szék"); // "széknek" dative("otthon"); // "otthonnak" ``` ```haskell dative "ablak" -- "ablaknak" dative "szék" -- "széknek" dative "otthon" -- "otthonnak" ``` ```groovy Kata.dative("ablak") == "ablaknak" Kata.dative("szék") == "széknek" Kata.dative("otthon") == "otthonnak" ``` ```csharp Kata.Dative("ablak") == "ablaknak" Kata.Dative("szék") == "széknek" Kata.Dative("otthon") == "otthonnak" ``` ```scala Kata.dative("ablak") == "ablaknak" Kata.dative("szék") == "széknek" Kata.dative("otthon") == "otthonnak" ``` ```java Kata.dative("ablak") == "ablaknak" Kata.dative("szék") == "széknek" Kata.dative("otthon") == "otthonnak" ``` ```go Dative("ablak") ==> "ablaknak", nil Dative("szék") ==> "széknek", nil Dative("otthon") ==> "otthonnak", nil ``` ```rust dative("ablak") // "ablaknak" dative("szék") // "széknek" dative("otthon") // "otthonnak" ``` ### Preconditions: 1. To keep it simple: All words end with a consonant :) 2. All strings are unicode strings. 3. There are no grammatical exceptions in the tests.
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 char_concat("abcdef") == 'af1be2cd3' char_concat("abc!def") == 'af1be2cd3' # same result ``` ```javascript charConcat("abcdef") == 'af1be2cd3' charConcat("abc!def") == 'af1be2cd3' // same result ``` ```ruby char_concat("abcdef") == 'af1be2cd3' char_concat("abc!def") == 'af1be2cd3' # same result ```
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 included), going in steps expressed by the third parameter: ```javascript sequenceSum(2,2,2) === 2 sequenceSum(2,6,2) === 12 // 2 + 4 + 6 sequenceSum(1,5,1) === 15 // 1 + 2 + 3 + 4 + 5 sequenceSum(1,5,3) === 5 // 1 + 4 ``` ```python sequence_sum(2, 2, 2) # 2 sequence_sum(2, 6, 2) # 12 (= 2 + 4 + 6) sequence_sum(1, 5, 1) # (= 1 + 2 + 3 + 4 + 5) sequence_sum(1, 5, 3) # 5 (= 1 + 4) ``` ```ruby sequence_sum(2, 2, 2) # 2 sequence_sum(2, 6, 2) # 12 (= 2 + 4 + 6) sequence_sum(1, 5, 1) # (= 1 + 2 + 3 + 4 + 5) sequence_sum(1, 5, 3) # 5 (= 1 + 4) ``` ```crystal sequence_sum(2, 2, 2) # 2 sequence_sum(2, 6, 2) # 12 (= 2 + 4 + 6) sequence_sum(1, 5, 1) # (= 1 + 2 + 3 + 4 + 5) sequence_sum(1, 5, 3) # 5 (= 1 + 4) ``` ```csharp SequenceSum(2, 2, 2) # 2 SequenceSum(2, 6, 2) # 12 (= 2 + 4 + 6) SequenceSum(1, 5, 1) # (= 1 + 2 + 3 + 4 + 5) SequenceSum(1, 3, 5) # 1 ``` If it is an impossible sequence (with the beginning being larger the end and a positive step or the other way around), just return `0`. See the provided test cases for further examples :) **Note:** differing from the other base kata, much larger ranges are going to be tested, so you should hope to get your algo optimized and to avoid brute-forcing your way through the solution.
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 an orderly manner. You decide the best course of action would be to put the same number of baubles on each of the branches (if possible) or add one more bauble to some of the branches - starting from the beginning of the tree. In this kata you will return an array of baubles on each of the branches. For example: 10 baubles, 2 branches: [5,5] 5 baubles, 7 branches: [1,1,1,1,1,0,0] 12 baubles, 5 branches: [3,3,2,2,2] The numbers of branches and baubles will always be greater or equal to 0. If there are 0 branches return: "Grandma, we will have to buy a Christmas tree first!". Good luck - I think your granny may have some minced pies for you if you do a good job!
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